Local, full Windows search replacement, clipboard manager, and launcher: files, apps, settings and semantic media search with Google's EmbeddingGemma 2.
Rust clipboard-historyembedding-modelsembeddinggemma-2embeddinggemma2embeddingslocal-firstmcp-serversearchsemantic-searchwindows-11
Fix compact dialogs, keep automatic indexing targeted, and decouple app launches
ampersandrue12f80c2ba47
diff --git a/native/docs/AUTO_INDEX_AUDIT.md b/native/docs/AUTO_INDEX_AUDIT.mdnew file mode 100644index 0000000..8c96b7c--- /dev/null+++ b/native/docs/AUTO_INDEX_AUDIT.md@@ -0,0 +1,31 @@+# Automatic indexing and action responsiveness audit++Unreleased follow-up on PR #16 after 0.3.25-beta.4.++## Observed behavior++Recent logs showed normal targeted updates checking one or a few files, and one 508-path notification batch checking 547 entries. A created/renamed folder legitimately includes its descendants. These are not complete-drive scans. Logs also showed an avoidable queued recovery scan checking about 1.13 million files after a manual update. Independently, refreshing the displayed database totals queried the index broadly; those SQL counts did not re-read files, but repeating them during bursts wasted resources.++## Changes++- A successful full/manual scan acknowledges only notification work queued before it started. Repeated writes and recovery signals queued during that scan survive. The old startup-recovery flag is cleared when already covered. Failed/cancelled scans do not acknowledge queued work.+- Known change paths stay durable and targeted beyond the former 4,096-path threshold, drained in batches of at most 4,096. The callback's busy-channel spill retains up to 32,768 exact paths. SQL queue reads use a queued-time index and generation acknowledgements use primary-key lookups/prepared statements.+- Memory remains bounded if the durable queue cannot be written. Exceptional catch-up reasons are visible in Logs. Extreme callback spill saturation checks only affected configured sources rather than unrelated sources; unknown lost-event information can still require broader recovery.+- Targeted runs resume only Full jobs and deferred Quick names within the notified file/folder scope. Unrelated unfinished jobs are left for their own notification or a full update. Directory metadata-only events remain ignored; create/rename folder events still cover that subtree.+- Display statistics use one coalesced worker, with at least five seconds between database-wide recounts during bursts. Counts may briefly lag; searchable index updates are not delayed by the statistics cooldown.+- Logs include the actual targeted scope and actual inaccessible path, rather than attributing every vanished temporary file to an unavailable containing drive.+- Enter/click activation cancels the stale semantic query, snapshots the selected path and dispatches Windows opening on a separate thread. The compact popup closes immediately. Failures are reported and restore a hidden popup. COM initialization and a completed shell handoff keep shortcuts/packaged-app activation safe after the worker exits. Windows retains normal application-startup time; there is no embedding dependency.++## Necessary broader scans++An initial catch-up without continuous journal coverage, a journal gap, or a provider notification-loss signal may require checking more files because exact changed paths are unknown. This is a reliability fallback, not the response to an ordinary file-change notification. Folder creation/rename notifications cover the named subtree. Explicit Update index and configured scheduled updates intentionally check their configured sources. Existing idle/game/power rules still gate automatic work.++## Validation++173 automated tests passed (10 existing opt-in tests not run), and build/formatting checks passed. The screenshot dialog regression fixtures were also rechecked with the combined build.++The tests cover real Windows notification delivery after a manual scan: the old recovery is acknowledged, the next created file produces a one-file targeted update, and an unchanged sibling's scan epoch stays unchanged. Ten thousand known paths drain in three bounded targeted batches without duplicates or a global recovery. Other tests preserve newer writes/recovery generations, leave unrelated Full/Quick jobs untouched, bound memory during queue failure, and coalesce a 50-request statistics burst.++A blocked local embedding-server fixture verifies independent selected-action dispatch. Additional real Windows checks launched a harmless, window-free fixture executable and its shortcut before releasing the embedding response (test durations 0.11 s and 0.82 s respectively). These are handoff regression checks, not general application-startup benchmarks.++Shell handoff reference: [Microsoft SHELLEXECUTEINFO documentation](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfow). No external embeddings server or active user index was changed for these tests.diff --git a/native/docs/COMPACT-DIALOGS.md b/native/docs/COMPACT-DIALOGS.mdnew file mode 100644index 0000000..0f93ed0--- /dev/null+++ b/native/docs/COMPACT-DIALOGS.md@@ -0,0 +1,12 @@+# Compact popup dialog sizing++Unreleased follow-up on PR #16 after 0.3.25-beta.4.++The screenshot chooser is an egui window inside the search viewport, not a separate native window. Previously only Filter/dropdown state expanded that viewport, so the screenshot chooser could be constrained to a 254-pixel host and lose its title/controls.++- Screenshot selection, sent-image viewing and changelog dialogs expand the popup to at least 640 pixels. Save Search, clipboard clearing, delete/uninstall/index confirmations, Filter and dropdown menus request at least 500 pixels. Closing the final dialog/menu restores the normal empty Search/AI height.+- All in-window dialogs use a shared viewport-constrained, scrollable builder. The separate native Quick Look window retains its normal sizing; its embedded fallback also uses the constrained builder.+- Screenshot selection uses bounded-height preview/list columns. Long window titles truncate with full-title tooltips. Attach stays below the preview rather than inside a growing list. Sent-image previews reserve room for Copy.+- Dialog state now also prevents the popup host's focus-loss dismissal from interrupting these dialogs.++Validation: application build and formatting passed; 173 tests passed (10 existing opt-in tests not run), including a geometry regression that resizes a long-content dialog through 940×640, 780×500 and 780×254 hosts. Eighteen harmless UI fixture checks covered all nine dialog types, empty/landscape/portrait screenshot previews, visible Attach/Copy actions, main-window capture, Filter/type dropdowns, and restoring compact heights after closing capture/Save Search/sent-image dialogs. Destructive confirmation dialogs were rendered without activating their actions. No actual screenshots, external servers or active user index were used by these fixtures.diff --git a/native/src/app.rs b/native/src/app.rsindex b599ec5..508aab5 100644--- a/native/src/app.rs+++ b/native/src/app.rs@@ -150,7 +150,7 @@ pub struct App {model_warm_attempted: bool,model_warm_error: Option<String>,last_search_mode: String,- popup_model_panel: bool,+ popup_panel_height: u32,clear_index_confirm: bool,index_clearing: bool,tool: String,@@ -442,7 +442,7 @@ impl App {model_warm_attempted: false,model_warm_error: None,last_search_mode: String::new(),- popup_model_panel: false,+ popup_panel_height: 0,clear_index_confirm: false,index_clearing: false,tool: "Search".into(),@@ -670,6 +670,95 @@ impl App {app.search_pending = false;}}+ if app.smoke.is_some() {+ let args = std::env::args().collect::<Vec<_>>();+ if let Some(kind) = args+ .iter()+ .position(|v| v == "--smoke-dialog")+ .and_then(|i| args.get(i + 1))+ {+ match kind.as_str() {+ "capture" => {+ app.tool = "AI".into();+ app.capture_open = true;+ app.capture_targets = (0..30)+ .map(|id| crate::capture::Target {+ id,+ window: true,+ label: format!(+ "Window {id}: {}",+ "Long application title ".repeat(12)+ ),+ })+ .collect();+ }+ "save" => {+ app.save_search_open = true;+ app.query = "Search query ".repeat(50);+ }+ "clipboard-clear" => app.clipboard_clear_confirm = true,+ "delete" => {+ app.delete_confirm = Some(Hit {+ path: "C:\\fixture\\selected-file.txt".into(),+ kind: "file".into(),+ text: String::new(),+ score: 0.0,+ reason: String::new(),+ page: 0,+ seconds: 0.0,+ line: 0,+ })+ }+ "component" => app.remove_component = Some("dictation".into()),+ "uninstall" => app.uninstall_confirm = true,+ "clear-index" => app.clear_index_confirm = true,+ "changelog" => {+ app.show_changelog = true;+ app.update_release = Some(crate::updates::Release {+ version: "fixture".into(),+ page: String::new(),+ url: String::new(),+ digest: String::new(),+ size: 0,+ name: String::new(),+ changes: vec![crate::updates::ReleaseNote {+ version: "fixture".into(),+ date: String::new(),+ title: "Fixture changes".into(),+ body: "A release note with enough text to require scrolling.\n"+ .repeat(80),+ page: String::new(),+ }],+ });+ }+ "sent-image" => {+ app.tool = "AI".into();+ }+ _ => {}+ }+ if let Some(path) = args+ .iter()+ .position(|v| v == "--smoke-dialog-image")+ .and_then(|i| args.get(i + 1))+ {+ let bytes = std::fs::read(path)?;+ if kind == "sent-image" {+ app.ai_image_view = Some(crate::capture::vision(&bytes, None)?);+ } else if kind == "capture" {+ let image = image::load_from_memory(&bytes)?.to_rgba8();+ app.capture_texture = Some(cc.egui_ctx.load_texture(+ "fixture-capture",+ egui::ColorImage::from_rgba_unmultiplied(+ [image.width() as usize, image.height() as usize],+ image.as_raw(),+ ),+ Default::default(),+ ));+ app.capture_bytes = Some(bytes);+ }+ }+ }+ }if app.smoke.is_some() {// Hidden popups may stop receiving frames; use a background deadline.let tx = app.engine.tx.clone();@@ -1366,6 +1455,18 @@ impl App {}}Event::Progress(p) => self.progress = p,+ Event::OpenDone(result) => {+ if let Err(error) = result {+ self.status = error.clone();+ self.engine+ .log("Error", format!("Open selected item failed: {error}"));+ if self.quick {+ self.search_visible = true;+ ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);+ }+ }+ }Event::IndexDone(result) => {self.indexing = false;if result.is_ok() {@@ -3105,6 +3206,11 @@ impl App {return;}if let Some(hit) = self.hits.get(self.selected).cloned() {+ // Activation is independent of the optional semantic request.+ self.engine.models.cancel_query();+ self.sequence += 1;+ self.search_pending = false;+ self.dirty = false;if hit.kind == "calculator" {ctx.copy_text(hit.path);return;@@ -3123,7 +3229,11 @@ impl App {_ => {}}}- self.run(crate::platform::open(&hit.path));+ let tx = self.engine.tx.clone();+ crate::engine::dispatch_action(tx, move || crate::platform::open(&hit.path));+ if self.quick {+ self.close_window(ctx);+ }}}fn sources(&mut self, ui: &mut egui::Ui) {@@ -4996,12 +5106,25 @@ impl App {});}+ fn popup_dialog_open(&self) -> bool {+ self.capture_open+ || self.save_search_open+ || self.filter_open+ || self.clipboard_clear_confirm+ || self.ai_image_view.is_some()+ || self.show_changelog+ || self.delete_confirm.is_some()+ || self.remove_component.is_some()+ || self.uninstall_confirm+ || self.clear_index_confirm+ }+fn capture_ui(&mut self, ctx: &egui::Context) {if !self.capture_open {return;}let mut open = true;- egui::Window::new("Screenshot for AI").open(&mut open).default_width(860.0).resizable(true).show(ctx,|ui|{+ dialog_window(ctx, "Screenshot for AI", 860.0).min_height((ctx.content_rect().height()-110.0).clamp(100.0,520.0)).open(&mut open).default_width(860.0).resizable(true).show(ctx,|ui|{ui.label("Choose a window or monitor and review its preview. Attach a screenshot; Send submits it to the selected vision model.");if ui.add_enabled(!self.capture_busy,egui::Button::new("Select area anywhere on screen")).clicked(){self.capture_busy=true;self.capture_target=None;self.capture_preview_key=None;self.capture_texture=None;self.capture_bytes=None;@@ -5013,16 +5136,19 @@ impl App {let _=tx.send(Event::Screenshot(result));});}+ let body_height = (ctx.content_rect().height()-220.0).clamp(100.0,330.0);+ ui.allocate_ui_with_layout(egui::vec2(ui.available_width(),body_height),egui::Layout::top_down(egui::Align::Min),|ui| {ui.columns(2,|columns|{- egui::ScrollArea::vertical().id_salt("capture-choices").max_height(330.0).show(&mut columns[0],|ui|{+ egui::ScrollArea::vertical().id_salt("capture-choices").max_height(body_height).auto_shrink([false,false]).show(&mut columns[0],|ui|{for target in &self.capture_targets{- if ui.add_enabled(!self.capture_busy, egui::Button::new(&target.label).selected(self.capture_target.as_ref().is_some_and(|t|t.id==target.id&&t.window==target.window))).clicked(){self.capture_target=Some(target.clone());self.capture_bytes=None;self.capture_texture=None;}+ if ui.add_enabled_ui(!self.capture_busy, |ui| ui.add_sized([ui.available_width(),34.0], egui::Button::new(&target.label).truncate().selected(self.capture_target.as_ref().is_some_and(|t|t.id==target.id&&t.window==target.window)))).inner.on_hover_text(&target.label).clicked(){self.capture_target=Some(target.clone());self.capture_bytes=None;self.capture_texture=None;}}});let ui=&mut columns[1];- if let Some(texture)=&self.capture_texture{ui.add(egui::Image::new(texture).max_size(egui::vec2(ui.available_width(),330.0)));}+ if let Some(texture)=&self.capture_texture{ui.add(egui::Image::new(texture).max_size(egui::vec2(ui.available_width(),body_height)));}else if self.capture_busy{ui.spinner();}else{ui.centered_and_justified(|ui|{ui.label("Select a source to preview.");});}});+ });if let Some(target)=self.capture_target.clone(){let key=(target.id,target.window);if self.capture_preview_key!=Some(key)&&!self.capture_busy{@@ -5030,7 +5156,9 @@ impl App {let tx=self.engine.tx.clone();std::thread::spawn(move||{let _=tx.send(Event::Screenshot(crate::capture::grab(&target).map_err(|e|e.to_string())));});}}- if ui.add_enabled(!self.capture_busy&&self.capture_bytes.is_some(),egui::Button::new("Attach screenshot")).clicked(){+ let attach = ui.add_enabled(!self.capture_busy&&self.capture_bytes.is_some(),egui::Button::new("Attach screenshot"));+ if self.smoke.is_some() {ctx.data_mut(|d| d.insert_temp(egui::Id::new("qa-attach-screenshot"),attach.rect));}+ if attach.clicked(){if let Some(bytes)=&self.capture_bytes{match crate::capture::vision(bytes,None){Ok(url)=>{self.ai_images=vec![url];self.ai_attachment=self.capture_texture.clone();self.capture_open=false;},Err(e)=>self.ai_error=Some(e.to_string())}}}});@@ -6032,6 +6160,22 @@ impl eframe::App for App {{self.filter_open = false;}+ if self.smoke.is_some()+ && self.startup.elapsed() > Duration::from_secs(3)+ && std::env::args().any(|a| a == "--smoke-dialog-close")+ {+ self.capture_open = false;+ self.save_search_open = false;+ self.filter_open = false;+ self.clipboard_clear_confirm = false;+ self.ai_image_view = None;+ self.show_changelog = false;+ self.delete_confirm = None;+ self.remove_component = None;+ self.uninstall_confirm = false;+ self.clear_index_confirm = false;+ self.query.clear();+ }if ctx.input(|i| i.modifiers.ctrl && i.key_pressed(egui::Key::F)) {self.page = 0;self.select_query = true;@@ -6643,12 +6787,7 @@ impl eframe::App for App {let outside_down = crate::platform::left_button_down();let outside_click = outside_down && !self.popup_outside_down && !focused;self.popup_outside_down = outside_down;- if (self.ai_busy- || self.tts_busy- || self.dictation_busy- || self.capture_open- || self.save_search_open- || self.filter_open)+ if (self.ai_busy || self.tts_busy || self.dictation_busy || self.popup_dialog_open())&& !focused{self.popup_had_focus = false;@@ -6659,9 +6798,7 @@ impl eframe::App for App {&& !self.ai_busy&& !self.tts_busy&& !self.dictation_busy- && !self.capture_open- && !self.save_search_open- && !self.filter_open+ && !self.popup_dialog_open(){self.popup_had_focus = false;self.engine.models.cancel_query();@@ -6683,12 +6820,19 @@ impl eframe::App for App {};let expansion =ctx.animate_bool_with_time(egui::Id::new("popup-expansion"), !empty, 0.18);- let panel = self.filter_open || egui::Popup::is_any_open(ctx);+ let panel_height =+ if self.capture_open || self.ai_image_view.is_some() || self.show_changelog {+ 640+ } else if self.popup_dialog_open() || egui::Popup::is_any_open(ctx) {+ 500+ } else {+ 0+ };if self.popup_size_state != Some(empty)- || self.popup_model_panel != panel+ || self.popup_panel_height != panel_height|| (expansion > 0.0 && expansion < 1.0){- self.popup_model_panel = panel;+ self.popup_panel_height = panel_height;self.popup_size_state = Some(empty);ctx.send_viewport_cmd(egui::ViewportCommand::MinInnerSize(egui::vec2(780.0,@@ -6701,7 +6845,7 @@ impl eframe::App for App {} else {194.0 + 446.0 * expansion}- .max(if panel { 500.0 } else { 0.0 }),+ .max(panel_height as f32),)));}} else {@@ -6924,7 +7068,8 @@ impl eframe::App for App {self.capture_ui(ctx);if let Some(image) = self.ai_image_view.clone() {let mut open = true;- egui::Window::new("Sent screenshot")+ dialog_window(ctx, "Sent screenshot", 700.0)+ .min_height((ctx.content_rect().height() - 110.0).clamp(100.0, 520.0)).open(&mut open).default_width(700.0).show(ctx, |ui| {@@ -6934,10 +7079,19 @@ impl eframe::App for App {format!("bytes://ai-screenshot-{}.jpg", image_key(&image)),bytes,)- .max_size(egui::vec2(ui.available_width(), 500.0)),+ .max_size(egui::vec2(+ ui.available_width(),+ (ctx.content_rect().height() - 180.0).clamp(100.0, 440.0),+ )),);}- if ui.button("Copy screenshot").clicked() {+ let copy = ui.button("Copy screenshot");+ if self.smoke.is_some() {+ ctx.data_mut(|d| {+ d.insert_temp(egui::Id::new("qa-copy-screenshot"), copy.rect)+ });+ }+ if copy.clicked() {self.run(copy_ai_image(&image));}});@@ -6946,7 +7100,7 @@ impl eframe::App for App {}}if let Some(key) = self.remove_component.clone() {- egui::Window::new("Uninstall downloaded item?").collapsible(false).resizable(false).show(ctx,|ui|{+ dialog_window(ctx, "Uninstall downloaded item?", 440.0).collapsible(false).resizable(false).show(ctx,|ui|{ui.label(format!("Remove the downloaded {key} files? Index data is kept. Active indexing and model work will stop."));ui.horizontal(|ui|{if ui.button("Uninstall").clicked(){@@ -6966,7 +7120,7 @@ impl eframe::App for App {}if self.save_search_open {let mut open = true;- egui::Window::new("Save search")+ dialog_window(ctx, "Save search", 340.0).open(&mut open).collapsible(false).resizable(false)@@ -7013,7 +7167,7 @@ impl eframe::App for App {self.save_search_open &= open;}if self.clipboard_clear_confirm {- egui::Window::new("Clear clipboard history?").collapsible(false).resizable(false).show(ctx,|ui|{+ dialog_window(ctx, "Clear clipboard history?", 440.0).collapsible(false).resizable(false).show(ctx,|ui|{ui.label("Remove all saved clipboard entries? Your current Windows clipboard is kept.");ui.horizontal(|ui|{if ui.button("Clear history").clicked(){self.clipboard_clear_confirm=false;let store=crate::launcher::Clipboard::new(&self.home);let tx=self.engine.tx.clone();std::thread::spawn(move||{let _=tx.send(Event::ClipboardCleared(store.clear().map_err(|e|e.to_string())));});}@@ -7023,7 +7177,7 @@ impl eframe::App for App {}if self.show_changelog {let mut open = true;- egui::Window::new("Changes since your installed version")+ dialog_window(ctx, "Changes since your installed version", 720.0).id(egui::Id::new("update-changelog")).open(&mut open).collapsible(false)@@ -7135,7 +7289,7 @@ impl eframe::App for App {}if class == egui::ViewportClass::Embedded {let mut open = true;- egui::Window::new("Quick Look")+ dialog_window(child, "Quick Look", 700.0).open(&mut open).fixed_size([900.0, 650.0]).show(child, |ui| self.preview(ui, child));@@ -7163,7 +7317,7 @@ impl eframe::App for App {);}if let Some(hit) = self.delete_confirm.clone() {- egui::Window::new("Delete selected item?")+ dialog_window(ctx, "Delete selected item?", 440.0).collapsible(false).show(ctx, |ui| {ui.label(&hit.path);@@ -7185,14 +7339,14 @@ impl eframe::App for App {});}if self.uninstall_confirm {- egui::Window::new("Uninstall downloaded models and runtimes?").collapsible(false).show(ctx,|ui|{+ dialog_window(ctx, "Uninstall downloaded models and runtimes?", 440.0).collapsible(false).show(ctx,|ui|{ui.label("Remove managed downloads from the current and legacy VectorDash folders? Source files, external tools and the index are kept. Automatic indexing will pause.");if ui.button("Uninstall downloads").clicked(){self.uninstall_downloads();}if ui.button("Cancel").clicked(){self.uninstall_confirm=false;}});}if self.clear_index_confirm {- egui::Window::new("Clear entire index?").collapsible(false).resizable(false).show(ctx, |ui| {+ dialog_window(ctx, "Clear entire index?", 440.0).collapsible(false).resizable(false).show(ctx, |ui| {ui.label("Remove all indexed names, document/OCR text, embeddings and indexing history from the active database?");ui.label("Your original files, sources, settings and downloaded models are kept. Retained conversion/import backups are not deleted.");ui.label("Automatic indexing will pause. Remove unwanted sources or add exclusions before rebuilding.");@@ -7226,6 +7380,8 @@ impl eframe::App for App {("footer_status", "qa-footer-status"),("footer_row", "qa-footer-row"),("filter_bounds", "qa-filter-bounds"),+ ("attach_screenshot", "qa-attach-screenshot"),+ ("copy_screenshot", "qa-copy-screenshot"),("type_last_choice", "qa-type-last"),("playback_pause", "qa-playback-pause"),("open_full_button", "qa-open-full"),@@ -7250,6 +7406,33 @@ impl eframe::App for App {);data["window_size"] =serde_json::json!([ctx.content_rect().width(), ctx.content_rect().height()]);+ let mut dialogs = std::collections::BTreeMap::new();+ for title in [+ "Screenshot for AI",+ "Sent screenshot",+ "Uninstall downloaded item?",+ "Save search",+ "Clear clipboard history?",+ "Delete selected item?",+ "Uninstall downloaded models and runtimes?",+ "Clear entire index?",+ ] {+ if let Some(rect) =+ ctx.memory(|m| m.area_rect(egui::Id::new(("app-dialog", title))))+ {+ dialogs.insert(+ title,+ [rect.left(), rect.top(), rect.right(), rect.bottom()],+ );+ }+ }+ if let Some(rect) = ctx.memory(|m| m.area_rect(egui::Id::new("update-changelog"))) {+ dialogs.insert(+ "Changes since your installed version",+ [rect.left(), rect.top(), rect.right(), rect.bottom()],+ );+ }+ data["dialogs"] = serde_json::json!(dialogs);data["filter_open"] = serde_json::json!(self.filter_open);data["qa_pause_seen"] = serde_json::json!(ctx.data(|d| d.get_temp::<bool>(egui::Id::new("qa-pause-seen")))@@ -7293,6 +7476,24 @@ impl eframe::App for App {self.mcp = None;}}+fn dialog_window<'a>(ctx: &egui::Context, title: &'a str, width: f32) -> egui::Window<'a> {+ let bounds = ctx.content_rect().shrink(12.0);+ let width = width.min((bounds.width() - 24.0).max(120.0));+ egui::Window::new(title)+ .id(egui::Id::new(("app-dialog", title)))+ .constrain_to(bounds)+ .default_pos(egui::pos2(+ (bounds.center().x - width * 0.5).max(bounds.left()),+ bounds.top(),+ ))+ .default_width(width)+ .min_width(120.0)+ .max_width((bounds.width() - 24.0).max(120.0))+ .min_height(0.0)+ .max_height((bounds.height() - 48.0).max(40.0))+ .vscroll(true)+}+fn combo(ui: &mut egui::Ui, id: &str, value: &mut String, items: &[&str]) -> egui::Response {egui::ComboBox::from_id_salt(id).selected_text(if *value == "Both" {@@ -7854,3 +8055,28 @@ mod preview_resize_tests {}}}++#[cfg(test)]+mod dialog_bounds_tests {+ use super::*;+ #[test]+ fn long_dialogs_stay_inside_small_or_resized_hosts() {+ let ctx = egui::Context::default();+ for size in [+ egui::vec2(940.0, 640.0),+ egui::vec2(780.0, 500.0),+ egui::vec2(780.0, 254.0),+ ] {+ for _ in 0..4 {+ let _=ctx.run(egui::RawInput{screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,size)),..Default::default()},|ctx|{+ let response=dialog_window(ctx,"Bounds regression",860.0).show(ctx,|ui|{+ for _ in 0..50 {ui.label("Long dialog content that must scroll rather than grow beyond the host window.");}+ let _ = ui.button("Action");+ }).unwrap();+ let r=response.response.rect;+ assert!(r.left()>=0.0 && r.top()>=0.0 && r.right()<=size.x+1.0 && r.bottom()<=size.y+1.0,"{r:?} outside {size:?}");+ });+ }+ }+ }+}diff --git a/native/src/changes.rs b/native/src/changes.rsindex c18d5be..54be6e7 100644--- a/native/src/changes.rs+++ b/native/src/changes.rs@@ -8,12 +8,45 @@ use std::{path::{Path, PathBuf},time::{Duration, Instant},};+/// Bounded overflow buffer retains exact paths if the event channel is busy.+/// Only a genuinely saturated spill falls back to the affected source, never+/// all sources. The durable queue is drained in bounded batches separately.+#[derive(Default)]+struct NotificationSpill {+ paths: HashSet<PathBuf>,+ roots: HashSet<PathBuf>,+}+impl NotificationSpill {+ fn insert(&mut self, path: PathBuf, settings: &Settings) {+ if self.roots.iter().any(|r| path.starts_with(r)) {+ return;+ }+ if self.paths.len() < 32768 {+ self.paths.insert(path);+ return;+ }+ if let Some(root) = settings+ .roots+ .iter()+ .filter(|r| under(&path.to_string_lossy(), &r.path))+ .max_by_key(|r| r.path.len())+ {+ let root = PathBuf::from(&root.path);+ self.paths.retain(|p| !p.starts_with(&root));+ self.roots.insert(root);+ }+ }+}#[derive(Default)]pub struct Monitor {watcher: Option<notify::RecommendedWatcher>,rx: Option<std::sync::mpsc::Receiver<notify::Result<notify::Event>>>,signature: String,+ settings: Option<Settings>,+ logger: Option<NotifySender>,overflow: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,+ spill: Option<std::sync::Arc<std::sync::Mutex<NotificationSpill>>>,+ recovery_reason: String,pending: HashSet<PathBuf>,recovery: bool,recovery_saved: bool,@@ -48,6 +81,9 @@ impl Monitor {return;}self.signature = signature;+ self.settings = Some(s.clone());+ self.logger = Some(tx.clone());+ self.recovery_reason.clear();self.watcher = None;self.rx = None;self.pending.clear();@@ -62,7 +98,7 @@ impl Monitor {}if let Ok(db) = crate::db::Database::new(home, s) {if let Ok(c) = db.connect(false) {- let result=c.execute_batch("CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL);");+ let result=c.execute_batch("CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS native_changes_queued ON native_changes(queued,path);");if result.is_ok() {let _ = crate::db::register_search(&c, s, "All files", "", "", None);let _=c.execute("DELETE FROM native_changes WHERE path!='' AND NOT vd_match(path,'file',0,0)",[]);@@ -97,6 +133,8 @@ impl Monitor {let (sender, rx) = std::sync::mpsc::sync_channel(1024);let overflow = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));let flag = overflow.clone();+ let spill = std::sync::Arc::new(std::sync::Mutex::new(NotificationSpill::default()));+ let callback_spill = spill.clone();let filter = s.clone();let data_home = home.to_path_buf();let mut watcher =@@ -126,8 +164,21 @@ impl Monitor {{return;}- if sender.try_send(event).is_err() {- flag.store(true, std::sync::atomic::Ordering::Relaxed);+ if let Err(std::sync::mpsc::TrySendError::Full(event)) = sender.try_send(event) {+ match event {+ Ok(e) if !e.need_rescan() => {+ if let Ok(mut spill) = callback_spill.lock() {+ for path in e.paths {+ spill.insert(path, &filter);+ }+ } else {+ flag.store(true, std::sync::atomic::Ordering::Relaxed);+ }+ }+ _ => {+ flag.store(true, std::sync::atomic::Ordering::Relaxed);+ }+ }}}) {Ok(w) => w,@@ -172,12 +223,12 @@ impl Monitor {if !self.pending.is_empty() && !self.recovery {self.startup_recovery = true;} else {- self.recovery = true;- self.last = Some(Instant::now());+ self.request_recovery("startup catch-up without continuous journal coverage");self.first = self.last;}}self.overflow = Some(overflow);+ self.spill = Some(spill);self.rx = Some(rx);self.watcher = Some(watcher);let _ = tx.send(Event::Log(@@ -188,82 +239,100 @@ impl Monitor {),));}+ fn request_recovery(&mut self, reason: &str) {+ self.recovery = true;+ self.recovery_reason = reason.into();+ self.dirty.insert(PathBuf::new()); // refresh the durable recovery generation/time too+ self.last = Some(Instant::now());+ }+ fn queue_path(&mut self, path: PathBuf) {+ if self.dirty.len() >= 8192 && !self.dirty.contains(&path) {+ let saved = self.persist().is_ok() && self.dirty.is_empty();+ if !saved {+ self.pending.clear();+ self.dirty.clear();+ self.request_recovery("durable change queue unavailable; bounded memory fallback");+ }+ }+ self.last = Some(Instant::now());+ self.dirty.insert(path.clone());+ if self.pending.len() < 4096 || self.pending.contains(&path) {+ self.pending.insert(path);+ } else if self.store.is_none() {+ self.request_recovery("durable change queue unavailable");+ }+ // Additional known paths are persisted, then loaded after this batch.+ }pub fn collect(&mut self, s: &Settings, home: &Path) {let (paths, recovery) = self.journal.poll();if recovery {- self.recovery = true;- self.last = Some(Instant::now());+ self.request_recovery("NTFS journal gap or inaccessible journal");}for path in paths {- if !under(&path.to_string_lossy(), &home.to_string_lossy())- && s.roots- .iter()- .any(|r| under(&path.to_string_lossy(), &r.path))- && s.allowed(&path)- {- if self.pending.len() < 4096 {- self.dirty.insert(path.clone());- self.pending.insert(path);- } else {- self.recovery = true;- self.pending.clear();- }- self.last = Some(Instant::now());+ if !under(&path.to_string_lossy(), &home.to_string_lossy()) && s.searched(&path) {+ self.queue_path(path);}}-if self.overflow.as_ref().is_some_and(|f| f.swap(false, std::sync::atomic::Ordering::Relaxed)){- self.recovery = true;- self.last = Some(Instant::now());+ self.request_recovery("notification information was lost");}- if let Some(rx) = &self.rx {- for result in rx.try_iter().take(1024) {- match result {- Ok(event) => {- if event.need_rescan() {- self.recovery = true;- self.last = Some(Instant::now());- }- if matches!(event.kind, notify::EventKind::Access(_)) {+ let spilled = self.spill.as_ref().and_then(|buffer| {+ buffer.lock().ok().map(|mut buffer| {+ let mut paths = buffer.paths.drain().collect::<Vec<_>>();+ let roots=buffer.roots.drain().collect::<Vec<_>>();+ if !roots.is_empty() {+ if let Some(tx)=&self.logger {let _=tx.send(Event::Log("Warning".into(),format!("Notification spill reached its memory limit; rechecking only affected sources: {}",roots.iter().map(|r|r.display().to_string()).collect::<Vec<_>>().join("; "))));}+ }+ paths.extend(roots);+ paths+ })+ });+ if let Some(paths) = spilled {+ for path in paths {+ self.queue_path(path);+ }+ }+ let events = self+ .rx+ .as_ref()+ .map(|rx| rx.try_iter().take(4096).collect::<Vec<_>>())+ .unwrap_or_default();+ for result in events {+ match result {+ Ok(event) => {+ if event.need_rescan() {+ self.request_recovery(+ "Windows/provider requested a rescan after missed events",+ );+ }+ if matches!(event.kind, notify::EventKind::Access(_)) {+ continue;+ }+ for path in event.paths {+ if directory_metadata_only(&event.kind, &path) {continue;}- for path in event.paths {- if directory_metadata_only(&event.kind, &path) {- continue;- }- if !under(&path.to_string_lossy(), &home.to_string_lossy())- && s.roots- .iter()- .any(|r| under(&path.to_string_lossy(), &r.path))- && s.roots- .iter()- .filter(|r| under(&path.to_string_lossy(), &r.path))- .max_by_key(|r| r.path.len())- .is_some_and(|root| {- path.ancestors()- .take_while(|p| under(&p.to_string_lossy(), &root.path))- .all(|p| s.allowed(p))- })- {- self.last = Some(Instant::now());- if self.pending.len() < 4096 {- self.dirty.insert(path.clone());- self.pending.insert(path);- } else {- self.recovery = true;- self.pending.clear();- }- }+ if !under(&path.to_string_lossy(), &home.to_string_lossy())+ && s.roots+ .iter()+ .filter(|r| under(&path.to_string_lossy(), &r.path))+ .max_by_key(|r| r.path.len())+ .is_some_and(|root| {+ path.ancestors()+ .take_while(|p| under(&p.to_string_lossy(), &root.path))+ .all(|p| s.allowed(p))+ })+ {+ self.queue_path(path);}}- Err(_) => {- self.recovery = true;- self.last = Some(Instant::now());- }+ }+ Err(error) => {+ self.request_recovery(&format!("folder watcher reported an error: {error}"))}}}@@ -272,6 +341,28 @@ impl Monitor {}let _ = self.persist();}+ /// A completed whole-source scan covers only notifications queued before+ /// it started. Later generations (including repeated writes to one path)+ /// must survive and remain targeted.+ pub fn acknowledge_full_scan(&mut self, started: i64, s: &Settings) -> anyhow::Result<()> {+ self.persist()?;+ let Some(db) = &self.store else {+ return Ok(());+ };+ let c = db.connect(false)?;+ c.execute("DELETE FROM native_changes WHERE queued<?1", [started])?;+ drop(c);+ self.pending.clear();+ self.recovery = false;+ self.recovery_saved = false;+ self.startup_recovery = false;+ self.last = None;+ self.first = None;+ self.retry_after = None;+ self.failures = 0;+ self.restore(s);+ Ok(())+ }fn persist(&mut self) -> anyhow::Result<()> {if self.recovery && !self.recovery_saved {self.dirty.insert(PathBuf::new());@@ -285,8 +376,16 @@ impl Monitor {let mut c = db.connect(false)?;let tx = c.transaction()?;self.generation += 1;- for path in &self.dirty {- tx.execute("INSERT INTO native_changes VALUES(?1,?2,?3) ON CONFLICT(path) DO UPDATE SET generation=excluded.generation",rusqlite::params![path.to_string_lossy(),self.generation,chrono::Utc::now().timestamp_millis()])?;+ {+ let queued = chrono::Utc::now().timestamp_millis();+ let mut statement=tx.prepare_cached("INSERT INTO native_changes VALUES(?1,?2,?3) ON CONFLICT(path) DO UPDATE SET generation=excluded.generation,queued=excluded.queued")?;+ for path in &self.dirty {+ statement.execute(rusqlite::params![+ path.to_string_lossy(),+ self.generation,+ queued+ ])?;+ }}tx.commit()?;if self.dirty.contains(&PathBuf::new()) {@@ -302,7 +401,7 @@ impl Monitor {let Ok(c) = db.connect(true) else {return;};- let Ok(mut stmt) = c.prepare("SELECT path FROM native_changes ORDER BY queued LIMIT 4097")+ let Ok(mut stmt) = c.prepare("SELECT path FROM native_changes ORDER BY queued LIMIT 4096")else {return;};@@ -311,7 +410,7 @@ impl Monitor {if path.is_empty() {self.recovery = true;self.recovery_saved = true;- } else if s.searched(Path::new(&path)) {+ } else if s.searched(Path::new(&path)) && self.pending.len() < 4096 {self.pending.insert(path.into());}}@@ -347,7 +446,14 @@ impl Monitor {return "No sources could be monitored; check warnings in Logs".into();}let pending = if self.recovery {- "catch-up/recovery scan queued".into()+ format!(+ "catch-up/recovery scan queued ({})",+ if self.recovery_reason.is_empty() {+ "startup/interrupted work"+ } else {+ &self.recovery_reason+ }+ )} else {format!("{} changed paths queued", self.pending.len())};@@ -408,8 +514,14 @@ impl Monitor {if let Ok(mut c) = db.connect(false) {if let Ok(tx) = c.transaction() {let result = (|| -> anyhow::Result<()> {+ let mut statement = tx.prepare_cached(+ "DELETE FROM native_changes WHERE path=?1 AND generation=?2",+ )?;for (path, generation) in &inflight {- tx.execute("DELETE FROM native_changes WHERE path=?1 AND generation=?2",rusqlite::params![path.to_string_lossy(),generation])?;+ statement.execute(rusqlite::params![+ path.to_string_lossy(),+ generation+ ])?;}Ok(())})();@@ -431,6 +543,11 @@ impl Monitor {self.first = self.last;}}+ if success {+ if let Some(settings) = self.settings.clone() {+ self.restore(&settings);+ }+ }if success && self.startup_recovery {self.startup_recovery = false;self.recovery = true;@@ -455,19 +572,28 @@ impl Monitor {let mut inflight = vec![];if let Some(db) = &self.store {if let Ok(c) = db.connect(true) {- if let Ok(mut stmt) = c.prepare(- "SELECT path,generation FROM native_changes ORDER BY queued LIMIT 4097",- ) {- if let Ok(rows) =- stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))+ if let Some(paths) = &paths {+ if let Ok(mut statement) =+ c.prepare_cached("SELECT generation FROM native_changes WHERE path=?1"){- for (path, generation) in rows.flatten() {- let path = PathBuf::from(path);- if paths.as_ref().is_none_or(|p| p.contains(&path)) {- inflight.push((path, generation));+ for path in paths {+ if let Ok(generation) = statement+ .query_row([path.to_string_lossy().as_ref()], |r| {+ r.get::<_, i64>(0)+ })+ {+ inflight.push((path.clone(), generation));}}}+ } else if let Ok(mut statement) = c.prepare(+ "SELECT path,generation FROM native_changes ORDER BY queued LIMIT 4096",+ ) {+ if let Ok(rows) = statement+ .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))+ {+ inflight.extend(rows.flatten().map(|(p, g)| (PathBuf::from(p), g)));+ }}}}@@ -622,6 +748,124 @@ mod durable_tests {(home, root, s, monitor)}#[test]+ fn unavailable_durable_queue_keeps_memory_bounded_and_requests_recovery() {+ let mut monitor = Monitor::default();+ for i in 0..20000 {+ monitor.queue_path(PathBuf::from(format!("file-{i}.txt")));+ }+ assert!(monitor.recovery);+ assert!(monitor.pending.len() <= 4096);+ assert!(monitor.dirty.len() <= 8192);+ }+ #[test]+ fn successful_full_scan_clears_old_recovery_but_preserves_new_notifications() {+ let (_home, root, s, mut monitor) = fixture();+ let old = root.path().join("old.txt");+ let later = root.path().join("later.txt");+ monitor.queue_path(old.clone());+ monitor.request_recovery("startup catch-up");+ monitor.persist().unwrap();+ monitor.startup_recovery = true;+ let db = monitor.store.as_ref().unwrap().clone();+ let c = db.connect(false).unwrap();+ c.execute("UPDATE native_changes SET queued=100", [])+ .unwrap();+ monitor.queue_path(later.clone());+ monitor.persist().unwrap();+ c.execute(+ "UPDATE native_changes SET queued=300 WHERE path=?1",+ [later.to_string_lossy().as_ref()],+ )+ .unwrap();+ drop(c);+ monitor.acknowledge_full_scan(200, &s).unwrap();+ assert!(!monitor.recovery && !monitor.startup_recovery);+ assert_eq!(monitor.take().unwrap(), vec![later]);+ }+ #[test]+ fn new_overflow_during_full_scan_is_not_acknowledged_as_old_work() {+ let (_home, _root, s, mut monitor) = fixture();+ monitor.request_recovery("new notification gap");+ monitor.persist().unwrap();+ let c = monitor.store.as_ref().unwrap().connect(false).unwrap();+ c.execute("UPDATE native_changes SET queued=300 WHERE path=''", [])+ .unwrap();+ drop(c);+ monitor.acknowledge_full_scan(200, &s).unwrap();+ assert!(monitor.recovery);+ }+ #[test]+ fn large_known_burst_is_durable_targeted_batches_not_a_global_recovery() {+ let (home, root, _s, mut monitor) = fixture();+ for i in 0..10000 {+ monitor.queue_path(root.path().join(format!("changed-{i}.txt")));+ }+ monitor.persist().unwrap();+ assert!(!monitor.recovery);+ assert!(monitor.pending.len() <= 4096);+ let c = monitor.store.as_ref().unwrap().connect(true).unwrap();+ let mut plan = c+ .prepare(+ "EXPLAIN QUERY PLAN SELECT path FROM native_changes ORDER BY queued LIMIT 4096",+ )+ .unwrap();+ let details = plan+ .query_map([], |r| r.get::<_, String>(3))+ .unwrap()+ .collect::<rusqlite::Result<Vec<_>>>()+ .unwrap();+ assert!(+ details.iter().any(|p| p.contains("native_changes_queued")),+ "{details:?}"+ );+ drop(plan);+ drop(c);+ let mut seen = HashSet::new();+ let mut batches = 0;+ while !monitor.pending.is_empty() {+ let paths = monitor.take().expect("known paths must stay targeted");+ assert!(paths.len() <= 4096);+ for path in paths {+ assert!(+ seen.insert(path),+ "path visited twice without a new generation"+ );+ }+ monitor.complete(true, home.path());+ batches += 1;+ }+ assert_eq!(seen.len(), 10000);+ assert_eq!(batches, 3);+ assert!(!monitor.recovery);+ let c = monitor.store.as_ref().unwrap().connect(true).unwrap();+ assert_eq!(+ c.query_row("SELECT count(*) FROM native_changes", [], |r| r+ .get::<_, usize>(0))+ .unwrap(),+ 0+ );+ }+ #[test]+ fn notification_spill_keeps_exact_paths_and_limits_extreme_fallback_to_affected_root() {+ let (_home, root, mut s, _monitor) = fixture();+ let other = tempfile::tempdir().unwrap();+ s.roots.push(crate::config::Source {+ path: other.path().to_string_lossy().into(),+ mode: "quick".into(),+ });+ let mut spill = NotificationSpill::default();+ for i in 0..10000 {+ spill.insert(root.path().join(format!("changed-{i}")), &s);+ }+ assert_eq!(spill.paths.len(), 10000);+ assert!(spill.roots.is_empty());+ for i in 10000..33000 {+ spill.insert(root.path().join(format!("changed-{i}")), &s);+ }+ assert!(spill.paths.len() <= 32768);+ assert_eq!(spill.roots, HashSet::from([root.path().to_path_buf()]));+ }+ #[test]fn pending_paths_survive_restart_and_failed_updates_stay_targeted() {let (home, root, s, mut monitor) = fixture();let path = root.path().join("changed.txt");diff --git a/native/src/engine.rs b/native/src/engine.rsindex 6d2b25e..354ca59 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -178,6 +178,7 @@ pub enum Event {Quit,Progress(Progress),IndexDone(Result<String, String>),+ OpenDone(Result<(), String>),Search(u64, Result<Vec<Hit>, String>, f64),SearchPartial(u64, Vec<Hit>, f64),SearchWarning(u64, String),@@ -201,7 +202,12 @@ pub struct Control {pub paused: Arc<AtomicBool>,pub automatic: Arc<AtomicBool>,pub watching: Arc<AtomicBool>,+ stats_busy: Arc<AtomicBool>,+ stats_requested: Arc<AtomicBool>,+ stats_started: Arc<std::sync::Mutex<Option<Instant>>>,+ stats_roots: Arc<std::sync::Mutex<Vec<String>>>,pub last_run_success: Arc<AtomicBool>,+ pub successful_full_scan_started: Arc<std::sync::atomic::AtomicI64>,pub running: Arc<AtomicBool>,pub automatic_hold: Arc<AtomicBool>,pub index_maintenance: Arc<AtomicBool>,@@ -332,22 +338,69 @@ pub struct Engine {pub searching: Arc<AtomicBool>,pub vectors: crate::vector_cache::Cache,}+pub(crate) fn dispatch_action(+ tx: NotifySender,+ action: impl FnOnce() -> Result<()> + Send + 'static,+) {+ std::thread::spawn(move || {+ let _ = tx.send(Event::OpenDone(action().map_err(|e| e.to_string())));+ });+}impl Engine {pub fn log(&self, level: &str, message: impl Into<String>) {let text = message.into();let _ = self.tx.send(Event::Log(level.into(), text));}pub fn refresh_stats(&self, s: &Settings) {- let d = self.db.clone();- let tx = self.tx.clone();- let roots = s.roots.clone();+ *self.control.stats_roots.lock().unwrap() =+ s.roots.iter().map(|r| r.path.clone()).collect();+ self.control.stats_requested.store(true, Ordering::Release);+ if self+ .control+ .stats_busy+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)+ .is_err()+ {+ return;+ }+ let owner = self.clone();std::thread::spawn(move || {- if let Ok(stats) = d.stats() {- let sources = roots- .iter()- .filter_map(|r| d.source_stats(&r.path).ok().map(|v| (r.path.clone(), v)))- .collect();- let _ = tx.send(Event::Stats(stats, sources));+ loop {+ let delay = owner+ .control+ .stats_started+ .lock()+ .unwrap()+ .map(|last| Duration::from_secs(5).saturating_sub(last.elapsed()))+ .unwrap_or_default();+ if !delay.is_zero() {+ std::thread::sleep(delay);+ }+ owner+ .control+ .stats_requested+ .store(false, Ordering::Release);+ *owner.control.stats_started.lock().unwrap() = Some(Instant::now());+ let roots = owner.control.stats_roots.lock().unwrap().clone();+ if let Ok(stats) = owner.db.stats() {+ let sources = roots+ .iter()+ .filter_map(|root| {+ owner.db.source_stats(root).ok().map(|v| (root.clone(), v))+ })+ .collect();+ let _ = owner.tx.send(Event::Stats(stats, sources));+ }+ owner.control.stats_busy.store(false, Ordering::Release);+ if !owner.control.stats_requested.load(Ordering::Acquire)+ || owner+ .control+ .stats_busy+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)+ .is_err()+ {+ break;+ }}});}@@ -379,6 +432,7 @@ impl Engine {let mut retry = Instant::now();let mut changes = crate::changes::Monitor::default();let mut last_watch_status = String::new();+ let mut acknowledged_full_scan = 0;let mut pruned_signature = engine.db.connect(true)@@ -449,6 +503,16 @@ impl Engine {}changes.persist_hold(engine.control.automatic_hold.load(Ordering::Acquire));changes.collect(&settings, &engine.db.home);+ let full_scan = engine+ .control+ .successful_full_scan_started+ .load(Ordering::Acquire);+ if full_scan > acknowledged_full_scan+ && changes.acknowledge_full_scan(full_scan, &settings).is_ok()+ {+ acknowledged_full_scan = full_scan;+ engine.log("Info","Completed full scan satisfied older queued monitoring work; later notifications remain targeted");+ }let watch_status = if engine.control.automatic_hold.load(Ordering::Acquire) {if engine.control.sources_pending.load(Ordering::Acquire) {"Sources changed; save to restart indexing with the updated sources".into()@@ -615,8 +679,16 @@ impl Engine {}self.control.paused.store(false, Ordering::Relaxed);let owner = self.clone();+ let full_scan = paths.is_none();+ let started = chrono::Utc::now().timestamp_millis();std::thread::spawn(move || {let result = owner.run_index(&s, force, paths).map_err(|e| e.to_string());+ if full_scan && result.is_ok() {+ owner+ .control+ .successful_full_scan_started+ .store(started, Ordering::Release);+ }owner.control.last_run_success@@ -654,6 +726,7 @@ impl Engine {self.run_index(s, force, None)}fn run_index(&self, s: &Settings, force: bool, paths: Option<Vec<PathBuf>>) -> Result<String> {+ let target_scope = paths.clone();let mut first = s.clone();let has_quick = s.roots.iter().any(|r| r.mode.eq_ignore_ascii_case("quick"));let has_full = s@@ -671,6 +744,19 @@ impl Engine {let summary = self.index_paths(&first, force, paths)?;let c = self.db.connect(false)?;crate::db::register_search(&c, s, "All files", "", "", None)?;+ c.create_scalar_function(+ "vd_run_scope",+ 1,+ rusqlite::functions::FunctionFlags::SQLITE_UTF8,+ move |ctx| {+ let path = ctx.get::<String>(0)?;+ Ok(target_scope.as_ref().is_none_or(|roots| {+ roots+ .iter()+ .any(|root| crate::config::under(&path, &root.to_string_lossy()))+ }))+ },+ )?;c.create_scalar_function("vd_available",1,@@ -682,7 +768,7 @@ impl Engine {)?;loop {self.control.file_checkpoint()?;- let mut stmt=c.prepare_cached("SELECT path FROM native_jobs j WHERE error='' AND vd_match(path,'text',0,0) AND vd_available(path) ORDER BY (SELECT coalesce(max(seq),-1) FROM native_staging WHERE token=j.token),rowid LIMIT 64")?;+ let mut stmt=c.prepare_cached("SELECT path FROM native_jobs j WHERE error='' AND vd_match(path,'text',0,0) AND CASE WHEN vd_run_scope(path) THEN vd_available(path) ELSE 0 END ORDER BY (SELECT coalesce(max(seq),-1) FROM native_staging WHERE token=j.token),rowid LIMIT 64")?;let paths = stmt.query_map([], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?@@ -702,7 +788,9 @@ impl Engine {}loop {self.control.file_checkpoint()?;- let mut stmt = c.prepare_cached("SELECT path FROM native_quick_queue LIMIT 256")?;+ let mut stmt = c.prepare_cached(+ "SELECT path FROM native_quick_queue WHERE vd_run_scope(path) LIMIT 256",+ )?;let queued = stmt.query_map([], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;@@ -790,6 +878,21 @@ impl Engine {selected.push(root);}}+ if partial {+ self.log(+ "Info",+ format!(+ "Targeted scan scope: {} path(s); {}",+ selected.len(),+ selected+ .iter()+ .take(4)+ .map(|p| p.display().to_string())+ .collect::<Vec<_>>()+ .join("; ")+ ),+ );+ }let mut pending_stmt = conn.prepare_cached("SELECT path FROM native_jobs WHERE error='' ORDER BY rowid LIMIT 64",)?;@@ -801,7 +904,7 @@ impl Engine {for path in pending.into_iter().rev()- .filter(|_| s.index_phase.is_empty())+ .filter(|_| s.index_phase.is_empty() && !partial){let path = PathBuf::from(path);if s.searched(&path) && !selected.contains(&path) {@@ -913,7 +1016,10 @@ impl Engine {if !root.exists() {self.log("Warning",- format!("Source unavailable; previous records retained: {root_s}"),+ format!(+ "Path unavailable; previous records retained: {} (source {root_s})",+ root.display()+ ),);progress.skipped += 1;continue;@@ -2637,6 +2743,116 @@ mod media_ranking_tests {mod automatic_watch_tests {use super::*;#[test]+ fn manual_scan_covers_startup_recovery_and_next_notification_visits_one_file() {+ let home = tempfile::tempdir().unwrap();+ let root = tempfile::Builder::new()+ .prefix("VD-manual-ack-")+ .tempdir()+ .unwrap();+ let existing = root.path().join("existing.txt");+ std::fs::write(&existing, "existing").unwrap();+ let mut s = Settings::default();+ s.encrypt_index = false;+ s.watch_changes = true;+ s.schedule = "Manual".into();+ s.check_cpu = false;+ s.check_gpu = false;+ s.check_user_idle = false;+ s.ac_only = false;+ s.pause_for_game = false;+ s.pause_for_fullscreen = false;+ s.roots = vec![crate::config::Source {+ path: root.path().to_string_lossy().into(),+ mode: "quick".into(),+ }];+ let (tx, rx) = crossbeam_channel::unbounded();+ let engine = Engine {+ db: Database::new(home.path(), &s).unwrap(),+ models: Models::default(),+ control: Control::default(),+ tx: tx.into(),+ searching: Arc::new(AtomicBool::new(false)),+ vectors: crate::vector_cache::Cache::default(),+ };+ *engine.control.schedule.lock().unwrap() = s.clone();+ let shutdown = Arc::new(AtomicBool::new(false));+ struct Stop(Arc<AtomicBool>);+ impl Drop for Stop {+ fn drop(&mut self) {+ self.0.store(true, Ordering::Release);+ }+ }+ let _stop = Stop(shutdown.clone());+ engine.start_scheduler(shutdown);+ let start = Instant::now();+ loop {+ assert!(start.elapsed() < Duration::from_secs(5));+ if let Ok(Event::WatchStatus(status)) = rx.recv_timeout(Duration::from_millis(100)) {+ if status.contains("recovery scan queued") {+ break;+ }+ }+ }+ std::thread::sleep(Duration::from_millis(20));+ engine.index(s, false);+ loop {+ assert!(start.elapsed() < Duration::from_secs(7));+ if let Ok(Event::IndexDone(result)) = rx.recv_timeout(Duration::from_millis(100)) {+ result.unwrap();+ break;+ }+ }+ let c = engine.db.connect(true).unwrap();+ let epoch = c+ .query_row(+ "SELECT epoch FROM source_seen WHERE path=?1",+ [existing.to_string_lossy().as_ref()],+ |r| r.get::<_, i64>(0),+ )+ .unwrap();+ loop {+ assert!(start.elapsed() < Duration::from_secs(9));+ if let Ok(Event::Log(_, line)) = rx.recv_timeout(Duration::from_millis(100)) {+ if line.starts_with("Completed full scan satisfied") {+ break;+ }+ }+ }+ assert_eq!(+ c.query_row(+ "SELECT count(*) FROM native_changes WHERE path=''",+ [],+ |r| r.get::<_, usize>(0)+ )+ .unwrap(),+ 0+ );+ let changed = root.path().join("only-new.txt");+ std::fs::write(&changed, "new").unwrap();+ let deadline = Instant::now() + Duration::from_secs(16);+ loop {+ assert!(Instant::now() < deadline);+ if let Ok(Event::IndexDone(result)) = rx.recv_timeout(Duration::from_millis(100)) {+ let summary = result.unwrap();+ assert!(+ summary.starts_with("Targeted changes · 1 files"),+ "{summary}"+ );+ break;+ }+ }+ assert_eq!(+ c.query_row(+ "SELECT epoch FROM source_seen WHERE path=?1",+ [existing.to_string_lossy().as_ref()],+ |r| r.get::<_, i64>(0)+ )+ .unwrap(),+ epoch,+ "unrelated existing file must not be revisited"+ );+ }+ #[test]fn new_and_modified_files_are_automatically_indexed_in_quick_and_full_sources() {use std::sync::atomic::AtomicUsize;let home = tempfile::tempdir().unwrap();@@ -3010,6 +3226,71 @@ mod scan_lifecycle_tests {s}#[test]+ fn targeted_run_does_not_resume_unrelated_full_or_quick_jobs() {+ let home = tempfile::tempdir().unwrap();+ let root = tempfile::tempdir().unwrap();+ let full = tempfile::tempdir().unwrap();+ let changed = root.path().join("changed.txt");+ std::fs::write(&changed, "changed").unwrap();+ let deferred = root.path().join("deferred.txt");+ std::fs::write(&deferred, "deferred").unwrap();+ let old_job = full.path().join("old-job.txt");+ std::fs::write(&old_job, "content").unwrap();+ let mut s = settings(root.path(), false);+ s.roots.push(crate::config::Source {+ path: full.path().to_string_lossy().into(),+ mode: "full".into(),+ });+ let engine = fixture(home.path(), &s);+ let c = engine.db.connect(false).unwrap();+ let (token, _) =+ Database::prepare_job(&c, &old_job.to_string_lossy(), "unfinished").unwrap();+ c.execute(+ "INSERT INTO native_quick_queue VALUES(?1)",+ [deferred.to_string_lossy().as_ref()],+ )+ .unwrap();+ engine+ .run_index(&s, false, Some(vec![changed.clone()]))+ .unwrap();+ assert_eq!(+ c.query_row(+ "SELECT error FROM native_jobs WHERE token=?1",+ [token],+ |r| r.get::<_, String>(0)+ )+ .unwrap(),+ ""+ );+ assert_eq!(+ c.query_row(+ "SELECT count(*) FROM native_quick_queue WHERE path=?1",+ [deferred.to_string_lossy().as_ref()],+ |r| r.get::<_, usize>(0)+ )+ .unwrap(),+ 1+ );+ assert_eq!(+ c.query_row(+ "SELECT count(*) FROM names WHERE path=?1",+ [changed.to_string_lossy().as_ref()],+ |r| r.get::<_, usize>(0)+ )+ .unwrap(),+ 1+ );+ assert_eq!(+ c.query_row(+ "SELECT count(*) FROM names WHERE path=?1",+ [old_job.to_string_lossy().as_ref()],+ |r| r.get::<_, usize>(0)+ )+ .unwrap(),+ 0+ );+ }+ #[test]fn changed_file_and_folder_never_walk_unrelated_sources() {let home = tempfile::tempdir().unwrap();let source = tempfile::Builder::new()diff --git a/native/src/platform.rs b/native/src/platform.rsindex 490a8e9..339c6aa 100644--- a/native/src/platform.rs+++ b/native/src/platform.rs@@ -187,28 +187,38 @@ pub fn limit_worker(_: &Child) -> Result<Job> {#[cfg(windows)]pub fn open(path: &str) -> Result<()> {use windows::{- Win32::{- Foundation::HWND,- UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL},+ Win32::UI::{+ Shell::{SEE_MASK_FLAG_NO_UI, SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW},+ WindowsAndMessaging::SW_SHOWNORMAL,},core::PCWSTR,};+ // Shell shortcuts and packaged apps can require COM on this launch thread.+ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoUninitialize};+ struct Apartment(bool);+ impl Drop for Apartment {+ fn drop(&mut self) {+ if self.0 {+ unsafe {+ CoUninitialize();+ }+ }+ }+ }+ let _apartment = Apartment(unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).is_ok() });let file = wide(path);let verb = wide("open");- unsafe {- let result = ShellExecuteW(- None,- PCWSTR(verb.as_ptr()),- PCWSTR(file.as_ptr()),- None,- None,- SW_SHOWNORMAL,- );- anyhow::ensure!(- result.0 as usize > 32,- "Windows could not open the selected item"- );- }+ // Complete the shell handoff before this worker exits, without making the+ // UI wait or waiting for the launched application's input-idle state.+ let mut launch = SHELLEXECUTEINFOW {+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,+ fMask: SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI,+ lpVerb: PCWSTR(verb.as_ptr()),+ lpFile: PCWSTR(file.as_ptr()),+ nShow: SW_SHOWNORMAL.0,+ ..Default::default()+ };+ unsafe { ShellExecuteExW(&mut launch) }.context("Windows could not open the selected item")?;Ok(())}#[cfg(not(windows))]diff --git a/native/src/stability_tests.rs b/native/src/stability_tests.rsindex e0dce77..3146b04 100644--- a/native/src/stability_tests.rs+++ b/native/src/stability_tests.rs@@ -450,3 +450,82 @@ fn real_backend_matches_pinned_text_and_image_reference() {);}}++#[test]+fn selected_action_dispatch_does_not_wait_for_inflight_embedding() {+ let (_home, root, mut s, e, rx) = fixture();+ add(&e, &s, &root.path().join("launch-report.exe"), "report");+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ s.remote_url = format!("http://{}", server.server_addr());+ let (arrived, arrival) = std::sync::mpsc::channel();+ let (release, gate) = std::sync::mpsc::channel();+ let http = std::thread::spawn(move || {+ let request = server+ .recv_timeout(Duration::from_secs(5))+ .unwrap()+ .unwrap();+ arrived.send(()).unwrap();+ let _ = gate.recv_timeout(Duration::from_secs(5));+ let _ = request.respond(tiny_http::Response::from_string(+ "{\"data\":[{\"index\":0,\"embedding\":[1,0]}]}",+ ));+ });+ e.search(+ 987,+ "report".into(),+ s,+ "Both".into(),+ "All files".into(),+ String::new(),+ String::new(),+ );+ arrival.recv_timeout(Duration::from_secs(5)).unwrap();+ let begin = Instant::now();+ e.models.cancel_query();+ let actual = std::env::var("VECTORDASH_TEST_OPEN_FIXTURE").ok();+ let timeout = if actual.is_some() {+ Duration::from_secs(3)+ } else {+ Duration::from_millis(500)+ };+ crate::engine::dispatch_action(e.tx.clone(), move || {+ if let Some(path) = actual {+ crate::platform::open(&path)+ } else {+ Ok(())+ }+ });+ let mut opened = false;+ while begin.elapsed() < timeout {+ if let Ok(Event::OpenDone(result)) = rx.recv_timeout(Duration::from_millis(50)) {+ result.unwrap();+ opened = true;+ break;+ }+ }+ release.send(()).unwrap();+ http.join().unwrap();+ assert!(+ opened,+ "selected action must run while the model response is still blocked"+ );+}++#[test]+fn burst_statistics_refreshes_are_coalesced_without_repeated_global_counts() {+ let (_home, _root, s, e, rx) = fixture();+ for _ in 0..50 {+ e.refresh_stats(&s);+ }+ let start = Instant::now();+ let mut counts = 0;+ while start.elapsed() < Duration::from_secs(2) {+ if let Ok(Event::Stats(_, _)) = rx.recv_timeout(Duration::from_millis(50)) {+ counts += 1;+ }+ }+ assert_eq!(+ counts, 1,+ "burst requests must not each run database-wide statistics queries"+ );+}