Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Harden Your Notes indexing and lifecycle

setalp3416fc1a09c8
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 80b62f3c1c..e69506f6b2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2540,7 +2540,6 @@ dependencies = [
"self_cell",
"serde",
"serde_json",
- "sha2 0.11.0",
"tempfile",
"thiserror 2.0.18",
"tokio",
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.toml
index 6208074ae9..261eb359e8 100644
--- a/rust/apps/ensu/src-tauri/Cargo.toml
+++ b/rust/apps/ensu/src-tauri/Cargo.toml
@@ -28,7 +28,7 @@ uuid = { version = "1", features = ["v4"] }
libc = "0.2"
[target.'cfg(windows)'.dependencies]
-windows-sys = { version = "0.61.2", features = ["Win32_System_SystemInformation"] }
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_SystemInformation"] }
[features]
custom-protocol = ["tauri/custom-protocol"]
diff --git a/rust/apps/ensu/src-tauri/capabilities/default.json b/rust/apps/ensu/src-tauri/capabilities/default.json
index 4b1d24150a..f3b4bb1ef1 100644
--- a/rust/apps/ensu/src-tauri/capabilities/default.json
+++ b/rust/apps/ensu/src-tauri/capabilities/default.json
@@ -27,6 +27,12 @@
{ "path": "$DOCUMENT" },
{ "path": "$DOCUMENT/*" },
{ "path": "$DOCUMENT/**" }
+ ],
+ "deny": [
+ { "path": "$APPDATA" },
+ { "path": "$APPDATA/notes" },
+ { "path": "$APPDATA/notes/*" },
+ { "path": "$APPDATA/notes/**" }
]
},
{
diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
index bfce79235a..1e12688062 100644
--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
@@ -4,7 +4,6 @@ use std::sync::{Arc, Mutex};
use ente_core::b64;
use ente_ensu::db::{self, ChatDb, SqliteBackend};
-use ente_ensu::retrieval::GroundedSource;
use serde::{Deserialize, Serialize};
use tauri::async_runtime;
use tauri::{AppHandle, Manager, State};
@@ -13,6 +12,7 @@ use uuid::Uuid;
use crate::commands::chat_db_migration;
use crate::commands::common::{ApiError, app_data_dir};
+use crate::commands::knowledge::GroundedSourceDto;
use crate::logging;
#[derive(Default)]
@@ -158,7 +158,7 @@ pub struct ChatMessageDto {
text: String,
created_at: i64,
attachments: Vec<ChatAttachmentDto>,
- sources: Vec<GroundedSource>,
+ sources: Vec<GroundedSourceDto>,
}
impl From<db::Message> for ChatMessageDto {
@@ -187,7 +187,7 @@ impl From<db::Message> for ChatMessageDto {
.into_iter()
.map(ChatAttachmentDto::from)
.collect(),
- sources: parsed.sources,
+ sources: parsed.sources.into_iter().map(Into::into).collect(),
}
}
}
@@ -200,7 +200,7 @@ pub struct ChatMessageInsertInput {
text: String,
parent_message_uuid: Option<String>,
attachments: Option<Vec<ChatAttachmentInput>>,
- sources: Option<Vec<GroundedSource>>,
+ sources: Option<Vec<GroundedSourceDto>>,
}
#[derive(Deserialize)]
@@ -332,7 +332,15 @@ pub async fn chat_db_insert_message(
let sender = normalize_sender(&input.sender)?;
let attachments = convert_attachments(input.attachments)?;
let text = if sender == "other" {
- let sources = input.sources.unwrap_or_default();
+ let sources = input
+ .sources
+ .unwrap_or_default()
+ .into_iter()
+ .map(Into::into)
+ .collect::<Vec<_>>();
+ if sources.len() > ente_ensu::retrieval::MAX_GROUNDED_SOURCES {
+ return Err(ApiError::new("invalid_input", "Too many grounded sources"));
+ }
let result = ente_ensu::retrieval::finalize_grounded_assistant_text(&input.text, &sources)
.map_err(crate::commands::knowledge::retrieval_error);
match result {
diff --git a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs b/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
index 5c27d607b6..bf914c569d 100644
--- a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex, PoisonError};
use ente_assets::{AssetStore, download};
use ente_ensu::config::{AttributionConfig, KnowledgeDatasetConfig};
use ente_ensu::{llm, retrieval};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use tauri::async_runtime;
use tauri::{AppHandle, Emitter, Manager, State as TauriState, WebviewWindow};
@@ -87,6 +87,133 @@ pub struct KnowledgePackDto {
attribution: AttributionDto,
}
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SourceCitationDto {
+ dataset_id: String,
+ dataset_label: String,
+ credit: String,
+ title: String,
+ source_url: String,
+ license_label: String,
+ license_url: String,
+}
+
+impl From<retrieval::SourceCitation> for SourceCitationDto {
+ fn from(value: retrieval::SourceCitation) -> Self {
+ Self {
+ dataset_id: value.dataset_id,
+ dataset_label: value.dataset_label,
+ credit: value.credit,
+ title: value.title,
+ source_url: value.source_url,
+ license_label: value.license_label,
+ license_url: value.license_url,
+ }
+ }
+}
+
+impl From<SourceCitationDto> for retrieval::SourceCitation {
+ fn from(value: SourceCitationDto) -> Self {
+ Self {
+ dataset_id: value.dataset_id,
+ dataset_label: value.dataset_label,
+ credit: value.credit,
+ title: value.title,
+ source_url: value.source_url,
+ license_label: value.license_label,
+ license_url: value.license_url,
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NoteSourceReferenceDto {
+ collection_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ collection_label: Option<String>,
+ document_id: String,
+ indexed_revision: String,
+ title: String,
+ section: Option<String>,
+}
+
+impl From<ente_ensu::notes::NoteSourceReference> for NoteSourceReferenceDto {
+ fn from(value: ente_ensu::notes::NoteSourceReference) -> Self {
+ Self {
+ collection_id: value.collection_id,
+ collection_label: value.collection_label,
+ document_id: value.document_id,
+ indexed_revision: value.indexed_revision,
+ title: value.title,
+ section: value.section,
+ }
+ }
+}
+
+impl From<NoteSourceReferenceDto> for ente_ensu::notes::NoteSourceReference {
+ fn from(value: NoteSourceReferenceDto) -> Self {
+ Self {
+ collection_id: value.collection_id,
+ collection_label: value.collection_label,
+ document_id: value.document_id,
+ indexed_revision: value.indexed_revision,
+ title: value.title,
+ section: value.section,
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "camelCase")]
+pub enum GroundedSourceDto {
+ EnsuPack { citation: SourceCitationDto },
+ LocalNote { reference: NoteSourceReferenceDto },
+}
+
+impl From<retrieval::GroundedSource> for GroundedSourceDto {
+ fn from(value: retrieval::GroundedSource) -> Self {
+ match value {
+ retrieval::GroundedSource::EnsuPack { citation } => Self::EnsuPack {
+ citation: citation.into(),
+ },
+ retrieval::GroundedSource::LocalNote { reference } => Self::LocalNote {
+ reference: reference.into(),
+ },
+ }
+ }
+}
+
+impl From<GroundedSourceDto> for retrieval::GroundedSource {
+ fn from(value: GroundedSourceDto) -> Self {
+ match value {
+ GroundedSourceDto::EnsuPack { citation } => Self::EnsuPack {
+ citation: citation.into(),
+ },
+ GroundedSourceDto::LocalNote { reference } => Self::LocalNote {
+ reference: reference.into(),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GroundedPromptContextDto {
+ text: String,
+ sources: Vec<GroundedSourceDto>,
+}
+
+impl From<retrieval::GroundedPromptContext> for GroundedPromptContextDto {
+ fn from(value: retrieval::GroundedPromptContext) -> Self {
+ Self {
+ text: value.text,
+ sources: value.sources.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
struct KnowledgeDownloadProgressDto {
@@ -119,14 +246,19 @@ fn select_verified_mixed_grounding(
note_hits: &[ente_ensu::notes::NotesSearchHit],
mut verify: impl FnMut(&ente_ensu::notes::NoteSourceReference) -> Result<bool, ApiError>,
) -> Result<Vec<retrieval::GroundedExcerpt>, ApiError> {
- let selected =
- retrieval::select_mixed_grounding(pack_hits, note_hits).map_err(retrieval_error)?;
+ let selected = retrieval::select_mixed_grounding_candidates(pack_hits, note_hits, usize::MAX)
+ .map_err(retrieval_error)?;
let mut verified = Vec::with_capacity(selected.len());
+ let mut verified_note_count = 0_usize;
for excerpt in selected {
- if let retrieval::GroundedSource::LocalNote { reference } = &excerpt.source
- && !verify(reference)?
- {
- continue;
+ if let retrieval::GroundedSource::LocalNote { reference } = &excerpt.source {
+ if verified_note_count == retrieval::MAX_NOTES_GROUNDING_HITS {
+ continue;
+ }
+ if !verify(reference)? {
+ continue;
+ }
+ verified_note_count += 1;
}
verified.push(excerpt);
}
@@ -380,10 +512,10 @@ pub async fn knowledge_retrieve(
enabled_stable_ids: Vec<String>,
max_context_utf8_bytes: u32,
retrieval_epoch: u64,
-) -> Result<Option<retrieval::GroundedPromptContext>, ApiError> {
+) -> Result<Option<GroundedPromptContextDto>, ApiError> {
let knowledge_state = app.state::<State>();
let notes_state = app.state::<crate::commands::notes::State>();
- let note_collection_ids = notes_state.available_open_index_collection_ids();
+ let note_collection_ids = notes_state.available_index_collection_ids();
if query.trim().is_empty()
|| (enabled_stable_ids.is_empty() && note_collection_ids.is_empty())
|| max_context_utf8_bytes == 0
@@ -517,6 +649,7 @@ pub async fn knowledge_retrieve(
check_cancelled()?;
retrieval::build_grounded_prompt_context(&excerpts, context_budget as usize)
+ .map(|context| context.map(Into::into))
.map_err(retrieval_error)
})
.await
@@ -541,3 +674,40 @@ pub(crate) fn clear_for_exit(app: &AppHandle) {
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ente_ensu::notes::NotesSearchHit;
+
+ const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
+
+ fn note(index: usize) -> NotesSearchHit {
+ NotesSearchHit {
+ collection_id: COLLECTION_ID.to_string(),
+ document_id: format!("note-{index}.md"),
+ revision: "a".repeat(64),
+ score: 1.0 - index as f32 / 100.0,
+ title: format!("Note {index}"),
+ section: None,
+ text: format!("passage {index}"),
+ }
+ }
+
+ #[test]
+ fn stale_top_notes_are_backfilled_with_verified_hits() {
+ let notes = (0..6).map(note).collect::<Vec<_>>();
+
+ let selected = select_verified_mixed_grounding(&[], &notes, |reference| {
+ Ok(reference.document_id == "note-5.md")
+ })
+ .unwrap();
+
+ assert_eq!(selected.len(), 1);
+ assert!(matches!(
+ &selected[0].source,
+ retrieval::GroundedSource::LocalNote { reference }
+ if reference.document_id == "note-5.md"
+ ));
+ }
+}
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes.rs b/rust/apps/ensu/src-tauri/src/commands/notes.rs
index 2276c2f8f7..ea5a0ff752 100644
--- a/rust/apps/ensu/src-tauri/src/commands/notes.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/notes.rs
@@ -1,119 +1,75 @@
-use std::collections::{BTreeMap, BTreeSet, HashMap};
-use std::fs::{self, OpenOptions};
-use std::io::Write;
+use std::collections::{BTreeSet, HashMap};
+use std::fs;
#[cfg(unix)]
-use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
-use std::path::{Component, Path, PathBuf};
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};
+use ente_ensu::model;
use ente_ensu::notes::{
- NOTES_MAX_SOURCE_BYTES, NoteSourceReference, NotesCollectionIndex, NotesError,
- NotesIndexWriter, NotesSourceDocument, notes_content_revision, prepare_notes_document,
- validate_document_id,
+ NoteSourceReference, NotesCollectionIndex, NotesError, NotesIndexOutcome,
+ notes_content_revision,
};
-use ente_ensu::{llm, model};
-use notify::event::{CreateKind, RemoveKind};
-use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
-use serde::{Deserialize, Serialize};
+use notify::RecommendedWatcher;
+use serde::Serialize;
use tauri::async_runtime;
-use tauri::{AppHandle, Emitter, Manager, State as TauriState};
+use tauri::{AppHandle, Manager, State as TauriState};
+use tauri_plugin_fs::FsExt;
use tauri_plugin_opener::OpenerExt;
use uuid::Uuid;
use crate::commands::common::ApiError;
use crate::commands::llm::ModelDownloadState;
+mod indexing;
+mod registry;
+mod source;
+mod watcher;
+
+use indexing::{index_collection, should_rebuild_derived_index};
+use registry::{RegisteredCollection, RegistryStore};
+use source::{
+ canonical_source_root, cleanup_unregistered_indexes, compact_source_location,
+ is_supported_file, read_collection_source, source_root_is_available, validate_new_source_root,
+};
+pub use watcher::initialize_for_app;
+pub(crate) use watcher::mark_reference_stale;
+use watcher::{
+ emit_state_changed, ensure_collection_watcher, install_collection_watcher,
+ mark_collection_dirty,
+};
+
const NOTES_DIRECTORY: &str = "notes";
const NOTES_INDEX_DIRECTORY: &str = "indexes";
-const NOTES_REGISTRY_FILE: &str = "collections.json";
-const NOTES_REGISTRY_BACKUP_FILE: &str = "collections.json.backup";
-const NOTES_REGISTRY_SCHEMA_VERSION: u32 = 1;
-const MAX_REGISTRY_BYTES: u64 = 1024 * 1024;
-const MAX_DOCUMENTS_PER_INDEX_SLICE: usize = 64;
-const TARGET_CHUNKS_PER_INDEX_SLICE: usize = 128;
+const NOTES_EMBEDDING_TITLE_MAX_UTF8_BYTES: usize = 512;
const NOTES_QUIET_PERIOD_MS: i64 = 5 * 60 * 1_000;
const NOTES_STATE_CHANGED_EVENT: &str = "notes-state-changed";
+const NOTES_MAX_SCAN_ENTRIES: usize = 250_000;
+const NOTES_MAX_WATCH_DIRECTORIES: usize = 20_000;
+const NOTES_INDEX_CACHE_MAX_BYTES: usize = 256 * 1024 * 1024;
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct RegisteredCollection {
- id: String,
- source_root: PathBuf,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-struct RegistryFile {
- schema_version: u32,
- collections: Vec<RegisteredCollection>,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct RegistryHeader {
- schema_version: u32,
-}
+#[cfg(test)]
+struct TestDirectory(PathBuf);
-impl Default for RegistryFile {
- fn default() -> Self {
- Self {
- schema_version: NOTES_REGISTRY_SCHEMA_VERSION,
- collections: Vec::new(),
- }
+#[cfg(test)]
+impl TestDirectory {
+ fn new() -> Self {
+ let path = std::env::temp_dir().join(format!("ensu-notes-{}", Uuid::new_v4()));
+ fs::create_dir(&path).unwrap();
+ Self(path)
}
-}
-struct RegistryStore {
- directory: PathBuf,
- registry: RegistryFile,
- incompatible_error: Option<String>,
-}
-
-impl RegistryStore {
- fn open(directory: PathBuf) -> Result<Self, ApiError> {
- ensure_directory(&directory)?;
- let (registry, incompatible_error) = match open_registry_file(&directory) {
- Ok(registry) => (registry, None),
- Err(error) if error.name == Some("incompatible_registry") => {
- crate::logging::log(
- "Notes",
- "incompatible registry preserved; Notes are disabled for this version",
- );
- (RegistryFile::default(), Some(error.message))
- }
- Err(error) if is_registry_content_error(&error) => {
- quarantine_invalid_registry_files(&directory)?;
- recover_registry_publication(&directory)?;
- crate::logging::log(
- "Notes",
- "invalid registry quarantined; starting with no registered folders",
- );
- (RegistryFile::default(), None)
- }
- Err(error) => return Err(error),
- };
- Ok(Self {
- directory,
- registry,
- incompatible_error,
- })
+ fn path(&self) -> &Path {
+ &self.0
}
+}
- fn ensure_compatible(&self) -> Result<(), ApiError> {
- match &self.incompatible_error {
- Some(message) => Err(ApiError::new("incompatible_registry", message.clone())),
- None => Ok(()),
- }
- }
-
- fn replace(&mut self, registry: RegistryFile) -> Result<(), ApiError> {
- self.ensure_compatible()?;
- validate_registry(&registry)?;
- publish_registry(&self.directory, &registry)?;
- self.registry = registry;
- Ok(())
+#[cfg(test)]
+impl Drop for TestDirectory {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.0);
}
}
@@ -176,12 +132,87 @@ pub struct NotesCollectionDto {
#[serde(rename_all = "camelCase")]
pub struct NotesIndexResultDto {
collection: NotesCollectionDto,
- has_more: bool,
+ needs_rerun: bool,
}
struct CollectionWatcher {
watcher: RecommendedWatcher,
- root_watched: bool,
+ watched_directories: BTreeSet<PathBuf>,
+}
+
+struct CachedIndex {
+ index: NotesCollectionIndex,
+ bytes: usize,
+ last_used: u64,
+}
+
+struct IndexCache {
+ entries: HashMap<String, CachedIndex>,
+ max_bytes: usize,
+ total_bytes: usize,
+ clock: u64,
+}
+
+impl IndexCache {
+ fn new(max_bytes: usize) -> Self {
+ Self {
+ entries: HashMap::new(),
+ max_bytes,
+ total_bytes: 0,
+ clock: 0,
+ }
+ }
+
+ fn search(
+ &mut self,
+ collection_id: &str,
+ query: &[f32],
+ ) -> Option<Result<Vec<ente_ensu::notes::NotesSearchHit>, NotesError>> {
+ self.clock = self.clock.wrapping_add(1);
+ let entry = self.entries.get_mut(collection_id)?;
+ entry.last_used = self.clock;
+ Some(entry.index.search(query))
+ }
+
+ fn insert(&mut self, collection_id: String, index: NotesCollectionIndex) {
+ self.remove(&collection_id);
+ let bytes = index.estimated_heap_bytes();
+ if bytes > self.max_bytes {
+ return;
+ }
+ while self.total_bytes.saturating_add(bytes) > self.max_bytes {
+ let Some(oldest) = self
+ .entries
+ .iter()
+ .min_by_key(|(_, entry)| entry.last_used)
+ .map(|(collection_id, _)| collection_id.clone())
+ else {
+ break;
+ };
+ self.remove(&oldest);
+ }
+ self.clock = self.clock.wrapping_add(1);
+ self.total_bytes = self.total_bytes.saturating_add(bytes);
+ self.entries.insert(
+ collection_id,
+ CachedIndex {
+ index,
+ bytes,
+ last_used: self.clock,
+ },
+ );
+ }
+
+ fn remove(&mut self, collection_id: &str) {
+ if let Some(entry) = self.entries.remove(collection_id) {
+ self.total_bytes = self.total_bytes.saturating_sub(entry.bytes);
+ }
+ }
+
+ fn clear(&mut self) {
+ self.entries.clear();
+ self.total_bytes = 0;
+ }
}
#[derive(Default)]
@@ -234,17 +265,19 @@ struct UpdateSnapshot {
pub struct State {
registry: Arc<Mutex<RegistryStore>>,
runtimes: Arc<Mutex<HashMap<String, CollectionRuntime>>>,
- indexes: Arc<Mutex<HashMap<String, NotesCollectionIndex>>>,
+ cached_indexes: Arc<Mutex<IndexCache>>,
index_root: PathBuf,
collection_lifecycles: Mutex<HashMap<String, Arc<async_runtime::Mutex<()>>>>,
watchers: Mutex<HashMap<String, CollectionWatcher>>,
+ watch_work: Mutex<HashMap<String, watcher::WatchWork>>,
updates: Mutex<HashMap<String, DesktopUpdateState>>,
}
#[derive(Clone)]
pub(crate) struct RetrievalHandle {
registry: Arc<Mutex<RegistryStore>>,
- indexes: Arc<Mutex<HashMap<String, NotesCollectionIndex>>>,
+ cached_indexes: Arc<Mutex<IndexCache>>,
+ index_root: PathBuf,
}
impl State {
@@ -253,15 +286,17 @@ impl State {
let index_root = notes_directory.join(NOTES_INDEX_DIRECTORY);
ensure_directory(&index_root)?;
let registry = RegistryStore::open(notes_directory)?;
+ if registry.incompatible_error.is_none() {
+ cleanup_unregistered_indexes(&index_root, &registry.registry.collections);
+ }
let mut runtimes = HashMap::new();
- let mut indexes = HashMap::new();
for collection in &registry.registry.collections {
let runtime = if !collection.source_root.is_dir() {
CollectionRuntime::unavailable()
} else {
- match NotesCollectionIndex::open(&index_root, collection.id.clone()) {
- Ok(index) => {
- let count = index.document_count();
+ match NotesCollectionIndex::inspect(&index_root, collection.id.clone()) {
+ Ok(summary) => {
+ let count = summary.document_count;
if count == 0 {
CollectionRuntime {
status: NotesCollectionStatusDto::Error,
@@ -271,18 +306,18 @@ impl State {
..CollectionRuntime::pending()
}
} else {
- let last_updated_at_ms = index.last_updated_at_ms();
- indexes.insert(collection.id.clone(), index);
CollectionRuntime {
status: NotesCollectionStatusDto::Ready,
index_available: true,
indexed_document_count: count as u64,
- last_updated_at_ms,
+ last_updated_at_ms: summary.last_updated_at_ms,
..CollectionRuntime::pending()
}
}
}
- Err(NotesError::NotReady | NotesError::Io(_)) => CollectionRuntime::pending(),
+ Err(
+ NotesError::NotReady | NotesError::IncompatibleIndex | NotesError::Io(_),
+ ) => CollectionRuntime::pending(),
Err(_) => CollectionRuntime {
status: NotesCollectionStatusDto::Error,
last_error: Some("The local index needs to be rebuilt".to_string()),
@@ -295,10 +330,11 @@ impl State {
Ok(Self {
registry: Arc::new(Mutex::new(registry)),
runtimes: Arc::new(Mutex::new(runtimes)),
- indexes: Arc::new(Mutex::new(indexes)),
+ cached_indexes: Arc::new(Mutex::new(IndexCache::new(NOTES_INDEX_CACHE_MAX_BYTES))),
index_root,
collection_lifecycles: Mutex::new(HashMap::new()),
watchers: Mutex::new(HashMap::new()),
+ watch_work: Mutex::new(HashMap::new()),
updates: Mutex::new(HashMap::new()),
})
}
@@ -397,11 +433,19 @@ impl State {
.remove(collection_id);
}
- fn has_open_index(&self, collection_id: &str) -> bool {
- self.indexes
+ fn evict_cached_index(&self, collection_id: &str) {
+ self.cached_indexes
.lock()
.unwrap_or_else(PoisonError::into_inner)
- .contains_key(collection_id)
+ .remove(collection_id);
+ }
+
+ fn has_available_index(&self, collection_id: &str) -> bool {
+ self.runtimes
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .get(collection_id)
+ .is_some_and(|runtime| runtime.index_available)
}
fn has_pending_update(&self, collection_id: &str) -> bool {
@@ -440,7 +484,7 @@ impl State {
&self,
collection_id: &str,
update_generation: u64,
- outcome: &IndexSliceOutcome,
+ outcome: &NotesIndexOutcome,
had_index: bool,
completed_index_updated_at_ms: Option<i64>,
) -> (bool, bool) {
@@ -448,31 +492,25 @@ impl State {
let generation_unchanged = updates
.get(collection_id)
.is_none_or(|update| update.generation == update_generation);
- let reconciliation_complete =
- !outcome.has_more && outcome.changed_during_indexing.is_none();
+ let reconciliation_complete = outcome.changed_during_indexing.is_none();
let ready = outcome.ready();
let update_completed = reconciliation_complete && generation_unchanged;
if update_completed {
updates.remove(collection_id);
}
- let continue_slices = (!had_index && !generation_unchanged)
- || (outcome.has_more
- && outcome.changed_during_indexing.is_none()
- && generation_unchanged);
+ let needs_rerun = !had_index && !generation_unchanged;
let mut runtime = self.runtime(collection_id);
if update_completed {
runtime.index_available = ready;
runtime.last_updated_at_ms = ready.then_some(completed_index_updated_at_ms).flatten();
}
- runtime.indexing_progress = continue_slices
- .then_some(runtime.indexing_progress)
- .flatten();
+ runtime.indexing_progress = needs_rerun.then_some(runtime.indexing_progress).flatten();
runtime.indexed_document_count = outcome.indexed_document_count;
runtime.status = if update_completed && ready {
NotesCollectionStatusDto::Ready
} else if update_completed {
NotesCollectionStatusDto::Error
- } else if continue_slices {
+ } else if needs_rerun {
if had_index {
NotesCollectionStatusDto::Updating
} else {
@@ -484,7 +522,7 @@ impl State {
runtime.last_error = (update_completed && !ready)
.then(|| "No supported non-empty UTF-8 notes were found".to_string());
self.set_runtime(collection_id, runtime);
- (continue_slices, update_completed)
+ (needs_rerun, update_completed)
}
fn report_indexing_progress(app: &AppHandle, collection_id: &str, progress: u8) {
@@ -502,13 +540,15 @@ impl State {
emit_state_changed(app, collection_id);
}
- pub(crate) fn available_open_index_collection_ids(&self) -> Vec<String> {
- let open_ids = self
- .indexes
+ pub(crate) fn available_index_collection_ids(&self) -> Vec<String> {
+ let available_ids = self
+ .runtimes
.lock()
.unwrap_or_else(PoisonError::into_inner)
- .keys()
- .cloned()
+ .iter()
+ .filter_map(|(collection_id, runtime)| {
+ runtime.index_available.then_some(collection_id.clone())
+ })
.collect::<BTreeSet<_>>();
let collections = self
.registry
@@ -520,7 +560,7 @@ impl State {
collections
.into_iter()
.filter(|collection| {
- open_ids.contains(&collection.id)
+ available_ids.contains(&collection.id)
&& source_root_is_available(&collection.source_root)
})
.map(|collection| collection.id)
@@ -530,397 +570,12 @@ impl State {
pub(crate) fn retrieval_handle(&self) -> RetrievalHandle {
RetrievalHandle {
registry: Arc::clone(&self.registry),
- indexes: Arc::clone(&self.indexes),
+ cached_indexes: Arc::clone(&self.cached_indexes),
+ index_root: self.index_root.clone(),
}
}
}
-#[derive(Default)]
-struct WatchChange {
- forced_document_ids: BTreeSet<String>,
- force_full_hash: bool,
-}
-
-struct StartupInspection {
- initial_complete: bool,
- changed: bool,
-}
-
-pub fn initialize_for_app(app: &AppHandle) {
- let collections = app
- .state::<State>()
- .registry
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .registry
- .collections
- .clone();
- for collection in collections {
- if let Err(error) = install_collection_watcher(app, &collection) {
- let state = app.state::<State>();
- let mut runtime = state.runtime(&collection.id);
- runtime.status = if source_root_is_available(&collection.source_root) {
- NotesCollectionStatusDto::Error
- } else {
- NotesCollectionStatusDto::Unavailable
- };
- runtime.last_error = Some(error.message);
- state.set_runtime(&collection.id, runtime);
- emit_state_changed(app, &collection.id);
- continue;
- }
- inspect_collection_on_startup(app.clone(), collection);
- }
-}
-
-fn inspect_collection_on_startup(app: AppHandle, collection: RegisteredCollection) {
- let index_root = app.state::<State>().index_root.clone();
- async_runtime::spawn(async move {
- let lifecycle = app.state::<State>().collection_lifecycle(&collection.id);
- let _collection_lifecycle = lifecycle.lock().await;
- if app
- .state::<State>()
- .registered_collection(&collection.id)
- .is_err()
- {
- return;
- }
- let inspection_collection = collection.clone();
- let inspection = async_runtime::spawn_blocking(move || {
- inspect_startup_freshness(&index_root, &inspection_collection)
- })
- .await;
- let Ok(inspection) = inspection else {
- return;
- };
- let state = app.state::<State>();
- if state.registered_collection(&collection.id).is_err() {
- return;
- }
- if inspection.is_ok() && state.has_pending_update(&collection.id) {
- return;
- }
- match inspection {
- Ok(inspection) if inspection.changed && inspection.initial_complete => {
- mark_collection_dirty(&app, &collection.id, [], false);
- }
- Ok(inspection) => {
- let mut runtime = state.runtime(&collection.id);
- if !inspection.initial_complete {
- runtime.status = NotesCollectionStatusDto::Pending;
- runtime.last_error = None;
- } else if state.has_open_index(&collection.id) {
- runtime.status = NotesCollectionStatusDto::Ready;
- runtime.last_error = None;
- }
- state.set_runtime(&collection.id, runtime);
- emit_state_changed(&app, &collection.id);
- }
- Err(error) => {
- let mut runtime = state.runtime(&collection.id);
- runtime.status = if source_root_is_available(&collection.source_root) {
- NotesCollectionStatusDto::Error
- } else {
- NotesCollectionStatusDto::Unavailable
- };
- runtime.last_error = Some(error.message);
- state.set_runtime(&collection.id, runtime);
- emit_state_changed(&app, &collection.id);
- }
- }
- });
-}
-
-fn inspect_startup_freshness(
- index_root: &Path,
- collection: &RegisteredCollection,
-) -> Result<StartupInspection, ApiError> {
- let canonical_root = canonical_source_root(&collection.source_root)?;
- if canonical_root != collection.source_root {
- return Err(ApiError::new(
- "source_changed",
- "Notes source folder identity changed",
- ));
- }
- let inventory = inventory_source_root(&canonical_root, || Ok(()))?;
- let writer = NotesIndexWriter::open(index_root, collection.id.clone()).map_err(notes_error)?;
- let plan = writer
- .plan_reconciliation(&inventory.documents, &[], false)
- .map_err(notes_error)?;
- Ok(StartupInspection {
- initial_complete: writer.initial_inventory_complete(),
- changed: !plan.is_up_to_date(),
- })
-}
-
-fn install_collection_watcher(
- app: &AppHandle,
- collection: &RegisteredCollection,
-) -> Result<(), ApiError> {
- let collection_id = collection.id.clone();
- let source_root = collection.source_root.clone();
- let callback_app = app.clone();
- let callback_collection_id = collection_id.clone();
- let callback_root = source_root.clone();
- let mut watcher = RecommendedWatcher::new(
- move |result| {
- handle_watch_event(
- &callback_app,
- &callback_collection_id,
- &callback_root,
- result,
- );
- },
- Config::default(),
- )
- .map_err(notify_error)?;
-
- let mut root_watched = false;
- if source_root_is_available(&source_root) {
- watcher
- .watch(&source_root, RecursiveMode::Recursive)
- .map_err(notify_error)?;
- root_watched = true;
- }
- let parent_watched = source_root
- .parent()
- .is_some_and(|parent| watcher.watch(parent, RecursiveMode::NonRecursive).is_ok());
- if !root_watched && !parent_watched {
- return Err(ApiError::new(
- "watcher",
- "The Notes folder could not be watched",
- ));
- }
- app.state::<State>()
- .watchers
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .insert(
- collection_id,
- CollectionWatcher {
- watcher,
- root_watched,
- },
- );
- Ok(())
-}
-
-fn handle_watch_event(
- app: &AppHandle,
- collection_id: &str,
- source_root: &Path,
- result: notify::Result<Event>,
-) {
- let change = match result {
- Ok(event) => classify_watch_event(source_root, &event),
- Err(_) => Some(WatchChange {
- force_full_hash: true,
- ..WatchChange::default()
- }),
- };
- let Some(change) = change else {
- return;
- };
- let event_app = app.clone();
- let event_collection_id = collection_id.to_string();
- let event_source_root = source_root.to_path_buf();
- async_runtime::spawn(async move {
- refresh_root_watch(&event_app, &event_collection_id, &event_source_root);
- mark_collection_dirty(
- &event_app,
- &event_collection_id,
- change.forced_document_ids,
- change.force_full_hash,
- );
- });
-}
-
-fn refresh_root_watch(app: &AppHandle, collection_id: &str, source_root: &Path) {
- let available = source_root_is_available(source_root);
- let state = app.state::<State>();
- let mut watchers = state
- .watchers
- .lock()
- .unwrap_or_else(PoisonError::into_inner);
- let Some(entry) = watchers.get_mut(collection_id) else {
- return;
- };
- if available && !entry.root_watched {
- entry.root_watched = entry
- .watcher
- .watch(source_root, RecursiveMode::Recursive)
- .is_ok();
- } else if !available && entry.root_watched {
- let _ = entry.watcher.unwatch(source_root);
- entry.root_watched = false;
- }
-}
-
-fn ensure_collection_watcher(
- app: &AppHandle,
- collection: &RegisteredCollection,
-) -> Result<(), ApiError> {
- if !source_root_is_available(&collection.source_root) {
- return Err(ApiError::new(
- "source_unavailable",
- "Source folder is unavailable",
- ));
- }
- refresh_root_watch(app, &collection.id, &collection.source_root);
- let state = app.state::<State>();
- let root_watched = state
- .watchers
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .get(&collection.id)
- .is_some_and(|entry| entry.root_watched);
- if root_watched {
- return Ok(());
- }
- state
- .watchers
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .remove(&collection.id);
- install_collection_watcher(app, collection)
-}
-
-fn classify_watch_event(source_root: &Path, event: &Event) -> Option<WatchChange> {
- if matches!(event.kind, EventKind::Access(_)) {
- return None;
- }
- let ambiguous = matches!(
- event.kind,
- EventKind::Any
- | EventKind::Other
- | EventKind::Create(CreateKind::Folder)
- | EventKind::Remove(RemoveKind::Folder)
- );
- classify_watch_paths(source_root, &event.paths, ambiguous)
-}
-
-fn classify_watch_paths(
- source_root: &Path,
- paths: &[PathBuf],
- overflow_or_ambiguity: bool,
-) -> Option<WatchChange> {
- if paths.is_empty() {
- return overflow_or_ambiguity.then_some(WatchChange {
- force_full_hash: true,
- ..WatchChange::default()
- });
- }
- let mut change = WatchChange::default();
- let mut saw_relevant_path = false;
- for path in paths {
- if path == source_root {
- saw_relevant_path = true;
- change.force_full_hash = true;
- continue;
- }
- let Ok(relative) = path.strip_prefix(source_root) else {
- continue;
- };
- if relative.components().any(|component| {
- matches!(component, Component::Normal(name) if name.to_string_lossy().starts_with('.'))
- }) {
- continue;
- }
- if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
- continue;
- }
- saw_relevant_path = true;
- if is_supported_file(path) {
- if let Some(document_id) = relative_document_id(source_root, path) {
- change.forced_document_ids.insert(document_id);
- }
- continue;
- }
- if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir()) {
- change.force_full_hash = true;
- }
- }
- change.force_full_hash |= overflow_or_ambiguity && saw_relevant_path;
- (!change.forced_document_ids.is_empty() || change.force_full_hash).then_some(change)
-}
-
-fn mark_collection_for_update(
- app: &AppHandle,
- collection_id: &str,
- record_update: impl FnOnce(&mut DesktopUpdateState) -> bool,
-) {
- let state = app.state::<State>();
- let Ok(collection) = state.registered_collection(collection_id) else {
- return;
- };
- let changed = {
- let mut updates = state.updates.lock().unwrap_or_else(PoisonError::into_inner);
- let update = updates.entry(collection_id.to_string()).or_default();
- record_update(update)
- };
- if !changed {
- return;
- }
-
- let available = source_root_is_available(&collection.source_root);
- let mut runtime = state.runtime(collection_id);
- if !available
- && !matches!(
- runtime.status,
- NotesCollectionStatusDto::Indexing | NotesCollectionStatusDto::Updating
- )
- {
- runtime.status = NotesCollectionStatusDto::Unavailable;
- } else if available
- && matches!(
- runtime.status,
- NotesCollectionStatusDto::Unavailable | NotesCollectionStatusDto::Error
- )
- {
- runtime.status = if runtime.index_available {
- NotesCollectionStatusDto::Ready
- } else {
- NotesCollectionStatusDto::Pending
- };
- }
- runtime.last_error = (!available).then(|| "Source folder is unavailable".to_string());
- state.set_runtime(collection_id, runtime);
- emit_state_changed(app, collection_id);
-}
-
-pub(crate) fn mark_collection_dirty(
- app: &AppHandle,
- collection_id: &str,
- forced_document_ids: impl IntoIterator<Item = String>,
- force_full_hash: bool,
-) {
- mark_collection_for_update(app, collection_id, move |update| {
- update.record_change(now_ms(), forced_document_ids, force_full_hash);
- true
- });
-}
-
-pub(crate) fn mark_reference_stale(app: &AppHandle, collection_id: &str, document_id: String) {
- mark_collection_for_update(app, collection_id, move |update| {
- update.record_stale_reference(now_ms(), document_id)
- });
-}
-
-fn emit_state_changed(app: &AppHandle, collection_id: &str) {
- let state = app.state::<State>();
- if let Ok(collection) = state.collection_dto(collection_id) {
- let _ = app.emit(NOTES_STATE_CHANGED_EVENT, collection);
- }
-}
-
-fn source_root_is_available(source_root: &Path) -> bool {
- canonical_source_root(source_root).is_ok_and(|canonical| canonical == source_root)
-}
-
-fn notify_error(_: notify::Error) -> ApiError {
- ApiError::new("watcher", "The Notes folder could not be watched")
-}
-
impl RetrievalHandle {
pub(crate) fn collection_label(&self, collection_id: &str) -> Option<String> {
self.registry
@@ -938,11 +593,21 @@ impl RetrievalHandle {
collection_id: &str,
query: &[f32],
) -> Result<Vec<ente_ensu::notes::NotesSearchHit>, NotesError> {
- let indexes = self.indexes.lock().unwrap_or_else(PoisonError::into_inner);
- let Some(index) = indexes.get(collection_id) else {
- return Ok(Vec::new());
- };
- index.search(query)
+ if let Some(result) = self
+ .cached_indexes
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .search(collection_id, query)
+ {
+ return result;
+ }
+ let index = NotesCollectionIndex::open(&self.index_root, collection_id.to_string())?;
+ let hits = index.search(query)?;
+ self.cached_indexes
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .insert(collection_id.to_string(), index);
+ Ok(hits)
}
pub(crate) fn verify_source_reference(&self, reference: &NoteSourceReference) -> bool {
@@ -958,8 +623,8 @@ impl RetrievalHandle {
let Some(collection) = collection else {
return false;
};
- resolve_document_path(&collection.source_root, &reference.document_id)
- .and_then(|path| read_supported_source(&path))
+ read_collection_source(&collection.source_root, &reference.document_id)
+ .map(|(_, bytes, _)| bytes)
.map(|bytes| notes_content_revision(&bytes) == reference.indexed_revision)
.unwrap_or(false)
}
@@ -1021,7 +686,7 @@ pub fn notes_list_collections(
#[tauri::command]
pub fn notes_has_available_index(notes_state: TauriState<'_, State>) -> bool {
- !notes_state.available_open_index_collection_ids().is_empty()
+ !notes_state.available_index_collection_ids().is_empty()
}
#[tauri::command]
@@ -1031,6 +696,33 @@ pub fn notes_add_collection(
source_root: String,
) -> Result<NotesCollectionDto, ApiError> {
let root = canonical_source_root(Path::new(&source_root))?;
+ if !app.fs_scope().is_allowed(&root) {
+ return Err(ApiError::new(
+ "io_scope",
+ "Notes folder is outside the allowed filesystem scope",
+ ));
+ }
+ register_collection(&app, &notes_state, &root)
+}
+
+fn register_collection(
+ app: &AppHandle,
+ notes_state: &State,
+ source_root: &Path,
+) -> Result<NotesCollectionDto, ApiError> {
+ let root = canonical_source_root(source_root)?;
+ let notes_directory = notes_state
+ .index_root
+ .parent()
+ .ok_or_else(|| ApiError::new("notes_storage", "Notes storage path is invalid"))?;
+ let notes_directory = fs::canonicalize(notes_directory)
+ .map_err(|_| ApiError::new("notes_storage", "Notes storage path is unavailable"))?;
+ if root.starts_with(&notes_directory) || notes_directory.starts_with(&root) {
+ return Err(ApiError::new(
+ "invalid_folder",
+ "Choose a folder outside Ensu's private Notes storage",
+ ));
+ }
let collection = RegisteredCollection {
id: Uuid::new_v4().hyphenated().to_string(),
source_root: root,
@@ -1046,7 +738,7 @@ pub fn notes_add_collection(
store.replace(registry)?;
}
notes_state.set_runtime(&collection.id, CollectionRuntime::pending());
- if let Err(error) = install_collection_watcher(&app, &collection) {
+ if let Err(error) = install_collection_watcher(app, &collection) {
notes_state.set_runtime(
&collection.id,
CollectionRuntime {
@@ -1068,9 +760,6 @@ pub async fn notes_remove_collection(
let _lifecycle = lifecycle.lock().await;
let collection = notes_state.registered_collection(&collection_id)?;
let derived_directory = notes_state.index_root.join(&collection.id);
- if path_exists(&derived_directory)? {
- remove_owned_entry(&derived_directory)?;
- }
{
let mut store = notes_state
.registry
@@ -1087,17 +776,33 @@ pub async fn notes_remove_collection(
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&collection_id);
- notes_state.cancel_update(&collection_id);
notes_state
- .indexes
+ .watch_work
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&collection_id);
+ notes_state.cancel_update(&collection_id);
+ notes_state.evict_cached_index(&collection_id);
notes_state
.runtimes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&collection_id);
+ let cleanup_result = (|| -> Result<(), ApiError> {
+ if path_exists(&derived_directory)? {
+ remove_owned_entry(&derived_directory)?;
+ }
+ Ok(())
+ })();
+ if let Err(error) = cleanup_result {
+ crate::logging::log(
+ "Notes",
+ format!(
+ "removed collection but could not clean derived index collection={} error={}",
+ collection_id, error.message
+ ),
+ );
+ }
notes_state
.collection_lifecycles
.lock()
@@ -1152,13 +857,20 @@ pub async fn notes_index_collection(
let lifecycle = notes_state.collection_lifecycle(&collection_id);
let _collection_lifecycle = lifecycle.lock().await;
let collection = notes_state.registered_collection(&collection_id)?;
- if let Err(error) = ensure_collection_watcher(&app, &collection) {
+ let watcher_app = app.clone();
+ let watcher_collection = collection.clone();
+ let watcher_result = async_runtime::spawn_blocking(move || {
+ ensure_collection_watcher(&watcher_app, &watcher_collection)
+ })
+ .await
+ .map_err(|_| ApiError::new("watcher_thread", "Notes watcher task failed"))?;
+ if let Err(error) = watcher_result {
report_index_error(&app, &notes_state, &collection_id, None, &error);
return Err(error);
}
- let had_index = notes_state.has_open_index(&collection_id);
+ let had_index = notes_state.has_available_index(&collection_id);
let rebuild_derived_index =
- should_rebuild_derived_index(&notes_state.index_root, &collection_id, force)?;
+ should_rebuild_derived_index(&notes_state.index_root, &collection_id, force, had_index)?;
let mut update = notes_state.prepare_update(&collection_id, force, had_index)?;
update.rebuild_derived_index = rebuild_derived_index;
let cancellation_epoch = llm_state.retrieval_epoch();
@@ -1190,7 +902,7 @@ pub async fn notes_index_collection(
let progress_app = app.clone();
let progress_collection_id = collection_id.clone();
let result = async_runtime::spawn_blocking(move || {
- index_collection_slice(
+ index_collection(
&index_root,
&collection,
embedding_path.as_deref(),
@@ -1202,8 +914,21 @@ pub async fn notes_index_collection(
},
)
})
- .await
- .map_err(|_| ApiError::new("index_thread", "Notes indexing task failed"))?;
+ .await;
+ let result = match result {
+ Ok(result) => result,
+ Err(_) => {
+ let error = ApiError::new("index_thread", "Notes indexing task failed");
+ report_index_error(
+ &app,
+ &notes_state,
+ &collection_id,
+ Some(update_generation),
+ &error,
+ );
+ return Err(error);
+ }
+ };
let outcome = match result {
Ok(outcome) => outcome,
@@ -1220,6 +945,7 @@ pub async fn notes_index_collection(
};
let opened_index = if outcome.ready() {
+ notes_state.evict_cached_index(&collection_id);
match NotesCollectionIndex::open(&notes_state.index_root, collection_id.clone()) {
Ok(index) => Some(index),
Err(error) => {
@@ -1249,7 +975,7 @@ pub async fn notes_index_collection(
let completed_index_updated_at_ms = opened_index
.as_ref()
.and_then(NotesCollectionIndex::last_updated_at_ms);
- let (continue_slices, update_completed) = notes_state.apply_index_outcome(
+ let (needs_rerun, update_completed) = notes_state.apply_index_outcome(
&collection_id,
update_generation,
&outcome,
@@ -1259,23 +985,19 @@ pub async fn notes_index_collection(
if update_completed {
if let Some(index) = opened_index {
notes_state
- .indexes
+ .cached_indexes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(collection_id.clone(), index);
} else {
- notes_state
- .indexes
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .remove(&collection_id);
+ notes_state.evict_cached_index(&collection_id);
}
}
emit_state_changed(&app, &collection_id);
let dto = notes_state.collection_dto(&collection_id)?;
Ok(NotesIndexResultDto {
collection: dto,
- has_more: continue_slices,
+ needs_rerun,
})
}
@@ -1285,465 +1007,25 @@ pub fn notes_open_document(
notes_state: TauriState<'_, State>,
collection_id: String,
document_id: String,
+ indexed_revision: String,
) -> Result<(), ApiError> {
let collection = notes_state.registered_collection(&collection_id)?;
- let path = resolve_document_path(&collection.source_root, &document_id)?;
+ let (path, bytes, _) = read_collection_source(&collection.source_root, &document_id)?;
if !is_supported_file(&path) {
return Err(ApiError::new(
"invalid_document",
"Unsupported note document",
));
}
- app.opener()
- .open_path(path.to_string_lossy().into_owned(), None::<String>)
- .map_err(|_| ApiError::new("open_failed", "Source note could not be opened"))
-}
-
-struct Inventory {
- documents: Vec<NotesSourceDocument>,
- paths: BTreeMap<String, PathBuf>,
-}
-
-struct IndexSliceOutcome {
- has_more: bool,
- changed_during_indexing: Option<String>,
- unchecked_document_ids: Vec<String>,
- indexed_document_count: u64,
-}
-
-impl IndexSliceOutcome {
- fn ready(&self) -> bool {
- !self.has_more && self.changed_during_indexing.is_none() && self.indexed_document_count > 0
- }
-}
-
-fn index_collection_slice(
- index_root: &Path,
- collection: &RegisteredCollection,
- embedding_path: Option<&Path>,
- cancellation_epoch: &std::sync::atomic::AtomicU64,
- retrieval_epoch: u64,
- update: &UpdateSnapshot,
- mut on_progress: impl FnMut(u8),
-) -> Result<IndexSliceOutcome, ApiError> {
- check_cancelled(cancellation_epoch, retrieval_epoch)?;
- let canonical_root = canonical_source_root(&collection.source_root)?;
- if canonical_root != collection.source_root {
+ if notes_content_revision(&bytes) != indexed_revision {
return Err(ApiError::new(
"source_changed",
- "Notes source folder identity changed",
- ));
- }
- let inventory = inventory_source_root(&canonical_root, || {
- check_cancelled(cancellation_epoch, retrieval_epoch)
- })?;
- if update.rebuild_derived_index {
- let derived_directory = index_root.join(&collection.id);
- if path_exists(&derived_directory)? {
- remove_owned_entry(&derived_directory)?;
- }
- }
- let mut writer =
- NotesIndexWriter::open(index_root, collection.id.clone()).map_err(notes_error)?;
- let index_was_ready = writer.initial_inventory_complete();
- let plan = writer
- .plan_reconciliation(
- &inventory.documents,
- &update.forced_document_ids,
- update.force_full_hash,
- )
- .map_err(notes_error)?;
- writer
- .commit_deletions(&plan.deleted_document_ids)
- .map_err(notes_error)?;
-
- let source_document_count = inventory.documents.len() as u64;
- let requested = plan.content_required_document_ids;
- let mut progress_document_count = source_document_count.saturating_sub(requested.len() as u64);
- on_progress(indexing_progress(
- progress_document_count,
- source_document_count,
- ));
- let mut processed_requested = 0_usize;
- let mut embedded_documents = 0_usize;
- let mut embedded_chunks = 0_usize;
- let mut embedding_context = None;
- for document_id in &requested {
- check_cancelled(cancellation_epoch, retrieval_epoch)?;
- let source_metadata = inventory
- .documents
- .iter()
- .find(|source| source.document_id == *document_id)
- .expect("reconciliation returns a source inventory document");
- let path = inventory
- .paths
- .get(document_id)
- .expect("source inventory contains every document path");
- let prepared = match read_supported_source(path) {
- Ok(bytes) => prepare_notes_document(document_id, &bytes).ok(),
- Err(error) if error.name == Some("invalid_document") => None,
- Err(error)
- if error.name == Some("source_changed")
- && source_root_is_available(&canonical_root) =>
- {
- return changed_during_indexing_outcome(
- &mut writer,
- index_was_ready,
- document_id,
- &requested,
- processed_requested,
- );
- }
- Err(error) => return Err(error),
- };
- let Some(prepared) = prepared else {
- writer
- .commit_deletions(std::slice::from_ref(document_id))
- .map_err(notes_error)?;
- processed_requested += 1;
- progress_document_count += 1;
- on_progress(indexing_progress(
- progress_document_count,
- source_document_count,
- ));
- continue;
- };
- let embedding_path = embedding_path.ok_or_else(|| {
- ApiError::new(
- "embedding_missing",
- "The knowledge embedding model is not downloaded",
- )
- })?;
- if embedding_context.is_none() {
- let model = llm::Model::load(llm::ModelLoadParams {
- model_path: embedding_path.display().to_string(),
- n_gpu_layers: Some(0),
- use_mmap: Some(true),
- use_mlock: Some(false),
- })
- .map_err(crate::commands::llm::llm_api_error)?;
- let threads = std::thread::available_parallelism()
- .map(|count| count.get().saturating_sub(1).max(1))
- .unwrap_or(1);
- embedding_context = Some(
- llm::Context::new_knowledge_embedding(
- &model,
- Some(i32::try_from(threads).unwrap_or(1)),
- )
- .map_err(crate::commands::llm::llm_api_error)?,
- );
- }
- let context = embedding_context
- .as_ref()
- .expect("embedding context was initialized");
- let mut embeddings = Vec::with_capacity(prepared.chunks.len());
- for chunk in &prepared.chunks {
- check_cancelled(cancellation_epoch, retrieval_epoch)?;
- let embedding_title = match chunk.section.as_deref() {
- Some(section) if section != prepared.title => {
- format!("{} β€” {section}", prepared.title)
- }
- _ => prepared.title.clone(),
- };
- embeddings.push(
- context
- .embed_document(&embedding_title, &chunk.text)
- .map_err(crate::commands::llm::llm_api_error)?,
- );
- }
- check_cancelled(cancellation_epoch, retrieval_epoch)?;
- let current_bytes = match read_supported_source(path) {
- Ok(bytes) => bytes,
- Err(error)
- if error.name == Some("source_changed")
- && source_root_is_available(&canonical_root) =>
- {
- return changed_during_indexing_outcome(
- &mut writer,
- index_was_ready,
- document_id,
- &requested,
- processed_requested,
- );
- }
- Err(error) => return Err(error),
- };
- if notes_content_revision(&current_bytes) != prepared.revision {
- return changed_during_indexing_outcome(
- &mut writer,
- index_was_ready,
- document_id,
- &requested,
- processed_requested,
- );
- }
- writer
- .commit_document(&prepared, &embeddings, source_metadata)
- .map_err(notes_error)?;
- processed_requested += 1;
- progress_document_count += 1;
- on_progress(indexing_progress(
- progress_document_count,
- source_document_count,
+ "Source note changed after this answer was generated",
));
- embedded_documents += 1;
- embedded_chunks += prepared.chunks.len();
- if embedded_documents >= MAX_DOCUMENTS_PER_INDEX_SLICE
- || embedded_chunks >= TARGET_CHUNKS_PER_INDEX_SLICE
- {
- break;
- }
}
-
- let has_more = embedded_documents > 0 && processed_requested < requested.len();
- writer
- .publish(index_was_ready || !has_more)
- .map_err(notes_error)?;
- Ok(IndexSliceOutcome {
- has_more,
- changed_during_indexing: None,
- unchecked_document_ids: requested.into_iter().skip(processed_requested).collect(),
- indexed_document_count: writer.indexed_document_ids().count() as u64,
- })
-}
-
-fn indexing_progress(processed_document_count: u64, source_document_count: u64) -> u8 {
- if source_document_count == 0 {
- return 100;
- }
- (processed_document_count
- .min(source_document_count)
- .saturating_mul(100)
- / source_document_count) as u8
-}
-
-fn changed_during_indexing_outcome(
- writer: &mut NotesIndexWriter,
- index_was_ready: bool,
- document_id: &str,
- requested: &[String],
- processed_requested: usize,
-) -> Result<IndexSliceOutcome, ApiError> {
- writer.publish(index_was_ready).map_err(notes_error)?;
- Ok(IndexSliceOutcome {
- has_more: false,
- changed_during_indexing: Some(document_id.to_string()),
- unchecked_document_ids: requested
- .iter()
- .skip(processed_requested)
- .cloned()
- .collect(),
- indexed_document_count: writer.indexed_document_ids().count() as u64,
- })
-}
-
-fn inventory_source_root(
- root: &Path,
- mut check_for_cancellation: impl FnMut() -> Result<(), ApiError>,
-) -> Result<Inventory, ApiError> {
- let mut directories = vec![root.to_path_buf()];
- let mut documents = Vec::new();
- let mut paths = BTreeMap::new();
- while let Some(directory) = directories.pop() {
- check_for_cancellation()?;
- let entries = fs::read_dir(&directory).map_err(source_scan_error)?;
- for entry in entries {
- check_for_cancellation()?;
- let entry = entry.map_err(source_scan_error)?;
- let name = entry.file_name();
- let Some(name) = name.to_str() else { continue };
- if name.starts_with('.') {
- continue;
- }
- let path = entry.path();
- let metadata = fs::symlink_metadata(&path).map_err(source_scan_error)?;
- if metadata.file_type().is_symlink() {
- continue;
- }
- if metadata.is_dir() {
- directories.push(path);
- continue;
- }
- if !metadata.is_file() || !is_supported_file(&path) {
- continue;
- }
- if metadata.len() > NOTES_MAX_SOURCE_BYTES as u64 {
- continue;
- }
- let Some(document_id) = relative_document_id(root, &path) else {
- continue;
- };
- let modified_at_ms = metadata.modified().ok().and_then(system_time_ms);
- let source = NotesSourceDocument {
- document_id: document_id.clone(),
- size: metadata.len(),
- modified_at_ms,
- };
- paths.insert(document_id, path);
- documents.push(source);
- }
- }
- documents.sort_by(|left, right| left.document_id.cmp(&right.document_id));
- Ok(Inventory { documents, paths })
-}
-
-fn should_rebuild_derived_index(
- index_root: &Path,
- collection_id: &str,
- force: bool,
-) -> Result<bool, ApiError> {
- if !force {
- return Ok(false);
- }
- match NotesCollectionIndex::open(index_root, collection_id.to_string()) {
- Ok(_) | Err(NotesError::NotReady) => Ok(false),
- Err(NotesError::InvalidIndex(_) | NotesError::IncompatibleIndex | NotesError::Json(_)) => {
- Ok(true)
- }
- Err(NotesError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
- Err(error) => Err(notes_error(error)),
- }
-}
-
-fn relative_document_id(root: &Path, path: &Path) -> Option<String> {
- let document_id = path
- .strip_prefix(root)
- .ok()?
- .components()
- .map(|component| match component {
- Component::Normal(value) => value.to_str(),
- _ => None,
- })
- .collect::<Option<Vec<_>>>()?
- .join("/");
- validate_document_id(&document_id)
- .is_ok()
- .then_some(document_id)
-}
-
-fn resolve_document_path(root: &Path, document_id: &str) -> Result<PathBuf, ApiError> {
- validate_document_id(document_id)
- .map_err(|_| ApiError::new("invalid_document", "Invalid note document ID"))?;
- let mut path = root.to_path_buf();
- for component in document_id.split('/') {
- path.push(component);
- let metadata = fs::symlink_metadata(&path)
- .map_err(|_| ApiError::new("source_unavailable", "Source note is unavailable"))?;
- if metadata.file_type().is_symlink() {
- return Err(ApiError::new(
- "invalid_document",
- "Source note path is not allowed",
- ));
- }
- }
- let metadata = fs::symlink_metadata(&path)
- .map_err(|_| ApiError::new("source_unavailable", "Source note is unavailable"))?;
- if !metadata.is_file() || metadata.len() > NOTES_MAX_SOURCE_BYTES as u64 {
- return Err(ApiError::new(
- "invalid_document",
- "Source note is not supported",
- ));
- }
- let canonical = fs::canonicalize(&path)
- .map_err(|_| ApiError::new("source_unavailable", "Source note is unavailable"))?;
- if !canonical.starts_with(root) {
- return Err(ApiError::new(
- "invalid_document",
- "Source note escaped its collection",
- ));
- }
- Ok(canonical)
-}
-
-fn read_supported_source(path: &Path) -> Result<Vec<u8>, ApiError> {
- let metadata = fs::symlink_metadata(path).map_err(source_file_error)?;
- if !metadata.is_file() || metadata.len() > NOTES_MAX_SOURCE_BYTES as u64 {
- return Err(ApiError::new(
- "invalid_document",
- "Source note is not supported",
- ));
- }
- let bytes = fs::read(path).map_err(source_file_error)?;
- if bytes.len() > NOTES_MAX_SOURCE_BYTES {
- return Err(ApiError::new(
- "invalid_document",
- "Source note is too large",
- ));
- }
- Ok(bytes)
-}
-
-fn source_file_error(error: std::io::Error) -> ApiError {
- if error.kind() == std::io::ErrorKind::NotFound {
- ApiError::new(
- "source_changed",
- "Source note changed while it was being indexed",
- )
- } else {
- ApiError::new("source_io", "Source note could not be read")
- }
-}
-
-fn canonical_source_root(path: &Path) -> Result<PathBuf, ApiError> {
- if path.as_os_str().is_empty() {
- return Err(ApiError::new("invalid_folder", "Choose a Notes folder"));
- }
- let metadata = fs::symlink_metadata(path)
- .map_err(|_| ApiError::new("unavailable", "The selected folder is unavailable"))?;
- if !metadata.is_dir() {
- return Err(ApiError::new(
- "invalid_folder",
- "Choose a folder, not a file",
- ));
- }
- let canonical = fs::canonicalize(path)
- .map_err(|_| ApiError::new("unavailable", "The selected folder is unavailable"))?;
- if canonical.to_str().is_none() {
- return Err(ApiError::new(
- "invalid_folder",
- "The selected folder name is not supported",
- ));
- }
- Ok(canonical)
-}
-
-fn compact_source_location(root: &Path) -> String {
- root.file_name()
- .and_then(|name| name.to_str())
- .filter(|name| !name.is_empty())
- .unwrap_or("Selected folder")
- .to_string()
-}
-
-fn validate_new_source_root(
- collections: &[RegisteredCollection],
- source_root: &Path,
-) -> Result<(), ApiError> {
- for existing in collections {
- if source_root == existing.source_root {
- return Err(ApiError::new(
- "duplicate",
- "That folder is already in Your Notes",
- ));
- }
- if source_root.starts_with(&existing.source_root)
- || existing.source_root.starts_with(source_root)
- {
- return Err(ApiError::new(
- "nested",
- "Notes collection folders must not contain one another",
- ));
- }
- }
- Ok(())
-}
-
-fn is_supported_file(path: &Path) -> bool {
- path.extension()
- .and_then(|extension| extension.to_str())
- .is_some_and(|extension| {
- matches!(extension.to_ascii_lowercase().as_str(), "md" | "markdown")
- })
+ app.opener()
+ .open_path(path.to_string_lossy().into_owned(), None::<String>)
+ .map_err(|_| ApiError::new("open_failed", "Source note could not be opened"))
}
fn check_cancelled(
@@ -1765,159 +1047,15 @@ fn notes_error(error: NotesError) -> ApiError {
("incompatible_index", "The Notes index needs to be rebuilt")
}
NotesError::NotReady => ("not_ready", "The Notes collection is not ready"),
+ NotesError::CollectionTooLarge(message) => {
+ return ApiError::new("collection_too_large", message);
+ }
NotesError::Io(_) => ("io", "The Notes index could not be accessed"),
NotesError::Json(_) => ("json", "The Notes index could not be read"),
};
ApiError::new(code, message)
}
-fn validate_registry(registry: &RegistryFile) -> Result<(), ApiError> {
- if registry.schema_version != NOTES_REGISTRY_SCHEMA_VERSION {
- return Err(ApiError::new(
- "incompatible_registry",
- "This version of Ensu cannot use the existing Notes registry",
- ));
- }
- let mut ids = std::collections::BTreeSet::new();
- let mut roots = Vec::<&Path>::new();
- for collection in &registry.collections {
- Uuid::parse_str(&collection.id)
- .map_err(|_| ApiError::new("registry", "Notes registry collection ID is invalid"))?;
- if !collection.source_root.is_absolute()
- || collection.source_root.to_str().is_none()
- || !ids.insert(&collection.id)
- {
- return Err(ApiError::new(
- "invalid_registry",
- "The Notes registry is invalid",
- ));
- }
- if roots.iter().any(|root| {
- collection.source_root.starts_with(root) || root.starts_with(&collection.source_root)
- }) {
- return Err(ApiError::new(
- "invalid_registry",
- "The Notes registry is invalid",
- ));
- }
- roots.push(&collection.source_root);
- }
- Ok(())
-}
-
-fn open_registry_file(directory: &Path) -> Result<RegistryFile, ApiError> {
- recover_registry_publication(directory)?;
- let path = directory.join(NOTES_REGISTRY_FILE);
- if !path_exists(&path)? {
- return Ok(RegistryFile::default());
- }
- load_valid_registry_file(&path)
-}
-
-fn load_valid_registry_file(path: &Path) -> Result<RegistryFile, ApiError> {
- let registry = load_registry_file(path)?;
- validate_registry(&registry)?;
- Ok(registry)
-}
-
-fn is_registry_content_error(error: &ApiError) -> bool {
- matches!(error.name, Some("registry" | "invalid_registry"))
-}
-
-fn quarantine_invalid_registry_files(directory: &Path) -> Result<(), ApiError> {
- for name in [NOTES_REGISTRY_FILE, NOTES_REGISTRY_BACKUP_FILE] {
- let path = directory.join(name);
- if path_exists(&path)? {
- let quarantined =
- directory.join(format!("{name}.invalid-{}", Uuid::new_v4().hyphenated()));
- fs::rename(path, quarantined).map_err(io_error)?;
- }
- }
- Ok(())
-}
-
-fn load_registry_file(path: &Path) -> Result<RegistryFile, ApiError> {
- let metadata = fs::symlink_metadata(path).map_err(io_error)?;
- if !metadata.is_file() || metadata.len() == 0 || metadata.len() > MAX_REGISTRY_BYTES {
- return Err(ApiError::new(
- "invalid_registry",
- "The Notes registry is invalid",
- ));
- }
- let bytes = fs::read(path).map_err(io_error)?;
- let header = serde_json::from_slice::<RegistryHeader>(&bytes)
- .map_err(|_| ApiError::new("invalid_registry", "The Notes registry is invalid"))?;
- if header.schema_version != NOTES_REGISTRY_SCHEMA_VERSION {
- return Err(ApiError::new(
- "incompatible_registry",
- "This version of Ensu cannot use the existing Notes registry",
- ));
- }
- serde_json::from_slice(&bytes)
- .map_err(|_| ApiError::new("invalid_registry", "The Notes registry is invalid"))
-}
-
-fn publish_registry(directory: &Path, registry: &RegistryFile) -> Result<(), ApiError> {
- let active = directory.join(NOTES_REGISTRY_FILE);
- let backup = directory.join(NOTES_REGISTRY_BACKUP_FILE);
- if path_exists(&backup)? {
- remove_owned_entry(&backup)?;
- }
- let temporary = directory.join(format!(".collections.tmp-{}", Uuid::new_v4().hyphenated()));
- let mut bytes = serde_json::to_vec_pretty(registry)
- .map_err(|_| ApiError::new("json", "The Notes registry could not be written"))?;
- bytes.push(b'\n');
- write_new_file(&temporary, &bytes)?;
- load_registry_file(&temporary)?;
- let had_active = path_exists(&active)?;
- if had_active {
- fs::rename(&active, &backup).map_err(io_error)?;
- }
- if let Err(error) = fs::rename(&temporary, &active) {
- if had_active && path_exists(&backup).unwrap_or(false) {
- let _ = fs::rename(&backup, &active);
- }
- let _ = fs::remove_file(&temporary);
- return Err(io_error(error));
- }
- if path_exists(&backup)? {
- remove_owned_entry(&backup)?;
- }
- Ok(())
-}
-
-fn recover_registry_publication(directory: &Path) -> Result<(), ApiError> {
- let active = directory.join(NOTES_REGISTRY_FILE);
- let backup = directory.join(NOTES_REGISTRY_BACKUP_FILE);
- match (path_exists(&active)?, path_exists(&backup)?) {
- (false, true) => {
- load_valid_registry_file(&backup)?;
- fs::rename(&backup, &active).map_err(io_error)?;
- }
- (true, true) => match load_valid_registry_file(&active) {
- Ok(_) => remove_owned_entry(&backup)?,
- Err(error) if error.name == Some("incompatible_registry") => return Err(error),
- Err(_) => {
- load_valid_registry_file(&backup)?;
- remove_owned_entry(&active)?;
- fs::rename(&backup, &active).map_err(io_error)?;
- }
- },
- _ => {}
- }
- for entry in fs::read_dir(directory).map_err(io_error)? {
- let entry = entry.map_err(io_error)?;
- if entry
- .file_name()
- .to_string_lossy()
- .starts_with(".collections.tmp-")
- {
- remove_owned_entry(&entry.path())?;
- }
- }
- Ok(())
-}
-
fn ensure_directory(path: &Path) -> Result<(), ApiError> {
if !path_exists(path)? {
fs::create_dir_all(path).map_err(io_error)?;
@@ -1933,16 +1071,6 @@ fn ensure_directory(path: &Path) -> Result<(), ApiError> {
Ok(())
}
-fn write_new_file(path: &Path, bytes: &[u8]) -> Result<(), ApiError> {
- let mut options = OpenOptions::new();
- options.write(true).create_new(true);
- #[cfg(unix)]
- options.mode(0o600);
- let mut file = options.open(path).map_err(io_error)?;
- file.write_all(bytes).map_err(io_error)?;
- file.sync_all().map_err(io_error)
-}
-
fn path_exists(path: &Path) -> Result<bool, ApiError> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(true),
@@ -1989,14 +1117,90 @@ pub(crate) fn clear_for_exit(app: &AppHandle) {
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
+ state
+ .watch_work
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clear();
state
.updates
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
state
- .indexes
+ .cached_indexes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ente_ensu::notes::{NotesIndexWriter, NotesSourceDocument, prepare_notes_document};
+
+ const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
+ const SECOND_COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174001";
+
+ fn publish_test_index(index_root: &Path, collection_id: &str, document_id: &str) {
+ let prepared = prepare_notes_document(document_id, b"test note").unwrap();
+ let mut embedding = vec![0.0; 512];
+ embedding[0] = 1.0;
+ let metadata = NotesSourceDocument {
+ document_id: document_id.to_string(),
+ size: 9,
+ modified_at_ms: Some(1),
+ };
+ let mut writer = NotesIndexWriter::open(index_root, collection_id.to_string()).unwrap();
+ writer
+ .commit_document(&prepared, &[embedding], &metadata)
+ .unwrap();
+ writer.publish(true).unwrap();
+ }
+
+ #[test]
+ fn retrieval_cache_retains_multiple_collection_indexes_within_budget() {
+ let temp = TestDirectory::new();
+ let index_root = temp.path().join("indexes");
+ publish_test_index(&index_root, COLLECTION_ID, "first.md");
+ publish_test_index(&index_root, SECOND_COLLECTION_ID, "other.md");
+ let cached_indexes = Arc::new(Mutex::new(IndexCache::new(NOTES_INDEX_CACHE_MAX_BYTES)));
+ let handle = RetrievalHandle {
+ registry: Arc::new(Mutex::new(
+ RegistryStore::open(temp.path().join("registry")).unwrap(),
+ )),
+ cached_indexes: Arc::clone(&cached_indexes),
+ index_root,
+ };
+ let mut query = vec![0.0; 512];
+ query[0] = 1.0;
+
+ handle.search_collection(COLLECTION_ID, &query).unwrap();
+ handle
+ .search_collection(SECOND_COLLECTION_ID, &query)
+ .unwrap();
+ let cached_indexes = cached_indexes
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ assert!(cached_indexes.entries.contains_key(COLLECTION_ID));
+ assert!(cached_indexes.entries.contains_key(SECOND_COLLECTION_ID));
+ }
+
+ #[test]
+ fn retrieval_cache_evicts_the_least_recently_used_index_at_its_budget() {
+ let temp = TestDirectory::new();
+ let index_root = temp.path().join("indexes");
+ publish_test_index(&index_root, COLLECTION_ID, "first.md");
+ publish_test_index(&index_root, SECOND_COLLECTION_ID, "other.md");
+ let first = NotesCollectionIndex::open(&index_root, COLLECTION_ID.to_string()).unwrap();
+ let second =
+ NotesCollectionIndex::open(&index_root, SECOND_COLLECTION_ID.to_string()).unwrap();
+ let mut cache = IndexCache::new(first.estimated_heap_bytes());
+
+ cache.insert(COLLECTION_ID.to_string(), first);
+ cache.insert(SECOND_COLLECTION_ID.to_string(), second);
+
+ assert!(!cache.entries.contains_key(COLLECTION_ID));
+ assert!(cache.entries.contains_key(SECOND_COLLECTION_ID));
+ }
+}
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes/indexing.rs b/rust/apps/ensu/src-tauri/src/commands/notes/indexing.rs
new file mode 100644
index 0000000000..6aaf6a03db
--- /dev/null
+++ b/rust/apps/ensu/src-tauri/src/commands/notes/indexing.rs
@@ -0,0 +1,188 @@
+use std::path::Path;
+
+use ente_ensu::llm;
+use ente_ensu::notes::{
+ NotesCollectionIndex, NotesDocumentLoad, NotesError, NotesIndexInput, NotesIndexOutcome,
+ NotesIndexingError, NotesRevisionStatus, index_notes_collection, notes_content_revision,
+ prepare_notes_document,
+};
+
+use crate::commands::common::ApiError;
+
+use super::registry::RegisteredCollection;
+use super::source::{
+ canonical_source_root, inventory_source_root, read_collection_source, source_root_is_available,
+};
+use super::{
+ NOTES_EMBEDDING_TITLE_MAX_UTF8_BYTES, UpdateSnapshot, check_cancelled, notes_error,
+ path_exists, remove_owned_entry,
+};
+
+pub(super) fn index_collection(
+ index_root: &Path,
+ collection: &RegisteredCollection,
+ embedding_path: Option<&Path>,
+ cancellation_epoch: &std::sync::atomic::AtomicU64,
+ retrieval_epoch: u64,
+ update: &UpdateSnapshot,
+ on_progress: impl FnMut(u8),
+) -> Result<NotesIndexOutcome, ApiError> {
+ check_cancelled(cancellation_epoch, retrieval_epoch)?;
+ let canonical_root = canonical_source_root(&collection.source_root)?;
+ if canonical_root != collection.source_root {
+ return Err(ApiError::new(
+ "source_changed",
+ "Notes source folder identity changed",
+ ));
+ }
+ let inventory = inventory_source_root(&canonical_root, || {
+ check_cancelled(cancellation_epoch, retrieval_epoch)
+ })?;
+ if update.rebuild_derived_index {
+ let derived_directory = index_root.join(&collection.id);
+ if path_exists(&derived_directory)? {
+ remove_owned_entry(&derived_directory)?;
+ }
+ }
+ let mut embedding_context = None;
+ index_notes_collection(
+ NotesIndexInput {
+ index_root,
+ collection_id: collection.id.clone(),
+ inventory,
+ forced_document_ids: &update.forced_document_ids,
+ force_full_hash: update.force_full_hash,
+ },
+ || check_cancelled(cancellation_epoch, retrieval_epoch),
+ |document_id| load_notes_document(&canonical_root, document_id),
+ |prepared| {
+ let embedding_path = embedding_path.ok_or_else(|| {
+ ApiError::new(
+ "embedding_missing",
+ "The knowledge embedding model is not downloaded",
+ )
+ })?;
+ if embedding_context.is_none() {
+ let model = llm::Model::load(llm::ModelLoadParams {
+ model_path: embedding_path.display().to_string(),
+ n_gpu_layers: Some(0),
+ use_mmap: Some(true),
+ use_mlock: Some(false),
+ })
+ .map_err(crate::commands::llm::llm_api_error)?;
+ let threads = std::thread::available_parallelism()
+ .map(|count| count.get().saturating_sub(1).max(1))
+ .unwrap_or(1);
+ embedding_context = Some(
+ llm::Context::new_knowledge_embedding(
+ &model,
+ Some(i32::try_from(threads).unwrap_or(1)),
+ )
+ .map_err(crate::commands::llm::llm_api_error)?,
+ );
+ }
+ let context = embedding_context
+ .as_ref()
+ .expect("embedding context was initialized");
+ let mut embeddings = Vec::with_capacity(prepared.chunks.len());
+ for chunk in &prepared.chunks {
+ check_cancelled(cancellation_epoch, retrieval_epoch)?;
+ let full_embedding_title = match chunk.section.as_deref() {
+ Some(section) if section != prepared.title => {
+ format!("{} β€” {section}", prepared.title)
+ }
+ _ => prepared.title.clone(),
+ };
+ let embedding_title = truncate_utf8_bytes(
+ &full_embedding_title,
+ NOTES_EMBEDDING_TITLE_MAX_UTF8_BYTES,
+ );
+ match context.embed_document(embedding_title, &chunk.text) {
+ Ok(embedding) => embeddings.push(embedding),
+ Err(llm::Error::PromptTooLong { .. }) => return Ok(None),
+ Err(error) => return Err(crate::commands::llm::llm_api_error(error)),
+ }
+ }
+ Ok(Some(embeddings))
+ },
+ |document_id, revision| {
+ verify_notes_document_revision(&canonical_root, document_id, revision)
+ },
+ on_progress,
+ )
+ .map_err(notes_indexing_error)
+}
+
+pub(super) fn should_rebuild_derived_index(
+ index_root: &Path,
+ collection_id: &str,
+ force: bool,
+ has_available_index: bool,
+) -> Result<bool, ApiError> {
+ if !force {
+ if has_available_index {
+ return Ok(false);
+ }
+ return match NotesCollectionIndex::open(index_root, collection_id.to_string()) {
+ Err(NotesError::IncompatibleIndex) => Ok(true),
+ _ => Ok(false),
+ };
+ }
+ match NotesCollectionIndex::open(index_root, collection_id.to_string()) {
+ Ok(_) | Err(NotesError::NotReady) => Ok(false),
+ Err(NotesError::InvalidIndex(_) | NotesError::IncompatibleIndex | NotesError::Json(_)) => {
+ Ok(true)
+ }
+ Err(NotesError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
+ Err(error) => Err(notes_error(error)),
+ }
+}
+
+fn load_notes_document(root: &Path, document_id: &str) -> Result<NotesDocumentLoad, ApiError> {
+ match read_collection_source(root, document_id) {
+ Ok((_, bytes, source)) => Ok(match prepare_notes_document(document_id, &bytes) {
+ Ok(document) => NotesDocumentLoad::Prepared { document, source },
+ Err(_) => NotesDocumentLoad::Unindexable { source },
+ }),
+ Err(error) if error.name == Some("invalid_document") => Ok(NotesDocumentLoad::Changed),
+ Err(error) if error.name == Some("source_changed") && source_root_is_available(root) => {
+ Ok(NotesDocumentLoad::Changed)
+ }
+ Err(error) => Err(error),
+ }
+}
+
+fn verify_notes_document_revision(
+ root: &Path,
+ document_id: &str,
+ expected_revision: &str,
+) -> Result<NotesRevisionStatus, ApiError> {
+ match read_collection_source(root, document_id) {
+ Ok((_, bytes, source)) if notes_content_revision(&bytes) == expected_revision => {
+ Ok(NotesRevisionStatus::Matches { source })
+ }
+ Ok(_) => Ok(NotesRevisionStatus::Changed),
+ Err(error) if error.name == Some("source_changed") && source_root_is_available(root) => {
+ Ok(NotesRevisionStatus::Changed)
+ }
+ Err(error) => Err(error),
+ }
+}
+
+fn notes_indexing_error(error: NotesIndexingError<ApiError>) -> ApiError {
+ match error {
+ NotesIndexingError::Notes(error) => notes_error(error),
+ NotesIndexingError::Adapter(error) => error,
+ }
+}
+
+fn truncate_utf8_bytes(value: &str, max_bytes: usize) -> &str {
+ if value.len() <= max_bytes {
+ return value;
+ }
+ let mut end = max_bytes;
+ while !value.is_char_boundary(end) {
+ end -= 1;
+ }
+ &value[..end]
+}
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes/registry.rs b/rust/apps/ensu/src-tauri/src/commands/notes/registry.rs
new file mode 100644
index 0000000000..574a5b0b3c
--- /dev/null
+++ b/rust/apps/ensu/src-tauri/src/commands/notes/registry.rs
@@ -0,0 +1,332 @@
+use std::collections::BTreeSet;
+use std::fs::{self, OpenOptions};
+use std::io::Write;
+#[cfg(unix)]
+use std::os::unix::fs::OpenOptionsExt;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::commands::common::ApiError;
+
+#[cfg(test)]
+use super::TestDirectory;
+use super::{ensure_directory, io_error, path_exists, remove_owned_entry};
+
+const NOTES_REGISTRY_FILE: &str = "collections.json";
+const NOTES_REGISTRY_BACKUP_FILE: &str = "collections.json.backup";
+const NOTES_REGISTRY_SCHEMA_VERSION: u32 = 1;
+const MAX_REGISTRY_BYTES: u64 = 1024 * 1024;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(super) struct RegisteredCollection {
+ pub(super) id: String,
+ pub(super) source_root: PathBuf,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub(super) struct RegistryFile {
+ pub(super) schema_version: u32,
+ pub(super) collections: Vec<RegisteredCollection>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RegistryHeader {
+ schema_version: u32,
+}
+
+impl Default for RegistryFile {
+ fn default() -> Self {
+ Self {
+ schema_version: NOTES_REGISTRY_SCHEMA_VERSION,
+ collections: Vec::new(),
+ }
+ }
+}
+
+pub(super) struct RegistryStore {
+ directory: PathBuf,
+ pub(super) registry: RegistryFile,
+ pub(super) incompatible_error: Option<String>,
+}
+
+impl RegistryStore {
+ pub(super) fn open(directory: PathBuf) -> Result<Self, ApiError> {
+ ensure_directory(&directory)?;
+ let (registry, incompatible_error) = match open_registry_file(&directory) {
+ Ok(registry) => (registry, None),
+ Err(error) if error.name == Some("incompatible_registry") => {
+ crate::logging::log(
+ "Notes",
+ "incompatible registry preserved; Notes are disabled for this version",
+ );
+ (RegistryFile::default(), Some(error.message))
+ }
+ Err(error) if is_registry_content_error(&error) => {
+ quarantine_invalid_registry_files(&directory)?;
+ recover_registry_publication(&directory)?;
+ crate::logging::log(
+ "Notes",
+ "invalid registry quarantined; starting with no registered folders",
+ );
+ (RegistryFile::default(), None)
+ }
+ Err(error) => return Err(error),
+ };
+ Ok(Self {
+ directory,
+ registry,
+ incompatible_error,
+ })
+ }
+
+ pub(super) fn ensure_compatible(&self) -> Result<(), ApiError> {
+ match &self.incompatible_error {
+ Some(message) => Err(ApiError::new("incompatible_registry", message.clone())),
+ None => Ok(()),
+ }
+ }
+
+ pub(super) fn replace(&mut self, registry: RegistryFile) -> Result<(), ApiError> {
+ self.ensure_compatible()?;
+ validate_registry(&registry)?;
+ publish_registry(&self.directory, &registry)?;
+ self.registry = registry;
+ Ok(())
+ }
+}
+
+fn validate_registry(registry: &RegistryFile) -> Result<(), ApiError> {
+ if registry.schema_version != NOTES_REGISTRY_SCHEMA_VERSION {
+ return Err(ApiError::new(
+ "incompatible_registry",
+ "This version of Ensu cannot use the existing Notes registry",
+ ));
+ }
+ let mut ids = BTreeSet::new();
+ let mut roots = Vec::<&Path>::new();
+ for collection in &registry.collections {
+ Uuid::parse_str(&collection.id)
+ .map_err(|_| ApiError::new("registry", "Notes registry collection ID is invalid"))?;
+ if !collection.source_root.is_absolute()
+ || collection.source_root.to_str().is_none()
+ || !ids.insert(&collection.id)
+ {
+ return Err(ApiError::new(
+ "invalid_registry",
+ "The Notes registry is invalid",
+ ));
+ }
+ if roots.iter().any(|root| {
+ collection.source_root.starts_with(root) || root.starts_with(&collection.source_root)
+ }) {
+ return Err(ApiError::new(
+ "invalid_registry",
+ "The Notes registry is invalid",
+ ));
+ }
+ roots.push(&collection.source_root);
+ }
+ Ok(())
+}
+
+fn open_registry_file(directory: &Path) -> Result<RegistryFile, ApiError> {
+ recover_registry_publication(directory)?;
+ let path = directory.join(NOTES_REGISTRY_FILE);
+ if !path_exists(&path)? {
+ return Ok(RegistryFile::default());
+ }
+ load_valid_registry_file(&path)
+}
+
+fn load_valid_registry_file(path: &Path) -> Result<RegistryFile, ApiError> {
+ let registry = load_registry_file(path)?;
+ validate_registry(&registry)?;
+ Ok(registry)
+}
+
+fn is_registry_content_error(error: &ApiError) -> bool {
+ matches!(error.name, Some("registry" | "invalid_registry"))
+}
+
+fn quarantine_invalid_registry_files(directory: &Path) -> Result<(), ApiError> {
+ for name in [NOTES_REGISTRY_FILE, NOTES_REGISTRY_BACKUP_FILE] {
+ let path = directory.join(name);
+ if path_exists(&path)? {
+ let quarantined =
+ directory.join(format!("{name}.invalid-{}", Uuid::new_v4().hyphenated()));
+ fs::rename(path, quarantined).map_err(io_error)?;
+ }
+ }
+ Ok(())
+}
+
+fn load_registry_file(path: &Path) -> Result<RegistryFile, ApiError> {
+ let metadata = fs::symlink_metadata(path).map_err(io_error)?;
+ if !metadata.is_file() || metadata.len() == 0 || metadata.len() > MAX_REGISTRY_BYTES {
+ return Err(ApiError::new(
+ "invalid_registry",
+ "The Notes registry is invalid",
+ ));
+ }
+ let bytes = fs::read(path).map_err(io_error)?;
+ let header = serde_json::from_slice::<RegistryHeader>(&bytes)
+ .map_err(|_| ApiError::new("invalid_registry", "The Notes registry is invalid"))?;
+ if header.schema_version != NOTES_REGISTRY_SCHEMA_VERSION {
+ return Err(ApiError::new(
+ "incompatible_registry",
+ "This version of Ensu cannot use the existing Notes registry",
+ ));
+ }
+ serde_json::from_slice(&bytes)
+ .map_err(|_| ApiError::new("invalid_registry", "The Notes registry is invalid"))
+}
+
+fn publish_registry(directory: &Path, registry: &RegistryFile) -> Result<(), ApiError> {
+ let active = directory.join(NOTES_REGISTRY_FILE);
+ let backup = directory.join(NOTES_REGISTRY_BACKUP_FILE);
+ if path_exists(&backup)? {
+ remove_owned_entry(&backup)?;
+ }
+ let temporary = directory.join(format!(".collections.tmp-{}", Uuid::new_v4().hyphenated()));
+ let mut bytes = serde_json::to_vec_pretty(registry)
+ .map_err(|_| ApiError::new("json", "The Notes registry could not be written"))?;
+ bytes.push(b'\n');
+ write_new_file(&temporary, &bytes)?;
+ load_registry_file(&temporary)?;
+ let had_active = path_exists(&active)?;
+ if had_active {
+ fs::rename(&active, &backup).map_err(io_error)?;
+ }
+ if let Err(error) = fs::rename(&temporary, &active) {
+ if had_active && path_exists(&backup).unwrap_or(false) {
+ let _ = fs::rename(&backup, &active);
+ }
+ let _ = fs::remove_file(&temporary);
+ return Err(io_error(error));
+ }
+ if path_exists(&backup)? {
+ remove_owned_entry(&backup)?;
+ }
+ Ok(())
+}
+
+fn recover_registry_publication(directory: &Path) -> Result<(), ApiError> {
+ let active = directory.join(NOTES_REGISTRY_FILE);
+ let backup = directory.join(NOTES_REGISTRY_BACKUP_FILE);
+ match (path_exists(&active)?, path_exists(&backup)?) {
+ (false, true) => {
+ load_valid_registry_file(&backup)?;
+ fs::rename(&backup, &active).map_err(io_error)?;
+ }
+ (true, true) => match load_valid_registry_file(&active) {
+ Ok(_) => remove_owned_entry(&backup)?,
+ Err(error) if error.name == Some("incompatible_registry") => return Err(error),
+ Err(_) => {
+ load_valid_registry_file(&backup)?;
+ remove_owned_entry(&active)?;
+ fs::rename(&backup, &active).map_err(io_error)?;
+ }
+ },
+ _ => {}
+ }
+ for entry in fs::read_dir(directory).map_err(io_error)? {
+ let entry = entry.map_err(io_error)?;
+ if entry
+ .file_name()
+ .to_string_lossy()
+ .starts_with(".collections.tmp-")
+ {
+ remove_owned_entry(&entry.path())?;
+ }
+ }
+ Ok(())
+}
+
+fn write_new_file(path: &Path, bytes: &[u8]) -> Result<(), ApiError> {
+ let mut options = OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ options.mode(0o600);
+ let mut file = options.open(path).map_err(io_error)?;
+ file.write_all(bytes).map_err(io_error)?;
+ file.sync_all().map_err(io_error)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
+
+ fn registry_with_source(source_root: PathBuf) -> RegistryFile {
+ RegistryFile {
+ schema_version: NOTES_REGISTRY_SCHEMA_VERSION,
+ collections: vec![RegisteredCollection {
+ id: COLLECTION_ID.to_string(),
+ source_root,
+ }],
+ }
+ }
+
+ #[test]
+ fn recovers_interrupted_registry_publications() {
+ let backup_only = TestDirectory::new();
+ let source_root = backup_only.path().join("source");
+ fs::create_dir(&source_root).unwrap();
+ let registry = registry_with_source(fs::canonicalize(source_root).unwrap());
+ publish_registry(backup_only.path(), &registry).unwrap();
+ let active = backup_only.path().join(NOTES_REGISTRY_FILE);
+ let backup = backup_only.path().join(NOTES_REGISTRY_BACKUP_FILE);
+ fs::rename(&active, &backup).unwrap();
+ recover_registry_publication(backup_only.path()).unwrap();
+ assert_eq!(
+ load_valid_registry_file(&active).unwrap().collections[0].id,
+ COLLECTION_ID
+ );
+ assert!(!backup.exists());
+
+ let valid_active = TestDirectory::new();
+ let source_root = valid_active.path().join("source");
+ fs::create_dir(&source_root).unwrap();
+ let registry = registry_with_source(fs::canonicalize(source_root).unwrap());
+ publish_registry(valid_active.path(), &registry).unwrap();
+ let active = valid_active.path().join(NOTES_REGISTRY_FILE);
+ let backup = valid_active.path().join(NOTES_REGISTRY_BACKUP_FILE);
+ let temporary = valid_active.path().join(".collections.tmp-abandoned");
+ fs::copy(&active, &backup).unwrap();
+ fs::write(&temporary, b"incomplete").unwrap();
+ let expected = fs::read(&active).unwrap();
+ recover_registry_publication(valid_active.path()).unwrap();
+ assert_eq!(fs::read(&active).unwrap(), expected);
+ assert!(!backup.exists());
+ assert!(!temporary.exists());
+
+ let corrupt_active = TestDirectory::new();
+ let source_root = corrupt_active.path().join("source");
+ fs::create_dir(&source_root).unwrap();
+ let registry = registry_with_source(fs::canonicalize(source_root).unwrap());
+ publish_registry(corrupt_active.path(), &registry).unwrap();
+ let active = corrupt_active.path().join(NOTES_REGISTRY_FILE);
+ let backup = corrupt_active.path().join(NOTES_REGISTRY_BACKUP_FILE);
+ let expected = fs::read(&active).unwrap();
+ fs::copy(&active, &backup).unwrap();
+ fs::write(&active, b"not a registry").unwrap();
+ recover_registry_publication(corrupt_active.path()).unwrap();
+ assert_eq!(fs::read(&active).unwrap(), expected);
+ assert!(!backup.exists());
+
+ let invalid_backup = TestDirectory::new();
+ fs::write(
+ invalid_backup.path().join(NOTES_REGISTRY_BACKUP_FILE),
+ b"invalid",
+ )
+ .unwrap();
+ assert!(recover_registry_publication(invalid_backup.path()).is_err());
+ assert!(!invalid_backup.path().join(NOTES_REGISTRY_FILE).exists());
+ }
+}
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes/source.rs b/rust/apps/ensu/src-tauri/src/commands/notes/source.rs
new file mode 100644
index 0000000000..db7c0961a0
--- /dev/null
+++ b/rust/apps/ensu/src-tauri/src/commands/notes/source.rs
@@ -0,0 +1,438 @@
+use std::collections::BTreeSet;
+use std::fs::{self, File, Metadata};
+use std::io::Read;
+#[cfg(unix)]
+use std::os::fd::{AsRawFd, FromRawFd};
+#[cfg(unix)]
+use std::os::unix::ffi::OsStrExt;
+#[cfg(windows)]
+use std::os::windows::ffi::OsStringExt;
+#[cfg(windows)]
+use std::os::windows::io::AsRawHandle;
+use std::path::{Component, Path, PathBuf};
+
+use ente_ensu::notes::{
+ NOTES_MAX_COLLECTION_DOCUMENTS, NOTES_MAX_COLLECTION_SOURCE_BYTES, NOTES_MAX_SOURCE_BYTES,
+ NotesSourceDocument, validate_document_id,
+};
+
+use crate::commands::common::ApiError;
+
+use super::registry::RegisteredCollection;
+use super::{NOTES_MAX_SCAN_ENTRIES, remove_owned_entry, source_scan_error, system_time_ms};
+
+pub(super) fn inventory_source_root(
+ root: &Path,
+ check_for_cancellation: impl FnMut() -> Result<(), ApiError>,
+) -> Result<Vec<NotesSourceDocument>, ApiError> {
+ let mut documents = Vec::new();
+ let mut source_bytes = 0_u64;
+ walk_source_tree(
+ root,
+ check_for_cancellation,
+ || {
+ ApiError::new(
+ "collection_too_large",
+ "The folder contains too many filesystem entries to scan",
+ )
+ },
+ |_| Ok(()),
+ |path, metadata| {
+ if !metadata.is_file() || !is_supported_file(path) {
+ return Ok(());
+ }
+ if metadata.len() > NOTES_MAX_SOURCE_BYTES as u64 {
+ return Ok(());
+ }
+ let Some(document_id) = relative_document_id(root, path) else {
+ return Ok(());
+ };
+ let modified_at_ms = metadata.modified().ok().and_then(system_time_ms);
+ if documents.len() >= NOTES_MAX_COLLECTION_DOCUMENTS {
+ return Err(ApiError::new(
+ "collection_too_large",
+ "The folder contains too many notes to index",
+ ));
+ }
+ source_bytes = source_bytes.checked_add(metadata.len()).ok_or_else(|| {
+ ApiError::new(
+ "collection_too_large",
+ "The folder contains too much note content to index",
+ )
+ })?;
+ if source_bytes > NOTES_MAX_COLLECTION_SOURCE_BYTES {
+ return Err(ApiError::new(
+ "collection_too_large",
+ "The folder contains too much note content to index",
+ ));
+ }
+ documents.push(NotesSourceDocument {
+ document_id,
+ size: metadata.len(),
+ modified_at_ms,
+ });
+ Ok(())
+ },
+ )?;
+ documents.sort_by(|left, right| left.document_id.cmp(&right.document_id));
+ Ok(documents)
+}
+
+pub(super) fn walk_source_tree(
+ root: &Path,
+ mut check_for_cancellation: impl FnMut() -> Result<(), ApiError>,
+ entry_limit_error: impl Fn() -> ApiError,
+ mut visit_directory: impl FnMut(&Path) -> Result<(), ApiError>,
+ mut visit_file: impl FnMut(&Path, &Metadata) -> Result<(), ApiError>,
+) -> Result<(), ApiError> {
+ let mut pending = vec![root.to_path_buf()];
+ let mut visited_entries = 0_usize;
+ while let Some(directory) = pending.pop() {
+ check_for_cancellation()?;
+ let metadata = fs::symlink_metadata(&directory).map_err(source_scan_error)?;
+ if metadata.file_type().is_symlink() || !metadata.is_dir() {
+ continue;
+ }
+ visit_directory(&directory)?;
+ for entry in fs::read_dir(&directory).map_err(source_scan_error)? {
+ check_for_cancellation()?;
+ visited_entries = visited_entries.saturating_add(1);
+ if visited_entries > NOTES_MAX_SCAN_ENTRIES {
+ return Err(entry_limit_error());
+ }
+ let entry = entry.map_err(source_scan_error)?;
+ let name = entry.file_name();
+ if name.to_str().is_none_or(|name| name.starts_with('.')) {
+ continue;
+ }
+ let path = entry.path();
+ let metadata = fs::symlink_metadata(&path).map_err(source_scan_error)?;
+ if metadata.file_type().is_symlink() {
+ continue;
+ }
+ if metadata.is_dir() {
+ pending.push(path);
+ } else if metadata.is_file() {
+ visit_file(&path, &metadata)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+pub(super) fn relative_document_id(root: &Path, path: &Path) -> Option<String> {
+ let document_id = path
+ .strip_prefix(root)
+ .ok()?
+ .components()
+ .map(|component| match component {
+ Component::Normal(value) => value.to_str(),
+ _ => None,
+ })
+ .collect::<Option<Vec<_>>>()?
+ .join("/");
+ validate_document_id(&document_id)
+ .is_ok()
+ .then_some(document_id)
+}
+
+fn read_supported_source_file(mut file: File) -> Result<(Vec<u8>, Metadata), ApiError> {
+ let initial_metadata = file.metadata().map_err(source_file_error)?;
+ if !initial_metadata.is_file() || initial_metadata.len() > NOTES_MAX_SOURCE_BYTES as u64 {
+ return Err(ApiError::new(
+ "invalid_document",
+ "Source note is not supported",
+ ));
+ }
+ let mut bytes = Vec::with_capacity(initial_metadata.len() as usize);
+ (&mut file)
+ .take(NOTES_MAX_SOURCE_BYTES as u64 + 1)
+ .read_to_end(&mut bytes)
+ .map_err(source_file_error)?;
+ if bytes.len() > NOTES_MAX_SOURCE_BYTES {
+ return Err(ApiError::new(
+ "invalid_document",
+ "Source note is too large",
+ ));
+ }
+ let metadata = file.metadata().map_err(source_file_error)?;
+ if metadata.len() != bytes.len() as u64
+ || metadata.len() != initial_metadata.len()
+ || metadata.modified().ok() != initial_metadata.modified().ok()
+ {
+ return Err(ApiError::new(
+ "source_changed",
+ "Source note changed while it was being indexed",
+ ));
+ }
+ Ok((bytes, metadata))
+}
+
+pub(super) fn read_collection_source(
+ root: &Path,
+ document_id: &str,
+) -> Result<(PathBuf, Vec<u8>, NotesSourceDocument), ApiError> {
+ validate_document_id(document_id)
+ .map_err(|_| ApiError::new("invalid_document", "Invalid note document ID"))?;
+ let mut path = root.to_path_buf();
+ for component in document_id.split('/') {
+ path.push(component);
+ }
+ let file = open_collection_source(root, document_id, &path)?;
+ let (bytes, metadata) = read_supported_source_file(file)?;
+ let source = NotesSourceDocument {
+ document_id: document_id.to_string(),
+ size: metadata.len(),
+ modified_at_ms: metadata.modified().ok().and_then(system_time_ms),
+ };
+ Ok((path, bytes, source))
+}
+
+#[cfg(unix)]
+fn open_collection_source(root: &Path, document_id: &str, _path: &Path) -> Result<File, ApiError> {
+ use std::ffi::CString;
+
+ let root = CString::new(root.as_os_str().as_bytes())
+ .map_err(|_| ApiError::new("invalid_document", "Source note path is not allowed"))?;
+ let root_fd = unsafe {
+ libc::open(
+ root.as_ptr(),
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
+ )
+ };
+ if root_fd < 0 {
+ return Err(scoped_open_error(std::io::Error::last_os_error()));
+ }
+ let mut directory = unsafe { File::from_raw_fd(root_fd) };
+ let components = document_id.split('/').collect::<Vec<_>>();
+ for component in &components[..components.len().saturating_sub(1)] {
+ let component = CString::new(component.as_bytes())
+ .map_err(|_| ApiError::new("invalid_document", "Source note path is not allowed"))?;
+ let fd = unsafe {
+ libc::openat(
+ directory.as_raw_fd(),
+ component.as_ptr(),
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
+ )
+ };
+ if fd < 0 {
+ return Err(scoped_open_error(std::io::Error::last_os_error()));
+ }
+ directory = unsafe { File::from_raw_fd(fd) };
+ }
+ let file_name = CString::new(components.last().copied().unwrap_or_default().as_bytes())
+ .map_err(|_| ApiError::new("invalid_document", "Source note path is not allowed"))?;
+ let fd = unsafe {
+ libc::openat(
+ directory.as_raw_fd(),
+ file_name.as_ptr(),
+ libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
+ )
+ };
+ if fd < 0 {
+ return Err(scoped_open_error(std::io::Error::last_os_error()));
+ }
+ Ok(unsafe { File::from_raw_fd(fd) })
+}
+
+#[cfg(unix)]
+fn scoped_open_error(error: std::io::Error) -> ApiError {
+ if matches!(
+ error.raw_os_error(),
+ Some(code) if code == libc::ELOOP || code == libc::ENOTDIR
+ ) {
+ ApiError::new("invalid_document", "Source note path is not allowed")
+ } else {
+ source_file_error(error)
+ }
+}
+
+#[cfg(windows)]
+fn open_collection_source(root: &Path, _document_id: &str, path: &Path) -> Result<File, ApiError> {
+ let file = File::open(path).map_err(source_file_error)?;
+ let final_path = final_windows_handle_path(&file)?;
+ if !windows_path_is_beneath(&final_path, root) {
+ return Err(ApiError::new(
+ "invalid_document",
+ "Source note escaped its collection",
+ ));
+ }
+ Ok(file)
+}
+
+#[cfg(windows)]
+fn final_windows_handle_path(file: &File) -> Result<PathBuf, ApiError> {
+ use std::ffi::OsString;
+ use windows_sys::Win32::Foundation::HANDLE;
+ use windows_sys::Win32::Storage::FileSystem::{
+ FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW, VOLUME_NAME_DOS,
+ };
+
+ let handle = file.as_raw_handle() as HANDLE;
+ let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS;
+ let length = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) };
+ if length == 0 {
+ return Err(source_file_error(std::io::Error::last_os_error()));
+ }
+ let mut buffer = vec![0_u16; length as usize + 1];
+ let written = unsafe {
+ GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags)
+ };
+ if written == 0 || written as usize >= buffer.len() {
+ return Err(source_file_error(std::io::Error::last_os_error()));
+ }
+ Ok(PathBuf::from(OsString::from_wide(
+ &buffer[..written as usize],
+ )))
+}
+
+#[cfg(windows)]
+fn windows_path_is_beneath(path: &Path, root: &Path) -> bool {
+ let path = path.to_string_lossy().to_ascii_lowercase();
+ let root = root
+ .to_string_lossy()
+ .trim_end_matches(['\\', '/'])
+ .to_ascii_lowercase();
+ path == root
+ || path
+ .strip_prefix(&root)
+ .is_some_and(|suffix| suffix.starts_with('\\') || suffix.starts_with('/'))
+}
+
+fn source_file_error(error: std::io::Error) -> ApiError {
+ if error.kind() == std::io::ErrorKind::NotFound {
+ ApiError::new(
+ "source_changed",
+ "Source note changed while it was being indexed",
+ )
+ } else {
+ ApiError::new("source_io", "Source note could not be read")
+ }
+}
+
+pub(super) fn canonical_source_root(path: &Path) -> Result<PathBuf, ApiError> {
+ if path.as_os_str().is_empty() {
+ return Err(ApiError::new("invalid_folder", "Choose a Notes folder"));
+ }
+ let metadata = fs::symlink_metadata(path)
+ .map_err(|_| ApiError::new("unavailable", "The selected folder is unavailable"))?;
+ if !metadata.is_dir() {
+ return Err(ApiError::new(
+ "invalid_folder",
+ "Choose a folder, not a file",
+ ));
+ }
+ let canonical = fs::canonicalize(path)
+ .map_err(|_| ApiError::new("unavailable", "The selected folder is unavailable"))?;
+ if canonical.to_str().is_none() {
+ return Err(ApiError::new(
+ "invalid_folder",
+ "The selected folder name is not supported",
+ ));
+ }
+ Ok(canonical)
+}
+
+pub(super) fn compact_source_location(root: &Path) -> String {
+ root.file_name()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("Selected folder")
+ .to_string()
+}
+
+pub(super) fn validate_new_source_root(
+ collections: &[RegisteredCollection],
+ source_root: &Path,
+) -> Result<(), ApiError> {
+ for existing in collections {
+ if source_root == existing.source_root {
+ return Err(ApiError::new(
+ "duplicate",
+ "That folder is already in Your Notes",
+ ));
+ }
+ if source_root.starts_with(&existing.source_root)
+ || existing.source_root.starts_with(source_root)
+ {
+ return Err(ApiError::new(
+ "nested",
+ "Notes collection folders must not contain one another",
+ ));
+ }
+ }
+ Ok(())
+}
+
+pub(super) fn cleanup_unregistered_indexes(
+ index_root: &Path,
+ collections: &[RegisteredCollection],
+) {
+ let registered = collections
+ .iter()
+ .map(|collection| collection.id.as_str())
+ .collect::<BTreeSet<_>>();
+ let Ok(entries) = fs::read_dir(index_root) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else { continue };
+ if registered.contains(name) {
+ continue;
+ }
+ if let Err(error) = remove_owned_entry(&entry.path()) {
+ crate::logging::log(
+ "Notes",
+ format!(
+ "could not clean unregistered derived index path={} error={}",
+ entry.path().display(),
+ error.message
+ ),
+ );
+ }
+ }
+}
+
+pub(super) fn is_supported_file(path: &Path) -> bool {
+ path.extension()
+ .and_then(|extension| extension.to_str())
+ .is_some_and(|extension| {
+ matches!(extension.to_ascii_lowercase().as_str(), "md" | "markdown")
+ })
+}
+
+pub(super) fn source_root_is_available(source_root: &Path) -> bool {
+ canonical_source_root(source_root).is_ok_and(|canonical| canonical == source_root)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::TestDirectory;
+ use super::*;
+
+ #[cfg(unix)]
+ #[test]
+ fn collection_read_rejects_an_intermediate_directory_symlink_swap() {
+ use std::os::unix::fs::symlink;
+
+ let temp = TestDirectory::new();
+ let root = temp.path().join("root");
+ let nested = root.join("nested");
+ let outside = temp.path().join("outside");
+ fs::create_dir_all(&nested).unwrap();
+ fs::create_dir(&outside).unwrap();
+ fs::write(nested.join("note.md"), "inside").unwrap();
+ fs::write(outside.join("note.md"), "outside").unwrap();
+ let root = fs::canonicalize(root).unwrap();
+ let inventory = inventory_source_root(&root, || Ok(())).unwrap();
+ assert_eq!(inventory.len(), 1);
+
+ fs::remove_file(root.join("nested/note.md")).unwrap();
+ fs::remove_dir(root.join("nested")).unwrap();
+ symlink(&outside, root.join("nested")).unwrap();
+
+ let error = read_collection_source(&root, "nested/note.md").unwrap_err();
+ assert_eq!(error.name, Some("invalid_document"));
+ }
+}
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs b/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs
new file mode 100644
index 0000000000..e664e4a47b
--- /dev/null
+++ b/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs
@@ -0,0 +1,773 @@
+use std::collections::{BTreeSet, hash_map::Entry};
+use std::fs;
+use std::path::{Component, Path, PathBuf};
+use std::sync::PoisonError;
+
+use ente_ensu::notes::{
+ NotesCollectionIndex, NotesError, NotesIndexWriter, notes_content_revision,
+};
+use notify::event::{CreateKind, ModifyKind, RemoveKind};
+use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
+use tauri::async_runtime;
+use tauri::{AppHandle, Emitter, Manager};
+
+use crate::commands::common::ApiError;
+
+use super::registry::RegisteredCollection;
+use super::source::{
+ canonical_source_root, inventory_source_root, is_supported_file, read_collection_source,
+ relative_document_id, source_root_is_available, walk_source_tree,
+};
+use super::{
+ CollectionWatcher, DesktopUpdateState, NOTES_MAX_WATCH_DIRECTORIES, NOTES_STATE_CHANGED_EVENT,
+ NotesCollectionStatusDto, State, notes_error, now_ms,
+};
+
+#[derive(Default)]
+pub(super) struct WatchChange {
+ pub(super) forced_document_ids: BTreeSet<String>,
+ pub(super) force_full_hash: bool,
+ pub(super) reattach_root: bool,
+ pub(super) refresh_watches: bool,
+}
+
+impl WatchChange {
+ fn merge(&mut self, change: Self) {
+ self.forced_document_ids.extend(change.forced_document_ids);
+ self.force_full_hash |= change.force_full_hash;
+ self.reattach_root |= change.reattach_root;
+ self.refresh_watches |= change.refresh_watches;
+ }
+}
+
+pub(super) struct WatchWork {
+ pending: Option<WatchChange>,
+}
+
+pub(super) struct StartupInspection {
+ pub(super) initial_complete: bool,
+ pub(super) changed: bool,
+ pub(super) forced_document_ids: BTreeSet<String>,
+ pub(super) opened_index: Option<NotesCollectionIndex>,
+}
+
+pub async fn initialize_for_app(app: AppHandle) {
+ let collections = app
+ .state::<State>()
+ .registry
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .registry
+ .collections
+ .clone();
+ for collection in collections {
+ let install_app = app.clone();
+ let install_collection = collection.clone();
+ let install_result = async_runtime::spawn_blocking(move || {
+ install_collection_watcher(&install_app, &install_collection)
+ })
+ .await;
+ let install_result = match install_result {
+ Ok(result) => result,
+ Err(_) => Err(ApiError::new("watcher_thread", "Notes watcher task failed")),
+ };
+ if let Err(error) = install_result {
+ let state = app.state::<State>();
+ let mut runtime = state.runtime(&collection.id);
+ runtime.status = if source_root_is_available(&collection.source_root) {
+ NotesCollectionStatusDto::Error
+ } else {
+ NotesCollectionStatusDto::Unavailable
+ };
+ runtime.last_error = Some(error.message);
+ state.set_runtime(&collection.id, runtime);
+ emit_state_changed(&app, &collection.id);
+ continue;
+ }
+ inspect_collection_on_startup(app.clone(), collection).await;
+ }
+}
+
+async fn inspect_collection_on_startup(app: AppHandle, collection: RegisteredCollection) {
+ let index_root = app.state::<State>().index_root.clone();
+ let lifecycle = app.state::<State>().collection_lifecycle(&collection.id);
+ let _collection_lifecycle = lifecycle.lock().await;
+ if app
+ .state::<State>()
+ .registered_collection(&collection.id)
+ .is_err()
+ {
+ return;
+ }
+ let inspection_collection = collection.clone();
+ let inspection = async_runtime::spawn_blocking(move || {
+ inspect_startup_freshness(&index_root, &inspection_collection)
+ })
+ .await;
+ let Ok(inspection) = inspection else {
+ return;
+ };
+ let state = app.state::<State>();
+ if state.registered_collection(&collection.id).is_err() {
+ return;
+ }
+ match inspection {
+ Ok(inspection) => {
+ let StartupInspection {
+ initial_complete,
+ changed,
+ forced_document_ids,
+ opened_index,
+ } = inspection;
+ let mut runtime = state.runtime(&collection.id);
+ runtime.index_available = opened_index.is_some();
+ runtime.indexed_document_count = opened_index
+ .as_ref()
+ .map_or(0, |index| index.document_count() as u64);
+ runtime.last_updated_at_ms = opened_index
+ .as_ref()
+ .and_then(NotesCollectionIndex::last_updated_at_ms);
+ runtime.indexing_progress = None;
+ if runtime.index_available {
+ runtime.status = NotesCollectionStatusDto::Ready;
+ runtime.last_error = None;
+ } else if initial_complete {
+ runtime.status = NotesCollectionStatusDto::Error;
+ runtime.last_error =
+ Some("No supported non-empty UTF-8 notes were found".to_string());
+ } else {
+ runtime.status = NotesCollectionStatusDto::Pending;
+ runtime.last_error = None;
+ }
+ state.set_runtime(&collection.id, runtime);
+ if let Some(index) = opened_index {
+ state
+ .cached_indexes
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .insert(collection.id.clone(), index);
+ }
+ if changed && initial_complete && !state.has_pending_update(&collection.id) {
+ mark_collection_dirty(&app, &collection.id, forced_document_ids, false);
+ } else {
+ emit_state_changed(&app, &collection.id);
+ }
+ }
+ Err(error) => {
+ let mut runtime = state.runtime(&collection.id);
+ runtime.status = if source_root_is_available(&collection.source_root) {
+ NotesCollectionStatusDto::Error
+ } else {
+ NotesCollectionStatusDto::Unavailable
+ };
+ runtime.last_error = Some(error.message);
+ state.set_runtime(&collection.id, runtime);
+ emit_state_changed(&app, &collection.id);
+ }
+ }
+}
+
+pub(super) fn inspect_startup_freshness(
+ index_root: &Path,
+ collection: &RegisteredCollection,
+) -> Result<StartupInspection, ApiError> {
+ let canonical_root = canonical_source_root(&collection.source_root)?;
+ if canonical_root != collection.source_root {
+ return Err(ApiError::new(
+ "source_changed",
+ "Notes source folder identity changed",
+ ));
+ }
+ let inventory = inventory_source_root(&canonical_root, || Ok(()))?;
+ let writer = match NotesIndexWriter::open(index_root, collection.id.clone()) {
+ Ok(writer) => writer,
+ Err(NotesError::IncompatibleIndex) => {
+ return Ok(StartupInspection {
+ initial_complete: false,
+ changed: true,
+ forced_document_ids: BTreeSet::new(),
+ opened_index: None,
+ });
+ }
+ Err(error) => return Err(notes_error(error)),
+ };
+ let plan = writer
+ .plan_reconciliation(&inventory, &[], false)
+ .map_err(notes_error)?;
+ let planned = plan
+ .content_required_document_ids
+ .iter()
+ .map(String::as_str)
+ .collect::<BTreeSet<_>>();
+ let mut forced_document_ids = BTreeSet::new();
+ for source in &inventory {
+ if planned.contains(source.document_id.as_str()) {
+ continue;
+ }
+ let Some(indexed_revision) = writer.indexed_revision(&source.document_id) else {
+ continue;
+ };
+ match read_collection_source(&canonical_root, &source.document_id) {
+ Ok((_, bytes, _)) if notes_content_revision(&bytes) == indexed_revision => {}
+ Ok(_) => {
+ forced_document_ids.insert(source.document_id.clone());
+ }
+ Err(error) if error.name == Some("source_changed") => {
+ forced_document_ids.insert(source.document_id.clone());
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ let initial_complete = writer.initial_inventory_complete();
+ let opened_index = if initial_complete {
+ match NotesCollectionIndex::open(index_root, collection.id.clone()) {
+ Ok(index) => Some(index),
+ Err(NotesError::NotReady) => None,
+ Err(error) => return Err(notes_error(error)),
+ }
+ } else {
+ None
+ };
+ Ok(StartupInspection {
+ initial_complete,
+ changed: !plan.is_up_to_date() || !forced_document_ids.is_empty(),
+ forced_document_ids,
+ opened_index,
+ })
+}
+
+pub(super) fn watch_directories(root: &Path) -> Result<BTreeSet<PathBuf>, ApiError> {
+ if !source_root_is_available(root) {
+ return Ok(BTreeSet::new());
+ }
+ let mut directories = BTreeSet::new();
+ walk_source_tree(
+ root,
+ || Ok(()),
+ || {
+ ApiError::new(
+ "watcher",
+ "The Notes folder contains too many filesystem entries to watch",
+ )
+ },
+ |directory| {
+ if directories.len() >= NOTES_MAX_WATCH_DIRECTORIES {
+ return Err(ApiError::new(
+ "watcher",
+ "The Notes folder contains too many directories to watch",
+ ));
+ }
+ directories.insert(directory.to_path_buf());
+ Ok(())
+ },
+ |_, _| Ok(()),
+ )?;
+ Ok(directories)
+}
+
+pub(super) fn install_collection_watcher(
+ app: &AppHandle,
+ collection: &RegisteredCollection,
+) -> Result<(), ApiError> {
+ let collection_id = collection.id.clone();
+ let source_root = collection.source_root.clone();
+ let callback_app = app.clone();
+ let callback_collection_id = collection_id.clone();
+ let callback_root = source_root.clone();
+ let mut watcher = RecommendedWatcher::new(
+ move |result| {
+ handle_watch_event(
+ &callback_app,
+ &callback_collection_id,
+ &callback_root,
+ result,
+ );
+ },
+ Config::default(),
+ )
+ .map_err(notify_error)?;
+
+ let watched_directories = watch_directories(&source_root)?;
+ for directory in &watched_directories {
+ watcher
+ .watch(directory, RecursiveMode::NonRecursive)
+ .map_err(notify_error)?;
+ }
+ let parent_watched = source_root
+ .parent()
+ .is_some_and(|parent| watcher.watch(parent, RecursiveMode::NonRecursive).is_ok());
+ if watched_directories.is_empty() && !parent_watched {
+ return Err(ApiError::new(
+ "watcher",
+ "The Notes folder could not be watched",
+ ));
+ }
+ app.state::<State>()
+ .watchers
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .insert(
+ collection_id,
+ CollectionWatcher {
+ watcher,
+ watched_directories,
+ },
+ );
+ Ok(())
+}
+
+fn handle_watch_event(
+ app: &AppHandle,
+ collection_id: &str,
+ source_root: &Path,
+ result: notify::Result<Event>,
+) {
+ let change = match result {
+ Ok(event) => classify_watch_event(source_root, &event),
+ Err(_) => Some(WatchChange {
+ force_full_hash: true,
+ reattach_root: true,
+ refresh_watches: true,
+ ..WatchChange::default()
+ }),
+ };
+ let Some(change) = change else {
+ return;
+ };
+ let should_spawn = {
+ let state = app.state::<State>();
+ let mut work = state
+ .watch_work
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ match work.entry(collection_id.to_string()) {
+ Entry::Occupied(mut entry) => {
+ match &mut entry.get_mut().pending {
+ Some(pending) => pending.merge(change),
+ pending => *pending = Some(change),
+ }
+ false
+ }
+ Entry::Vacant(entry) => {
+ entry.insert(WatchWork {
+ pending: Some(change),
+ });
+ true
+ }
+ }
+ };
+ if !should_spawn {
+ return;
+ }
+ let event_app = app.clone();
+ let event_collection_id = collection_id.to_string();
+ let event_source_root = source_root.to_path_buf();
+ async_runtime::spawn(async move {
+ process_watch_changes(event_app, event_collection_id, event_source_root).await;
+ });
+}
+
+async fn process_watch_changes(app: AppHandle, collection_id: String, source_root: PathBuf) {
+ loop {
+ let change = {
+ let state = app.state::<State>();
+ let mut work = state
+ .watch_work
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ let Some(change) = work
+ .get_mut(&collection_id)
+ .and_then(|work| work.pending.take())
+ else {
+ work.remove(&collection_id);
+ return;
+ };
+ change
+ };
+ if change.refresh_watches {
+ let refresh_app = app.clone();
+ let refresh_collection_id = collection_id.clone();
+ let refresh_source_root = source_root.clone();
+ let _ = async_runtime::spawn_blocking(move || {
+ refresh_collection_watches(
+ &refresh_app,
+ &refresh_collection_id,
+ &refresh_source_root,
+ change.reattach_root,
+ )
+ })
+ .await;
+ }
+ mark_collection_dirty(
+ &app,
+ &collection_id,
+ change.forced_document_ids,
+ change.force_full_hash,
+ );
+ }
+}
+
+fn refresh_collection_watches(
+ app: &AppHandle,
+ collection_id: &str,
+ source_root: &Path,
+ reattach_root: bool,
+) -> Result<bool, ApiError> {
+ let desired = watch_directories(source_root)?;
+ let state = app.state::<State>();
+ let mut watchers = state
+ .watchers
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ let Some(entry) = watchers.get_mut(collection_id) else {
+ return Ok(false);
+ };
+ if reattach_root {
+ for directory in std::mem::take(&mut entry.watched_directories) {
+ let _ = entry.watcher.unwatch(&directory);
+ }
+ }
+ let removed = entry
+ .watched_directories
+ .difference(&desired)
+ .cloned()
+ .collect::<Vec<_>>();
+ for directory in removed {
+ let _ = entry.watcher.unwatch(&directory);
+ entry.watched_directories.remove(&directory);
+ }
+ let added = desired
+ .difference(&entry.watched_directories)
+ .cloned()
+ .collect::<Vec<_>>();
+ for directory in added {
+ entry
+ .watcher
+ .watch(&directory, RecursiveMode::NonRecursive)
+ .map_err(notify_error)?;
+ entry.watched_directories.insert(directory);
+ }
+ Ok(entry.watched_directories.contains(source_root))
+}
+
+pub(super) fn ensure_collection_watcher(
+ app: &AppHandle,
+ collection: &RegisteredCollection,
+) -> Result<(), ApiError> {
+ if !source_root_is_available(&collection.source_root) {
+ return Err(ApiError::new(
+ "source_unavailable",
+ "Source folder is unavailable",
+ ));
+ }
+ if refresh_collection_watches(app, &collection.id, &collection.source_root, false)
+ .unwrap_or(false)
+ {
+ return Ok(());
+ }
+ let state = app.state::<State>();
+ state
+ .watchers
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .remove(&collection.id);
+ install_collection_watcher(app, collection)
+}
+
+pub(super) fn classify_watch_event(source_root: &Path, event: &Event) -> Option<WatchChange> {
+ if matches!(event.kind, EventKind::Access(_)) {
+ return None;
+ }
+ let ambiguous = matches!(
+ event.kind,
+ EventKind::Any
+ | EventKind::Other
+ | EventKind::Create(CreateKind::Folder)
+ | EventKind::Remove(RemoveKind::Any | RemoveKind::Folder | RemoveKind::Other)
+ | EventKind::Modify(ModifyKind::Name(_))
+ );
+ classify_watch_paths(source_root, &event.paths, ambiguous)
+}
+
+fn classify_watch_paths(
+ source_root: &Path,
+ paths: &[PathBuf],
+ overflow_or_ambiguity: bool,
+) -> Option<WatchChange> {
+ if paths.is_empty() {
+ return overflow_or_ambiguity.then_some(WatchChange {
+ force_full_hash: true,
+ refresh_watches: true,
+ ..WatchChange::default()
+ });
+ }
+ let mut change = WatchChange {
+ refresh_watches: overflow_or_ambiguity,
+ ..WatchChange::default()
+ };
+ let mut saw_relevant_path = false;
+ for path in paths {
+ if path == source_root {
+ saw_relevant_path = true;
+ change.force_full_hash = true;
+ change.reattach_root = true;
+ change.refresh_watches = true;
+ continue;
+ }
+ let Ok(relative) = path.strip_prefix(source_root) else {
+ continue;
+ };
+ if relative.components().any(|component| {
+ matches!(component, Component::Normal(name) if name.to_string_lossy().starts_with('.'))
+ }) {
+ continue;
+ }
+ let metadata = fs::symlink_metadata(path).ok();
+ if metadata
+ .as_ref()
+ .is_some_and(|metadata| metadata.file_type().is_symlink())
+ {
+ saw_relevant_path = true;
+ change.force_full_hash = true;
+ change.refresh_watches = true;
+ continue;
+ }
+ saw_relevant_path = true;
+ if is_supported_file(path) {
+ if let Some(document_id) = relative_document_id(source_root, path) {
+ change.forced_document_ids.insert(document_id);
+ }
+ continue;
+ }
+ if metadata.as_ref().is_some_and(|metadata| metadata.is_dir())
+ || (metadata.is_none() && overflow_or_ambiguity)
+ {
+ change.force_full_hash = true;
+ change.refresh_watches = true;
+ }
+ }
+ change.force_full_hash |= overflow_or_ambiguity && saw_relevant_path;
+ (!change.forced_document_ids.is_empty() || change.force_full_hash).then_some(change)
+}
+
+fn mark_collection_for_update(
+ app: &AppHandle,
+ collection_id: &str,
+ record_update: impl FnOnce(&mut DesktopUpdateState) -> bool,
+) {
+ let state = app.state::<State>();
+ let Ok(collection) = state.registered_collection(collection_id) else {
+ return;
+ };
+ let changed = {
+ let mut updates = state.updates.lock().unwrap_or_else(PoisonError::into_inner);
+ let update = updates.entry(collection_id.to_string()).or_default();
+ record_update(update)
+ };
+ if !changed {
+ return;
+ }
+
+ let available = source_root_is_available(&collection.source_root);
+ let mut runtime = state.runtime(collection_id);
+ if !available
+ && !matches!(
+ runtime.status,
+ NotesCollectionStatusDto::Indexing | NotesCollectionStatusDto::Updating
+ )
+ {
+ runtime.status = NotesCollectionStatusDto::Unavailable;
+ } else if available
+ && matches!(
+ runtime.status,
+ NotesCollectionStatusDto::Unavailable | NotesCollectionStatusDto::Error
+ )
+ {
+ runtime.status = if runtime.index_available {
+ NotesCollectionStatusDto::Ready
+ } else {
+ NotesCollectionStatusDto::Pending
+ };
+ }
+ runtime.last_error = (!available).then(|| "Source folder is unavailable".to_string());
+ state.set_runtime(collection_id, runtime);
+ emit_state_changed(app, collection_id);
+}
+
+pub(crate) fn mark_collection_dirty(
+ app: &AppHandle,
+ collection_id: &str,
+ forced_document_ids: impl IntoIterator<Item = String>,
+ force_full_hash: bool,
+) {
+ mark_collection_for_update(app, collection_id, move |update| {
+ update.record_change(now_ms(), forced_document_ids, force_full_hash);
+ true
+ });
+}
+
+pub(crate) fn mark_reference_stale(app: &AppHandle, collection_id: &str, document_id: String) {
+ mark_collection_for_update(app, collection_id, move |update| {
+ update.record_stale_reference(now_ms(), document_id)
+ });
+}
+
+pub(super) fn emit_state_changed(app: &AppHandle, collection_id: &str) {
+ let state = app.state::<State>();
+ if let Ok(collection) = state.collection_dto(collection_id) {
+ let _ = app.emit(NOTES_STATE_CHANGED_EVENT, collection);
+ }
+}
+
+fn notify_error(_: notify::Error) -> ApiError {
+ ApiError::new("watcher", "The Notes folder could not be watched")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::TestDirectory;
+ use super::*;
+ use ente_ensu::notes::{NotesSourceDocument, prepare_notes_document};
+ use notify::event::RenameMode;
+
+ const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
+
+ #[test]
+ fn incompatible_startup_index_remains_eligible_for_automatic_rebuild() {
+ let temp = TestDirectory::new();
+ let source_root = temp.path().join("source");
+ fs::create_dir(&source_root).unwrap();
+ fs::write(source_root.join("note.md"), "note").unwrap();
+ let source_root = fs::canonicalize(source_root).unwrap();
+ let index_root = temp.path().join("indexes");
+ let mut writer = NotesIndexWriter::open(&index_root, COLLECTION_ID.to_string()).unwrap();
+ writer.publish(false).unwrap();
+ let manifest_path = index_root.join(COLLECTION_ID).join("manifest.json");
+ let manifest = fs::read_to_string(&manifest_path).unwrap();
+ let incompatible = manifest.replacen("\"schema_version\": 2", "\"schema_version\": 1", 1);
+ assert_ne!(manifest, incompatible);
+ fs::write(manifest_path, incompatible).unwrap();
+
+ let inspection = inspect_startup_freshness(
+ &index_root,
+ &RegisteredCollection {
+ id: COLLECTION_ID.to_string(),
+ source_root,
+ },
+ )
+ .unwrap();
+ assert!(!inspection.initial_complete);
+ assert!(inspection.changed);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn watcher_directory_enumeration_does_not_follow_symlinks() {
+ use std::os::unix::fs::symlink;
+
+ let temp = TestDirectory::new();
+ let root = temp.path().join("root");
+ let nested = root.join("nested");
+ let outside = temp.path().join("outside");
+ fs::create_dir_all(&nested).unwrap();
+ fs::create_dir(&outside).unwrap();
+ symlink(&outside, root.join("linked")).unwrap();
+ let root = fs::canonicalize(root).unwrap();
+ let nested = root.join("nested");
+
+ let directories = watch_directories(&root).unwrap();
+
+ assert_eq!(directories, BTreeSet::from([root.clone(), nested]));
+ assert!(!directories.contains(&outside));
+ }
+
+ #[test]
+ fn root_watch_events_request_identity_reattachment() {
+ let root = PathBuf::from("/notes");
+ let event = Event::new(EventKind::Create(CreateKind::Folder)).add_path(root.clone());
+
+ let change = classify_watch_event(&root, &event).unwrap();
+
+ assert!(change.force_full_hash);
+ assert!(change.reattach_root);
+ }
+
+ #[test]
+ fn moved_out_directories_force_reconciliation_and_watch_refresh() {
+ let temp = TestDirectory::new();
+ let root = temp.path().join("root");
+ fs::create_dir(&root).unwrap();
+ let path = root.join("moved");
+ let event =
+ Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::From))).add_path(path);
+
+ let change = classify_watch_event(&root, &event).unwrap();
+
+ assert!(change.force_full_hash);
+ assert!(change.refresh_watches);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlink_replacements_force_reconciliation_and_watch_refresh() {
+ use std::os::unix::fs::symlink;
+
+ let temp = TestDirectory::new();
+ let root = temp.path().join("root");
+ let outside = temp.path().join("outside");
+ fs::create_dir(&root).unwrap();
+ fs::write(&outside, "outside").unwrap();
+ let path = root.join("note.md");
+ symlink(outside, &path).unwrap();
+ let event = Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path);
+
+ let change = classify_watch_event(&root, &event).unwrap();
+
+ assert!(change.force_full_hash);
+ assert!(change.refresh_watches);
+ }
+
+ #[test]
+ fn startup_hashes_files_even_when_metadata_hints_match() {
+ let temp = TestDirectory::new();
+ let source_root = temp.path().join("source");
+ fs::create_dir(&source_root).unwrap();
+ let source_path = source_root.join("note.md");
+ fs::write(&source_path, "new!").unwrap();
+ let source_root = fs::canonicalize(source_root).unwrap();
+ let metadata = fs::metadata(&source_path).unwrap();
+ let source = NotesSourceDocument {
+ document_id: "note.md".to_string(),
+ size: metadata.len(),
+ modified_at_ms: metadata
+ .modified()
+ .ok()
+ .and_then(super::super::system_time_ms),
+ };
+ let prepared = prepare_notes_document("note.md", b"old!").unwrap();
+ let mut embedding = vec![0.0; 512];
+ embedding[0] = 1.0;
+ let index_root = temp.path().join("indexes");
+ let mut writer = NotesIndexWriter::open(&index_root, COLLECTION_ID.to_string()).unwrap();
+ writer
+ .commit_document(&prepared, &[embedding], &source)
+ .unwrap();
+ writer.publish(true).unwrap();
+
+ let inspection = inspect_startup_freshness(
+ &index_root,
+ &RegisteredCollection {
+ id: COLLECTION_ID.to_string(),
+ source_root,
+ },
+ )
+ .unwrap();
+
+ assert!(inspection.changed);
+ assert_eq!(
+ inspection.forced_document_ids,
+ BTreeSet::from(["note.md".to_string()])
+ );
+ assert!(inspection.opened_index.is_some());
+ }
+}
diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rs
index 5eaf291ea6..fcf4704969 100644
--- a/rust/apps/ensu/src-tauri/src/main.rs
+++ b/rust/apps/ensu/src-tauri/src/main.rs
@@ -1,6 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
-use tauri::{Manager, RunEvent};
+use tauri::{Manager, RunEvent, async_runtime};
mod commands;
mod logging;
@@ -29,14 +29,16 @@ fn main() {
commands::notes::State::new(app.path().app_data_dir()?)
.map_err(|error| std::io::Error::other(error.message))?,
);
- commands::notes::initialize_for_app(app.handle());
-
if let Some(window) = app.get_webview_window("main")
&& let Err(err) = window.show()
{
logging::log("App", format!("failed to show main window error={err}"));
return Err(Box::new(err));
}
+ let notes_app = app.handle().clone();
+ async_runtime::spawn(async move {
+ commands::notes::initialize_for_app(notes_app).await;
+ });
logging::log("App", "setup complete");
Ok(())
})
diff --git a/rust/crates/ensu-crypto/src/lib.rs b/rust/crates/ensu-crypto/src/lib.rs
index 3d2f6b3662..b934dc8bd5 100644
--- a/rust/crates/ensu-crypto/src/lib.rs
+++ b/rust/crates/ensu-crypto/src/lib.rs
@@ -3,13 +3,23 @@ use ente_core::{
crypto::{self, Header, Key, blob},
};
use hkdf::Hkdf;
-use sha2::Sha256;
+use sha2::{Digest, Sha256};
use thiserror::Error;
const ATTACHMENT_KEY_INFO: &[u8] = b"llmchat_attachment_v1";
pub type Result<T> = std::result::Result<T, Error>;
+pub fn sha256_hex(bytes: &[u8]) -> String {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let mut encoded = String::with_capacity(64);
+ for byte in Sha256::digest(bytes) {
+ encoded.push(char::from(HEX[usize::from(byte >> 4)]));
+ encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
+ }
+ encoded
+}
+
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid blob length: expected at least {minimum} bytes, got {actual}")]
diff --git a/rust/crates/ensu/Cargo.toml b/rust/crates/ensu/Cargo.toml
index 16c4a1fbb1..beb23708bd 100644
--- a/rust/crates/ensu/Cargo.toml
+++ b/rust/crates/ensu/Cargo.toml
@@ -14,7 +14,6 @@ rusqlite = { version = "0.38", features = ["bundled"], optional = true }
self_cell = "1"
serde.workspace = true
serde_json.workspace = true
-sha2.workspace = true
thiserror.workspace = true
tokio = { version = "1", features = ["rt", "time"] }
transcribe-rs = { git = "https://github.com/cjpais/transcribe-rs.git", rev = "efc66111d519a434e28d51d94740008a7ce29360", default-features = false, features = ["onnx", "vad-silero"], optional = true }
diff --git a/rust/crates/ensu/src/config/knowledge.rs b/rust/crates/ensu/src/config/knowledge.rs
index 9a5ccff3af..a94371a9ba 100644
--- a/rust/crates/ensu/src/config/knowledge.rs
+++ b/rust/crates/ensu/src/config/knowledge.rs
@@ -24,7 +24,7 @@ const SOURCE_DIM: u32 = 768;
const RETRIEVAL_DIM: u32 = 512;
const EMBEDDING_CONTEXT_SIZE: u32 = 2_048;
const MAX_HITS: u32 = 2;
-const MAX_CONTEXT_UTF8_BYTES: u32 = 6_000;
+const MAX_CONTEXT_UTF8_BYTES: u32 = 8_192;
const MODIFICATION_NOTICE: &str = "Adapted by Ente";
#[derive(Debug, Clone, PartialEq)]
diff --git a/rust/crates/ensu/src/notes.rs b/rust/crates/ensu/src/notes.rs
index 8ba8ed9af1..8622c37a08 100644
--- a/rust/crates/ensu/src/notes.rs
+++ b/rust/crates/ensu/src/notes.rs
@@ -1,20 +1,24 @@
mod chunk;
mod document;
mod index;
+mod indexing;
mod manifest;
mod reconcile;
mod shard;
mod source;
mod writer;
-use sha2::{Digest, Sha256};
use thiserror::Error;
use uuid::Uuid;
-const NOTES_INDEX_CONTRACT_VERSION: u32 = 1;
+const NOTES_INDEX_CONTRACT_VERSION: u32 = 2;
pub const NOTES_MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024;
-const NOTES_CHUNK_CHARACTERS: usize = 1_400;
-const NOTES_CHUNK_OVERLAP_CHARACTERS: usize = 200;
+pub const NOTES_MAX_COLLECTION_SOURCE_BYTES: u64 = 128 * 1024 * 1024;
+pub const NOTES_MAX_COLLECTION_DOCUMENTS: usize = 20_000;
+const NOTES_MAX_COLLECTION_CHUNKS: u64 = 131_072;
+const NOTES_CHUNK_UTF8_BYTES: usize = 1_400;
+const NOTES_CHUNK_OVERLAP_UTF8_BYTES: usize = 200;
+const NOTES_HEADING_MAX_UTF8_BYTES: usize = 512;
#[derive(Debug, Error)]
pub enum NotesError {
@@ -26,6 +30,8 @@ pub enum NotesError {
IncompatibleIndex,
#[error("Notes collection is not ready")]
NotReady,
+ #[error("Notes collection is too large: {0}")]
+ CollectionTooLarge(String),
#[error("Notes index I/O failed: {0}")]
Io(#[from] std::io::Error),
#[error("Notes index JSON failed: {0}")]
@@ -35,7 +41,11 @@ pub enum NotesError {
pub use document::{
NotesSourceDocument, PreparedNotesChunk, PreparedNotesDocument, prepare_notes_document,
};
-pub use index::{NotesCollectionIndex, NotesSearchHit};
+pub use index::{NotesCollectionIndex, NotesCollectionIndexSummary, NotesSearchHit};
+pub use indexing::{
+ NotesDocumentLoad, NotesIndexInput, NotesIndexOutcome, NotesIndexingError, NotesRevisionStatus,
+ index_notes_collection,
+};
pub use reconcile::NotesReconciliationPlan;
pub use source::NoteSourceReference;
pub use writer::NotesIndexWriter;
@@ -45,13 +55,7 @@ pub fn notes_content_revision(bytes: &[u8]) -> String {
}
fn sha256_hex(bytes: &[u8]) -> String {
- const HEX: &[u8; 16] = b"0123456789abcdef";
- let mut encoded = String::with_capacity(64);
- for byte in Sha256::digest(bytes) {
- encoded.push(char::from(HEX[usize::from(byte >> 4)]));
- encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
- }
- encoded
+ ente_ensu_crypto::sha256_hex(bytes)
}
pub fn validate_document_id(document_id: &str) -> Result<(), NotesError> {
@@ -65,6 +69,12 @@ pub fn validate_document_id(document_id: &str) -> Result<(), NotesError> {
"document ID contains a control character".to_string(),
));
}
+ #[cfg(windows)]
+ if document_id.contains('\\') {
+ return Err(NotesError::InvalidInput(
+ "document ID contains an invalid path separator".to_string(),
+ ));
+ }
if looks_like_absolute_local_path(document_id) {
return Err(NotesError::InvalidInput(
"document ID must not be an absolute local path".to_string(),
@@ -121,6 +131,12 @@ fn is_valid_label(value: &str) -> bool {
!value.trim().is_empty() && value.len() <= 4_096 && !value.chars().any(char::is_control)
}
+fn contains_unsupported_control(value: &str) -> bool {
+ value
+ .chars()
+ .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'))
+}
+
fn invalid_index_input(error: NotesError) -> NotesError {
NotesError::InvalidIndex(match error {
NotesError::InvalidInput(detail) => detail,
diff --git a/rust/crates/ensu/src/notes/chunk.rs b/rust/crates/ensu/src/notes/chunk.rs
index e6c1424006..f34e3db76b 100644
--- a/rust/crates/ensu/src/notes/chunk.rs
+++ b/rust/crates/ensu/src/notes/chunk.rs
@@ -1,5 +1,10 @@
use super::document::PreparedNotesChunk;
-use super::{NOTES_CHUNK_CHARACTERS, NOTES_CHUNK_OVERLAP_CHARACTERS, NotesError, is_valid_label};
+use super::{
+ NOTES_CHUNK_OVERLAP_UTF8_BYTES, NOTES_CHUNK_UTF8_BYTES, NOTES_HEADING_MAX_UTF8_BYTES,
+ NotesError, is_valid_label,
+};
+
+const CHUNK_COMPACTION_THRESHOLD: usize = 1_024;
#[derive(Debug)]
struct DocumentGroup {
@@ -19,19 +24,20 @@ pub(super) fn prepare_chunks(
let mut fence = None;
for line in source.lines() {
- if let Some((marker, count)) = fence_marker(line) {
- match fence {
- Some((open_marker, open_count)) if marker == open_marker && count >= open_count => {
+ match fence {
+ Some((marker, count)) => {
+ if is_closing_fence(line, marker, count) {
fence = None;
}
- None => fence = Some((marker, count)),
- _ => {}
+ }
+ None => {
+ fence = opening_fence(line);
}
}
if fence.is_none()
&& let Some((level, heading)) = atx_heading(line)
{
- if !is_valid_label(&heading) {
+ if heading.len() > NOTES_HEADING_MAX_UTF8_BYTES || !is_valid_label(&heading) {
return Err(NotesError::InvalidInput(
"heading length or characters are invalid".to_string(),
));
@@ -77,6 +83,9 @@ pub(super) fn prepare_chunks(
});
}
}
+ if chunks.len() > CHUNK_COMPACTION_THRESHOLD {
+ chunks = compact_chunks(chunks);
+ }
if chunks.is_empty() {
return Err(NotesError::InvalidInput(
"source document produced no chunks".to_string(),
@@ -94,10 +103,47 @@ fn flush_group(groups: &mut Vec<DocumentGroup>, section: Option<String>, lines:
section,
text: lines[start..=end].join("\n"),
});
+ } else if let Some(section) = section {
+ groups.push(DocumentGroup {
+ section: None,
+ text: section,
+ });
}
lines.clear();
}
+fn append_chunk(chunks: &mut Vec<PreparedNotesChunk>, section: Option<String>, text: String) {
+ if let Some(previous) = chunks.last_mut() {
+ let separator = match section.as_deref() {
+ Some(section) => format!("\n\n## {section}\n"),
+ None => "\n\n".to_string(),
+ };
+ if previous
+ .text
+ .len()
+ .checked_add(separator.len())
+ .and_then(|size| size.checked_add(text.len()))
+ .is_some_and(|size| size <= NOTES_CHUNK_UTF8_BYTES)
+ {
+ previous.text.push_str(&separator);
+ previous.text.push_str(&text);
+ if previous.section != section {
+ previous.section = None;
+ }
+ return;
+ }
+ }
+ chunks.push(PreparedNotesChunk { section, text });
+}
+
+fn compact_chunks(chunks: Vec<PreparedNotesChunk>) -> Vec<PreparedNotesChunk> {
+ let mut compacted = Vec::new();
+ for chunk in chunks {
+ append_chunk(&mut compacted, chunk.section, chunk.text);
+ }
+ compacted
+}
+
fn atx_heading(line: &str) -> Option<(usize, String)> {
let leading_spaces = line.bytes().take_while(|byte| *byte == b' ').count();
if leading_spaces > 3 {
@@ -130,8 +176,13 @@ fn atx_heading(line: &str) -> Option<(usize, String)> {
}
}
-fn fence_marker(line: &str) -> Option<(char, usize)> {
- let line = line.trim_start();
+fn fence_candidate(line: &str) -> Option<&str> {
+ let leading_spaces = line.bytes().take_while(|byte| *byte == b' ').count();
+ (leading_spaces <= 3).then(|| &line[leading_spaces..])
+}
+
+fn opening_fence(line: &str) -> Option<(char, usize)> {
+ let line = fence_candidate(line)?;
let marker = line.chars().next()?;
if !matches!(marker, '`' | '~') {
return None;
@@ -140,12 +191,25 @@ fn fence_marker(line: &str) -> Option<(char, usize)> {
.chars()
.take_while(|character| *character == marker)
.count();
- (count >= 3).then_some((marker, count))
+ if count < 3 || (marker == '`' && line[count..].contains('`')) {
+ return None;
+ }
+ Some((marker, count))
+}
+
+fn is_closing_fence(line: &str, marker: char, open_count: usize) -> bool {
+ let Some(line) = fence_candidate(line) else {
+ return false;
+ };
+ let count = line
+ .chars()
+ .take_while(|character| *character == marker)
+ .count();
+ count >= open_count && line[count..].trim().is_empty()
}
fn split_group(text: &str) -> Vec<String> {
- let character_count = text.chars().count();
- if character_count <= NOTES_CHUNK_CHARACTERS {
+ if text.len() <= NOTES_CHUNK_UTF8_BYTES {
return vec![text.to_string()];
}
@@ -155,17 +219,51 @@ fn split_group(text: &str) -> Vec<String> {
.chain(std::iter::once(text.len()))
.collect::<Vec<_>>();
let mut chunks = Vec::new();
- let mut start = 0;
- while start < character_count {
- let end = (start + NOTES_CHUNK_CHARACTERS).min(character_count);
+ let mut start = 0_usize;
+ while start + 1 < boundaries.len() {
+ let maximum_end_byte = boundaries[start].saturating_add(NOTES_CHUNK_UTF8_BYTES);
+ let end = boundaries
+ .partition_point(|boundary| *boundary <= maximum_end_byte)
+ .saturating_sub(1)
+ .max(start + 1);
let chunk = text[boundaries[start]..boundaries[end]].trim();
if !chunk.is_empty() {
chunks.push(chunk.to_string());
}
- if end == character_count {
+ if end + 1 == boundaries.len() {
break;
}
- start = end - NOTES_CHUNK_OVERLAP_CHARACTERS;
+ let minimum_start_byte = boundaries[end].saturating_sub(NOTES_CHUNK_OVERLAP_UTF8_BYTES);
+ let overlapped_start =
+ boundaries.partition_point(|boundary| *boundary < minimum_start_byte);
+ start = if overlapped_start > start {
+ overlapped_start.min(end)
+ } else {
+ end
+ };
}
chunks
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cross_section_compaction_uses_document_level_metadata() {
+ let compacted = compact_chunks(vec![
+ PreparedNotesChunk {
+ section: Some("First".to_string()),
+ text: "first passage".to_string(),
+ },
+ PreparedNotesChunk {
+ section: Some("Second".to_string()),
+ text: "second passage".to_string(),
+ },
+ ]);
+
+ assert_eq!(compacted.len(), 1);
+ assert_eq!(compacted[0].section, None);
+ assert!(compacted[0].text.contains("## Second\nsecond passage"));
+ }
+}
diff --git a/rust/crates/ensu/src/notes/document.rs b/rust/crates/ensu/src/notes/document.rs
index a46571ada5..7b17ab5828 100644
--- a/rust/crates/ensu/src/notes/document.rs
+++ b/rust/crates/ensu/src/notes/document.rs
@@ -1,5 +1,8 @@
use super::chunk::prepare_chunks;
-use super::{NOTES_MAX_SOURCE_BYTES, NotesError, notes_content_revision, validate_document_id};
+use super::{
+ NOTES_MAX_SOURCE_BYTES, NotesError, contains_unsupported_control, notes_content_revision,
+ validate_document_id,
+};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NotesSourceDocument {
@@ -51,6 +54,11 @@ pub fn prepare_notes_document(
"source document must not be empty".to_string(),
));
}
+ if contains_unsupported_control(text) {
+ return Err(NotesError::InvalidInput(
+ "source document contains an unsupported control character".to_string(),
+ ));
+ }
let revision = notes_content_revision(bytes);
let (title, chunks) = prepare_chunks(document_id, text)?;
@@ -65,7 +73,9 @@ pub fn prepare_notes_document(
#[cfg(test)]
mod tests {
use super::*;
- use crate::notes::{NOTES_CHUNK_CHARACTERS, NOTES_CHUNK_OVERLAP_CHARACTERS};
+ use crate::notes::{
+ NOTES_CHUNK_OVERLAP_UTF8_BYTES, NOTES_CHUNK_UTF8_BYTES, NOTES_HEADING_MAX_UTF8_BYTES,
+ };
#[test]
fn prepares_and_chunks_markdown() {
@@ -85,22 +95,81 @@ mod tests {
let text = "Γ©".repeat(1_600);
let prepared = prepare_notes_document("unicode.md", text.as_bytes()).unwrap();
assert_eq!(prepared.title, "unicode.md");
- assert_eq!(prepared.chunks.len(), 2);
+ assert_eq!(prepared.chunks.len(), 3);
+ assert!(
+ prepared
+ .chunks
+ .iter()
+ .all(|chunk| chunk.text.len() <= NOTES_CHUNK_UTF8_BYTES)
+ );
+ for pair in prepared.chunks.windows(2) {
+ let overlap_characters = NOTES_CHUNK_OVERLAP_UTF8_BYTES / "Γ©".len();
+ let overlap = pair[0]
+ .text
+ .chars()
+ .rev()
+ .take(overlap_characters)
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .collect::<String>();
+ let next = pair[1]
+ .text
+ .chars()
+ .take(overlap_characters)
+ .collect::<String>();
+ assert!(overlap.len() <= NOTES_CHUNK_OVERLAP_UTF8_BYTES);
+ assert_eq!(overlap, next);
+ }
+ }
+
+ #[test]
+ fn preserves_heading_only_outlines() {
+ let prepared =
+ prepare_notes_document("outline.md", b"# Project\n## Alice\n## Bob\n## Carol\n")
+ .unwrap();
+ assert_eq!(prepared.title, "Project");
+ assert_eq!(prepared.chunks.len(), 3);
assert_eq!(
- prepared.chunks[0].text.chars().count(),
- NOTES_CHUNK_CHARACTERS
+ prepared
+ .chunks
+ .iter()
+ .map(|chunk| chunk.text.as_str())
+ .collect::<Vec<_>>(),
+ ["Alice", "Bob", "Carol"]
);
- assert_eq!(prepared.chunks[1].text.chars().count(), 400);
- let overlap = prepared.chunks[0]
- .text
- .chars()
- .skip(NOTES_CHUNK_CHARACTERS - NOTES_CHUNK_OVERLAP_CHARACTERS)
- .collect::<String>();
- let next = prepared.chunks[1]
- .text
- .chars()
- .take(NOTES_CHUNK_OVERLAP_CHARACTERS)
- .collect::<String>();
- assert_eq!(overlap, next);
+ }
+
+ #[test]
+ fn rejects_controls_that_expand_unboundedly_in_json() {
+ let error = prepare_notes_document("controls.md", b"safe\x1funsafe").unwrap_err();
+ assert!(matches!(error, NotesError::InvalidInput(_)));
+ }
+
+ #[test]
+ fn rejects_headings_above_the_serialization_bound() {
+ let source = format!("# {}\n\nbody", "a".repeat(NOTES_HEADING_MAX_UTF8_BYTES + 1));
+ assert!(matches!(
+ prepare_notes_document("heading.md", source.as_bytes()),
+ Err(NotesError::InvalidInput(_))
+ ));
+ }
+
+ #[test]
+ fn ignores_heading_syntax_until_a_valid_fence_closer() {
+ let source = "```rust\n```not-a-closer\n# Code heading\n```\n# Real title\nbody";
+ let prepared = prepare_notes_document("fenced.md", source.as_bytes()).unwrap();
+ assert_eq!(prepared.title, "Real title");
+ assert!(prepared.chunks.iter().all(|chunk| {
+ chunk.section.as_deref() != Some("Code heading")
+ && !chunk.text.starts_with("Code heading")
+ }));
+ }
+
+ #[test]
+ fn does_not_treat_indented_code_as_a_fence() {
+ let source = " ```\n# Real title\nbody";
+ let prepared = prepare_notes_document("indented.md", source.as_bytes()).unwrap();
+ assert_eq!(prepared.title, "Real title");
}
}
diff --git a/rust/crates/ensu/src/notes/index.rs b/rust/crates/ensu/src/notes/index.rs
index af86845a47..5316c9ef65 100644
--- a/rust/crates/ensu/src/notes/index.rs
+++ b/rust/crates/ensu/src/notes/index.rs
@@ -2,12 +2,12 @@ use std::collections::BTreeMap;
use std::path::Path;
use super::manifest::{collection_directory, load_published_manifest, shard_directory};
-use super::shard::load_and_validate_shard;
+use super::shard::{NotesShardIntegrity, load_and_validate_shard};
use super::{NotesError, validate_collection_id};
-const RELEVANCE_THRESHOLD: f32 = 0.45;
-const MAX_HITS_PER_COLLECTION: usize = 3;
-const MAX_HITS_PER_DOCUMENT: usize = 2;
+const RELEVANCE_THRESHOLD: f32 = 0.50;
+const MAX_HITS_PER_COLLECTION: usize = 5;
+const MAX_HITS_PER_DOCUMENT: usize = 3;
#[derive(Debug, Clone, PartialEq)]
pub struct NotesSearchHit {
@@ -39,7 +39,26 @@ pub struct NotesCollectionIndex {
vectors: Vec<u8>,
}
+pub struct NotesCollectionIndexSummary {
+ pub document_count: usize,
+ pub last_updated_at_ms: Option<i64>,
+}
+
impl NotesCollectionIndex {
+ pub fn inspect(
+ index_root: impl AsRef<Path>,
+ collection_id: String,
+ ) -> Result<NotesCollectionIndexSummary, NotesError> {
+ validate_collection_id(&collection_id)?;
+ let collection_directory = collection_directory(index_root.as_ref(), &collection_id);
+ let (manifest, last_updated_at_ms) =
+ load_published_manifest(&collection_directory, &collection_id, true)?;
+ Ok(NotesCollectionIndexSummary {
+ document_count: manifest.documents.len(),
+ last_updated_at_ms,
+ })
+ }
+
pub fn open(index_root: impl AsRef<Path>, collection_id: String) -> Result<Self, NotesError> {
validate_collection_id(&collection_id)?;
let collection_directory = collection_directory(index_root.as_ref(), &collection_id);
@@ -80,6 +99,10 @@ impl NotesCollectionIndex {
document_id,
&document.revision,
document.chunk_count as usize,
+ NotesShardIntegrity {
+ shard_sha256: &document.shard_sha256,
+ vectors_sha256: &document.vectors_sha256,
+ },
None,
)?;
let title = loaded.shard.title;
@@ -125,6 +148,25 @@ impl NotesCollectionIndex {
self.last_updated_at_ms
}
+ pub fn estimated_heap_bytes(&self) -> usize {
+ self.collection_id
+ .capacity()
+ .saturating_add(
+ self.chunks
+ .capacity()
+ .saturating_mul(std::mem::size_of::<IndexedChunk>()),
+ )
+ .saturating_add(self.vectors.capacity())
+ .saturating_add(self.chunks.iter().fold(0_usize, |total, chunk| {
+ total
+ .saturating_add(chunk.document_id.capacity())
+ .saturating_add(chunk.revision.capacity())
+ .saturating_add(chunk.title.capacity())
+ .saturating_add(chunk.section.as_ref().map_or(0, String::capacity))
+ .saturating_add(chunk.text.capacity())
+ }))
+ }
+
pub fn search(&self, query: &[f32]) -> Result<Vec<NotesSearchHit>, NotesError> {
validate_search(query, self.dimension)?;
let mut ranked = self
diff --git a/rust/crates/ensu/src/notes/indexing.rs b/rust/crates/ensu/src/notes/indexing.rs
new file mode 100644
index 0000000000..6023f3abe3
--- /dev/null
+++ b/rust/crates/ensu/src/notes/indexing.rs
@@ -0,0 +1,492 @@
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use super::{NotesError, NotesIndexWriter, NotesSourceDocument, PreparedNotesDocument};
+
+const INITIAL_CHECKPOINT_DOCUMENTS: usize = 64;
+const INITIAL_CHECKPOINT_CHUNKS: usize = 128;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum NotesDocumentLoad {
+ Prepared {
+ document: PreparedNotesDocument,
+ source: NotesSourceDocument,
+ },
+ Unindexable {
+ source: NotesSourceDocument,
+ },
+ Changed,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum NotesRevisionStatus {
+ Matches { source: NotesSourceDocument },
+ Changed,
+}
+
+struct PreparedSummary {
+ revision_and_chunks: Option<(String, u32)>,
+ source: NotesSourceDocument,
+}
+
+#[derive(Debug)]
+pub enum NotesIndexingError<E> {
+ Notes(NotesError),
+ Adapter(E),
+}
+
+impl<E> From<NotesError> for NotesIndexingError<E> {
+ fn from(error: NotesError) -> Self {
+ Self::Notes(error)
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct NotesIndexInput<'a> {
+ pub index_root: &'a Path,
+ pub collection_id: String,
+ pub inventory: Vec<NotesSourceDocument>,
+ pub forced_document_ids: &'a [String],
+ pub force_full_hash: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct NotesIndexOutcome {
+ pub changed_during_indexing: Option<String>,
+ pub unchecked_document_ids: Vec<String>,
+ pub indexed_document_count: u64,
+}
+
+impl NotesIndexOutcome {
+ pub fn ready(&self) -> bool {
+ self.changed_during_indexing.is_none() && self.indexed_document_count > 0
+ }
+}
+
+pub fn index_notes_collection<E>(
+ input: NotesIndexInput<'_>,
+ mut check_for_cancellation: impl FnMut() -> Result<(), E>,
+ mut load_document: impl FnMut(&str) -> Result<NotesDocumentLoad, E>,
+ mut embed_document: impl FnMut(&PreparedNotesDocument) -> Result<Option<Vec<Vec<f32>>>, E>,
+ mut verify_revision: impl FnMut(&str, &str) -> Result<NotesRevisionStatus, E>,
+ mut on_progress: impl FnMut(u8),
+) -> Result<NotesIndexOutcome, NotesIndexingError<E>> {
+ let NotesIndexInput {
+ index_root,
+ collection_id,
+ inventory,
+ forced_document_ids,
+ force_full_hash,
+ } = input;
+ check_for_cancellation().map_err(NotesIndexingError::Adapter)?;
+ NotesIndexWriter::validate_inventory_capacity(&collection_id, &inventory)?;
+ let mut writer = NotesIndexWriter::open(index_root, collection_id.clone())?;
+ let index_was_ready = writer.initial_inventory_complete();
+ let plan = writer.plan_reconciliation(&inventory, forced_document_ids, force_full_hash)?;
+ writer.commit_deletions(&plan.deleted_document_ids)?;
+
+ let source_document_count = inventory.len() as u64;
+ let requested = plan.content_required_document_ids;
+ let mut prepared_summaries = BTreeMap::<String, PreparedSummary>::new();
+ let mut prepared_chunk_counts = BTreeMap::<String, u32>::new();
+ for document_id in &requested {
+ check_for_cancellation().map_err(NotesIndexingError::Adapter)?;
+ let (prepared, source) =
+ match load_document(document_id).map_err(NotesIndexingError::Adapter)? {
+ NotesDocumentLoad::Prepared { document, source } => (Some(document), source),
+ NotesDocumentLoad::Unindexable { source } => (None, source),
+ NotesDocumentLoad::Changed => {
+ return changed_during_indexing_outcome(
+ &mut writer,
+ index_was_ready,
+ document_id,
+ &requested,
+ 0,
+ );
+ }
+ };
+ if source.document_id != *document_id {
+ return Err(NotesError::InvalidInput(
+ "loaded source metadata does not match its document ID".to_string(),
+ )
+ .into());
+ }
+ let revision_and_chunks = prepared
+ .map(|prepared| {
+ let chunk_count = u32::try_from(prepared.chunks.len()).map_err(|_| {
+ NotesError::CollectionTooLarge(
+ "The folder contains too many note chunks to index".to_string(),
+ )
+ })?;
+ Ok::<_, NotesError>((prepared.revision, chunk_count))
+ })
+ .transpose()?;
+ let chunk_count = revision_and_chunks.as_ref().map_or(0, |(_, count)| *count);
+ prepared_chunk_counts.insert(document_id.clone(), chunk_count);
+ prepared_summaries.insert(
+ document_id.clone(),
+ PreparedSummary {
+ revision_and_chunks,
+ source,
+ },
+ );
+ }
+ let mut verified_inventory = inventory.clone();
+ let inventory_positions = verified_inventory
+ .iter()
+ .enumerate()
+ .map(|(index, source)| (source.document_id.clone(), index))
+ .collect::<BTreeMap<_, _>>();
+ for (document_id, summary) in &prepared_summaries {
+ let index = *inventory_positions
+ .get(document_id)
+ .expect("reconciliation returns a source inventory document");
+ verified_inventory[index] = summary.source.clone();
+ }
+ NotesIndexWriter::validate_inventory_capacity(&collection_id, &verified_inventory)?;
+ writer.validate_reconciliation_capacity(&verified_inventory, &prepared_chunk_counts)?;
+
+ let mut progress_document_count = source_document_count.saturating_sub(requested.len() as u64);
+ on_progress(indexing_progress(
+ progress_document_count,
+ source_document_count,
+ ));
+ let mut processed_requested = 0_usize;
+ let mut embedded_documents = 0_usize;
+ let mut embedded_chunks = 0_usize;
+ let mut next_document_checkpoint = INITIAL_CHECKPOINT_DOCUMENTS;
+ let mut next_chunk_checkpoint = INITIAL_CHECKPOINT_CHUNKS;
+ for document_id in &requested {
+ check_for_cancellation().map_err(NotesIndexingError::Adapter)?;
+ let (prepared, source_metadata) =
+ match load_document(document_id).map_err(NotesIndexingError::Adapter)? {
+ NotesDocumentLoad::Prepared { document, source } => (Some(document), source),
+ NotesDocumentLoad::Unindexable { source } => (None, source),
+ NotesDocumentLoad::Changed => {
+ return changed_during_indexing_outcome(
+ &mut writer,
+ index_was_ready,
+ document_id,
+ &requested,
+ processed_requested,
+ );
+ }
+ };
+ let prepared_matches_preflight =
+ prepared_summaries.get(document_id).is_some_and(|summary| {
+ summary.source == source_metadata
+ && match (&summary.revision_and_chunks, prepared.as_ref()) {
+ (None, None) => true,
+ (Some((revision, chunk_count)), Some(prepared)) => {
+ prepared.revision == *revision
+ && prepared.chunks.len() == *chunk_count as usize
+ }
+ _ => false,
+ }
+ });
+ if !prepared_matches_preflight {
+ return changed_during_indexing_outcome(
+ &mut writer,
+ index_was_ready,
+ document_id,
+ &requested,
+ processed_requested,
+ );
+ }
+ let Some(prepared) = prepared else {
+ writer.commit_deletions(std::slice::from_ref(document_id))?;
+ processed_requested += 1;
+ progress_document_count += 1;
+ on_progress(indexing_progress(
+ progress_document_count,
+ source_document_count,
+ ));
+ continue;
+ };
+ match writer.validate_document(&prepared, &source_metadata) {
+ Ok(()) => {}
+ Err(NotesError::InvalidInput(_)) => {
+ writer.commit_deletions(std::slice::from_ref(document_id))?;
+ processed_requested += 1;
+ progress_document_count += 1;
+ on_progress(indexing_progress(
+ progress_document_count,
+ source_document_count,
+ ));
+ continue;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ let Some(embeddings) = embed_document(&prepared).map_err(NotesIndexingError::Adapter)?
+ else {
+ writer.commit_deletions(std::slice::from_ref(document_id))?;
+ processed_requested += 1;
+ progress_document_count += 1;
+ on_progress(indexing_progress(
+ progress_document_count,
+ source_document_count,
+ ));
+ continue;
+ };
+ check_for_cancellation().map_err(NotesIndexingError::Adapter)?;
+ let NotesRevisionStatus::Matches {
+ source: verified_source,
+ } = verify_revision(document_id, &prepared.revision)
+ .map_err(NotesIndexingError::Adapter)?
+ else {
+ return changed_during_indexing_outcome(
+ &mut writer,
+ index_was_ready,
+ document_id,
+ &requested,
+ processed_requested,
+ );
+ };
+ if verified_source != source_metadata {
+ return changed_during_indexing_outcome(
+ &mut writer,
+ index_was_ready,
+ document_id,
+ &requested,
+ processed_requested,
+ );
+ }
+ writer.commit_document(&prepared, &embeddings, &verified_source)?;
+ processed_requested += 1;
+ progress_document_count += 1;
+ on_progress(indexing_progress(
+ progress_document_count,
+ source_document_count,
+ ));
+ embedded_documents += 1;
+ embedded_chunks += prepared.chunks.len();
+ if processed_requested < requested.len()
+ && (embedded_documents >= next_document_checkpoint
+ || embedded_chunks >= next_chunk_checkpoint)
+ {
+ writer.publish(index_was_ready)?;
+ next_document_checkpoint = next_document_checkpoint.saturating_mul(2);
+ next_chunk_checkpoint = next_chunk_checkpoint.saturating_mul(2);
+ }
+ }
+
+ writer.publish(true)?;
+ Ok(NotesIndexOutcome {
+ changed_during_indexing: None,
+ unchecked_document_ids: Vec::new(),
+ indexed_document_count: writer.indexed_document_ids().count() as u64,
+ })
+}
+
+fn indexing_progress(processed_document_count: u64, source_document_count: u64) -> u8 {
+ if source_document_count == 0 {
+ return 100;
+ }
+ (processed_document_count
+ .min(source_document_count)
+ .saturating_mul(100)
+ / source_document_count) as u8
+}
+
+fn changed_during_indexing_outcome<E>(
+ writer: &mut NotesIndexWriter,
+ index_was_ready: bool,
+ document_id: &str,
+ requested: &[String],
+ processed_requested: usize,
+) -> Result<NotesIndexOutcome, NotesIndexingError<E>> {
+ writer.publish(index_was_ready)?;
+ Ok(NotesIndexOutcome {
+ changed_during_indexing: Some(document_id.to_string()),
+ unchecked_document_ids: requested
+ .iter()
+ .skip(processed_requested)
+ .cloned()
+ .collect(),
+ indexed_document_count: writer.indexed_document_ids().count() as u64,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use std::cell::Cell;
+
+ use super::*;
+ use crate::notes::{NotesCollectionIndex, prepare_notes_document};
+
+ const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
+
+ fn source() -> NotesSourceDocument {
+ source_at(1)
+ }
+
+ fn source_at(modified_at_ms: i64) -> NotesSourceDocument {
+ NotesSourceDocument {
+ document_id: "note.md".to_string(),
+ size: 4,
+ modified_at_ms: Some(modified_at_ms),
+ }
+ }
+
+ fn embedding(prepared: &PreparedNotesDocument) -> Vec<Vec<f32>> {
+ prepared
+ .chunks
+ .iter()
+ .map(|_| {
+ let mut embedding = vec![0.0; 512];
+ embedding[0] = 1.0;
+ embedding
+ })
+ .collect()
+ }
+
+ #[test]
+ fn coordinates_platform_callbacks_and_publishes_the_index() {
+ let temp = tempfile::tempdir().unwrap();
+ let prepared = prepare_notes_document("note.md", b"note").unwrap();
+ let progress = Cell::new(0);
+ let outcome = index_notes_collection::<()>(
+ NotesIndexInput {
+ index_root: temp.path(),
+ collection_id: COLLECTION_ID.to_string(),
+ inventory: vec![source()],
+ forced_document_ids: &[],
+ force_full_hash: false,
+ },
+ || Ok(()),
+ |_| {
+ Ok(NotesDocumentLoad::Prepared {
+ document: prepared.clone(),
+ source: source(),
+ })
+ },
+ |document| Ok(Some(embedding(document))),
+ |_, _| Ok(NotesRevisionStatus::Matches { source: source() }),
+ |value| progress.set(value),
+ )
+ .unwrap();
+
+ assert!(outcome.ready());
+ assert_eq!(progress.get(), 100);
+ assert_eq!(
+ NotesCollectionIndex::open(temp.path(), COLLECTION_ID.to_string())
+ .unwrap()
+ .document_count(),
+ 1
+ );
+ }
+
+ #[test]
+ fn preserves_the_previous_publication_when_a_source_changes() {
+ let temp = tempfile::tempdir().unwrap();
+ let prepared = prepare_notes_document("note.md", b"note").unwrap();
+ let load_count = Cell::new(0);
+ let outcome = index_notes_collection::<()>(
+ NotesIndexInput {
+ index_root: temp.path(),
+ collection_id: COLLECTION_ID.to_string(),
+ inventory: vec![source()],
+ forced_document_ids: &[],
+ force_full_hash: false,
+ },
+ || Ok(()),
+ |_| {
+ load_count.set(load_count.get() + 1);
+ Ok(if load_count.get() == 1 {
+ NotesDocumentLoad::Prepared {
+ document: prepared.clone(),
+ source: source(),
+ }
+ } else {
+ NotesDocumentLoad::Changed
+ })
+ },
+ |document| Ok(Some(embedding(document))),
+ |_, _| Ok(NotesRevisionStatus::Matches { source: source() }),
+ |_| {},
+ )
+ .unwrap();
+
+ assert_eq!(outcome.changed_during_indexing.as_deref(), Some("note.md"));
+ assert_eq!(outcome.unchecked_document_ids, ["note.md"]);
+ assert!(matches!(
+ NotesCollectionIndex::open(temp.path(), COLLECTION_ID.to_string()),
+ Err(NotesError::NotReady)
+ ));
+ }
+
+ #[test]
+ fn commits_metadata_from_the_verified_source_reads() {
+ let temp = tempfile::tempdir().unwrap();
+ let prepared = prepare_notes_document("note.md", b"note").unwrap();
+ let verified_source = source_at(2);
+ let outcome = index_notes_collection::<()>(
+ NotesIndexInput {
+ index_root: temp.path(),
+ collection_id: COLLECTION_ID.to_string(),
+ inventory: vec![source_at(1)],
+ forced_document_ids: &[],
+ force_full_hash: false,
+ },
+ || Ok(()),
+ |_| {
+ Ok(NotesDocumentLoad::Prepared {
+ document: prepared.clone(),
+ source: verified_source.clone(),
+ })
+ },
+ |document| Ok(Some(embedding(document))),
+ |_, _| {
+ Ok(NotesRevisionStatus::Matches {
+ source: verified_source.clone(),
+ })
+ },
+ |_| {},
+ )
+ .unwrap();
+
+ assert!(outcome.ready());
+ let writer = NotesIndexWriter::open(temp.path(), COLLECTION_ID.to_string()).unwrap();
+ assert!(
+ writer
+ .plan_reconciliation(&[verified_source], &[], false)
+ .unwrap()
+ .is_up_to_date()
+ );
+ }
+
+ #[test]
+ fn stops_before_embedding_when_source_metadata_changes_after_preflight() {
+ let temp = tempfile::tempdir().unwrap();
+ let prepared = prepare_notes_document("note.md", b"note").unwrap();
+ let load_count = Cell::new(0);
+ let embed_count = Cell::new(0);
+ let outcome = index_notes_collection::<()>(
+ NotesIndexInput {
+ index_root: temp.path(),
+ collection_id: COLLECTION_ID.to_string(),
+ inventory: vec![source()],
+ forced_document_ids: &[],
+ force_full_hash: false,
+ },
+ || Ok(()),
+ |_| {
+ load_count.set(load_count.get() + 1);
+ Ok(NotesDocumentLoad::Prepared {
+ document: prepared.clone(),
+ source: source_at(load_count.get()),
+ })
+ },
+ |_| {
+ embed_count.set(embed_count.get() + 1);
+ Ok(Some(embedding(&prepared)))
+ },
+ |_, _| Ok(NotesRevisionStatus::Matches { source: source() }),
+ |_| {},
+ )
+ .unwrap();
+
+ assert_eq!(outcome.changed_during_indexing.as_deref(), Some("note.md"));
+ assert_eq!(embed_count.get(), 0);
+ }
+}
diff --git a/rust/crates/ensu/src/notes/manifest.rs b/rust/crates/ensu/src/notes/manifest.rs
index bad230887d..1e1901e437 100644
--- a/rust/crates/ensu/src/notes/manifest.rs
+++ b/rust/crates/ensu/src/notes/manifest.rs
@@ -8,14 +8,15 @@ use serde::{Deserialize, Serialize};
use crate::config::knowledge_index_contract;
use super::{
- NOTES_INDEX_CONTRACT_VERSION, NOTES_MAX_SOURCE_BYTES, NotesError, invalid_index_input,
- sha256_hex, validate_collection_id, validate_document_id, validate_revision,
+ NOTES_INDEX_CONTRACT_VERSION, NOTES_MAX_COLLECTION_CHUNKS, NOTES_MAX_COLLECTION_SOURCE_BYTES,
+ NOTES_MAX_SOURCE_BYTES, NotesError, invalid_index_input, sha256_hex, validate_collection_id,
+ validate_document_id, validate_revision,
};
pub(super) const NOTES_MANIFEST_FILE: &str = "manifest.json";
pub(super) const NOTES_MANIFEST_BACKUP_FILE: &str = "manifest.json.backup";
pub(super) const NOTES_DOCUMENTS_DIRECTORY: &str = "documents";
-const NOTES_MANIFEST_SCHEMA_VERSION: u32 = 1;
+const NOTES_MANIFEST_SCHEMA_VERSION: u32 = 2;
const MAX_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -62,6 +63,10 @@ pub(super) struct NotesManifestDocument {
pub(super) source_size: u64,
pub(super) source_modified_at_ms: Option<i64>,
pub(super) chunk_count: u32,
+ #[serde(default)]
+ pub(super) shard_sha256: String,
+ #[serde(default)]
+ pub(super) vectors_sha256: String,
}
pub(super) fn empty_manifest(collection_id: &str) -> NotesManifest {
@@ -114,9 +119,13 @@ pub(super) fn validate_manifest(
return Err(NotesError::NotReady);
}
+ let mut total_source_bytes = 0_u64;
+ let mut total_chunks = 0_u64;
for (document_id, document) in &manifest.documents {
validate_document_id(document_id).map_err(invalid_index_input)?;
validate_revision(&document.revision).map_err(invalid_index_input)?;
+ validate_revision(&document.shard_sha256).map_err(invalid_index_input)?;
+ validate_revision(&document.vectors_sha256).map_err(invalid_index_input)?;
if document.source_size > NOTES_MAX_SOURCE_BYTES as u64 {
return Err(NotesError::InvalidIndex(
"manifest source size exceeds the supported limit".to_string(),
@@ -129,10 +138,42 @@ pub(super) fn validate_manifest(
"manifest document chunk count is invalid".to_string(),
));
}
+ total_source_bytes = total_source_bytes
+ .checked_add(document.source_size)
+ .ok_or_else(|| {
+ NotesError::InvalidIndex("collection source byte count overflow".to_string())
+ })?;
+ total_chunks = total_chunks
+ .checked_add(u64::from(document.chunk_count))
+ .ok_or_else(|| {
+ NotesError::InvalidIndex("collection chunk count overflow".to_string())
+ })?;
+ }
+ if total_source_bytes > NOTES_MAX_COLLECTION_SOURCE_BYTES
+ || total_chunks > NOTES_MAX_COLLECTION_CHUNKS
+ {
+ return Err(NotesError::InvalidIndex(
+ "collection exceeds the supported aggregate index size".to_string(),
+ ));
}
Ok(())
}
+pub(super) fn serialize_manifest_for_publish(
+ manifest: &NotesManifest,
+ collection_id: &str,
+) -> Result<Vec<u8>, NotesError> {
+ validate_manifest(manifest, collection_id, false)?;
+ let mut bytes = serde_json::to_vec_pretty(manifest)?;
+ bytes.push(b'\n');
+ if bytes.len() as u64 > MAX_MANIFEST_BYTES {
+ return Err(NotesError::CollectionTooLarge(
+ "The folder contains too many notes to index".to_string(),
+ ));
+ }
+ Ok(bytes)
+}
+
pub(super) fn load_manifest_file(
path: &Path,
collection_id: &str,
diff --git a/rust/crates/ensu/src/notes/shard.rs b/rust/crates/ensu/src/notes/shard.rs
index db9ae2f8f2..26cc06730a 100644
--- a/rust/crates/ensu/src/notes/shard.rs
+++ b/rust/crates/ensu/src/notes/shard.rs
@@ -5,8 +5,9 @@ use serde::{Deserialize, Serialize};
use super::manifest::notes_index_contract;
use super::{
- NOTES_CHUNK_CHARACTERS, NotesError, PreparedNotesDocument, invalid_index_input, is_valid_label,
- validate_collection_id, validate_document_id, validate_revision,
+ NOTES_CHUNK_UTF8_BYTES, NotesError, PreparedNotesDocument, contains_unsupported_control,
+ invalid_index_input, is_valid_label, sha256_hex, validate_collection_id, validate_document_id,
+ validate_revision,
};
pub(super) const NOTES_SHARD_FILE: &str = "shard.json";
@@ -33,6 +34,12 @@ pub(super) struct ValidatedNotesShard {
pub vectors: Vec<u8>,
}
+#[derive(Clone, Copy)]
+pub(super) struct NotesShardIntegrity<'a> {
+ pub shard_sha256: &'a str,
+ pub vectors_sha256: &'a str,
+}
+
impl NotesShard {
pub(super) fn from_prepared(collection_id: &str, prepared: &PreparedNotesDocument) -> Self {
Self {
@@ -52,14 +59,27 @@ impl NotesShard {
}
}
+pub(super) fn serialize_shard(shard: &NotesShard) -> Result<Vec<u8>, NotesError> {
+ let bytes = serde_json::to_vec(shard)?;
+ if bytes.is_empty() || bytes.len() as u64 > MAX_SHARD_JSON_BYTES {
+ return Err(NotesError::InvalidInput(
+ "serialized shard metadata exceeds the supported size".to_string(),
+ ));
+ }
+ Ok(bytes)
+}
+
pub(super) fn load_and_validate_shard(
directory: &Path,
collection_id: &str,
expected_document_id: &str,
expected_revision: &str,
expected_chunk_count: usize,
+ expected_integrity: NotesShardIntegrity<'_>,
expected_prepared: Option<&PreparedNotesDocument>,
) -> Result<ValidatedNotesShard, NotesError> {
+ validate_revision(expected_integrity.shard_sha256).map_err(invalid_index_input)?;
+ validate_revision(expected_integrity.vectors_sha256).map_err(invalid_index_input)?;
let directory_metadata = fs::symlink_metadata(directory)?;
if !directory_metadata.file_type().is_dir() {
return Err(NotesError::InvalidIndex(
@@ -74,7 +94,15 @@ pub(super) fn load_and_validate_shard(
"shard metadata size is outside the supported range".to_string(),
));
}
- let shard: NotesShard = serde_json::from_slice(&fs::read(shard_path)?)?;
+ let shard_bytes = fs::read(shard_path)?;
+ if shard_bytes.len() as u64 != shard_metadata.len()
+ || sha256_hex(&shard_bytes) != expected_integrity.shard_sha256
+ {
+ return Err(NotesError::InvalidIndex(
+ "shard metadata digest does not match its manifest".to_string(),
+ ));
+ }
+ let shard: NotesShard = serde_json::from_slice(&shard_bytes)?;
validate_shard(
&shard,
collection_id,
@@ -93,15 +121,20 @@ pub(super) fn load_and_validate_shard(
.len()
.checked_mul(vector_dimension)
.ok_or_else(|| NotesError::InvalidIndex("shard vector byte length overflow".to_string()))?;
- if vector_metadata.len() != expected_vector_bytes as u64 {
+ let vectors = fs::read(vectors_path)?;
+ if vector_metadata.len() != expected_vector_bytes as u64
+ || vectors.len() != expected_vector_bytes
+ {
return Err(NotesError::InvalidIndex(
"shard vector byte length does not match its metadata".to_string(),
));
}
- Ok(ValidatedNotesShard {
- shard,
- vectors: fs::read(vectors_path)?,
- })
+ if sha256_hex(&vectors) != expected_integrity.vectors_sha256 {
+ return Err(NotesError::InvalidIndex(
+ "shard vector digest does not match its manifest".to_string(),
+ ));
+ }
+ Ok(ValidatedNotesShard { shard, vectors })
}
fn validate_shard(
@@ -134,7 +167,10 @@ fn validate_shard(
));
}
for chunk in &shard.chunks {
- if chunk.text.trim().is_empty() || chunk.text.chars().count() > NOTES_CHUNK_CHARACTERS {
+ if chunk.text.trim().is_empty()
+ || chunk.text.len() > NOTES_CHUNK_UTF8_BYTES
+ || contains_unsupported_control(&chunk.text)
+ {
return Err(NotesError::InvalidIndex(
"shard chunk text length is outside the supported range".to_string(),
));
diff --git a/rust/crates/ensu/src/notes/writer.rs b/rust/crates/ensu/src/notes/writer.rs
index 437b1474c4..2944c62563 100644
--- a/rust/crates/ensu/src/notes/writer.rs
+++ b/rust/crates/ensu/src/notes/writer.rs
@@ -10,14 +10,18 @@ use uuid::Uuid;
use super::manifest::{
NOTES_DOCUMENTS_DIRECTORY, NOTES_MANIFEST_BACKUP_FILE, NOTES_MANIFEST_FILE, NotesManifest,
NotesManifestDocument, collection_directory, empty_manifest, load_manifest_file,
- notes_index_contract, shard_directory, validate_manifest,
+ notes_index_contract, serialize_manifest_for_publish, shard_directory,
};
use super::reconcile::{IndexedNotesDocument, plan_notes_reconciliation};
-use super::shard::{NOTES_SHARD_FILE, NOTES_VECTORS_FILE, NotesShard, load_and_validate_shard};
+use super::shard::{
+ NOTES_SHARD_FILE, NOTES_VECTORS_FILE, NotesShard, NotesShardIntegrity, load_and_validate_shard,
+ serialize_shard,
+};
use super::{
- NOTES_CHUNK_CHARACTERS, NotesError, NotesReconciliationPlan, NotesSourceDocument,
- PreparedNotesDocument, is_valid_label, validate_collection_id, validate_document_id,
- validate_revision,
+ NOTES_CHUNK_UTF8_BYTES, NOTES_MAX_COLLECTION_CHUNKS, NOTES_MAX_COLLECTION_DOCUMENTS,
+ NOTES_MAX_COLLECTION_SOURCE_BYTES, NotesError, NotesReconciliationPlan, NotesSourceDocument,
+ PreparedNotesDocument, contains_unsupported_control, is_valid_label, sha256_hex,
+ validate_collection_id, validate_document_id, validate_revision,
};
pub struct NotesIndexWriter {
@@ -27,6 +31,91 @@ pub struct NotesIndexWriter {
}
impl NotesIndexWriter {
+ pub fn validate_inventory_capacity(
+ collection_id: &str,
+ inventory: &[NotesSourceDocument],
+ ) -> Result<(), NotesError> {
+ validate_collection_id(collection_id)?;
+ if inventory.len() > NOTES_MAX_COLLECTION_DOCUMENTS {
+ return Err(NotesError::CollectionTooLarge(
+ "The folder contains too many notes to index".to_string(),
+ ));
+ }
+ let total_source_bytes = inventory.iter().try_fold(0_u64, |total, source| {
+ source.validate()?;
+ total
+ .checked_add(source.size)
+ .ok_or_else(source_content_too_large)
+ })?;
+ ensure_collection_capacity(total_source_bytes, 0)?;
+ let digest = "a".repeat(64);
+ let mut manifest = empty_manifest(collection_id);
+ for source in inventory {
+ manifest.documents.insert(
+ source.document_id.clone(),
+ NotesManifestDocument {
+ revision: digest.clone(),
+ source_size: source.size,
+ source_modified_at_ms: source.modified_at_ms,
+ chunk_count: 1,
+ shard_sha256: digest.clone(),
+ vectors_sha256: digest.clone(),
+ },
+ );
+ }
+ serialize_manifest_for_publish(&manifest, collection_id).map(|_| ())
+ }
+
+ pub fn validate_reconciliation_capacity(
+ &self,
+ inventory: &[NotesSourceDocument],
+ prepared_chunk_counts: &BTreeMap<String, u32>,
+ ) -> Result<(), NotesError> {
+ let digest = "a".repeat(64);
+ let mut manifest = empty_manifest(&self.collection_id);
+ let mut source_bytes = 0_u64;
+ let mut chunks = 0_u64;
+ for source in inventory {
+ source.validate()?;
+ let chunk_count = prepared_chunk_counts
+ .get(&source.document_id)
+ .copied()
+ .or_else(|| {
+ self.manifest
+ .documents
+ .get(&source.document_id)
+ .map(|document| document.chunk_count)
+ })
+ .ok_or_else(|| {
+ NotesError::InvalidInput(
+ "source document has no prepared or indexed chunk count".to_string(),
+ )
+ })?;
+ if chunk_count == 0 {
+ continue;
+ }
+ source_bytes = source_bytes
+ .checked_add(source.size)
+ .ok_or_else(source_content_too_large)?;
+ chunks = chunks
+ .checked_add(u64::from(chunk_count))
+ .ok_or_else(chunk_count_too_large)?;
+ manifest.documents.insert(
+ source.document_id.clone(),
+ NotesManifestDocument {
+ revision: digest.clone(),
+ source_size: source.size,
+ source_modified_at_ms: source.modified_at_ms,
+ chunk_count,
+ shard_sha256: digest.clone(),
+ vectors_sha256: digest.clone(),
+ },
+ );
+ }
+ ensure_collection_capacity(source_bytes, chunks)?;
+ serialize_manifest_for_publish(&manifest, &self.collection_id).map(|_| ())
+ }
+
pub fn open(index_root: impl AsRef<Path>, collection_id: String) -> Result<Self, NotesError> {
validate_collection_id(&collection_id)?;
ensure_directory(index_root.as_ref())?;
@@ -57,6 +146,13 @@ impl NotesIndexWriter {
self.manifest.documents.keys().map(String::as_str)
}
+ pub fn indexed_revision(&self, document_id: &str) -> Option<&str> {
+ self.manifest
+ .documents
+ .get(document_id)
+ .map(|document| document.revision.as_str())
+ }
+
pub fn plan_reconciliation(
&self,
inventory: &[NotesSourceDocument],
@@ -83,7 +179,7 @@ impl NotesIndexWriter {
embeddings: &[Vec<f32>],
source_metadata: &NotesSourceDocument,
) -> Result<(), NotesError> {
- validate_prepared_document(prepared, source_metadata)?;
+ self.validate_document(prepared, source_metadata)?;
if embeddings.len() != prepared.chunks.len() {
return Err(NotesError::InvalidInput(
"embedding count does not match prepared chunks".to_string(),
@@ -114,6 +210,10 @@ impl NotesIndexWriter {
.clamp(-scale, scale) as i8 as u8
}));
}
+ let shard = NotesShard::from_prepared(&self.collection_id, prepared);
+ let shard_bytes = serialize_shard(&shard)?;
+ let shard_sha256 = sha256_hex(&shard_bytes);
+ let vectors_sha256 = sha256_hex(&vector_bytes);
let final_directory = shard_directory(
&self.collection_directory,
@@ -127,10 +227,19 @@ impl NotesIndexWriter {
&prepared.document_id,
&prepared.revision,
prepared.chunks.len(),
+ NotesShardIntegrity {
+ shard_sha256: &shard_sha256,
+ vectors_sha256: &vectors_sha256,
+ },
Some(prepared),
) {
Ok(_) => {
- self.activate_document(prepared, source_metadata)?;
+ self.activate_document(
+ prepared,
+ source_metadata,
+ &shard_sha256,
+ &vectors_sha256,
+ )?;
return Ok(());
}
Err(
@@ -153,11 +262,7 @@ impl NotesIndexWriter {
));
fs::create_dir(&temporary_directory)?;
let write_result = (|| {
- let shard = NotesShard::from_prepared(&self.collection_id, prepared);
- write_new_file(
- &temporary_directory.join(NOTES_SHARD_FILE),
- &serde_json::to_vec(&shard)?,
- )?;
+ write_new_file(&temporary_directory.join(NOTES_SHARD_FILE), &shard_bytes)?;
write_new_file(&temporary_directory.join(NOTES_VECTORS_FILE), &vector_bytes)?;
load_and_validate_shard(
&temporary_directory,
@@ -165,6 +270,10 @@ impl NotesIndexWriter {
&prepared.document_id,
&prepared.revision,
prepared.chunks.len(),
+ NotesShardIntegrity {
+ shard_sha256: &shard_sha256,
+ vectors_sha256: &vectors_sha256,
+ },
Some(prepared),
)?;
match fs::rename(&temporary_directory, &final_directory) {
@@ -176,6 +285,10 @@ impl NotesIndexWriter {
&prepared.document_id,
&prepared.revision,
prepared.chunks.len(),
+ NotesShardIntegrity {
+ shard_sha256: &shard_sha256,
+ vectors_sha256: &vectors_sha256,
+ },
Some(prepared),
)?;
Ok(())
@@ -187,7 +300,43 @@ impl NotesIndexWriter {
let _ = remove_owned_entry(&temporary_directory);
}
write_result?;
- self.activate_document(prepared, source_metadata)
+ self.activate_document(prepared, source_metadata, &shard_sha256, &vectors_sha256)
+ }
+
+ pub fn validate_document(
+ &self,
+ prepared: &PreparedNotesDocument,
+ source_metadata: &NotesSourceDocument,
+ ) -> Result<(), NotesError> {
+ validate_prepared_document(prepared, source_metadata)?;
+ let (existing_source_bytes, existing_chunks) = self
+ .manifest
+ .documents
+ .iter()
+ .filter(|(document_id, _)| *document_id != &prepared.document_id)
+ .try_fold(
+ (0_u64, 0_u64),
+ |(source_total, chunk_total), (_, document)| {
+ let source_total = source_total
+ .checked_add(document.source_size)
+ .ok_or_else(source_content_too_large)?;
+ let chunk_total = chunk_total
+ .checked_add(u64::from(document.chunk_count))
+ .ok_or_else(chunk_count_too_large)?;
+ Ok::<_, NotesError>((source_total, chunk_total))
+ },
+ )?;
+ let source_bytes = existing_source_bytes
+ .checked_add(source_metadata.size)
+ .ok_or_else(source_content_too_large)?;
+ let chunk_count =
+ u64::try_from(prepared.chunks.len()).map_err(|_| chunk_count_too_large())?;
+ let chunks = existing_chunks
+ .checked_add(chunk_count)
+ .ok_or_else(chunk_count_too_large)?;
+ ensure_collection_capacity(source_bytes, chunks)?;
+ serialize_shard(&NotesShard::from_prepared(&self.collection_id, prepared))?;
+ Ok(())
}
pub fn commit_deletions(&mut self, document_ids: &[String]) -> Result<(), NotesError> {
@@ -200,7 +349,6 @@ impl NotesIndexWriter {
pub fn publish(&mut self, initial_complete: bool) -> Result<(), NotesError> {
self.manifest.initial_inventory_complete = initial_complete;
- validate_manifest(&self.manifest, &self.collection_id, false)?;
publish_manifest_atomically(
&self.collection_directory,
&self.manifest,
@@ -214,7 +362,11 @@ impl NotesIndexWriter {
&mut self,
prepared: &PreparedNotesDocument,
source_metadata: &NotesSourceDocument,
+ shard_sha256: &str,
+ vectors_sha256: &str,
) -> Result<(), NotesError> {
+ validate_revision(shard_sha256)?;
+ validate_revision(vectors_sha256)?;
let chunk_count = u32::try_from(prepared.chunks.len()).map_err(|_| {
NotesError::InvalidInput("prepared document has too many chunks".to_string())
})?;
@@ -225,12 +377,32 @@ impl NotesIndexWriter {
source_size: source_metadata.size,
source_modified_at_ms: source_metadata.modified_at_ms,
chunk_count,
+ shard_sha256: shard_sha256.to_string(),
+ vectors_sha256: vectors_sha256.to_string(),
},
);
Ok(())
}
}
+fn ensure_collection_capacity(source_bytes: u64, chunks: u64) -> Result<(), NotesError> {
+ if source_bytes > NOTES_MAX_COLLECTION_SOURCE_BYTES {
+ return Err(source_content_too_large());
+ }
+ if chunks > NOTES_MAX_COLLECTION_CHUNKS {
+ return Err(chunk_count_too_large());
+ }
+ Ok(())
+}
+
+fn source_content_too_large() -> NotesError {
+ NotesError::CollectionTooLarge("The folder contains too much note content to index".to_string())
+}
+
+fn chunk_count_too_large() -> NotesError {
+ NotesError::CollectionTooLarge("The folder contains too many note chunks to index".to_string())
+}
+
fn validate_prepared_document(
prepared: &PreparedNotesDocument,
source_metadata: &NotesSourceDocument,
@@ -263,7 +435,10 @@ fn validate_prepared_document(
"prepared chunk section is invalid".to_string(),
));
}
- if chunk.text.trim().is_empty() || chunk.text.chars().count() > NOTES_CHUNK_CHARACTERS {
+ if chunk.text.trim().is_empty()
+ || chunk.text.len() > NOTES_CHUNK_UTF8_BYTES
+ || contains_unsupported_control(&chunk.text)
+ {
return Err(NotesError::InvalidInput(
"prepared chunk text is invalid".to_string(),
));
@@ -317,8 +492,7 @@ fn publish_manifest_atomically(
}
let temporary_path =
collection_directory.join(format!(".manifest.tmp-{}", Uuid::new_v4().hyphenated()));
- let mut bytes = serde_json::to_vec_pretty(manifest)?;
- bytes.push(b'\n');
+ let bytes = serialize_manifest_for_publish(manifest, collection_id)?;
write_new_file(&temporary_path, &bytes)?;
load_manifest_file(&temporary_path, collection_id, false)?;
@@ -420,7 +594,7 @@ fn remove_owned_entry(path: &Path) -> Result<(), NotesError> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::notes::{NotesCollectionIndex, prepare_notes_document};
+ use crate::notes::{NOTES_MAX_SOURCE_BYTES, NotesCollectionIndex, prepare_notes_document};
fn collection() -> String {
"123e4567-e89b-12d3-a456-426614174000".to_string()
@@ -450,6 +624,20 @@ mod tests {
.collect()
}
+ fn publish_ready_manifest(index_root: &Path) -> PathBuf {
+ let document = prepared("note.md", "note");
+ let mut writer = NotesIndexWriter::open(index_root, collection()).unwrap();
+ writer
+ .commit_document(
+ &document,
+ &embeddings(&document, &[1.0]),
+ &metadata(&document, 4),
+ )
+ .unwrap();
+ writer.publish(true).unwrap();
+ collection_directory(index_root, &collection())
+ }
+
#[test]
fn writes_opens_and_searches_documents() {
let temp = tempfile::tempdir().unwrap();
@@ -483,5 +671,151 @@ mod tests {
assert_eq!(hits[0].document_id, "first.md");
assert_eq!(hits[1].document_id, "second.md");
assert!(hits[0].score > hits[1].score);
+
+ let vectors_path = shard_directory(
+ &collection_directory(temp.path(), &collection()),
+ &first.document_id,
+ &first.revision,
+ )
+ .join(NOTES_VECTORS_FILE);
+ let mut corrupted = fs::read(&vectors_path).unwrap();
+ corrupted[0] ^= 1;
+ fs::write(vectors_path, corrupted).unwrap();
+ assert!(matches!(
+ NotesCollectionIndex::open(temp.path(), collection()),
+ Err(NotesError::InvalidIndex(_))
+ ));
+ }
+
+ #[test]
+ fn maximum_supported_sources_fit_a_shard() {
+ let heading = "\\".repeat(crate::notes::NOTES_HEADING_MAX_UTF8_BYTES);
+ let prefix = format!("## {heading}\n");
+ let temp = tempfile::tempdir().unwrap();
+ let writer = NotesIndexWriter::open(temp.path(), collection()).unwrap();
+ for unit in ["\\", "πŸ˜€"] {
+ let remaining = NOTES_MAX_SOURCE_BYTES - prefix.len();
+ assert_eq!(remaining % unit.len(), 0);
+ let source = format!("{prefix}{}", unit.repeat(remaining / unit.len()));
+ assert_eq!(source.len(), NOTES_MAX_SOURCE_BYTES);
+ let prepared = prepare_notes_document("maximum.md", source.as_bytes()).unwrap();
+ let metadata = metadata(&prepared, source.len());
+ writer.validate_document(&prepared, &metadata).unwrap();
+ }
+ validate_maximum_source_with_many_small_sections();
+ }
+
+ fn validate_maximum_source_with_many_small_sections() {
+ let unit = "## \\\n\\\n";
+ let source = unit.repeat(NOTES_MAX_SOURCE_BYTES / unit.len());
+ assert!(source.len() <= NOTES_MAX_SOURCE_BYTES);
+ let prepared = prepare_notes_document("many-sections.md", source.as_bytes()).unwrap();
+ let metadata = metadata(&prepared, source.len());
+ let temp = tempfile::tempdir().unwrap();
+ let writer = NotesIndexWriter::open(temp.path(), collection()).unwrap();
+ writer.validate_document(&prepared, &metadata).unwrap();
+ }
+
+ #[test]
+ fn rejects_an_inventory_that_cannot_fit_the_manifest_before_indexing() {
+ let inventory = (0..25_000)
+ .map(|index| NotesSourceDocument {
+ document_id: format!("note-{index:05}.md"),
+ size: 1,
+ modified_at_ms: Some(1),
+ })
+ .collect::<Vec<_>>();
+ NotesIndexWriter::validate_inventory_capacity(&collection(), &inventory[..20_000]).unwrap();
+ assert!(matches!(
+ NotesIndexWriter::validate_inventory_capacity(&collection(), &inventory),
+ Err(NotesError::CollectionTooLarge(_))
+ ));
+ }
+
+ #[test]
+ fn rejects_aggregate_source_content_before_indexing() {
+ let supported_count = NOTES_MAX_COLLECTION_SOURCE_BYTES / NOTES_MAX_SOURCE_BYTES as u64;
+ let inventory = (0..=supported_count)
+ .map(|index| NotesSourceDocument {
+ document_id: format!("note-{index:03}.md"),
+ size: NOTES_MAX_SOURCE_BYTES as u64,
+ modified_at_ms: Some(1),
+ })
+ .collect::<Vec<_>>();
+ NotesIndexWriter::validate_inventory_capacity(
+ &collection(),
+ &inventory[..supported_count as usize],
+ )
+ .unwrap();
+ assert!(matches!(
+ NotesIndexWriter::validate_inventory_capacity(&collection(), &inventory),
+ Err(NotesError::CollectionTooLarge(_))
+ ));
+ }
+
+ #[test]
+ fn rejects_exact_aggregate_chunks_before_embedding() {
+ let inventory = (0..129)
+ .map(|index| NotesSourceDocument {
+ document_id: format!("note-{index:03}.md"),
+ size: 7_168,
+ modified_at_ms: Some(1),
+ })
+ .collect::<Vec<_>>();
+ NotesIndexWriter::validate_inventory_capacity(&collection(), &inventory).unwrap();
+ let prepared_chunk_counts = inventory
+ .iter()
+ .map(|source| (source.document_id.clone(), 1_024))
+ .collect::<BTreeMap<_, _>>();
+ let temp = tempfile::tempdir().unwrap();
+ let writer = NotesIndexWriter::open(temp.path(), collection()).unwrap();
+
+ assert!(matches!(
+ writer.validate_reconciliation_capacity(&inventory, &prepared_chunk_counts),
+ Err(NotesError::CollectionTooLarge(_))
+ ));
+ }
+
+ #[test]
+ fn recovers_interrupted_manifest_publications() {
+ let backup_only = tempfile::tempdir().unwrap();
+ let directory = publish_ready_manifest(backup_only.path());
+ let active = directory.join(NOTES_MANIFEST_FILE);
+ let backup = directory.join(NOTES_MANIFEST_BACKUP_FILE);
+ fs::rename(&active, &backup).unwrap();
+ recover_manifest_publication(&directory, &collection()).unwrap();
+ assert!(active.is_file());
+ assert!(!backup.exists());
+
+ let valid_active = tempfile::tempdir().unwrap();
+ let directory = publish_ready_manifest(valid_active.path());
+ let active = directory.join(NOTES_MANIFEST_FILE);
+ let backup = directory.join(NOTES_MANIFEST_BACKUP_FILE);
+ let temporary = directory.join(".manifest.tmp-abandoned");
+ fs::copy(&active, &backup).unwrap();
+ fs::write(&temporary, b"incomplete").unwrap();
+ let expected = fs::read(&active).unwrap();
+ recover_manifest_publication(&directory, &collection()).unwrap();
+ assert_eq!(fs::read(&active).unwrap(), expected);
+ assert!(!backup.exists());
+ assert!(!temporary.exists());
+
+ let corrupt_active = tempfile::tempdir().unwrap();
+ let directory = publish_ready_manifest(corrupt_active.path());
+ let active = directory.join(NOTES_MANIFEST_FILE);
+ let backup = directory.join(NOTES_MANIFEST_BACKUP_FILE);
+ let expected = fs::read(&active).unwrap();
+ fs::copy(&active, &backup).unwrap();
+ fs::write(&active, b"not a manifest").unwrap();
+ recover_manifest_publication(&directory, &collection()).unwrap();
+ assert_eq!(fs::read(&active).unwrap(), expected);
+ assert!(!backup.exists());
+
+ let invalid_backup = tempfile::tempdir().unwrap();
+ let directory = invalid_backup.path().join(collection());
+ fs::create_dir_all(&directory).unwrap();
+ fs::write(directory.join(NOTES_MANIFEST_BACKUP_FILE), b"invalid").unwrap();
+ assert!(recover_manifest_publication(&directory, &collection()).is_err());
+ assert!(!directory.join(NOTES_MANIFEST_FILE).exists());
}
}
diff --git a/rust/crates/ensu/src/retrieval.rs b/rust/crates/ensu/src/retrieval.rs
index ee68ae4d44..494cd15a5b 100644
--- a/rust/crates/ensu/src/retrieval.rs
+++ b/rust/crates/ensu/src/retrieval.rs
@@ -40,13 +40,13 @@ const BEGIN_CONTEXT_SENTINEL: &str = "----- BEGIN KNOWLEDGE CONTEXT -----";
const END_CONTEXT_SENTINEL: &str = "----- END KNOWLEDGE CONTEXT -----";
pub use citation::{
- ParsedAssistantText, ParsedGroundedAssistantText, SourceCitation, clean_assistant_text,
- finalize_assistant_text, finalize_grounded_assistant_text, knowledge_source_chip_label,
- parse_assistant_text, parse_grounded_assistant_text,
+ MAX_GROUNDED_SOURCES, ParsedAssistantText, ParsedGroundedAssistantText, SourceCitation,
+ clean_assistant_text, finalize_assistant_text, finalize_grounded_assistant_text,
+ knowledge_source_chip_label, parse_assistant_text, parse_grounded_assistant_text,
};
pub use grounded::{
- GroundedExcerpt, GroundedPromptContext, GroundedSource, build_grounded_prompt_context,
- select_mixed_grounding,
+ GroundedExcerpt, GroundedPromptContext, GroundedSource, MAX_NOTES_GROUNDING_HITS,
+ build_grounded_prompt_context, select_mixed_grounding_candidates,
};
pub use index::{RetrievalHit, RetrievalIndex};
pub use pack::{
diff --git a/rust/crates/ensu/src/retrieval/citation.rs b/rust/crates/ensu/src/retrieval/citation.rs
index b6d8d16983..620a4fb24c 100644
--- a/rust/crates/ensu/src/retrieval/citation.rs
+++ b/rust/crates/ensu/src/retrieval/citation.rs
@@ -17,6 +17,7 @@ const MIXED_END_SENTINEL: &str = "----- END ENSU GROUNDED SOURCES -----";
const MIXED_SOURCES_PREFIX: &str = "Sources: ";
const LICENSE_HEADER: &str =
"Adapted sources Β· CC BY-SA 4.0: https://creativecommons.org/licenses/by-sa/4.0/";
+pub const MAX_GROUNDED_SOURCES: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -46,6 +47,11 @@ pub fn finalize_assistant_text(
raw_assistant_text: &str,
citations: &[SourceCitation],
) -> Result<String, RetrievalError> {
+ if citations.len() > MAX_GROUNDED_SOURCES {
+ return Err(RetrievalError::InvalidInput(
+ "too many grounded sources".to_string(),
+ ));
+ }
let assistant_text = neutralize_model_sentinels(raw_assistant_text.trim());
if assistant_text.is_empty() || citations.is_empty() {
return Ok(assistant_text);
@@ -80,6 +86,11 @@ pub fn finalize_grounded_assistant_text(
raw_assistant_text: &str,
sources: &[GroundedSource],
) -> Result<String, RetrievalError> {
+ if sources.len() > MAX_GROUNDED_SOURCES {
+ return Err(RetrievalError::InvalidInput(
+ "too many grounded sources".to_string(),
+ ));
+ }
let pack_citations = sources
.iter()
.map(|source| match source {
@@ -274,7 +285,7 @@ fn parse_mixed_assistant_text_inner(stored_text: &str) -> Option<ParsedGroundedA
return None;
}
let sources = serde_json::from_str::<Vec<GroundedSource>>(sources_json).ok()?;
- if sources.is_empty() || sources.len() > 64 {
+ if sources.is_empty() || sources.len() > MAX_GROUNDED_SOURCES {
return None;
}
let sources = normalize_grounded_sources(&sources).ok()?;
@@ -350,6 +361,9 @@ fn parse_footer(footer: &str) -> Option<Vec<SourceCitation>> {
license_label: license_label.to_owned(),
license_url: license_url.to_owned(),
});
+ if citations.len() > MAX_GROUNDED_SOURCES {
+ return None;
+ }
match lines.get(cursor).copied()? {
END_SENTINEL if cursor + 1 == lines.len() => break,
@@ -564,4 +578,27 @@ mod tests {
assert_eq!(pack_view.text, "Grounded answer");
assert_eq!(pack_view.citations, [pack]);
}
+
+ #[test]
+ fn rejects_source_lists_larger_than_the_parser_limit() {
+ let pack = citation(
+ "simplewiki",
+ "Simple English Wikipedia",
+ "https://simple.wikipedia.org/wiki/Example",
+ );
+ let sources = (0..=MAX_GROUNDED_SOURCES)
+ .map(|index| GroundedSource::LocalNote {
+ reference: crate::notes::NoteSourceReference {
+ collection_id: "123e4567-e89b-12d3-a456-426614174000".to_string(),
+ collection_label: Some("InterestAreas".to_string()),
+ document_id: format!("note-{index}.md"),
+ indexed_revision: "a".repeat(64),
+ title: format!("Note {index}"),
+ section: None,
+ },
+ })
+ .collect::<Vec<_>>();
+ assert!(finalize_grounded_assistant_text("Answer", &sources).is_err());
+ assert!(finalize_assistant_text("Answer", &vec![pack; MAX_GROUNDED_SOURCES + 1]).is_err());
+ }
}
diff --git a/rust/crates/ensu/src/retrieval/grounded.rs b/rust/crates/ensu/src/retrieval/grounded.rs
index 2b65702617..c527614412 100644
--- a/rust/crates/ensu/src/retrieval/grounded.rs
+++ b/rust/crates/ensu/src/retrieval/grounded.rs
@@ -11,7 +11,7 @@ use super::{
};
const MAX_PACK_HITS: usize = 2;
-const MAX_NOTES_HITS: usize = 6;
+pub const MAX_NOTES_GROUNDING_HITS: usize = 5;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
@@ -33,9 +33,10 @@ pub struct GroundedPromptContext {
pub sources: Vec<GroundedSource>,
}
-pub fn select_mixed_grounding(
+pub fn select_mixed_grounding_candidates(
pack_hits: &[KnowledgePromptHit],
notes_hits: &[NotesSearchHit],
+ notes_limit: usize,
) -> Result<Vec<GroundedExcerpt>, RetrievalError> {
let datasets = knowledge_datasets();
let mut packs = pack_hits.iter().collect::<Vec<_>>();
@@ -101,7 +102,7 @@ pub fn select_mixed_grounding(
.then_with(|| left.section.cmp(&right.section))
.then_with(|| left.text.cmp(&right.text))
});
- for hit in notes.into_iter().take(MAX_NOTES_HITS) {
+ for hit in notes.into_iter().take(notes_limit) {
let reference = NoteSourceReference {
collection_id: hit.collection_id.clone(),
collection_label: None,
@@ -161,12 +162,12 @@ pub fn build_grounded_prompt_context(
RetrievalError::InvalidInput("grounded context byte budget overflow".to_string())
})?;
let Some(available) = max_utf8_bytes.checked_sub(reserved) else {
- break;
+ continue;
};
let sanitized = sanitize_excerpt(&excerpt.text);
let passage = truncate_utf8(&sanitized, available).trim();
if passage.is_empty() {
- break;
+ continue;
}
text.push_str(&prefix);
text.push_str(passage);
@@ -292,7 +293,8 @@ mod tests {
note("two.md", 0.91),
note("three.md", 0.89),
];
- let selected = select_mixed_grounding(&packs, &notes).unwrap();
+ let selected =
+ select_mixed_grounding_candidates(&packs, &notes, MAX_NOTES_GROUNDING_HITS).unwrap();
assert_eq!(selected.len(), 5);
assert_eq!(
@@ -317,4 +319,27 @@ mod tests {
assert!(context.text.contains("(Your Notes Β· one.md)"));
assert_eq!(context.sources.len(), selected.len());
}
+
+ #[test]
+ fn skips_an_unfit_source_label_and_uses_the_next_excerpt() {
+ let long_document_id = format!("{}.md", "a".repeat(4_093));
+ let selected = select_mixed_grounding_candidates(
+ &[],
+ &[
+ NotesSearchHit {
+ title: long_document_id.clone(),
+ ..note(&long_document_id, 0.95)
+ },
+ note("short.md", 0.90),
+ ],
+ MAX_NOTES_GROUNDING_HITS,
+ )
+ .unwrap();
+ let context = build_grounded_prompt_context(&selected, 512)
+ .unwrap()
+ .unwrap();
+ assert_eq!(context.sources.len(), 1);
+ assert!(context.text.contains("short.md passage"));
+ assert!(!context.text.contains(&long_document_id));
+ }
}
diff --git a/web/apps/ensu/package.json b/web/apps/ensu/package.json
index ddd4fd1561..9988398020 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": "vitest --run"
+ },
"dependencies": {
"@hugeicons/core-free-icons": "1.2.1",
"@hugeicons/react": "1.1.6",
@@ -24,6 +27,7 @@
"remark-math": "6.0.0"
},
"devDependencies": {
- "ente-build-config": "*"
+ "ente-build-config": "*",
+ "vitest": "4.1.8"
}
}
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index b399885e7e..f51643fe8f 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -73,23 +73,6 @@ const formatBytes = (bytes: number) => {
return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
};
-const notesStatusLabel = (status: NotesCollection["status"]) => {
- switch (status) {
- case "indexing":
- return "Indexing";
- case "updating":
- return "Updating";
- case "ready":
- return "Ready";
- case "pending":
- return "Pending";
- case "unavailable":
- return "Folder unavailable";
- case "error":
- return "Needs attention";
- }
-};
-
const formatNotesUpdatedAt = (timestamp: number) =>
new Date(timestamp).toLocaleString(undefined, {
dateStyle: "medium",
@@ -878,10 +861,6 @@ export const ChatDialogs = memo(
noWrap
sx={{ color: "text.muted" }}
>
- {notesStatusLabel(
- collection.status,
- )}{" "}
- Β·{" "}
{
collection.indexedDocumentCount
}{" "}
@@ -889,22 +868,16 @@ export const ChatDialogs = memo(
1
? "note indexed"
: "notes indexed"}
+ {collection.lastUpdatedAtMs !=
+ null && (
+ <>
+ {" Β· Updated at "}
+ {formatNotesUpdatedAt(
+ collection.lastUpdatedAtMs,
+ )}
+ </>
+ )}
</Typography>
- {collection.lastUpdatedAtMs !=
- null && (
- <Typography
- variant="mini"
- noWrap
- sx={{
- color: "text.muted",
- }}
- >
- Last updated{" "}
- {formatNotesUpdatedAt(
- collection.lastUpdatedAtMs,
- )}
- </Typography>
- )}
</Stack>
<IconButton
aria-label={`Remove ${collection.label}`}
@@ -924,14 +897,25 @@ export const ChatDialogs = memo(
</IconButton>
</Stack>
{indexing && (
- <LinearProgress
- variant={
- progress == null
- ? "indeterminate"
- : "determinate"
- }
- value={progress ?? undefined}
- />
+ <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>
)}
{collection.lastError && (
<Typography
@@ -968,7 +952,7 @@ export const ChatDialogs = memo(
{...compactIconProps}
/>
<Typography variant="small" sx={{ flex: 1 }}>
- Select notes folder
+ Add notes folder
</Typography>
</ListItemButton>
<Typography
diff --git a/web/apps/ensu/src/components/chat/ChatMessageList.tsx b/web/apps/ensu/src/components/chat/ChatMessageList.tsx
index 1125eb8e4b..34acd22002 100644
--- a/web/apps/ensu/src/components/chat/ChatMessageList.tsx
+++ b/web/apps/ensu/src/components/chat/ChatMessageList.tsx
@@ -273,6 +273,7 @@ const LocalNoteSourceCard = memo(
void openNoteDocument(
reference.collectionId,
reference.documentId,
+ reference.indexedRevision,
).catch((error: unknown) =>
setOpenError(noteSourceErrorMessage(error)),
);
diff --git a/web/apps/ensu/src/hooks/use-notes-collections.ts b/web/apps/ensu/src/hooks/use-notes-collections.ts
new file mode 100644
index 0000000000..1a65b50bc8
--- /dev/null
+++ b/web/apps/ensu/src/hooks/use-notes-collections.ts
@@ -0,0 +1,346 @@
+import type { LlmProvider } from "@/services/llm/provider";
+import {
+ addNotesCollection,
+ indexNotesCollection,
+ listenForNotesStateChanged,
+ listNotesCollections,
+ notesErrorMessage,
+ removeNotesCollection,
+ selectNotesFolder,
+ type NotesCollection,
+} from "@/services/notes";
+import { NotesLifecycleController } from "@/services/notes-lifecycle";
+import { isNamedError } from "ente-base/error";
+import log from "ente-base/log";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+const NOTES_INDEX_RERUN_YIELD_MS = 25;
+const NOTES_REMOVE_WAIT_ERROR =
+ "Wait for indexing to finish, then remove this folder.";
+
+interface UseNotesCollectionsOptions {
+ isTauriRuntime: boolean;
+ isGenerating: boolean;
+ isGenerationStarting: () => boolean;
+ modelReady: boolean;
+ ensureProvider: () => Promise<LlmProvider>;
+ cancelIndexing: () => void;
+ confirmRemoval: (label: string, remove: () => Promise<void>) => void;
+}
+
+export const useNotesCollections = ({
+ isTauriRuntime,
+ isGenerating,
+ isGenerationStarting,
+ modelReady,
+ ensureProvider,
+ cancelIndexing,
+ confirmRemoval,
+}: UseNotesCollectionsOptions) => {
+ const [collections, setCollections] = useState<NotesCollection[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [operationError, setOperationError] = useState<string | null>(null);
+ const [listError, setListError] = useState<string | null>(null);
+ const [subscriptionError, setSubscriptionError] = useState<string | null>(
+ null,
+ );
+ const [syncAttempt, setSyncAttempt] = useState(0);
+ const controllerRef = useRef<NotesLifecycleController | null>(null);
+ if (!controllerRef.current) {
+ controllerRef.current = new NotesLifecycleController();
+ }
+ const controller = controllerRef.current;
+ const runIndexRef = useRef<
+ ((collectionId: string, force?: boolean) => void) | null
+ >(null);
+
+ useEffect(() => {
+ controller.activate();
+ return () => {
+ if (controller.hasActiveJobs()) cancelIndexing();
+ controller.dispose();
+ };
+ }, [cancelIndexing, controller]);
+
+ const refresh = useCallback(async () => {
+ if (!isTauriRuntime) return;
+ const request = controller.beginRefresh();
+ setLoading(true);
+ try {
+ while (controller.isRefreshCurrent(request)) {
+ const mutation = controller.refreshMutationSnapshot();
+ try {
+ const next = await listNotesCollections();
+ if (!controller.isRefreshCurrent(request)) return;
+ if (!controller.canApplyRefresh(request, mutation)) {
+ continue;
+ }
+ setCollections(next);
+ setListError(null);
+ return;
+ } catch (error) {
+ if (!controller.isRefreshCurrent(request)) return;
+ if (!controller.canApplyRefresh(request, mutation)) {
+ continue;
+ }
+ setListError(notesErrorMessage(error));
+ log.error("Failed to refresh Your Notes", error);
+ return;
+ }
+ }
+ } finally {
+ if (controller.isRefreshCurrent(request)) setLoading(false);
+ }
+ }, [controller, isTauriRuntime]);
+
+ const replaceCollection = useCallback(
+ (collection: NotesCollection) => {
+ controller.markMutation();
+ setCollections((current) => {
+ const exists = current.some(
+ (item) => item.id === collection.id,
+ );
+ return exists
+ ? current.map((item) =>
+ item.id === collection.id ? collection : item,
+ )
+ : [...current, collection];
+ });
+ },
+ [controller],
+ );
+
+ const updateCollection = useCallback(
+ (collection: NotesCollection) => {
+ controller.markMutation();
+ setCollections((current) =>
+ current.map((item) =>
+ item.id === collection.id ? collection : item,
+ ),
+ );
+ },
+ [controller],
+ );
+
+ const runIndex = useCallback(
+ (collectionId: string, force = false) => {
+ const request = controller.requestIndex(
+ collectionId,
+ force,
+ isGenerating || isGenerationStarting(),
+ );
+ if (request !== "start") return;
+ setOperationError(null);
+
+ void ensureProvider()
+ .then((provider) =>
+ provider.withKnowledgeRetrieval(
+ async (retrievalEpoch) => {
+ let needsRerun = true;
+ let bypassQuietPeriod = force;
+ while (
+ needsRerun &&
+ controller.canContinueIndex(collectionId)
+ ) {
+ const result = await indexNotesCollection(
+ collectionId,
+ bypassQuietPeriod,
+ retrievalEpoch,
+ );
+ if (
+ !controller.canContinueIndex(collectionId)
+ ) {
+ return;
+ }
+ bypassQuietPeriod = false;
+ replaceCollection(result.collection);
+ needsRerun = result.needsRerun;
+ if (needsRerun) {
+ await new Promise<void>((resolve) =>
+ window.setTimeout(
+ resolve,
+ NOTES_INDEX_RERUN_YIELD_MS,
+ ),
+ );
+ }
+ }
+ },
+ () => controller.canContinueIndex(collectionId),
+ ),
+ )
+ .catch((error: unknown) => {
+ if (controller.isRemoving(collectionId)) return;
+ if (isNamedError(error, "cancelled")) {
+ controller.queueIndex(collectionId, force);
+ } else if (!isNamedError(error, "not_due")) {
+ setOperationError(notesErrorMessage(error));
+ log.error("Failed to index Your Notes", error);
+ }
+ void refresh();
+ })
+ .finally(() => {
+ const completion = controller.finishIndex(collectionId);
+ if (completion.queuedForce !== undefined) {
+ runIndexRef.current?.(
+ collectionId,
+ completion.queuedForce,
+ );
+ } else if (completion.clearedRemovalWait) {
+ setOperationError((current) =>
+ current === NOTES_REMOVE_WAIT_ERROR
+ ? null
+ : current,
+ );
+ }
+ });
+ },
+ [
+ controller,
+ ensureProvider,
+ isGenerating,
+ isGenerationStarting,
+ refresh,
+ replaceCollection,
+ ],
+ );
+ runIndexRef.current = runIndex;
+
+ useEffect(() => {
+ for (const [collectionId, force] of controller.drainQueued(
+ isGenerating || isGenerationStarting(),
+ )) {
+ runIndex(collectionId, force);
+ }
+ }, [controller, isGenerating, isGenerationStarting, runIndex]);
+
+ useEffect(() => {
+ if (!isTauriRuntime) return;
+ let disposed = false;
+ let unlisten: (() => void) | undefined;
+ const initialRefresh = refresh();
+ const refreshAfterSubscription = async () => {
+ await initialRefresh;
+ if (!disposed) await refresh();
+ };
+ void listenForNotesStateChanged((collection) => {
+ if (!disposed) updateCollection(collection);
+ })
+ .then(async (listener) => {
+ if (disposed) {
+ listener();
+ return;
+ }
+ unlisten = listener;
+ setSubscriptionError(null);
+ await refreshAfterSubscription();
+ })
+ .catch((error: unknown) => {
+ if (disposed) return;
+ setSubscriptionError(notesErrorMessage(error));
+ log.error("Failed to listen for Your Notes updates", error);
+ });
+ return () => {
+ disposed = true;
+ controller.cancelRefreshes();
+ unlisten?.();
+ };
+ }, [controller, isTauriRuntime, refresh, syncAttempt, updateCollection]);
+
+ useEffect(() => {
+ if (!isTauriRuntime || !modelReady) return;
+ const timeouts: number[] = [];
+ const now = Date.now();
+ for (const collection of collections) {
+ if (
+ collection.updateDueAtMs != null &&
+ (collection.status === "ready" ||
+ collection.status === "pending")
+ ) {
+ timeouts.push(
+ window.setTimeout(
+ () => runIndex(collection.id),
+ Math.max(0, collection.updateDueAtMs - now),
+ ),
+ );
+ }
+ }
+ return () => {
+ for (const timeout of timeouts) window.clearTimeout(timeout);
+ };
+ }, [collections, isTauriRuntime, modelReady, runIndex]);
+
+ useEffect(() => {
+ if (!isTauriRuntime || !modelReady) return;
+ for (const collection of collections) {
+ if (
+ collection.status === "pending" &&
+ collection.updateDueAtMs == null &&
+ controller.markResumed(collection.id)
+ ) {
+ runIndex(collection.id);
+ }
+ }
+ }, [collections, controller, isTauriRuntime, modelReady, runIndex]);
+
+ const retry = useCallback(() => {
+ setOperationError(null);
+ setSyncAttempt((attempt) => attempt + 1);
+ }, []);
+
+ const addFolder = useCallback(async () => {
+ setOperationError(null);
+ try {
+ const sourceRoot = await selectNotesFolder();
+ if (!sourceRoot) return;
+ const collection = await addNotesCollection(sourceRoot);
+ replaceCollection(collection);
+ runIndex(collection.id);
+ } catch (error) {
+ setOperationError(notesErrorMessage(error));
+ log.error("Failed to add Notes folder", error);
+ }
+ }, [replaceCollection, runIndex]);
+
+ const removeCollection = useCallback(
+ (collectionId: string, label: string) => {
+ confirmRemoval(label, async () => {
+ const removal = controller.beginRemoval(collectionId);
+ if (removal.kind === "wait") {
+ setOperationError(NOTES_REMOVE_WAIT_ERROR);
+ return;
+ }
+ setOperationError(null);
+ try {
+ await removeNotesCollection(collectionId);
+ controller.markMutation();
+ controller.finishRemoval(collectionId);
+ setCollections((current) =>
+ current.filter((item) => item.id !== collectionId),
+ );
+ } catch (error) {
+ controller.cancelRemoval(collectionId);
+ setOperationError(notesErrorMessage(error));
+ log.error("Failed to remove Notes collection", error);
+ void refresh();
+ if (removal.queuedForce !== undefined) {
+ runIndexRef.current?.(
+ collectionId,
+ removal.queuedForce,
+ );
+ }
+ }
+ });
+ },
+ [confirmRemoval, controller, refresh],
+ );
+
+ return {
+ collections,
+ loading,
+ error: subscriptionError ?? listError ?? operationError,
+ retry,
+ addFolder,
+ removeCollection,
+ runIndex,
+ };
+};
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index ec519ab17b..008cefba90 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 { useNotesCollections } from "@/hooks/use-notes-collections";
import { handleManualAppUpdateCheck } from "@/services/app-update";
import {
buildSelectedPath,
@@ -61,17 +62,7 @@ import type {
ModelInfo,
ModelSettings,
} from "@/services/llm/types";
-import {
- addNotesCollection,
- hasAvailableNotesIndex,
- indexNotesCollection,
- listenForNotesStateChanged,
- listNotesCollections,
- notesErrorMessage,
- removeNotesCollection,
- selectNotesFolder,
- type NotesCollection,
-} from "@/services/notes";
+import { hasAvailableNotesIndex } from "@/services/notes";
import { isTauriRuntime as detectTauriAppRuntime } from "@/services/tauri-runtime";
import { Menu01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -273,10 +264,6 @@ const SESSION_TITLE_PROMPT =
const REPEAT_PENALTY = 1.18;
const STREAMING_OUTRO_DURATION_MS = 520;
-const NOTES_INDEX_SLICE_YIELD_MS = 25;
-const NOTES_REMOVE_WAIT_ERROR =
- "Wait for indexing to finish, then remove this folder.";
-
interface DocumentAttachment {
id: string;
name: string;
@@ -572,20 +559,6 @@ const Page: React.FC = () => {
const [knowledgeErrors, setKnowledgeErrors] = useState<
Record<string, string | undefined>
>({});
- const [notesCollections, setNotesCollections] = useState<NotesCollection[]>(
- [],
- );
- const [notesCollectionsLoading, setNotesCollectionsLoading] =
- useState(false);
- const [notesOperationError, setNotesOperationError] = useState<
- string | null
- >(null);
- const [notesListError, setNotesListError] = useState<string | null>(null);
- const [notesSubscriptionError, setNotesSubscriptionError] = useState<
- string | null
- >(null);
- const [notesSyncAttempt, setNotesSyncAttempt] = useState(0);
-
const [modelSettingsLoaded, setModelSettingsLoaded] = useState(false);
const [resolvedDefaultModel, setResolvedDefaultModel] =
useState<ModelInfo>(DEFAULT_MODEL);
@@ -654,16 +627,6 @@ const Page: React.FC = () => {
const currentJobIdRef = useRef<number | null>(null);
const activeKnowledgeSourcesRef = useRef<GroundedSource[]>([]);
const activeKnowledgeDownloadsRef = useRef(new Set<string>());
- const activeNotesJobsRef = useRef(new Set<string>());
- const queuedNotesJobsRef = useRef(new Map<string, boolean>());
- const removingNotesCollectionsRef = useRef(new Set<string>());
- const notesRemovalWaitCollectionRef = useRef<string | null>(null);
- const runNotesIndexRef = useRef<
- ((collectionId: string, force?: boolean) => void) | null
- >(null);
- const resumedNotesCollectionsRef = useRef(new Set<string>());
- const notesCollectionsMutationRef = useRef(0);
- const notesCollectionsRefreshRequestRef = useRef(0);
const knowledgeCatalogPromiseRef = useRef<Promise<KnowledgePack[]> | null>(
null,
);
@@ -783,43 +746,6 @@ const Page: React.FC = () => {
}
}, [isTauriRuntime, loadKnowledgeCatalogOnce]);
- const refreshNotesCollections = useCallback(async () => {
- if (!isTauriRuntime) return;
- const request = ++notesCollectionsRefreshRequestRef.current;
- setNotesCollectionsLoading(true);
- try {
- while (request === notesCollectionsRefreshRequestRef.current) {
- const mutation = notesCollectionsMutationRef.current;
- try {
- const collections = await listNotesCollections();
- if (request !== notesCollectionsRefreshRequestRef.current) {
- return;
- }
- if (mutation !== notesCollectionsMutationRef.current) {
- continue;
- }
- setNotesCollections(collections);
- setNotesListError(null);
- return;
- } catch (error) {
- if (request !== notesCollectionsRefreshRequestRef.current) {
- return;
- }
- if (mutation !== notesCollectionsMutationRef.current) {
- continue;
- }
- setNotesListError(notesErrorMessage(error));
- log.error("Failed to refresh Your Notes", error);
- return;
- }
- }
- } finally {
- if (request === notesCollectionsRefreshRequestRef.current) {
- setNotesCollectionsLoading(false);
- }
- }
- }, [isTauriRuntime]);
-
const sessionFromQuery = useMemo(() => {
if (!router.isReady) return undefined;
const value = router.query.session;
@@ -1874,6 +1800,50 @@ const Page: React.FC = () => {
return providerRef.current;
}, []);
+ const isNotesGenerationStarting = useCallback(
+ () => generationStartingRef.current,
+ [],
+ );
+ const cancelNotesIndexing = useCallback(() => {
+ const provider = providerRef.current;
+ if (provider?.getBackendKind() === "tauri") {
+ void provider
+ .cancelGeneration(-1)
+ .catch((error: unknown) =>
+ log.warn("Failed to cancel Notes indexing", error),
+ );
+ }
+ }, []);
+ const confirmNotesRemoval = useCallback(
+ (label: string, remove: () => Promise<void>) => {
+ showMiniDialog({
+ title: "Remove notes folder?",
+ message: `Remove β€œ${label}” from Your Notes? Source files will not be changed.`,
+ continue: { text: "Remove", color: "critical", action: remove },
+ cancel: "Cancel",
+ buttonDirection: "row",
+ });
+ },
+ [showMiniDialog],
+ );
+ const {
+ collections: notesCollections,
+ loading: notesCollectionsLoading,
+ error: notesCollectionsError,
+ retry: retryNotesCollections,
+ addFolder: handleAddNotesFolder,
+ removeCollection: handleRemoveNotesCollection,
+ runIndex: runNotesIndex,
+ } = useNotesCollections({
+ isTauriRuntime,
+ isGenerating,
+ isGenerationStarting: isNotesGenerationStarting,
+ modelReady: modelGateStatus === "ready",
+ ensureProvider,
+ cancelIndexing: cancelNotesIndexing,
+ confirmRemoval: confirmNotesRemoval,
+ });
+
const getModelSettings = useCallback((): ModelSettings => {
return {
modelId: selectedModelId || undefined,
@@ -2984,7 +2954,7 @@ const Page: React.FC = () => {
let startupCompleted = false;
try {
provider = await ensureProvider();
- if (activeNotesJobsRef.current.size > 0) {
+ if (provider.getBackendKind() === "tauri") {
await provider.cancelGeneration(-1);
if (!isActiveGeneration()) return;
}
@@ -3689,295 +3659,6 @@ const Page: React.FC = () => {
[],
);
- const replaceNotesCollection = useCallback(
- (collection: NotesCollection) => {
- notesCollectionsMutationRef.current += 1;
- setNotesCollections((current) => {
- const exists = current.some(
- (item) => item.id === collection.id,
- );
- return exists
- ? current.map((item) =>
- item.id === collection.id ? collection : item,
- )
- : [...current, collection];
- });
- },
- [],
- );
-
- const updateNotesCollection = useCallback((collection: NotesCollection) => {
- notesCollectionsMutationRef.current += 1;
- setNotesCollections((current) =>
- current.map((item) =>
- item.id === collection.id ? collection : item,
- ),
- );
- }, []);
-
- const runNotesIndex = useCallback(
- (collectionId: string, force = false) => {
- if (removingNotesCollectionsRef.current.has(collectionId)) return;
- if (
- isGenerating ||
- generationStartingRef.current ||
- activeNotesJobsRef.current.has(collectionId)
- ) {
- queuedNotesJobsRef.current.set(
- collectionId,
- force ||
- (queuedNotesJobsRef.current.get(collectionId) ?? false),
- );
- return;
- }
- resumedNotesCollectionsRef.current.add(collectionId);
- activeNotesJobsRef.current.add(collectionId);
- setNotesOperationError(null);
-
- void ensureProvider()
- .then((provider) =>
- provider.withKnowledgeRetrieval(
- async (retrievalEpoch) => {
- let hasMore = true;
- let bypassQuietPeriod = force;
- while (
- hasMore &&
- activeNotesJobsRef.current.has(collectionId)
- ) {
- const result = await indexNotesCollection(
- collectionId,
- bypassQuietPeriod,
- retrievalEpoch,
- );
- if (
- !activeNotesJobsRef.current.has(
- collectionId,
- ) ||
- removingNotesCollectionsRef.current.has(
- collectionId,
- )
- ) {
- return;
- }
- bypassQuietPeriod = false;
- replaceNotesCollection(result.collection);
- hasMore = result.hasMore;
- if (hasMore) {
- await new Promise<void>((resolve) =>
- window.setTimeout(
- resolve,
- NOTES_INDEX_SLICE_YIELD_MS,
- ),
- );
- }
- }
- },
- () =>
- activeNotesJobsRef.current.has(collectionId) &&
- !removingNotesCollectionsRef.current.has(
- collectionId,
- ),
- ),
- )
- .catch((error: unknown) => {
- if (removingNotesCollectionsRef.current.has(collectionId)) {
- return;
- }
- const { name } = tauriCommandError(error);
- if (name === "cancelled") {
- queuedNotesJobsRef.current.set(collectionId, force);
- } else if (name !== "not_due") {
- setNotesOperationError(notesErrorMessage(error));
- log.error("Failed to index Your Notes", error);
- }
- void refreshNotesCollections();
- })
- .finally(() => {
- activeNotesJobsRef.current.delete(collectionId);
- const queuedForce =
- queuedNotesJobsRef.current.get(collectionId);
- if (queuedForce !== undefined) {
- queuedNotesJobsRef.current.delete(collectionId);
- runNotesIndexRef.current?.(collectionId, queuedForce);
- } else if (
- notesRemovalWaitCollectionRef.current === collectionId
- ) {
- notesRemovalWaitCollectionRef.current = null;
- setNotesOperationError((current) =>
- current === NOTES_REMOVE_WAIT_ERROR
- ? null
- : current,
- );
- }
- });
- },
- [
- ensureProvider,
- isGenerating,
- refreshNotesCollections,
- replaceNotesCollection,
- ],
- );
- runNotesIndexRef.current = runNotesIndex;
-
- useEffect(() => {
- if (isGenerating || generationStartingRef.current) return;
- for (const [collectionId, force] of queuedNotesJobsRef.current) {
- if (activeNotesJobsRef.current.has(collectionId)) continue;
- queuedNotesJobsRef.current.delete(collectionId);
- runNotesIndex(collectionId, force);
- }
- }, [isGenerating, runNotesIndex]);
-
- useEffect(() => {
- if (!isTauriRuntime) return;
- let disposed = false;
- let unlisten: (() => void) | undefined;
- const initialRefresh = refreshNotesCollections();
- const refreshAfterSubscription = async () => {
- await initialRefresh;
- if (!disposed) await refreshNotesCollections();
- };
- void listenForNotesStateChanged((collection) => {
- if (disposed) return;
- updateNotesCollection(collection);
- })
- .then(async (listener) => {
- if (disposed) {
- listener();
- return;
- }
- unlisten = listener;
- setNotesSubscriptionError(null);
- await refreshAfterSubscription();
- })
- .catch((error: unknown) => {
- if (disposed) return;
- setNotesSubscriptionError(notesErrorMessage(error));
- log.error("Failed to listen for Your Notes updates", error);
- });
- return () => {
- disposed = true;
- notesCollectionsRefreshRequestRef.current += 1;
- unlisten?.();
- };
- }, [
- isTauriRuntime,
- notesSyncAttempt,
- refreshNotesCollections,
- updateNotesCollection,
- ]);
-
- const retryNotesCollections = useCallback(() => {
- setNotesOperationError(null);
- setNotesSyncAttempt((attempt) => attempt + 1);
- }, []);
-
- useEffect(() => {
- if (!isTauriRuntime || modelGateStatus !== "ready") return;
- const timeouts: number[] = [];
- for (const collection of notesCollections) {
- const dueAt = collection.updateDueAtMs;
- if (
- dueAt != null &&
- (collection.status === "ready" ||
- collection.status === "pending")
- ) {
- timeouts.push(
- window.setTimeout(
- () => runNotesIndex(collection.id),
- Math.max(0, dueAt - Date.now()),
- ),
- );
- }
- }
- return () => {
- for (const timeout of timeouts) window.clearTimeout(timeout);
- };
- }, [isTauriRuntime, modelGateStatus, notesCollections, runNotesIndex]);
-
- const handleAddNotesFolder = useCallback(async () => {
- setNotesOperationError(null);
- try {
- const sourceRoot = await selectNotesFolder();
- if (!sourceRoot) return;
- const collection = await addNotesCollection(sourceRoot);
- replaceNotesCollection(collection);
- runNotesIndex(collection.id);
- } catch (error) {
- setNotesOperationError(notesErrorMessage(error));
- log.error("Failed to add Notes folder", error);
- }
- }, [replaceNotesCollection, runNotesIndex]);
-
- const handleRemoveNotesCollection = useCallback(
- (collectionId: string, label: string) => {
- showMiniDialog({
- title: "Remove notes folder?",
- message: `Remove β€œ${label}” from Your Notes? Source files will not be changed.`,
- continue: {
- text: "Remove",
- color: "critical",
- action: async () => {
- if (activeNotesJobsRef.current.has(collectionId)) {
- notesRemovalWaitCollectionRef.current =
- collectionId;
- setNotesOperationError(NOTES_REMOVE_WAIT_ERROR);
- return;
- }
- const queuedForce =
- queuedNotesJobsRef.current.get(collectionId);
- queuedNotesJobsRef.current.delete(collectionId);
- removingNotesCollectionsRef.current.add(collectionId);
- setNotesOperationError(null);
- try {
- await removeNotesCollection(collectionId);
- notesCollectionsMutationRef.current += 1;
- setNotesCollections((current) =>
- current.filter(
- (item) => item.id !== collectionId,
- ),
- );
- } catch (error) {
- removingNotesCollectionsRef.current.delete(
- collectionId,
- );
- setNotesOperationError(notesErrorMessage(error));
- log.error(
- "Failed to remove Notes collection",
- error,
- );
- void refreshNotesCollections();
- if (queuedForce !== undefined) {
- runNotesIndexRef.current?.(
- collectionId,
- queuedForce,
- );
- }
- }
- },
- },
- cancel: "Cancel",
- buttonDirection: "row",
- });
- },
- [refreshNotesCollections, showMiniDialog],
- );
-
- useEffect(() => {
- if (!isTauriRuntime || modelGateStatus !== "ready") return;
- for (const collection of notesCollections) {
- if (
- collection.status === "pending" &&
- collection.updateDueAtMs == null &&
- !resumedNotesCollectionsRef.current.has(collection.id)
- ) {
- resumedNotesCollectionsRef.current.add(collection.id);
- runNotesIndex(collection.id);
- }
- }
- }, [isTauriRuntime, modelGateStatus, notesCollections, runNotesIndex]);
-
const handleBuildVersionTap = useCallback(() => {
if (advancedUnlocked || typeof window === "undefined") return;
if (buildVersionTapTimeoutRef.current) {
@@ -5056,11 +4737,7 @@ const Page: React.FC = () => {
handleSetKnowledgePackEnabled={handleSetKnowledgePackEnabled}
notesCollections={notesCollections}
notesCollectionsLoading={notesCollectionsLoading}
- notesCollectionsError={
- notesSubscriptionError ??
- notesListError ??
- notesOperationError
- }
+ notesCollectionsError={notesCollectionsError}
retryNotesCollections={retryNotesCollections}
handleAddNotesFolder={handleAddNotesFolder}
handleRemoveNotesCollection={handleRemoveNotesCollection}
diff --git a/web/apps/ensu/src/services/notes-lifecycle.ts b/web/apps/ensu/src/services/notes-lifecycle.ts
new file mode 100644
index 0000000000..edb59226b1
--- /dev/null
+++ b/web/apps/ensu/src/services/notes-lifecycle.ts
@@ -0,0 +1,151 @@
+type NotesIndexRequest = "start" | "queued" | "ignored";
+
+interface NotesIndexCompletion {
+ queuedForce?: boolean;
+ clearedRemovalWait: boolean;
+}
+
+type NotesRemovalStart =
+ | { kind: "wait" }
+ | { kind: "start"; queuedForce?: boolean };
+
+export class NotesLifecycleController {
+ private readonly active = new Set<string>();
+ private readonly queued = new Map<string, boolean>();
+ private readonly removing = new Set<string>();
+ private readonly resumed = new Set<string>();
+ private removalWaitCollection: string | null = null;
+ private mutation = 0;
+ private refreshRequest = 0;
+ private disposed = false;
+
+ requestIndex(
+ collectionId: string,
+ force: boolean,
+ blocked: boolean,
+ ): NotesIndexRequest {
+ if (this.disposed || this.removing.has(collectionId)) return "ignored";
+ if (blocked || this.active.has(collectionId)) {
+ this.queueIndex(collectionId, force);
+ return "queued";
+ }
+ this.resumed.add(collectionId);
+ this.active.add(collectionId);
+ return "start";
+ }
+
+ queueIndex(collectionId: string, force: boolean) {
+ if (this.disposed || this.removing.has(collectionId)) return;
+ this.queued.set(
+ collectionId,
+ force || (this.queued.get(collectionId) ?? false),
+ );
+ }
+
+ canContinueIndex(collectionId: string) {
+ return (
+ !this.disposed &&
+ this.active.has(collectionId) &&
+ !this.removing.has(collectionId)
+ );
+ }
+
+ finishIndex(collectionId: string): NotesIndexCompletion {
+ this.active.delete(collectionId);
+ const queuedForce = this.queued.get(collectionId);
+ this.queued.delete(collectionId);
+ const clearedRemovalWait = this.removalWaitCollection === collectionId;
+ if (clearedRemovalWait) this.removalWaitCollection = null;
+ return { queuedForce, clearedRemovalWait };
+ }
+
+ drainQueued(blocked: boolean) {
+ if (this.disposed || blocked) return [] as [string, boolean][];
+ const ready: [string, boolean][] = [];
+ for (const [collectionId, force] of this.queued) {
+ if (
+ this.active.has(collectionId) ||
+ this.removing.has(collectionId)
+ ) {
+ continue;
+ }
+ this.queued.delete(collectionId);
+ ready.push([collectionId, force]);
+ }
+ return ready;
+ }
+
+ beginRemoval(collectionId: string): NotesRemovalStart {
+ if (this.active.has(collectionId)) {
+ this.removalWaitCollection = collectionId;
+ return { kind: "wait" };
+ }
+ const queuedForce = this.queued.get(collectionId);
+ this.queued.delete(collectionId);
+ this.removing.add(collectionId);
+ return { kind: "start", queuedForce };
+ }
+
+ cancelRemoval(collectionId: string) {
+ this.removing.delete(collectionId);
+ }
+
+ finishRemoval(collectionId: string) {
+ this.removing.delete(collectionId);
+ this.resumed.delete(collectionId);
+ if (this.removalWaitCollection === collectionId) {
+ this.removalWaitCollection = null;
+ }
+ }
+
+ isRemoving(collectionId: string) {
+ return this.removing.has(collectionId);
+ }
+
+ markResumed(collectionId: string) {
+ if (this.disposed || this.resumed.has(collectionId)) return false;
+ this.resumed.add(collectionId);
+ return true;
+ }
+
+ hasActiveJobs() {
+ return this.active.size > 0;
+ }
+
+ markMutation() {
+ this.mutation += 1;
+ }
+
+ beginRefresh() {
+ this.refreshRequest += 1;
+ return this.refreshRequest;
+ }
+
+ refreshMutationSnapshot() {
+ return this.mutation;
+ }
+
+ isRefreshCurrent(request: number) {
+ return !this.disposed && request === this.refreshRequest;
+ }
+
+ canApplyRefresh(request: number, mutation: number) {
+ return this.isRefreshCurrent(request) && mutation === this.mutation;
+ }
+
+ cancelRefreshes() {
+ this.refreshRequest += 1;
+ }
+
+ activate() {
+ this.disposed = false;
+ }
+
+ dispose() {
+ this.disposed = true;
+ this.active.clear();
+ this.queued.clear();
+ this.removing.clear();
+ this.cancelRefreshes();
+ }
+}
diff --git a/web/apps/ensu/src/services/notes.ts b/web/apps/ensu/src/services/notes.ts
index 2a351236d7..af412f3cec 100644
--- a/web/apps/ensu/src/services/notes.ts
+++ b/web/apps/ensu/src/services/notes.ts
@@ -30,7 +30,11 @@ const invokeNotes = async <T>(
export const selectNotesFolder = async () => {
const { open } = await import("@tauri-apps/plugin-dialog");
- const selected = await open({ directory: true, multiple: false });
+ const selected = await open({
+ directory: true,
+ multiple: false,
+ recursive: false,
+ });
return typeof selected === "string" ? selected : null;
};
@@ -51,7 +55,7 @@ export const indexNotesCollection = (
force: boolean,
retrievalEpoch: number,
) =>
- invokeNotes<{ collection: NotesCollection; hasMore: boolean }>(
+ invokeNotes<{ collection: NotesCollection; needsRerun: boolean }>(
"notes_index_collection",
{ collectionId, force, retrievalEpoch },
);
@@ -65,8 +69,16 @@ export const listenForNotesStateChanged = async (
);
};
-export const openNoteDocument = (collectionId: string, documentId: string) =>
- invokeNotes<null>("notes_open_document", { collectionId, documentId });
+export const openNoteDocument = (
+ collectionId: string,
+ documentId: string,
+ indexedRevision: string,
+) =>
+ invokeNotes<null>("notes_open_document", {
+ collectionId,
+ documentId,
+ indexedRevision,
+ });
const commandError = (error: unknown) =>
(error && typeof error === "object" ? error : {}) as {
@@ -87,6 +99,8 @@ export const notesErrorMessage = (error: unknown) => {
return "That folder is unavailable. Check its location and permissions.";
case "embedding_missing":
return "The knowledge embedding model must be downloaded first.";
+ case "collection_too_large":
+ return "This folder contains too many notes to index.";
default:
return typeof message === "string"
? message
@@ -96,7 +110,12 @@ export const notesErrorMessage = (error: unknown) => {
export const noteSourceErrorMessage = (error: unknown) => {
const { name } = commandError(error);
- return name === "open_failed"
- ? "The note could not be opened."
- : "Source no longer available.";
+ switch (name) {
+ case "open_failed":
+ return "The note could not be opened.";
+ case "source_changed":
+ return "This note changed after the answer was generated.";
+ default:
+ return "Source no longer available.";
+ }
};
diff --git a/web/apps/ensu/tests/notes-lifecycle.test.ts b/web/apps/ensu/tests/notes-lifecycle.test.ts
new file mode 100644
index 0000000000..6b16779c90
--- /dev/null
+++ b/web/apps/ensu/tests/notes-lifecycle.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from "vitest";
+import { NotesLifecycleController } from "../src/services/notes-lifecycle";
+
+describe("NotesLifecycleController", () => {
+ test("coalesces active and blocked requests without losing force", () => {
+ const controller = new NotesLifecycleController();
+
+ expect(controller.requestIndex("a", false, false)).toBe("start");
+ expect(controller.requestIndex("a", false, false)).toBe("queued");
+ expect(controller.requestIndex("a", true, false)).toBe("queued");
+ expect(controller.finishIndex("a").queuedForce).toBe(true);
+ expect(controller.requestIndex("b", false, true)).toBe("queued");
+ expect(controller.drainQueued(false)).toEqual([["b", false]]);
+ });
+
+ test("keeps removal separate from active and queued indexing", () => {
+ const controller = new NotesLifecycleController();
+
+ controller.requestIndex("a", false, false);
+ expect(controller.beginRemoval("a")).toEqual({ kind: "wait" });
+ expect(controller.finishIndex("a").clearedRemovalWait).toBe(true);
+
+ controller.queueIndex("a", true);
+ expect(controller.beginRemoval("a")).toEqual({
+ kind: "start",
+ queuedForce: true,
+ });
+ expect(controller.requestIndex("a", false, false)).toBe("ignored");
+ controller.cancelRemoval("a");
+ expect(controller.requestIndex("a", false, false)).toBe("start");
+ });
+
+ test("rejects stale refreshes after a mutation or newer request", () => {
+ const controller = new NotesLifecycleController();
+ const first = controller.beginRefresh();
+ const firstMutation = controller.refreshMutationSnapshot();
+ controller.markMutation();
+ expect(controller.canApplyRefresh(first, firstMutation)).toBe(false);
+
+ const secondMutation = controller.refreshMutationSnapshot();
+ const second = controller.beginRefresh();
+ expect(controller.isRefreshCurrent(first)).toBe(false);
+ expect(controller.canApplyRefresh(second, secondMutation)).toBe(true);
+ });
+
+ test("resumes each pending collection once and stops work after disposal", () => {
+ const controller = new NotesLifecycleController();
+ expect(controller.markResumed("a")).toBe(true);
+ expect(controller.markResumed("a")).toBe(false);
+ controller.dispose();
+ expect(controller.requestIndex("b", false, false)).toBe("ignored");
+ expect(controller.drainQueued(false)).toEqual([]);
+ controller.activate();
+ expect(controller.requestIndex("b", false, false)).toBe("start");
+ });
+});
diff --git a/web/apps/ensu/tsconfig.json b/web/apps/ensu/tsconfig.json
index 2ff1f734c6..6a2a667238 100644
--- a/web/apps/ensu/tsconfig.json
+++ b/web/apps/ensu/tsconfig.json
@@ -9,6 +9,7 @@
},
"include": [
"src",
+ "tests",
"next-env.d.ts",
"next.config.mjs",
"../../packages/base/global-electron.d.ts",
diff --git a/web/package-lock.json b/web/package-lock.json
index 4e037b9968..7df478b760 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -191,7 +191,8 @@
"remark-math": "6.0.0"
},
"devDependencies": {
- "ente-build-config": "*"
+ "ente-build-config": "*",
+ "vitest": "4.1.8"
}
},
"apps/ensu/node_modules/katex": {
diff --git a/web/package.json b/web/package.json
index 3bee38bffc..11ea951759 100644
--- a/web/package.json
+++ b/web/package.json
@@ -52,7 +52,7 @@
"dev:twoof3": "npm exec --workspace twoof3 -- next dev --webpack -p 3012",
"lint": "concurrently --names 'prettier,eslint,tsc,wasm-imports' \"prettier --check --log-level warn .\" \"npm exec --workspaces -- eslint --max-warnings 0\" \"npm exec --workspaces -- tsc\" \"npm run check:wasm-imports\"",
"lint:fix": "concurrently --names 'prettier,eslint,tsc' \"prettier --write --log-level warn .\" \"npm exec --workspaces -- eslint --fix --max-warnings 0\" \"npm exec --workspaces -- tsc\"",
- "test": "npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace locker && npm run test --workspace photos"
+ "test": "npm run test --workspace ensu && npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace locker && npm run test --workspace photos"
},
"overrides": {
"@types/react": "19.2.17",