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
Release VectorDash 0.3.11 with model resource controls and index reset
ampersandru0ea473bfa8be
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1index e261c4f..c603ead 100644--- a/Build-Rust.ps1+++ b/Build-Rust.ps1@@ -75,8 +75,8 @@ if (Test-Path $taskPortable) { throw 'Portable staging directory already exists.New-Item -ItemType Directory -Force $taskPortable | Out-NullGet-ChildItem -LiteralPath $taskBundle | Copy-Item -Destination $taskPortable -Recurse -ForceSet-Content -LiteralPath (Join-Path $taskPortable 'portable.flag') -Value '' -Encoding ascii-Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.9-x64.zip' -Force-$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.9-x64.exe'-$taskZip='dist/installer/VectorDash-Rust-0.3.9-x64.zip'+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.11-x64.zip' -Force+$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.11-x64.exe'+$taskZip='dist/installer/VectorDash-Rust-0.3.11-x64.zip'@($taskInstaller,$taskZip) | ForEach-Object {((Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash.ToLowerInvariant()+' '+(Split-Path $_ -Leaf))} | Set-Content 'dist/installer/RUST-SHA256SUMS.txt' -Encoding asciiWrite-Output "Native installer and portable ZIP ready."diff --git a/README.md b/README.mdindex 0509b93..d124e5c 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@ Search by name or exact words, or describe what you remember. Google's **Embeddi- **Your sources, your choice:** index names only for fast drive-wide search, or fully index selected folders. Nested Full folders override Quick drives. Select multiple search sources, exclude files/types or common Windows cache folders, and see Full/Quick counts and recent additions.- **Advanced and saved searches:** combine filenames, wildcards, size and dates, such as name:dog*.jpg size:>1MB or ext:pdf modified:today. Save queries together with their modes, sources and exclusions; rename or remove them in Settings.- **Automatic updates:** monitor new, modified and removed files, or schedule scans. Automatic changes obey CPU/GPU, inactivity and power conditions even when periodic scanning is Manual. Optional NTFS journal tracking replays saved changes when volume access is available; folder notifications and recovery scans provide fallback. Pause/cancel indexing and inspect VectorDash, model and File logs.-- **Flexible setup:** choose GPU, iGPU or CPU/system memory; install selected optional features or remove downloaded tools. Models load only when needed and can unload automatically after an adjustable idle period. Optional remote llama-server and read-only [MCP access for agents](docs/MCP.md), with bearer authentication and LAN access.+- **Flexible setup:** choose GPU, iGPU or CPU/system memory; install selected optional features or remove downloaded tools. Local models warm when Both/Semantic search opens, with loading progress, and can unload after an adjustable idle period. Optional game/full-screen rules pause indexing and unload models; Load anyway overrides model limits for that search session. Optional remote llama-server and read-only [MCP access for agents](docs/MCP.md), with bearer authentication and LAN access.- **Make it yours:** light/dark themes, app accent colors, popup tint/transparency/gradient, a collapsible icon sidebar, and one red Save / outlined Undo bar for settings. About includes updates and a changelog covering releases since your installed version.<img width="1000" height="678" alt="20261013-0738-48 7475530" src="https://github.com/user-attachments/assets/1eabcb5e-63ae-47d6-872b-fa72d85b91cd" />@@ -39,6 +39,8 @@ Search by name or exact words, or describe what you remember. Google's **Embeddi**Upgrading:** setup installs as **VectorDash** and replaces the older Python installation in its existing folder. A separately registered Rust preview is removed after a successful upgrade. Settings, models and indexes are retained; older Python indexes can be imported as a copy through Sources.+**Clear an index:** use **Sources → Clear entire index** and confirm. This removes indexed names, extracted text and vectors, while keeping your original files, sources, settings and downloaded models. Automatic indexing stays paused until you resume it or click Update index. Previously retained import/conversion backups are separate and are not deleted.+Enable **Include Start menu programs** in Sources to search installed program shortcuts. The catalog loads at startup. Select a result and press **Enter** to launch its original shortcut, preserving arguments and working folders.**File/Folder Names** search needs no model. In **Sources**, choose **Quick file / folder names** or **Full index** before adding drives, folders or files. To change existing sources, select entries (or **Select/Deselect all**) and apply a mode, then update the index. In either search window, choose **Both**, **File/Folder Names** or **Semantic**, and use the source dropdown to search some or all sources. More specific folders take priority when sources overlap. Index status shows Full/Quick file counts and how many files have vectors. Enable **Skip Windows system and frequently changing cache folders** in Sources to omit temp files, crash dumps, update staging and selected caches while keeping personal folders and Program Files.diff --git a/native/Cargo.lock b/native/Cargo.lockindex eaed9c4..bcde1a4 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -4478,7 +4478,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"[[package]]name = "vectordash"-version = "0.3.9"+version = "0.3.11"dependencies = ["anyhow","base64 0.22.1",diff --git a/native/Cargo.toml b/native/Cargo.tomlindex 87abbd6..3360543 100644--- a/native/Cargo.toml+++ b/native/Cargo.toml@@ -1,6 +1,6 @@[package]name = "vectordash"-version = "0.3.9"+version = "0.3.11"edition = "2024"license = "MIT"[dependencies]@@ -33,7 +33,7 @@ zip = { version = "4", default-features = false, features = ["deflate"] }[build-dependencies]embed-resource = "3"[target.'cfg(windows)'.dependencies]-windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }+windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }[dev-dependencies]tempfile = "3"[profile.release]diff --git a/native/docs/0.3.10.md b/native/docs/0.3.10.mdnew file mode 100644index 0000000..fc30960--- /dev/null+++ b/native/docs/0.3.10.md@@ -0,0 +1,10 @@+# VectorDash 0.3.10+- Cancel stops the current scan and holds queued automatic/recovery work for the current session. Use Update index or Scheduling -> Resume automatic indexing to continue.+- Editing roots, indexing modes or exclusions stops an in-flight scan at the next safe checkpoint. Save restarts with the latest sources; Undo restarts with the saved sources.+- Removing a drive after explicit Cancel does not restart the cancelled scan.+- Source restarts retain automatic/idle gating for an originally automatic scan.+- Settings must save successfully before a restart is queued. Completed files are retained.++Compatibility: the installer remains Windows 11-only (minimum build 22000). Windows 10 compatibility and Linux desktop/server releases are planned; neither is claimed by this patch.++Validation: 68 regression tests passed, including cancel/resume of pending recovery, updated-root restart, and removing a source after explicit cancellation. Installer/portable packages and checksums were verified.diff --git a/native/docs/0.3.11.md b/native/docs/0.3.11.mdnew file mode 100644index 0000000..09ba24d--- /dev/null+++ b/native/docs/0.3.11.md@@ -0,0 +1,13 @@+# 0.3.11 test build++- Local EmbeddingGemma 2 and llama-server warm when opening Both/Semantic search. Main and popup searches show server-start/model-readiness progress; Names stays model-free.+- Models & hardware includes optional game/full-screen pause and unload rules, an extra game executable list, CPU/GPU/power search-load limits, and search notices. Typing does not block model loading.+- Load anyway protects the local model for the current search session. Closing/hiding/minimizing search or leaving Search releases it. It does not override indexing pause rules. Remote servers are never terminated.+- Sources now offers Clear entire index with confirmation, covering names, text, vectors and active database indexing history. Original files, settings and models are retained. Automatic indexing remains held until Update index or Resume automatic indexing. Separate retained import/conversion backups are not erased.+- Includes the preceding scan-cancellation and source-change fixes: explicit cancellation does not immediately launch recovery; saved source changes restart with current sources.++## Validation++72 tests passed, including encrypted/plaintext index clearing, readiness transitions against an isolated HTTP server, active-request/session unload protection, resource policy checks, automatic Quick/Full file-change indexing and scan cancellation.+Game detection uses Windows notifications, full-screen geometry, common game paths and user-configured executable names; no heuristic recognizes every game.+Loading progress is indeterminate because llama-server reports readiness rather than an exact loading percentage.diff --git a/native/src/app.rs b/native/src/app.rsindex d752000..238f945 100644--- a/native/src/app.rs+++ b/native/src/app.rs@@ -130,6 +130,13 @@ pub struct App {qa_selection: Option<usize>,result_scroll_offset: f32,child_theme_key: String,+ search_visible: bool,+ model_warm_attempted: bool,+ model_warm_error: Option<String>,+ last_search_mode: String,+ popup_model_panel: bool,+ clear_index_confirm: bool,+ index_clearing: bool,}impl App {pub fn new(@@ -147,6 +154,7 @@ impl App {if let Some(path) = crate::setup::find_ocr(&s.ocr) {s.ocr = path.to_string_lossy().into_owned();}+ crate::platform::set_game_names(&s.game_processes);crate::scheduling::start_monitor();let db = Database::new(&home, &s)?;let (tx, rx) = crossbeam_channel::bounded(512);@@ -204,6 +212,7 @@ impl App {}cc.egui_ctx.set_fonts(fonts);egui_extras::install_image_loaders(&cc.egui_ctx);+ let saved_start_hidden = s.start_hidden;let mut app = Self {home,collapsed: s.sidebar_collapsed,@@ -311,6 +320,13 @@ impl App {qa_selection: None,result_scroll_offset: 0.0,child_theme_key: String::new(),+ search_visible: !(std::env::args().any(|a| a == "--startup") && saved_start_hidden),+ model_warm_attempted: false,+ model_warm_error: None,+ last_search_mode: String::new(),+ popup_model_panel: false,+ clear_index_confirm: false,+ index_clearing: false,};if let Ok(text) = tail_log(&app.home.join("vectordash.log")) {for line in text.lines() {@@ -388,7 +404,6 @@ impl App {self.s.setup_model = self.model_setup;self.s.setup_encoder = self.encoder_setup;self.s.setup_ocr = self.ocr_setup;- *self.engine.control.schedule.lock().unwrap() = self.s.clone();let pages = match self.s.performance.as_str() {"Low memory" => 8192,"Fast search" => 65536,@@ -400,7 +415,11 @@ impl App {}match self.s.save(&self.home) {Ok(()) => {+ self.engine.control.update_settings(self.s.clone());self.saved_settings = self.s.clone();+ crate::platform::set_game_names(&self.s.game_processes);+ self.model_warm_attempted = false;+ self.model_warm_error = None;self.status = "Settings saved".into();true}@@ -431,6 +450,7 @@ impl App {self.encoder_setup = self.s.setup_encoder;self.ocr_setup = self.s.setup_ocr;crate::appearance::apply(ctx, &self.s);+ self.engine.control.update_settings(self.s.clone());self.status = "Unsaved changes undone".into();}fn apply_settings(&mut self, ctx: &egui::Context) {@@ -519,6 +539,25 @@ impl App {for event in self.rx.try_iter().take(100).collect::<Vec<_>>() {let scoped_summon = matches!(&event, Event::ScopedSummon(..));match event {+ Event::ModelReady(result) => {+ self.model_warm_error = result.err();+ self.dirty = true;+ }+ Event::IndexCleared(result) => {+ self.index_clearing = false;+ self.setup_busy = false;+ self.sequence += 1;+ self.hits.clear();+ self.texture = None;+ self.thumbs.clear();+ self.thumb_pending.clear();+ self.thumb_failed.clear();+ self.preview_pending = None;+ self.preview_error = None;+ self.query.clear();+ self.dirty = false;+ self.status = result.unwrap_or_else(|e| e);+ }Event::Update(result) => {self.update_busy = false;match result {@@ -608,6 +647,15 @@ impl App {ctx.send_viewport_cmd(egui::ViewportCommand::Close);}Event::Full => {+ if !self.search_visible {+ self.model_warm_attempted = false;+ self.model_warm_error = None;+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);+ }+ self.search_visible = true;self.quick = false;self.page = 0;ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));@@ -722,6 +770,13 @@ impl App {if self.qa_hidden {self.qa_hidden_reopened = true;}+ self.search_visible = true;+ self.model_warm_attempted = false;+ self.model_warm_error = None;+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);self.large_preview = false;self.quick = true;self.popup_size_state = None;@@ -802,7 +857,108 @@ impl App {}}}+ fn warm_search_model(&mut self) {+ if self.last_search_mode != self.mode {+ self.last_search_mode = self.mode.clone();+ self.model_warm_attempted = false;+ }+ if !self.search_visible || self.page != 0 || self.mode == "Names" {+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);+ return;+ }+ if self.engine.models.search_hold(&self.s).is_some() {+ self.model_warm_attempted = false;+ self.model_warm_error = None;+ return;+ }+ if self.engine.models.loaded.load(Ordering::Acquire)+ && !self.engine.models.loading.load(Ordering::Acquire)+ {+ self.model_warm_error = None;+ }+ if self.model_warm_attempted+ || !self.s.remote_url.is_empty()+ || self.engine.models.search_hold(&self.s).is_some()+ || self.engine.models.loading.load(Ordering::Acquire)+ || self.index_clearing+ {+ return;+ }+ if !Path::new(&self.s.server).is_file() || !Path::new(&self.s.model).is_file() {+ return;+ }+ self.model_warm_attempted = true;+ let models = self.engine.models.clone();+ let s = self.s.clone();+ let tx = self.engine.tx.clone();+ std::thread::spawn(move || {+ let result = models.start(&s, false).map_err(|e| e.to_string());+ let _ = tx.send(Event::ModelReady(result));+ });+ }+ fn model_search_panel(&mut self, ui: &mut egui::Ui) {+ if self.mode == "Names" || !self.s.remote_url.is_empty() {+ return;+ }+ if self.engine.models.loading.load(Ordering::Acquire) {+ let phase = self.engine.models.loading_phase();+ let (rect, response) = ui+ .allocate_exact_size(egui::vec2(ui.available_width(), 26.0), egui::Sense::hover());+ ui.painter()+ .rect_filled(rect, 7.0, ui.visuals().widgets.inactive.bg_fill);+ let span = rect.width() * 0.22;+ let t = (ui.input(|i| i.time) * 0.8).fract() as f32;+ let left = rect.left() - span + t * (rect.width() + span);+ let moving = egui::Rect::from_min_size(+ egui::pos2(left, rect.top()),+ egui::vec2(span, rect.height()),+ )+ .intersect(rect);+ ui.painter()+ .rect_filled(moving, 7.0, self.accent().gamma_multiply(0.45));+ ui.painter().text(+ rect.center(),+ egui::Align2::CENTER_CENTER,+ phase,+ egui::FontId::proportional(12.0),+ ui.visuals().text_color(),+ );+ response.on_hover_text(+ "llama-server reports readiness rather than an exact loading percentage.",+ );+ return;+ }+ let held = self.engine.models.search_hold(&self.s);+ if held.is_some()+ || (self.s.show_model_notices && !self.engine.models.loaded.load(Ordering::Acquire))+ {+ ui.horizontal_wrapped(|ui| {+ let notice = if let Some(reason) = held {+ format!("EmbeddingGemma 2 {}: {reason}", if self.engine.models.loaded.load(Ordering::Acquire) {"paused"} else {"unloaded"})+ } else { "EmbeddingGemma 2 is unloaded. Both/Semantic searches may need a few seconds to load it.".into() };+ ui.label(RichText::new(notice).color(Color32::YELLOW));+ if held.is_some() && ui.button("Load anyway").clicked() {+ self.engine.models.session_override.store(true, Ordering::Release);+ self.model_warm_attempted = false; self.model_warm_error = None;+ self.dirty = true;+ }+ });+ }+ if let Some(error) = &self.model_warm_error {+ ui.colored_label(Color32::LIGHT_RED, error);+ }+ }fn dispatch(&mut self) {+ if self.index_clearing || !self.search_visible || self.page != 0 {+ return;+ }+ if self.mode != "Names" && self.engine.models.loading.load(Ordering::Acquire) {+ self.dirty = true;+ return;+ }if self.query.trim().is_empty() {if self.quick && self.changed.elapsed() < Duration::from_millis(200) {self.dirty = true;@@ -836,7 +992,9 @@ impl App {if self.indexing || self.setup_busy {return;}- self.save();+ if !self.save() {+ return;+ }self.indexing = true;self.progress = Progress::default();self.engine.index(self.s.clone(), force);@@ -906,6 +1064,11 @@ impl App {}}fn close_window(&mut self, ctx: &egui::Context) {+ self.search_visible = false;+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);self.large_preview = false;if self.quick {ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));@@ -1252,6 +1415,7 @@ impl App {{self.changed();}+ self.model_search_panel(ui);if self.quick&& self.query.is_empty()&& ctx.animate_bool_with_time(egui::Id::new("popup-expansion"), false, 0.18) <= 0.0@@ -1732,7 +1896,8 @@ impl App {.add_enabled(self.indexing, egui::Button::new("Cancel indexing")).clicked(){- self.engine.control.cancel.store(true, Ordering::Relaxed);+ self.engine.control.cancel_by_user();+ self.status = "Cancelled; automatic work paused until Update index or Resume automatic indexing".into();}if ui.add_enabled(!self.indexing, egui::Button::new("Rebuild full content"))@@ -1742,6 +1907,20 @@ impl App {}});});+ if ui+ .add_enabled(+ !self.setup_busy,+ egui::Button::new("Clear entire index")+ .stroke(egui::Stroke::new(1.0, Color32::LIGHT_RED)),+ )+ .clicked()+ {+ self.clear_index_confirm = true;+ }+ if self.index_clearing {+ ui.spinner();+ ui.label("Stopping indexing and clearing the active database…");+ }ui.checkbox(&mut self.s.retry_failed,"Retry previously skipped files on the next update",@@ -2026,6 +2205,29 @@ impl App {}fn models(&mut self, ui: &mut egui::Ui) {ui.checkbox(&mut self.s.unload_idle, "Unload local models when idle");+ ui.label("An unloaded model may take a few seconds to load for the next Both or Semantic search. File/Folder Names search needs no model.");+ ui.checkbox(+ &mut self.s.pause_for_game,+ "Unload local models and pause indexing when a game is detected",+ );+ ui.checkbox(+ &mut self.s.pause_for_fullscreen,+ "Unload local models and pause indexing for full-screen applications",+ );+ ui.horizontal(|ui| {+ ui.label("Additional game executable names");+ ui.text_edit_singleline(&mut self.s.game_processes).on_hover_text("Comma-separated names, such as forza.exe, cs2.exe. Windows detection also recognizes full-screen Direct3D and common game install paths.");+ });+ ui.checkbox(+ &mut self.s.defer_search_model,+ "Delay search model loading while CPU/GPU or power limits are not met",+ );+ ui.label("Uses Scheduling resource limits; keyboard/mouse activity is ignored for searches. Load anyway applies only while the current search window remains open.");+ ui.checkbox(+ &mut self.s.show_model_notices,+ "Show unloaded-model notices in search",+ );+if self.s.unload_idle {ui.add(egui::Slider::new(&mut self.s.unload_minutes, 1..=120)@@ -2054,7 +2256,7 @@ impl App {else{self.setup_busy=true;self.setup_progress=None;self.setup.install(self.s.clone(),self.runtime_setup,self.model_setup,self.encoder_setup,self.ocr_setup);}}if ui.add_enabled(loaded,egui::Button::new("Stop / unload models")).clicked(){let models=self.engine.models.clone();std::thread::spawn(move||{let _=models.stop();});}- if self.setup_busy&&ui.button("Cancel setup").clicked(){self.setup.cancel.store(true,Ordering::Relaxed);}+ if self.setup_busy&&!self.index_clearing&&ui.button("Cancel setup").clicked(){self.setup.cancel.store(true,Ordering::Relaxed);}});if self.setup_busy{if let Some((name,done,total))=&self.setup_progress{ui.label(name);if *total>0{ui.add(egui::ProgressBar::new(*done as f32/ *total as f32).show_percentage());}}}});@@ -2417,6 +2619,25 @@ impl App {} else {ui.label("File monitoring is off");}+ if self.engine.control.automatic_hold.load(Ordering::Acquire)+ && !self.engine.control.sources_pending.load(Ordering::Acquire)+ && !self+ .engine+ .control+ .restart_requested+ .load(Ordering::Acquire)+ && ui.button("Resume automatic indexing").clicked()+ {+ self.engine+ .control+ .cancelled_by_user+ .store(false, Ordering::SeqCst);+ self.engine+ .control+ .automatic_hold+ .store(false, Ordering::SeqCst);+ }+ui.label("Automatic file changes obey the idle conditions below, including when the periodic scan schedule is Manual. Manual only disables periodic scans.");ui.checkbox(&mut self.s.ntfs_journal,@@ -2785,6 +3006,20 @@ impl eframe::App for App {self.install_update(ctx);}self.events(ctx);+ if ctx.input(|i| i.viewport().minimized.unwrap_or(false)) {+ self.search_visible = false;+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);+ } else if ctx.input(|i| i.viewport().focused.unwrap_or(false)) {+ if !self.search_visible {+ self.model_warm_attempted = false;+ }+ self.search_visible = true;+ }+ self.warm_search_model();+let copy_event = ctx.input(|i| {i.events.iter().any(|e| matches!(e, egui::Event::Copy))|| i.modifiers.ctrl && i.key_pressed(egui::Key::C)@@ -2813,9 +3048,43 @@ impl eframe::App for App {self.dispatch();}self.indexing = self.engine.control.running.load(Ordering::Relaxed);+ if self.indexing+ && !self+ .engine+ .control+ .cancelled_by_user+ .load(Ordering::Acquire)+ && !self.engine.control.sources_pending.load(Ordering::Acquire)+ && crate::engine::source_signature(&self.s)+ != crate::engine::source_signature(&self.engine.control.schedule.lock().unwrap())+ {+ self.engine.control.interrupt_sources();+ self.status =+ "Sources changed; stopping the old scan. Save to restart with updated sources."+ .into();+ }+let metrics = crate::scheduling::metrics();+ if self.indexing {+ if let Some(reason) = crate::scheduling::resource_pause(&self.s, metrics) {+ self.progress.phase = format!("Indexing paused: {reason}");+ }+ }self.schedule_status =- if self.indexing && self.engine.control.automatic.load(Ordering::Relaxed) {+ if self.engine.control.automatic_hold.load(Ordering::Acquire) && !self.indexing {+ if self.engine.control.sources_pending.load(Ordering::Acquire) {+ "Sources changed; save to restart".into()+ } else if self+ .engine+ .control+ .restart_requested+ .load(Ordering::Acquire)+ {+ "Source restart queued; waiting for idle conditions".into()+ } else {+ "Automatic indexing paused after Cancel".into()+ }+ } else if self.indexing && self.engine.control.automatic.load(Ordering::Relaxed) {if self.engine.control.watching.load(Ordering::Relaxed)|| ["When idle", "Time + idle"].contains(&self.s.schedule.as_str()){@@ -2943,19 +3212,35 @@ impl eframe::App for App {}if self.popup_had_focus && !focused && !self.large_preview {self.popup_had_focus = false;+ self.search_visible = false;+ self.engine+ .models+ .session_override+ .store(false, Ordering::Release);ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));}let empty = self.query.is_empty();let expansion =ctx.animate_bool_with_time(egui::Id::new("popup-expansion"), !empty, 0.18);- if self.popup_size_state != Some(empty) || (expansion > 0.0 && expansion < 1.0) {+ let panel = self.mode != "Names"+ && self.s.remote_url.is_empty()+ && (self.engine.models.loading.load(Ordering::Acquire)+ || self.engine.models.search_hold(&self.s).is_some()+ || self.model_warm_error.is_some()+ || (self.s.show_model_notices+ && !self.engine.models.loaded.load(Ordering::Acquire)));+ if self.popup_size_state != Some(empty)+ || self.popup_model_panel != panel+ || (expansion > 0.0 && expansion < 1.0)+ {+ self.popup_model_panel = panel;self.popup_size_state = Some(empty);ctx.send_viewport_cmd(egui::ViewportCommand::MinInnerSize(egui::vec2(780.0, 200.0,)));ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(940.0,- 235.0 + 370.0 * expansion,+ 235.0 + 370.0 * expansion + if panel { 75.0 } else { 0.0 },)));}} else {@@ -2971,7 +3256,8 @@ impl eframe::App for App {ui.label("Unsaved changes");ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if ui- .add(+ .add_enabled(+ !self.index_clearing,egui::Button::new("Undo").fill(Color32::TRANSPARENT).stroke(egui::Stroke::new(1.0, self.accent())),@@ -2981,7 +3267,8 @@ impl eframe::App for App {self.undo_settings(ctx);}if ui- .add(+ .add_enabled(+ !self.index_clearing,egui::Button::new(RichText::new("Save").strong().color(Color32::WHITE),)@@ -3196,6 +3483,22 @@ impl eframe::App for App {if self.uninstall_confirm {egui::Window::new("Uninstall downloaded models and runtimes?").collapsible(false).show(ctx,|ui|{ui.label("Only managed downloads are removed. Source files, external tools and your index are retained.");if ui.button("Uninstall downloads").clicked(){let _=self.engine.models.stop();let result=self.setup.uninstall();if result.is_ok(){for path in [&mut self.s.server,&mut self.s.model,&mut self.s.projector]{if Path::new(path).starts_with(&self.home){path.clear();}}self.save();}else{self.run(result);}self.uninstall_confirm=false;}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| {+ 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.");+ ui.horizontal(|ui| {+ if ui.button("Clear entire index").clicked() {+ self.clear_index_confirm = false; self.index_clearing = true; self.setup_busy = true;+ self.sequence += 1; self.hits.clear(); self.texture = None; self.large_preview = false;+ self.status = "Stopping indexing and clearing the active index…".into();+ self.engine.clear_index();+ }+ if ui.button("Cancel").clicked() { self.clear_index_confirm = false; }+ });+ });+ }if let Some(report) = &self.smoke {if self.startup.elapsed() > Duration::from_secs(self.smoke_seconds)&& (self.qa_screenshot.is_none() || self.qa_captured)diff --git a/native/src/config.rs b/native/src/config.rsindex a156c03..472b3d4 100644--- a/native/src/config.rs+++ b/native/src/config.rs@@ -50,6 +50,11 @@ pub struct Settings {pub popup_opacity: f32,pub unload_idle: bool,pub unload_minutes: u32,+ pub pause_for_game: bool,+ pub pause_for_fullscreen: bool,+ pub defer_search_model: bool,+ pub show_model_notices: bool,+ pub game_processes: String,pub popup_gradient: f32,pub popup_tone: [u8; 3],pub sidebar_collapsed: bool,@@ -139,6 +144,11 @@ impl Default for Settings {popup_opacity: 0.8,unload_idle: true,unload_minutes: 5,+ pause_for_game: false,+ pause_for_fullscreen: false,+ defer_search_model: false,+ show_model_notices: true,+ game_processes: String::new(),popup_gradient: 0.2,popup_tone: [138, 115, 168],sidebar_collapsed: false,diff --git a/native/src/db.rs b/native/src/db.rsindex 51e0b51..c4a0e9a 100644--- a/native/src/db.rs+++ b/native/src/db.rs@@ -151,6 +151,42 @@ impl Database {}Ok(conn)}+ pub fn clear_index(&self) -> Result<String> {+ let mut c = self.connect(false)?;+ c.execute_batch("PRAGMA secure_delete=ON;")?;+ let tx = c.transaction()?;+ for table in [+ "words",+ "segment_vectors",+ "segments",+ "files",+ "names",+ "source_seen",+ "native_content",+ "native_staging",+ "metadata",+ ] {+ let exists: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",+ [table],+ |r| r.get(0),+ )?;+ if exists {+ tx.execute(&format!("DELETE FROM {table}"), [])?;+ }+ }+ tx.execute("INSERT INTO name_words(name_words) VALUES('rebuild')", [])?;+ tx.commit()?;+ self.generation.fetch_add(1, Ordering::SeqCst);+ // Search readers can delay reclamation; logical clearing is already committed.+ let reclamation = c.execute_batch(+ "PRAGMA wal_checkpoint(TRUNCATE); VACUUM; PRAGMA wal_checkpoint(TRUNCATE);",+ );+ Ok(match reclamation {+ Ok(()) => "Entire active index cleared. Automatic indexing is paused; Update index to rebuild when ready.".into(),+ Err(e) => format!("Entire active index cleared; storage reclamation deferred: {e}. Update index to rebuild when ready."),+ })+ }pub fn stats(&self) -> Result<Stats> {let c = self.connect(true)?;let mut s = Stats::default();@@ -1091,3 +1127,82 @@ mod advanced_filter_tests {);}}++#[cfg(test)]+mod clear_index_tests {+ use super::*;+ #[test]+ fn clears_all_catalog_content_and_vectors_but_keeps_files_settings_and_key() {+ for encrypted in [false, true] {+ let home = tempfile::tempdir().unwrap();+ let settings = Settings {+ encrypt_index: encrypted,+ ..Default::default()+ };+ settings.save(home.path()).unwrap();+ let original = home.path().join("original.txt");+ std::fs::write(&original, "original file").unwrap();+ let db = Database::new(home.path(), &settings).unwrap();+ let saved = std::fs::read(home.path().join("settings.json")).unwrap();+ let key = std::fs::read(home.path().join("index.key")).ok();+ let c = db.connect(false).unwrap();+ c.execute("INSERT INTO names(path,name,parent,kind,folded,base) VALUES('junk.txt','junk.txt','','text','junk','junk')",[]).unwrap();+ c.execute("INSERT INTO name_words(name_words) VALUES('rebuild')", [])+ .unwrap();+ c.execute(+ "INSERT INTO words(path,text) VALUES('junk.txt','junk secret text')",+ [],+ )+ .unwrap();+ c.execute(+ "INSERT INTO files VALUES('junk.txt','junk','[1,0]',1,1)",+ [],+ )+ .unwrap();+ c.execute(+ "INSERT INTO segments VALUES('junk.txt','n','text','junk','[1,0]','{}')",+ [],+ )+ .unwrap();+ c.execute("INSERT INTO segment_vectors(namespace,kind,channel,dimension,vector,path) VALUES('n','text','text',2,X'0000000000000000','junk.txt')",[]).unwrap();+ c.execute("INSERT INTO source_seen VALUES('junk.txt','root',1,1)", [])+ .unwrap();+ c.execute(+ "INSERT INTO native_content VALUES('junk.txt','fingerprint','')",+ [],+ )+ .unwrap();+ c.execute(+ "INSERT INTO metadata VALUES('native_vectors_generation','1')",+ [],+ )+ .unwrap();+ drop(c);+ db.clear_index().unwrap();+ let c = db.connect(true).unwrap();+ for table in [+ "names",+ "name_words",+ "words",+ "files",+ "segments",+ "segment_vectors",+ "source_seen",+ "native_content",+ "metadata",+ ] {+ let count: u64 = c+ .query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0))+ .unwrap();+ assert_eq!(count, 0, "{table}");+ }+ assert!(db.generation.load(Ordering::SeqCst) > 0);+ assert_eq!(+ std::fs::read(home.path().join("settings.json")).unwrap(),+ saved+ );+ assert_eq!(std::fs::read(home.path().join("index.key")).ok(), key);+ assert_eq!(std::fs::read_to_string(&original).unwrap(), "original file");+ }+ }+}diff --git a/native/src/engine.rs b/native/src/engine.rsindex a9b2b7b..3f4420a 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -116,6 +116,8 @@ impl From<crossbeam_channel::Sender<Event>> for NotifySender {#[derive(Clone)]pub enum Event {Update(crate::updates::Update),+ ModelReady(std::result::Result<(), String>),+ IndexCleared(std::result::Result<String, String>),Devices(Vec<(String, String)>),Download(String, u64, u64),Thumbnail(String, Result<Vec<u8>, String>),@@ -144,10 +146,48 @@ pub struct Control {pub watching: Arc<AtomicBool>,pub last_run_success: Arc<AtomicBool>,pub running: Arc<AtomicBool>,+ pub automatic_hold: Arc<AtomicBool>,+ pub index_maintenance: Arc<AtomicBool>,+ pub cancelled_by_user: Arc<AtomicBool>,+ pub sources_pending: Arc<AtomicBool>,+ pub restart_requested: Arc<AtomicBool>,+ pub restart_automatic: Arc<AtomicBool>,+ pub restart_watching: Arc<AtomicBool>,pub automatic_started: Arc<std::sync::atomic::AtomicI64>,pub schedule: Arc<std::sync::Mutex<Settings>>,}impl Control {+ pub fn cancel_by_user(&self) {+ self.cancelled_by_user.store(true, Ordering::SeqCst);+ self.automatic_hold.store(true, Ordering::SeqCst);+ self.sources_pending.store(false, Ordering::SeqCst);+ self.restart_requested.store(false, Ordering::SeqCst);+ self.cancel.store(true, Ordering::SeqCst);+ }+ pub fn interrupt_sources(&self) {+ if self.cancelled_by_user.load(Ordering::Acquire) {+ return;+ }+ if !self.sources_pending.swap(true, Ordering::SeqCst) {+ self.restart_automatic+ .store(self.automatic.load(Ordering::Relaxed), Ordering::Relaxed);+ self.restart_watching+ .store(self.watching.load(Ordering::Relaxed), Ordering::Relaxed);+ }+ self.automatic_hold.store(true, Ordering::SeqCst);+ self.cancel.store(true, Ordering::SeqCst);+ }+ pub fn update_settings(&self, settings: Settings) {+ let mut current = self.schedule.lock().unwrap();+ let changed = source_signature(¤t) != source_signature(&settings);+ if changed && self.running.load(Ordering::Acquire) {+ self.interrupt_sources();+ }+ *current = settings;+ if self.sources_pending.swap(false, Ordering::SeqCst) {+ self.restart_requested.store(true, Ordering::SeqCst);+ }+ }pub fn file_checkpoint(&self) -> Result<()> {self.check()?;while self.automatic.load(Ordering::Relaxed) {@@ -188,6 +228,18 @@ impl Control {anyhow::bail!("Maximum automatic run duration reached");}}+ loop {+ anyhow::ensure!(+ !self.cancel.load(Ordering::Relaxed),+ "Indexing cancelled; completed files retained"+ );+ let settings = self.schedule.lock().unwrap().clone();+ if crate::scheduling::resource_pause(&settings, crate::scheduling::metrics()).is_none()+ {+ break;+ }+ std::thread::sleep(Duration::from_millis(100));+ }while self.paused.load(Ordering::Relaxed) {anyhow::ensure!(!self.cancel.load(Ordering::Relaxed),@@ -202,6 +254,12 @@ impl Control {Ok(())}}+pub fn source_signature(s: &Settings) -> String {+ format!(+ "{:?}|{:?}|{}|{}|{}",+ s.roots, s.exclusions, s.excluded_types, s.skip_windows_churn, s.code_search+ )+}#[derive(Clone)]pub struct Engine {pub db: Database,@@ -240,8 +298,13 @@ impl Engine {unloader.log("Info",format!(- "Idle model unload after {} minute(s); local server stopped",- settings.unload_minutes+ "Local models unloaded; {}",+ crate::scheduling::model_hold(&settings, crate::scheduling::metrics())+ .map(str::to_string)+ .unwrap_or_else(|| format!(+ "idle for {} minute(s)",+ settings.unload_minutes+ ))),);}@@ -261,16 +324,69 @@ impl Engine {&engine.db.home,);}+ if !engine.control.index_maintenance.load(Ordering::Acquire)+ && engine.control.restart_requested.load(Ordering::Acquire)+ && !engine.control.running.load(Ordering::Acquire)+ && !engine.control.sources_pending.load(Ordering::Acquire)+ {+ let automatic = engine.control.restart_automatic.load(Ordering::Relaxed);+ if !automatic+ || crate::scheduling::idle_allowed(&settings, crate::scheduling::metrics())+ .is_ok()+ {+ if engine+ .control+ .running+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok()+ {+ engine+ .control+ .restart_requested+ .store(false, Ordering::SeqCst);+ engine.control.automatic_hold.store(false, Ordering::SeqCst);+ engine.control.automatic.store(automatic, Ordering::Relaxed);+ engine.control.watching.store(+ engine.control.restart_watching.load(Ordering::Relaxed),+ Ordering::Relaxed,+ );+ engine+ .control+ .automatic_started+ .store(chrono::Local::now().timestamp(), Ordering::Relaxed);+ engine.log(+ "Info",+ "Sources changed; restarting with current saved sources",+ );+ if automatic {+ let _ = engine.tx.send(Event::AutomaticStarted);+ }+ engine.launch_index(settings.clone(), false);+ }+ }+ }changes.configure(&settings, &engine.db.home, &engine.tx);changes.collect(&settings, &engine.db.home);- let watch_status =- changes.status(&settings, engine.control.running.load(Ordering::Relaxed));+ 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()+ } else if engine.control.restart_requested.load(Ordering::Acquire) {+ "Source update queued; waiting for the previous scan and idle conditions"+ .into()+ } else {+ "Automatic indexing paused after Cancel; Update index or Resume automatic indexing to continue".into()+ }+ } else {+ changes.status(&settings, engine.control.running.load(Ordering::Relaxed))+ };if watch_status != last_watch_status {engine.log("Info", format!("File monitoring: {watch_status}"));let _ = engine.tx.send(Event::WatchStatus(watch_status.clone()));last_watch_status = watch_status;}- if !engine.control.running.load(Ordering::Relaxed)+ if !engine.control.index_maintenance.load(Ordering::Acquire)+ && !engine.control.automatic_hold.load(Ordering::Acquire)+ && !engine.control.running.load(Ordering::Relaxed)&& changes.ready()&& crate::scheduling::idle_allowed(&settings, crate::scheduling::metrics()).is_ok()@@ -302,7 +418,11 @@ impl Engine {engine.launch_paths(settings.clone(), false, paths);}}- if !engine.control.running.load(Ordering::Relaxed) && Instant::now() >= retry {+ if !engine.control.index_maintenance.load(Ordering::Acquire)+ && !engine.control.automatic_hold.load(Ordering::Acquire)+ && !engine.control.running.load(Ordering::Relaxed)+ && Instant::now() >= retry+ {let settings = engine.control.schedule.lock().unwrap().clone();if !settings.roots.is_empty() {if let Ok(slot) = crate::scheduling::due(@@ -336,7 +456,35 @@ impl Engine {}});}+ pub fn clear_index(&self) {+ if self.control.index_maintenance.swap(true, Ordering::SeqCst) {+ return;+ }+ self.control.cancel_by_user();+ let engine = self.clone();+ std::thread::spawn(move || {+ let result = (|| -> Result<String> {+ let start = Instant::now();+ while engine.control.running.load(Ordering::Acquire) {+ anyhow::ensure!(start.elapsed() < Duration::from_secs(120),+ "Indexer is still stopping; index was not cleared. Try again after it finishes.");+ std::thread::sleep(Duration::from_millis(50));+ }+ engine.db.clear_index()+ })().map_err(|e|e.to_string());+ engine.vectors.clear();+ engine+ .control+ .index_maintenance+ .store(false, Ordering::Release);+ engine.refresh_stats(&engine.control.schedule.lock().unwrap().clone());+ let _ = engine.tx.send(Event::IndexCleared(result));+ });+ }pub fn index(&self, s: Settings, force: bool) {+ if self.control.index_maintenance.load(Ordering::Acquire) {+ return;+ }if self.control.running@@ -345,14 +493,32 @@ impl Engine {{return;}+ self.control+ .cancelled_by_user+ .store(false, Ordering::SeqCst);+ self.control.automatic_hold.store(false, Ordering::SeqCst);+ self.control+ .restart_requested+ .store(false, Ordering::SeqCst);+ self.control.sources_pending.store(false, Ordering::SeqCst);+ *self.control.schedule.lock().unwrap() = s.clone();self.control.automatic.store(false, Ordering::Relaxed);+ self.control.watching.store(false, Ordering::Relaxed);self.launch_index(s, force);}fn launch_index(&self, s: Settings, force: bool) {self.launch_paths(s, force, None);}fn launch_paths(&self, s: Settings, force: bool, paths: Option<Vec<PathBuf>>) {+ if self.control.index_maintenance.load(Ordering::Acquire) {+ self.control.running.store(false, Ordering::Release);+ return;+ }self.control.cancel.store(false, Ordering::Relaxed);+ if self.control.index_maintenance.load(Ordering::Acquire) {+ self.control.running.store(false, Ordering::Release);+ return;+ }self.control.paused.store(false, Ordering::Relaxed);let owner = self.clone();std::thread::spawn(move || {@@ -1014,6 +1180,11 @@ impl Engine {scope: &str,excluded: &str,) -> Result<Vec<Hit>> {+ let mode = if mode == "Both" && self.models.search_hold(s).is_some() {+ "Names"+ } else {+ mode+ };let expression = q.replace("% of", "/100*");if let Ok(value) = meval::eval_str(&expression) {if q.chars().any(|c| "+-*/^()%".contains(c)) {@@ -1976,3 +2147,130 @@ mod calculator_filter_tests {assert!(!engine.models.loaded.load(Ordering::Relaxed));}}++#[cfg(test)]+mod scan_lifecycle_tests {+ use super::*;+ fn fixture(home: &Path, settings: &Settings) -> Engine {+ let db = Database::new(home, settings).unwrap();+ let (tx, _rx) = crossbeam_channel::bounded(512);+ let engine = Engine {+ db,+ models: Models::default(),+ control: Control::default(),+ tx: NotifySender::new(tx, None).with_log(home.join("test.log")),+ searching: Arc::new(AtomicBool::new(false)),+ vectors: crate::vector_cache::Cache::default(),+ };+ *engine.control.schedule.lock().unwrap() = settings.clone();+ engine+ }+ fn settings(path: &Path, watch: bool) -> Settings {+ let mut s = Settings::default();+ s.encrypt_index = false;+ s.watch_changes = watch;+ s.schedule = "Manual".into();+ s.check_cpu = false;+ s.check_gpu = false;+ s.check_user_idle = false;+ s.ac_only = false;+ s.roots = vec![crate::config::Source {+ path: path.to_string_lossy().into_owned(),+ mode: "quick".into(),+ }];+ s+ }+ #[test]+ fn cancelled_scan_does_not_launch_pending_recovery() {+ let home = tempfile::tempdir().unwrap();+ let source = tempfile::Builder::new()+ .prefix("VD-source-")+ .tempdir()+ .unwrap();+ std::fs::write(source.path().join("note.txt"), "name").unwrap();+ let s = settings(source.path(), true);+ let engine = fixture(home.path(), &s);+ engine.control.cancel_by_user();+ let stop = Arc::new(AtomicBool::new(false));+ engine.start_scheduler(stop.clone());+ std::thread::sleep(Duration::from_secs(12));+ assert!(engine.control.automatic_hold.load(Ordering::Relaxed));+ assert!(!engine.control.running.load(Ordering::Relaxed));+ assert_eq!(engine.db.stats().unwrap().files, 0);+ engine+ .control+ .cancelled_by_user+ .store(false, Ordering::SeqCst);+ engine.control.automatic_hold.store(false, Ordering::SeqCst);+ let deadline = Instant::now() + Duration::from_secs(5);+ while engine.db.stats().unwrap().files == 0 && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(50));+ }+ assert_eq!(+ engine.db.stats().unwrap().files,+ 1,+ "Explicit resume should allow the queued recovery"+ );+ stop.store(true, Ordering::Relaxed);+ std::thread::sleep(Duration::from_millis(1100));+ }+ #[test]+ fn source_restart_uses_updated_roots_and_removes_old_drive() {+ let home = tempfile::tempdir().unwrap();+ let old = tempfile::Builder::new()+ .prefix("VD-old-")+ .tempdir()+ .unwrap();+ let new = tempfile::Builder::new()+ .prefix("VD-new-")+ .tempdir()+ .unwrap();+ std::fs::write(old.path().join("removed-drive.txt"), "old").unwrap();+ std::fs::write(new.path().join("kept-drive.txt"), "new").unwrap();+ let s = settings(old.path(), false);+ let engine = fixture(home.path(), &s);+ engine.control.running.store(true, Ordering::Relaxed);+ engine.control.interrupt_sources();+ assert!(engine.control.cancel.load(Ordering::Relaxed));+ engine.control.update_settings(settings(new.path(), false));+ assert!(engine.control.restart_requested.load(Ordering::Relaxed));+ engine.control.running.store(false, Ordering::Relaxed);+ let stop = Arc::new(AtomicBool::new(false));+ engine.start_scheduler(stop.clone());+ let deadline = Instant::now() + Duration::from_secs(5);+ while engine.db.stats().unwrap().files == 0 && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(50));+ }+ stop.store(true, Ordering::Relaxed);+ std::thread::sleep(Duration::from_millis(1100));+ let c = engine.db.connect(true).unwrap();+ let paths = c+ .prepare("SELECT path FROM names")+ .unwrap()+ .query_map([], |r| r.get::<_, String>(0))+ .unwrap()+ .collect::<rusqlite::Result<Vec<_>>>()+ .unwrap();+ assert!(+ paths.contains(+ &new.path()+ .join("kept-drive.txt")+ .to_string_lossy()+ .into_owned()+ ),+ "{}",+ std::fs::read_to_string(home.path().join("test.log")).unwrap_or_default()+ );+ assert!(paths.iter().all(|p| Path::new(p).starts_with(new.path())));+ }+ #[test]+ fn removing_sources_after_explicit_cancel_does_not_request_restart() {+ let c = Control::default();+ c.running.store(true, Ordering::Relaxed);+ *c.schedule.lock().unwrap() = settings(Path::new("Y:\\"), false);+ c.cancel_by_user();+ c.update_settings(settings(Path::new("C:\\"), false));+ assert!(!c.restart_requested.load(Ordering::Relaxed));+ assert!(c.automatic_hold.load(Ordering::Relaxed));+ }+}diff --git a/native/src/models.rs b/native/src/models.rsindex b05af83..3ca5d7e 100644--- a/native/src/models.rs+++ b/native/src/models.rs@@ -15,6 +15,9 @@ pub struct Models {inner: Arc<Mutex<State>>,agent: ureq::Agent,pub loaded: Arc<AtomicBool>,+ pub loading: Arc<AtomicBool>,+ pub session_override: Arc<AtomicBool>,+ load_phase: Arc<Mutex<String>>,active: Arc<AtomicUsize>,query_cache: Arc<Mutex<Option<(String, Instant, Vec<f32>)>>>,}@@ -61,6 +64,9 @@ impl Default for Models {.build().into(),loaded: Arc::new(AtomicBool::new(false)),+ loading: Arc::new(AtomicBool::new(false)),+ session_override: Arc::new(AtomicBool::new(false)),+ load_phase: Arc::new(Mutex::new(String::new())),active: Arc::new(AtomicUsize::new(0)),query_cache: Arc::new(Mutex::new(None)),}@@ -87,6 +93,11 @@ impl Models {state.media = false;state.marker = None;self.loaded.store(false, Ordering::Relaxed);+ self.loading.store(false, Ordering::Relaxed);+ drop(state);+ if let Ok(mut cache) = self.query_cache.try_lock() {+ *cache = None;+ }Ok(())}pub fn start(&self, s: &Settings, media: bool) -> Result<()> {@@ -94,17 +105,27 @@ impl Models {self.ensure(s, media)}pub fn media_loaded(&self) -> bool {- self.inner.try_lock().map(|s| s.media).unwrap_or(false)+ self.loaded.load(Ordering::Acquire)+ && self.inner.try_lock().map(|s| s.media).unwrap_or(false)}pub fn idle_unload(&self, s: &Settings) -> bool {- if !s.unload_idle {+ self.unload_with_metrics(s, crate::scheduling::metrics())+ }+ fn unload_with_metrics(&self, s: &Settings, metrics: crate::scheduling::Metrics) -> bool {+ if self.session_override.load(Ordering::Acquire) {+ return false;+ }+ let resource_hold = crate::scheduling::model_hold(s, metrics).is_some();+ if !s.unload_idle && !resource_hold {return false;}if let Ok(mut state) = self.inner.try_lock() {if self.active.load(Ordering::Acquire) == 0&& state.child.is_some()- && state.last_used.elapsed()- > Duration::from_secs(s.unload_minutes.max(1) as u64 * 60)+ && (resource_hold+ || (s.unload_idle+ && state.last_used.elapsed()+ > Duration::from_secs(s.unload_minutes.max(1) as u64 * 60))){if let Some(mut child) = state.child.take() {let _ = child.kill();@@ -123,7 +144,32 @@ impl Models {self.active.fetch_add(1, Ordering::AcqRel);Activity(self)}+ pub fn loading_phase(&self) -> String {+ self.load_phase.lock().unwrap().clone()+ }+ pub fn search_hold(&self, s: &Settings) -> Option<&'static str> {+ if self.session_override.load(Ordering::Acquire) {+ None+ } else {+ crate::scheduling::model_hold(s, crate::scheduling::metrics())+ }+ }fn ensure(&self, s: &Settings, media: bool) -> Result<()> {+ if !s.remote_url.is_empty() {+ return Ok(());+ }+ if !self.loaded.load(Ordering::Acquire) {+ self.loading.store(true, Ordering::Release);+ *self.load_phase.lock().unwrap() = "Starting local llama-server…".into();+ }+ let result = self.ensure_inner(s, media);+ self.loading.store(false, Ordering::Release);+ if let Err(error) = &result {+ *self.load_phase.lock().unwrap() = error.to_string();+ }+ result+ }+ fn ensure_inner(&self, s: &Settings, media: bool) -> Result<()> {let mut state = self.inner.lock()@@ -157,10 +203,17 @@ impl Models {let _ = c.kill();let _ = c.wait();}+ self.loaded.store(false, Ordering::Release);+ state.job = None;+ state.media = false;+ state.marker = None;anyhow::ensure!(!s.server.is_empty() && !s.model.is_empty(),"Set up or select llama-server and EmbeddingGemma 2 in Models & hardware. Names search does not need a model.");+ self.loaded.store(false, Ordering::Release);+ self.loading.store(true, Ordering::Release);+ *self.load_phase.lock().unwrap() = "Starting local llama-server…".into();let mut cmd = Command::new(&s.server);cmd.args(["-m",@@ -233,6 +286,11 @@ impl Models {self.wait_ready(s)}fn wait_ready(&self, s: &Settings) -> Result<()> {+ self.wait_ready_at(&Self::url(s))+ }+ fn wait_ready_at(&self, url: &str) -> Result<()> {+ *self.load_phase.lock().unwrap() =+ "Loading EmbeddingGemma 2 · waiting for server readiness…".into();let start = Instant::now();loop {let alive = {@@ -246,9 +304,12 @@ impl Models {.is_some_and(|c| c.try_wait().ok().flatten().is_none())};anyhow::ensure!(alive, "Local model stopped while loading; check Model logs");- if let Ok(r) = self.agent.get(format!("{}/health", Self::url(s))).call() {+ if let Ok(r) = self.agent.get(format!("{url}/health")).call() {if r.status().as_u16() == 200 {self.loaded.store(true, Ordering::Relaxed);+ self.loading.store(false, Ordering::Release);+ *self.load_phase.lock().unwrap() =+ "EmbeddingGemma 2 and llama-server are ready".into();return Ok(());}}@@ -403,6 +464,11 @@ impl Models {Ok(out)}pub fn query(&self, s: &Settings, q: &str) -> Result<Vec<f32>> {+ if let Some(reason) = self.search_hold(s) {+ anyhow::bail!(+ "EmbeddingGemma 2 is paused: {reason}. Use Load anyway for this search session."+ );+ }// One short-lived query vector avoids repeating inference for multi-source searches.let key = format!("{}|{}|{}|{}|{}",@@ -545,3 +611,84 @@ mod idle_unload_tests {assert!(!models.idle_unload(&s));}}++#[cfg(test)]+mod search_session_tests {+ use super::*;+ fn helper(models: &Models) {+ let mut cmd = Command::new(std::env::current_exe().unwrap());+ cmd.args([+ "--ignored",+ "--exact",+ "models::idle_unload_tests::sleeping_model_helper",+ ]);+ crate::content::hidden(&mut cmd);+ let child = cmd.spawn().unwrap();+ let job = crate::platform::owned_process(&child).unwrap();+ let mut state = models.inner.lock().unwrap();+ state.child = Some(child);+ state.job = Some(job);+ state.last_used = Instant::now() - Duration::from_secs(121);+ models.loaded.store(true, Ordering::Relaxed);+ }+ #[test]+ fn session_pin_defers_game_unload_until_closed_and_never_interrupts_a_request() {+ let models = Models::default();+ helper(&models);+ let s = Settings {+ pause_for_game: true,+ unload_idle: false,+ ..Default::default()+ };+ let metrics = crate::scheduling::Metrics {+ game: true,+ ..Default::default()+ };+ models.session_override.store(true, Ordering::Release);+ assert!(!models.unload_with_metrics(&s, metrics));+ models.session_override.store(false, Ordering::Release);+ let request = models.activity();+ assert!(!models.unload_with_metrics(&s, metrics));+ drop(request);+ assert!(models.unload_with_metrics(&s, metrics));+ assert!(!models.loaded.load(Ordering::Acquire));+ assert!(models.inner.lock().unwrap().child.is_none());+ }+ #[test]+ fn readiness_progress_waits_for_healthy_server() {+ let models = Models::default();+ helper(&models);+ models.loaded.store(false, Ordering::Relaxed);+ models.loading.store(true, Ordering::Release);+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let url = format!("http://{}", server.server_addr().to_ip().unwrap());+ let responded = Arc::new(AtomicBool::new(false));+ let seen = responded.clone();+ let task = std::thread::spawn(move || {+ let first = server.recv().unwrap();+ first+ .respond(tiny_http::Response::from_string("loading").with_status_code(503))+ .unwrap();+ seen.store(true, Ordering::Release);+ let second = server.recv().unwrap();+ std::thread::sleep(Duration::from_millis(300));+ second+ .respond(tiny_http::Response::from_string("ready").with_status_code(200))+ .unwrap();+ });+ let wait = models.clone();+ let loading = std::thread::spawn(move || wait.wait_ready_at(&url));+ let start = Instant::now();+ while !responded.load(Ordering::Acquire) && start.elapsed() < Duration::from_secs(3) {+ std::thread::sleep(Duration::from_millis(10));+ }+ assert!(models.loading.load(Ordering::Acquire));+ assert!(!models.loaded.load(Ordering::Acquire));+ assert!(models.loading_phase().contains("Loading EmbeddingGemma"));+ loading.join().unwrap().unwrap();+ task.join().unwrap();+ assert!(models.loaded.load(Ordering::Acquire));+ assert!(!models.loading.load(Ordering::Acquire));+ models.stop().unwrap();+ }+}diff --git a/native/src/platform.rs b/native/src/platform.rsindex 5d7513d..06d8cab 100644--- a/native/src/platform.rs+++ b/native/src/platform.rs@@ -1668,3 +1668,146 @@ mod playback_diagnostics_tests {);}}++static GAME_NAMES: std::sync::OnceLock<std::sync::Mutex<Vec<String>>> = std::sync::OnceLock::new();+pub fn set_game_names(names: &str) {+ *GAME_NAMES.get_or_init(Default::default).lock().unwrap() = names+ .split([',', ';', '\n'])+ .map(|s| s.trim().to_lowercase())+ .filter(|s| !s.is_empty())+ .collect();+}+#[cfg(windows)]+pub fn game_or_fullscreen() -> (bool, bool) {+ use windows::Win32::{+ Foundation::{CloseHandle, HWND, RECT},+ Graphics::Gdi::{+ GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromWindow,+ },+ System::{+ Diagnostics::ToolHelp::*,+ Threading::{+ OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,+ QueryFullProcessImageNameW,+ },+ },+ UI::{+ Shell::{+ QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_RUNNING_D3D_FULL_SCREEN,+ SHQueryUserNotificationState,+ },+ WindowsAndMessaging::*,+ },+ };+ static LAST: std::sync::OnceLock<std::sync::Mutex<(isize, bool)>> = std::sync::OnceLock::new();+ unsafe {+ let mut game = false;+ let names = GAME_NAMES+ .get_or_init(Default::default)+ .lock()+ .unwrap()+ .clone();+ if !names.is_empty() {+ if let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) {+ let mut entry = PROCESSENTRY32W {+ dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,+ ..Default::default()+ };+ if Process32FirstW(snapshot, &mut entry).is_ok() {+ loop {+ let name = String::from_utf16_lossy(+ &entry.szExeFile[..entry+ .szExeFile+ .iter()+ .position(|v| *v == 0)+ .unwrap_or(entry.szExeFile.len())],+ )+ .to_lowercase();+ if names.contains(&name) {+ game = true;+ break;+ }+ if Process32NextW(snapshot, &mut entry).is_err() {+ break;+ }+ }+ }+ let _ = CloseHandle(snapshot);+ }+ }+ let mut hwnd = GetForegroundWindow();+ let mut pid = 0;+ GetWindowThreadProcessId(hwnd, Some(&mut pid));+ let mut last = LAST.get_or_init(Default::default).lock().unwrap();+ let own = pid == std::process::id();+ if own {+ hwnd = HWND(last.0 as *mut _);+ }+ if hwnd.0.is_null() || !IsWindow(Some(hwnd)).as_bool() {+ return (game, false);+ }+ GetWindowThreadProcessId(hwnd, Some(&mut pid));+ let mut class = [0u16; 128];+ let len = GetClassNameW(hwnd, &mut class);+ let class = String::from_utf16_lossy(&class[..len.max(0) as usize]);+ if ["Progman", "WorkerW", "Shell_TrayWnd"].contains(&class.as_str()) {+ return (game, false);+ }+ let notification = if own {+ None+ } else {+ SHQueryUserNotificationState().ok()+ };+ let d3d = notification == Some(QUNS_RUNNING_D3D_FULL_SCREEN);+ let mut rect = RECT::default();+ let mut monitor = MONITORINFO {+ cbSize: std::mem::size_of::<MONITORINFO>() as u32,+ ..Default::default()+ };+ let fullscreen = !IsIconic(hwnd).as_bool()+ && GetWindowRect(hwnd, &mut rect).is_ok()+ && GetMonitorInfoW(+ MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST),+ &mut monitor,+ )+ .as_bool()+ && rect.left <= monitor.rcMonitor.left+ && rect.top <= monitor.rcMonitor.top+ && rect.right >= monitor.rcMonitor.right+ && rect.bottom >= monitor.rcMonitor.bottom+ && GetWindowLongW(hwnd, GWL_STYLE) as u32 & WS_CAPTION.0 == 0;+ if let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) {+ let mut path = [0u16; 32768];+ let mut size = path.len() as u32;+ if QueryFullProcessImageNameW(+ process,+ PROCESS_NAME_WIN32,+ windows::core::PWSTR(path.as_mut_ptr()),+ &mut size,+ )+ .is_ok()+ {+ let path = String::from_utf16_lossy(&path[..size as usize]).to_lowercase();+ game |= path.contains("\\steamapps\\")+ || path.contains("\\epic games\\")+ || path.contains("\\gog games\\");+ }+ let _ = CloseHandle(process);+ }+ game |= d3d || (own && last.1);+ if !own {+ *last = (hwnd.0 as isize, game);+ }+ (+ game,+ fullscreen+ || d3d+ || notification == Some(QUNS_BUSY)+ || notification == Some(QUNS_PRESENTATION_MODE),+ )+ }+}+#[cfg(not(windows))]+pub fn game_or_fullscreen() -> (bool, bool) {+ (false, false)+}diff --git a/native/src/scheduling.rs b/native/src/scheduling.rsindex 5f60b4e..c52ea3d 100644--- a/native/src/scheduling.rs+++ b/native/src/scheduling.rs@@ -7,6 +7,8 @@ pub struct Metrics {pub gpu: Option<f32>,pub idle: u64,pub on_ac: Option<bool>,+ pub game: bool,+ pub fullscreen: bool,}static METRICS: OnceLock<Mutex<Metrics>> = OnceLock::new();pub fn metrics() -> Metrics {@@ -15,7 +17,35 @@ pub fn metrics() -> Metrics {.lock().unwrap()}+pub fn resource_pause(s: &Settings, m: Metrics) -> Option<&'static str> {+ if s.pause_for_game && m.game {+ Some("A game is running")+ } else if s.pause_for_fullscreen && m.fullscreen {+ Some("A full-screen application is running")+ } else {+ None+ }+}+pub fn model_hold(s: &Settings, m: Metrics) -> Option<&'static str> {+ if !s.remote_url.is_empty() {+ return None;+ }+ if let Some(reason) = resource_pause(s, m) {+ return Some(reason);+ }+ if s.defer_search_model {+ let mut limits = s.clone();+ // Typing a search is activity; resource limits should not require typing to stop.+ limits.check_user_idle = false;+ idle_allowed(&limits, m).err()+ } else {+ None+ }+}pub fn idle_allowed(s: &Settings, m: Metrics) -> Result<(), &'static str> {+ if let Some(reason) = resource_pause(s, m) {+ return Err(reason);+ }if s.check_user_idle && m.idle < s.idle_seconds as u64 {return Err("Waiting for keyboard/mouse inactivity");}@@ -39,6 +69,9 @@ pub fn idle_allowed(s: &Settings, m: Metrics) -> Result<(), &'static str> {Ok(())}pub fn due(s: &Settings, now: DateTime<Local>, m: Metrics) -> Result<i64, String> {+ if let Some(reason) = resource_pause(s, m) {+ return Err(reason.into());+ }if s.schedule == "Manual" {return Err("Periodic scan scheduling is off".into());}@@ -85,9 +118,12 @@ pub fn start_monitor() {let mut sampler = Sampler::new();loop {#[cfg(windows)]- let value = sampler.sample();+ let mut value = sampler.sample();#[cfg(not(windows))]- let value = Metrics::default();+ let mut value = Metrics::default();+ let (game, fullscreen) = crate::platform::game_or_fullscreen();+ value.game = game;+ value.fullscreen = fullscreen;*METRICS.get_or_init(|| Mutex::new(Metrics::default())).lock()@@ -324,3 +360,74 @@ mod tests {assert!(due(&s, now, Metrics::default()).is_err());}}++#[cfg(test)]+mod model_resource_tests {+ use super::*;+ #[test]+ fn model_limits_ignore_typing_but_obey_gpu_and_game_flags() {+ let mut s = Settings {+ defer_search_model: true,+ check_cpu: false,+ check_gpu: true,+ check_user_idle: true,+ idle_seconds: 120,+ ac_only: false,+ gpu_limit: 30.0,+ ..Default::default()+ };+ assert!(+ model_hold(+ &s,+ Metrics {+ gpu: Some(10.0),+ idle: 0,+ ..Default::default()+ }+ )+ .is_none()+ );+ assert_eq!(+ model_hold(+ &s,+ Metrics {+ gpu: Some(80.0),+ ..Default::default()+ }+ ),+ Some("Waiting for GPU usage to fall")+ );+ s.pause_for_game = true;+ assert_eq!(+ model_hold(+ &s,+ Metrics {+ game: true,+ ..Default::default()+ }+ ),+ Some("A game is running")+ );+ s.remote_url = "http://127.0.0.1:9999".into();+ assert!(+ model_hold(+ &s,+ Metrics {+ game: true,+ ..Default::default()+ }+ )+ .is_none()+ );+ assert_eq!(+ resource_pause(+ &s,+ Metrics {+ game: true,+ ..Default::default()+ }+ ),+ Some("A game is running")+ );+ }+}diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.issindex 83dc6db..cddb97c 100644--- a/packaging/VectorDash-Rust.iss+++ b/packaging/VectorDash-Rust.iss@@ -3,7 +3,7 @@ AppId={{C6AC1B4D-A119-4D73-B2C8-6C507DEFE923}AppName=VectorDashAppVerName=VectorDashUninstallDisplayName=VectorDash-AppVersion=0.3.9+AppVersion=0.3.11AppPublisher=VectorDash contributorsAppPublisherURL=https://github.com/ampersandru/VectorDashDefaultDirName={localappdata}\Programs\VectorDash@@ -13,7 +13,7 @@ ArchitecturesAllowed=x64compatibleArchitecturesInstallIn64BitMode=x64compatibleMinVersion=10.0.22000OutputDir=..\dist\installer-OutputBaseFilename=VectorDash-Rust-Setup-0.3.9-x64+OutputBaseFilename=VectorDash-Rust-Setup-0.3.11-x64SetupIconFile=VectorDash.icoUninstallDisplayIcon={app}\VectorDash.exeLicenseFile=..\LICENSE