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
Select idle GPU and fix network, popup and clipboard activity (#22)
ampersandru52dca6b99e34
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1index 21ce900..1284c6e 100644--- a/Build-Rust.ps1+++ b/Build-Rust.ps1@@ -102,8 +102,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.44-x64.zip' -Force-$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.44-x64.exe'-$taskZip='dist/installer/VectorDash-Rust-0.3.44-x64.zip'+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.45-x64.zip' -Force+$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.45-x64.exe'+$taskZip='dist/installer/VectorDash-Rust-0.3.45-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/native/Cargo.lock b/native/Cargo.lockindex f355186..233bc45 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -5750,7 +5750,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"[[package]]name = "vectordash"-version = "0.3.44"+version = "0.3.45"dependencies = ["anyhow","arboard",diff --git a/native/Cargo.toml b/native/Cargo.tomlindex c4b3d2e..7d01783 100644--- a/native/Cargo.toml+++ b/native/Cargo.toml@@ -1,6 +1,6 @@[package]name = "vectordash"-version = "0.3.44"+version = "0.3.45"edition = "2024"license = "MIT"[dependencies]diff --git a/native/docs/0.3.45-beta.1.md b/native/docs/0.3.45-beta.1.mdnew file mode 100644index 0000000..07d7b4d--- /dev/null+++ b/native/docs/0.3.45-beta.1.md@@ -0,0 +1,9 @@+# VectorDash 0.3.45-beta.1++- Resolve mapped network drives through their UNC share for monitoring, enumeration and content reads, while retaining configured drive-letter paths, source settings and index identities.+- Reattach network watchers using the resolved share path and add a five-minute catch-up for configured network sources, covering missed SMB notifications. Existing idle, pause and retry rules still apply. Unavailable sources retain indexed records.+- Fix quick-search dismissal after speech stops or finishes: capture Escape before response widgets consume it and detect outside clicks using the actual window bounds. Keep the popup open while AI is responding or speech is playing/paused.++Validation: 430 unit tests, including mounted-source path/metadata and scoped catch-up coverage. The real T: mapping and its UNC share were checked, and native notifications passed using an automatically removed, uniquely named temporary folder on T:. Existing user files and drive mappings were not changed. Four GUI regressions passed: natural completion/outside click, completed speech/Escape, manual stop/outside click, and keeping the popup open during AI generation and speech.++Test: add a new folder/file on T:, then wait for notification processing or the five-minute catch-up and your idle conditions. In the quick popup, verify clicking away keeps it open during AI generation and speech, then verify outside-click and Escape dismissal after speech finishes or is stopped.diff --git a/native/docs/0.3.45-beta.2.md b/native/docs/0.3.45-beta.2.mdnew file mode 100644index 0000000..8b75932--- /dev/null+++ b/native/docs/0.3.45-beta.2.md@@ -0,0 +1,18 @@+# VectorDash 0.3.45-beta.2++## Clipboard performance++- Stop checking an empty OCR/image-embedding queue every two seconds. New image captures, imports and relevant settings changes invalidate the empty result; a once-per-minute safety check handles changes from outside the app. Existing captures still use the normal two-second worker cadence.+- Add indexes for embedding candidates, pending OCR and retention. Candidate checks read index metadata instead of repeatedly traversing large encrypted clipboard payloads.+- Perform schema inspection/index migration once, using the database schema version for subsequent connections. Existing history, saved items and encrypted payloads are retained.+- Respect capture pause for background image embedding as well as OCR.++## Includes beta.1 fixes++Mapped network monitoring/scanning resolves the UNC share while retaining configured drive-letter identities, with a five-minute network catch-up. Quick-search dismissal works after speech ends/stops and keeps the popup open during AI generation and active/paused speech.++## Validation++Migration, query bytecode, candidate selection, empty-queue timing and actual image-capture wakeup regressions are included. On a disposable copy of the reported database, the indexed lookup reduced SQLite page-cache misses from 7,985 to 7 and median lookup time from 15.485 ms to 0.0335 ms (APSW benchmark, four fresh connections per case). These are query measurements, not physical disk or whole-app CPU measurements. The source database was opened read-only; the disposable copy was deleted after testing.++After installation, fully restart VectorDash and repeat a 10–30 second idle Procmon recording. The regular two-second bursts of thousands of clipboard.sqlite reads should disappear. Some activity remains for retention cleanup, user actions, new captures and the one-minute safety check. Copy a new image to confirm capture and subsequent image search still work.diff --git a/native/docs/0.3.45.md b/native/docs/0.3.45.mdnew file mode 100644index 0000000..6438ed9--- /dev/null+++ b/native/docs/0.3.45.md@@ -0,0 +1,20 @@+# VectorDash 0.3.45++## New controls++- **GPU idle threshold selector:** choose which detected GPU the idle threshold applies to, or select Use model GPU. CUDA selections resolve to their Windows adapter identifier through the NVIDIA driver. Schedule status names the monitored GPU. A busy iGPU no longer blocks indexing on a selected NVIDIA GPU.++## Fixes since 0.3.44++- **Network drives:** resolve mapped-drive monitoring, traversal and content reads through the UNC share while retaining configured drive-letter paths and source policies. Add a five-minute network-only catch-up for missed SMB notifications, respecting idle/pause rules and retaining records when a share is unavailable.+- **Quick-search dismissal:** handle Escape before response widgets consume it and detect outside clicks using actual window bounds. Keep the popup open during AI generation and active/paused speech; restore dismissal once both are inactive.+- **Idle clipboard activity:** stop repeatedly querying empty OCR/image-embedding queues every two seconds. New captures/imports and relevant setting changes trigger a fresh check, with a one-minute safety recheck. Add indexes for background candidates and retention, and skip repeated schema inspection after migration.+- **Clipboard pause:** background image embedding now respects capture pause, matching OCR.++## Validation++Unit coverage includes per-adapter GPU filtering, saved selector settings, history migration, indexed candidate lookup without payload-table reads, empty-queue timing and image-capture wakeup. A live CUDA check mapped CUDA0 to the NVIDIA GeForce RTX 5080 and sampled its utilization. Previous beta GUI checks verified popup protection during AI/speech and dismissal after completion/stop; a native watcher test passed on a temporary folder on T:.++On a disposable copy of the reported clipboard database, the indexed query reduced SQLite page-cache misses from 7,985 to 7 and median lookup time from 15.485 ms to 0.0335 ms. These are query benchmarks, not physical disk or whole-app CPU measurements.++All fixes from 0.3.45-beta.1 and beta.2 are included. Multi-adapter compute APIs that cannot be resolved automatically require an explicit GPU selection rather than using another adapter's load.diff --git a/native/locales/de.json b/native/locales/de.jsonindex 37ef5cb..a0dfaf5 100644--- a/native/locales/de.json+++ b/native/locales/de.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/en.json b/native/locales/en.jsonindex d3477b7..567b6cb 100644--- a/native/locales/en.json+++ b/native/locales/en.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/es.json b/native/locales/es.jsonindex 30158bc..c746c47 100644--- a/native/locales/es.json+++ b/native/locales/es.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/fr.json b/native/locales/fr.jsonindex 0747784..98fd76b 100644--- a/native/locales/fr.json+++ b/native/locales/fr.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/hi.json b/native/locales/hi.jsonindex 26e737f..8669a46 100644--- a/native/locales/hi.json+++ b/native/locales/hi.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/it.json b/native/locales/it.jsonindex 8bf7f6b..02bc436 100644--- a/native/locales/it.json+++ b/native/locales/it.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/ja.json b/native/locales/ja.jsonindex 6dcd1d9..36ce02d 100644--- a/native/locales/ja.json+++ b/native/locales/ja.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/ko.json b/native/locales/ko.jsonindex b61d4af..2031e59 100644--- a/native/locales/ko.json+++ b/native/locales/ko.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/pt-BR.json b/native/locales/pt-BR.jsonindex 0077dc2..fbbe41c 100644--- a/native/locales/pt-BR.json+++ b/native/locales/pt-BR.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/ru.json b/native/locales/ru.jsonindex febd331..d7f4161 100644--- a/native/locales/ru.json+++ b/native/locales/ru.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/vi.json b/native/locales/vi.jsonindex 07b9aae..ff32d6d 100644--- a/native/locales/vi.json+++ b/native/locales/vi.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/zh-CN.json b/native/locales/zh-CN.jsonindex e2c0a7c..c402441 100644--- a/native/locales/zh-CN.json+++ b/native/locales/zh-CN.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/locales/zh-TW.json b/native/locales/zh-TW.jsonindex e3f039e..6e71771 100644--- a/native/locales/zh-TW.json+++ b/native/locales/zh-TW.json@@ -940,5 +940,9 @@"llama-server": "llama-server","Enable file monitoring or choose an idle schedule to configure these conditions.": "Enable file monitoring or choose an idle schedule to configure these conditions.","Password input (hidden)": "Password input (hidden)",- "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model."+ "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.": "Paradee uses CPU SIMD. Model variants apply to Heart; other voices use their own compact model.",+ "GPU for idle threshold": "GPU for idle threshold",+ "Use model GPU": "Use model GPU",+ "Selected GPU unavailable": "Selected GPU unavailable",+ "GPU monitored: {name}": "GPU monitored: {name}"}diff --git a/native/scripts/tts_dismissal_smoke.py b/native/scripts/tts_dismissal_smoke.pynew file mode 100644index 0000000..4893f13--- /dev/null+++ b/native/scripts/tts_dismissal_smoke.py@@ -0,0 +1,45 @@+"""Isolated GUI regression: sentence speech starts before streamed answer completes."""+import argparse,io,json,os,pathlib,subprocess,threading,time,uuid,wave+from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer+p=argparse.ArgumentParser();p.add_argument('--exe',default='native/target/debug/vectordash.exe');a=p.parse_args()+root=(pathlib.Path('windows/.smoke/tts-dismissal')/uuid.uuid4().hex).resolve();root.mkdir(parents=True)+audio=io.BytesIO()+with wave.open(audio,'wb') as wav:+ wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(24000);wav.writeframes(b'\0\0'*72000)+short_audio=io.BytesIO()+with wave.open(short_audio,'wb') as wav:+ wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(24000);wav.writeframes(b'\0\0'*2400)+state={};first='This is the first complete sentence for streamed speech.';second='This second sentence arrives later in the generated answer.'+class Handler(BaseHTTPRequestHandler):+ def log_message(self,*args):pass+ def do_GET(self):+ self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'data':[{'id':'fixture'}]}).encode())+ def do_POST(self):+ body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ if self.path.endswith('/chat/completions'):+ state['start']=time.monotonic();self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers()+ for text in ['This is the [first][source] complete **sentence** for streamed speech. ',second+' ']:+ self.wfile.write(('data: '+json.dumps({'choices':[{'delta':{'content':text}}]})+'\n\n').encode());self.wfile.flush();time.sleep(3)+ self.wfile.write(('data: '+json.dumps({'choices':[{'delta':{'content':'\n\n[source]: https://example.org/hidden?tracking=1\n'}}]})+'\n\n').encode());self.wfile.flush()+ state['end']=time.monotonic();self.wfile.write(b'data: [DONE]\n\n');self.wfile.flush()+ elif self.path.endswith('/audio/speech'):+ state['speech'].append({'at':time.monotonic(),'body':body})+ if body.get('stream_format'):+ self.send_response(400);self.end_headers();self.wfile.write(b'unsupported stream format');return+ data=short_audio.getvalue() if mode=="escape" else audio.getvalue();self.send_response(200);self.send_header('Content-Type','audio/wav');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)+ else:self.send_response(404);self.end_headers()+server=ThreadingHTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start()+try:+ for mode in ["outside","escape","stop","protected"]:+ enabled=False+ state.clear();state['speech']=[];profile=root/mode;profile.mkdir()+ config={'encrypt_index':False,'roots':[],'include_programs':False,'watch_changes':False,'mcp_enabled':False,'auto_check_updates':False,'language':'en','clipboard_enabled':False,'llm_enabled':True,'llm_url':f'http://127.0.0.1:{server.server_port}/v1','llm_model':'fixture','llm_context':8192,'tts_enabled':True,'tts_auto':True,'tts_streaming':enabled,'tts_url':f'http://127.0.0.1:{server.server_port}/v1','tts_model':'fixture','tts_voice':'fixture'}+ (profile/'settings.json').write_text(json.dumps(config),encoding='utf-8')+ report=profile/'report.json'+ subprocess.run([str(pathlib.Path(a.exe).resolve()),'--smoke-quick','--smoke-tts-'+('escape' if mode=='escape' else 'protected' if mode=='protected' else 'outside'),*(['--smoke-tts-stop']if mode=='stop'else []),'--smoke-tool','AI','--smoke-followup','Give two sentences.','--smoke-seconds','22','--smoke-keep-open','--smoke-report',str(report)],env={**os.environ,'VECTORDASH_DATA_HOME':str(profile)},stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=35,check=True)+ data=json.loads(report.read_text());assert data.get('closed') and data.get('quick') and not data.get('tts_busy'),data+ assert state['speech'],'Speech request must have been dispatched'+ if mode=='protected':assert data.get('ai_held') and data.get('speech_held'),data+ print('PASS popup dismissal after speech:',mode,flush=True)+ print('Artifacts:',root,flush=True)+finally:server.shutdown()diff --git a/native/src/app.rs b/native/src/app.rsindex 9268e15..e97f973 100644--- a/native/src/app.rs+++ b/native/src/app.rs@@ -310,7 +310,7 @@ impl App {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);let tx = crate::engine::NotifySender::new(tx, Some(cc.egui_ctx.clone()))@@ -329,6 +329,7 @@ impl App {crate::platform::hotkeys(tx.clone(), shutdown.clone(), s.clone());}*engine.control.schedule.lock().unwrap() = s.clone();+ crate::scheduling::start_monitor(engine.control.schedule.clone());let scheduler_shutdown = Arc::new(AtomicBool::new(false));if smoke.is_none() || std::env::args().any(|a| a == "--smoke-scheduler") {engine.start_scheduler(scheduler_shutdown.clone());@@ -2239,6 +2240,20 @@ impl App {self.status = e.to_string();}}+ fn qa_tts_closed(&mut self, ctx: &egui::Context) {+ if let Some(path) = &self.smoke {+ if std::env::args().any(|a| {+ matches!(+ a.as_str(),+ "--smoke-tts-outside" | "--smoke-tts-escape" | "--smoke-tts-protected"+ )+ }) {+ let data = serde_json::json!({"closed":!self.search_visible,"tts_busy":self.tts_busy,"ai_busy":self.ai_busy,"quick":self.quick,"ai_held":ctx.data(|d|d.get_temp::<bool>(egui::Id::new("qa-ai-held")).unwrap_or(false)),"speech_held":ctx.data(|d|d.get_temp::<bool>(egui::Id::new("qa-speech-held")).unwrap_or(false))});+ let _ = std::fs::write(path, serde_json::to_vec_pretty(&data).unwrap());+ self.exiting = true;+ }+ }+ }fn close_window(&mut self, ctx: &egui::Context) {self.clear_image_query();self.web.stop();@@ -2265,6 +2280,7 @@ impl App {self.large_preview = false;if self.quick {ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));+ self.qa_tts_closed(ctx);return;}match self.s.close_behavior.as_str() {@@ -6806,6 +6822,33 @@ impl App {}ui.checkbox(&mut self.s.check_gpu, t("Require low GPU usage"));if self.s.check_gpu {+ ui.label(t("GPU for idle threshold"));+ let adapters = crate::scheduling::gpu_adapters();+ let name = if self.s.gpu_idle_device == "model" {+ t("Use model GPU").to_owned()+ } else {+ adapters+ .iter()+ .find(|a| a.id == self.s.gpu_idle_device)+ .map(|a| a.name.clone())+ .unwrap_or_else(|| t("Selected GPU unavailable").to_owned())+ };+ egui::ComboBox::from_id_salt("gpu-idle-device")+ .selected_text(name)+ .show_ui(ui, |ui| {+ ui.selectable_value(+ &mut self.s.gpu_idle_device,+ "model".into(),+ t("Use model GPU"),+ );+ for adapter in adapters {+ ui.selectable_value(+ &mut self.s.gpu_idle_device,+ adapter.id,+ adapter.name,+ );+ }+ });ui.add(egui::Slider::new(&mut self.s.gpu_limit, 1.0..=100.0).text(t("GPU usage below (%)")),@@ -6829,6 +6872,9 @@ impl App {ui.label(tr(&self.schedule_status));if idle {let metrics = crate::scheduling::metrics();+ if let Some(name) = crate::scheduling::gpu_monitor_name() {+ ui.weak(tr(&format!("GPU monitored: {name}")));+ }ui.label(tr(&format!("Other apps: CPU {} · GPU {} · {}",metrics@@ -6963,6 +7009,27 @@ impl App {impl eframe::App for App {fn raw_input_hook(&mut self, _ctx: &egui::Context, input: &mut egui::RawInput) {input.events.append(&mut self.qa_web_events);+ if self.smoke.is_some()+ && self.startup.elapsed() > Duration::from_secs(10)+ && !self.ai_busy+ && self.tts_busy+ && std::env::args().any(|a| a == "--smoke-tts-stop")+ {+ self.stop_read_aloud();+ }+ if self.smoke.is_some()+ && self.startup.elapsed() > Duration::from_secs(10)+ && !self.ai_busy+ && std::env::args().any(|a| a == "--smoke-tts-escape")+ {+ input.events.push(egui::Event::Key {+ key: egui::Key::Escape,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers::NONE,+ });+ }if crate::platform::take_image_paste()&& (self.tool == "AI" && !self.ai_busy|| matches!(self.tool.as_str(), "Search" | "Clipboard")@@ -6972,6 +7039,8 @@ impl eframe::App for App {}}fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {+ // Capture Escape before response widgets/popups consume it during rendering.+ let dismiss_escape = ctx.input(|i| i.key_pressed(egui::Key::Escape));crate::local_tts::tick();crate::i18n::apply(ctx, &self.s.language);if self.smoke.is_some()@@ -7815,14 +7884,30 @@ impl eframe::App for App {self.popup_had_focus = true;}let outside_down = crate::platform::left_button_down();- let qa_outside = self.web_smoke_outside(ctx);- let outside_click = outside_down && !self.popup_outside_down && !focused || qa_outside;+ let qa_outside = self.web_smoke_outside(ctx)+ || (self.smoke.is_some()+ && self.tool == "AI"+ && !self.ai_busy+ && !self.tts_busy+ && self.startup.elapsed() > Duration::from_secs(10)+ && std::env::args().any(|a| a == "--smoke-tts-outside"));+ let qa_outside = qa_outside+ || (self.smoke.is_some()+ && self.tool == "AI"+ && self.startup.elapsed() > Duration::from_secs(4)+ && std::env::args().any(|a| a == "--smoke-tts-protected"));+ if qa_outside && self.ai_busy {+ ctx.data_mut(|d| d.insert_temp(egui::Id::new("qa-ai-held"), true));+ }+ if qa_outside && self.tts_busy {+ ctx.data_mut(|d| d.insert_temp(egui::Id::new("qa-speech-held"), true));+ }+ let outside_click = outside_down+ && !self.popup_outside_down+ && !crate::platform::pointer_in_main_window()+ || qa_outside;self.popup_outside_down = outside_down;- if (self.ai_busy- || self.web.busy- || self.tts_busy- || self.dictation_busy- || self.popup_dialog_open())+ if (self.ai_busy || self.web.busy || self.dictation_busy || self.popup_dialog_open())&& !focused{self.popup_had_focus = false;@@ -7838,6 +7923,7 @@ impl eframe::App for App {&& !self.dictation_busy&& !self.popup_dialog_open(){+ self.stop_read_aloud();self.popup_had_focus = false;self.engine.models.cancel_query();self.search_visible = false;@@ -7846,6 +7932,7 @@ impl eframe::App for App {.session_override.store(false, Ordering::Release);ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));+ self.qa_tts_closed(ctx);}let empty = match self.tool.as_str() {"Search" => self.hits.is_empty(),@@ -8094,7 +8181,7 @@ impl eframe::App for App {{self.open_selected(ctx);}- if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {+ if dismiss_escape {if self.save_search_open {self.save_search_open = false;} else if self.filter_open {diff --git a/native/src/app/settings_catalog.rs b/native/src/app/settings_catalog.rsindex 7c3d28b..3feabd5 100644--- a/native/src/app/settings_catalog.rs+++ b/native/src/app/settings_catalog.rs@@ -174,6 +174,9 @@ pub(super) const ENTRIES: &[Entry] = &[Entry { page: 3, section: "Idle conditions", title: "Require low CPU usage", aliases: "" },Entry { page: 3, section: "Idle conditions", title: "CPU usage below (%)", aliases: "" },Entry { page: 3, section: "Idle conditions", title: "Require low GPU usage", aliases: "" },+ Entry { page: 3, section: "Idle conditions", title: "GPU for idle threshold", aliases: "" },+ Entry { page: 3, section: "Idle conditions", title: "Use model GPU", aliases: "" },+ Entry { page: 3, section: "Idle conditions", title: "Selected GPU unavailable", aliases: "" },Entry { page: 3, section: "Idle conditions", title: "GPU usage below (%)", aliases: "" },Entry { page: 3, section: "Idle conditions", title: "Automatic indexing only on AC power", aliases: "" },Entry { page: 3, section: "Idle conditions", title: "Maximum automatic run (minutes)", aliases: "" },diff --git a/native/src/changes.rs b/native/src/changes.rsindex 410a0f0..35c594f 100644--- a/native/src/changes.rs+++ b/native/src/changes.rs@@ -99,6 +99,23 @@ fn deliver_notification(}}}+fn logical_watch_path(path: &Path, actual: &Path, configured: &Path) -> PathBuf {+ path.strip_prefix(actual).map_or_else(+ |_| path.to_path_buf(),+ |tail| {+ if tail.as_os_str().is_empty() {+ configured.to_path_buf()+ } else {+ configured.join(tail)+ }+ },+ )+}+fn network_root(path: &Path) -> bool {+ crate::platform::preview_path(&path.to_string_lossy())+ .to_string_lossy()+ .starts_with(r"\\")+}/// One callback per watched root retains the origin even when Windows supplies/// an empty overflow/error event. A shared watcher cannot identify that source.fn source_watcher(@@ -109,12 +126,31 @@ fn source_watcher(spill: std::sync::Arc<std::sync::Mutex<NotificationSpill>>,) -> notify::Result<notify::RecommendedWatcher> {let origin = target.to_path_buf();+ let actual = crate::platform::preview_path(&target.to_string_lossy());+ let callback_root = actual.clone();let filter = settings.clone();let data_home = home.to_path_buf();- let mut watcher = notify::recommended_watcher(move |event| {+ let mut watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {+ let event = event+ .map(|mut e| {+ e.paths = e+ .paths+ .into_iter()+ .map(|p| logical_watch_path(&p, &callback_root, &origin))+ .collect();+ e+ })+ .map_err(|mut e| {+ e.paths = e+ .paths+ .into_iter()+ .map(|p| logical_watch_path(&p, &callback_root, &origin))+ .collect();+ e+ });deliver_notification(event, &origin, &filter, &data_home, &sender, &spill);})?;- watcher.watch(target, RecursiveMode::Recursive)?;+ watcher.watch(&actual, RecursiveMode::Recursive)?;Ok(watcher)}#[derive(Default)]@@ -127,6 +163,7 @@ pub struct Monitor {logger: Option<NotifySender>,spill: Option<std::sync::Arc<std::sync::Mutex<NotificationSpill>>>,recovery_reason: String,+ network_catchup: BTreeMap<PathBuf, Instant>,journal_notification_log: BTreeMap<PathBuf, Instant>,pending: HashSet<PathBuf>,recovery: bool,@@ -170,6 +207,7 @@ impl Monitor {self.recovery_reason.clear();self.journal_notification_log.clear();self.watchers.clear();+ self.network_catchup.clear();self.sender = None;self.rx = None;self.pending.clear();@@ -237,6 +275,9 @@ impl Monitor {if watched.iter().any(|p| target.starts_with(p)) || target.starts_with(home) {continue;}+ if network_root(&target) {+ self.network_catchup.insert(target.clone(), Instant::now());+ }match source_watcher(&target, s, home, sender.clone(), spill.clone()) {Ok(watcher) => {self.watchers.insert(target.clone(), watcher);@@ -447,6 +488,25 @@ impl Monitor {// Additional known paths are persisted, then loaded after this batch.}pub fn collect(&mut self, s: &Settings, home: &Path) {+ let now = Instant::now();+ let due = self+ .network_catchup+ .iter_mut()+ .filter_map(|(root, last)| {+ if now.saturating_duration_since(*last) >= Duration::from_secs(300) {+ *last = now;+ Some(root.clone())+ } else {+ None+ }+ })+ .collect::<Vec<_>>();+ if !due.is_empty() {+ self.request_scoped_recovery(+ due,+ "periodic network catch-up (notifications may be incomplete)",+ );+ }self.retry_watches();let (paths, recovery) = self.journal.poll();if recovery {@@ -1478,3 +1538,48 @@ mod live_journal_overflow_tests {}}}++#[cfg(test)]+mod network_catchup_tests {+ use super::*;+ #[test]+ fn physical_notifications_keep_configured_drive_paths() {+ assert_eq!(+ logical_watch_path(+ Path::new(r"\\nas\share\new folder\a.txt"),+ Path::new(r"\\nas\share"),+ Path::new(r"T:\")+ ),+ PathBuf::from(r"T:\new folder\a.txt")+ );+ }+ #[test]+ fn silent_network_watch_queues_only_its_source() {+ let home = tempfile::tempdir().unwrap();+ let mut s = Settings::default();+ s.watch_changes = true;+ s.roots = vec![+ crate::config::Source {+ path: r"T:\".into(),+ mode: "quick".into(),+ },+ crate::config::Source {+ path: r"C:\".into(),+ mode: "quick".into(),+ },+ ];+ let mut monitor = Monitor::default();+ monitor.settings = Some(s.clone());+ monitor.network_catchup.insert(+ PathBuf::from(r"T:\"),+ Instant::now() - Duration::from_secs(301),+ );+ monitor.collect(&s, home.path());+ assert!(monitor.pending.contains(&PathBuf::from(r"T:\")));+ assert!(!monitor.pending.contains(&PathBuf::from(r"C:\")));+ assert!(!monitor.recovery);+ monitor.pending.clear();+ monitor.collect(&s, home.path());+ assert!(monitor.pending.is_empty(), "catch-up must be rate limited");+ }+}diff --git a/native/src/config.rs b/native/src/config.rsindex 193c48a..bdd13f7 100644--- a/native/src/config.rs+++ b/native/src/config.rs@@ -86,6 +86,7 @@ pub struct Settings {pub setup_ocr: bool,pub check_cpu: bool,pub check_gpu: bool,+ pub gpu_idle_device: String,pub check_user_idle: bool,pub cpu_limit: f32,pub gpu_limit: f32,@@ -275,6 +276,7 @@ impl Default for Settings {setup_ocr: true,check_cpu: true,check_gpu: false,+ gpu_idle_device: "model".into(),check_user_idle: true,cpu_limit: 25.0,gpu_limit: 20.0,diff --git a/native/src/engine.rs b/native/src/engine.rsindex d7f688a..4555519 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -1129,12 +1129,14 @@ impl Engine {root.to_string_lossy().into_owned()};if partial- && std::fs::symlink_metadata(&root)- .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)+ && std::fs::symlink_metadata(crate::platform::preview_path(+ &root.to_string_lossy(),+ ))+ .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound){let accessible = s.roots.iter().any(|r| {crate::config::under(&root.to_string_lossy(), &r.path)- && Path::new(&r.path).exists()+ && crate::platform::preview_path(&r.path).exists()});if accessible {let prefix =@@ -1162,7 +1164,7 @@ impl Engine {}continue;}- if !root.exists() {+ if !crate::platform::preview_path(&root.to_string_lossy()).exists() {self.log("Warning",format!(@@ -1584,8 +1586,10 @@ impl Engine {batch.clear();Ok(())};+ let physical_file =+ crate::platform::preview_path(&path.to_string_lossy());let parsed = crate::worker::visit_checked(- path,+ &physical_file,s,&self.control,start_page,@@ -1642,7 +1646,9 @@ impl Engine {count > 0 || !had_warning,"No readable content was extracted; previous file content retained");- let current = std::fs::metadata(path)?;+ let current = std::fs::metadata(crate::platform::preview_path(+ &path.to_string_lossy(),+ ))?;anyhow::ensure!(current.len() == meta.len()&& current.modified().ok() == meta.modified().ok(),@@ -1827,7 +1833,8 @@ impl Engine {stop: &AtomicBool,) -> Result<()> {let start = Instant::now();- let path = Path::new(&document.path);+ let resolved = crate::platform::preview_path(&document.path);+ let path = resolved.as_path();let mut records = vec![];let mut bytes = 0usize;let mut warning = false;@@ -2032,7 +2039,7 @@ impl Engine {self.control.file_checkpoint()?;let remaining = document.records.len().saturating_sub(document.resume);let result = (|| -> Result<()> {- let meta = std::fs::metadata(&document.path)?;+ let meta = std::fs::metadata(crate::platform::preview_path(&document.path))?;anyhow::ensure!(meta.len() == document.size && meta.modified().ok() == document.modified,"File changed while queued; retrying on its next update"@@ -2777,22 +2784,71 @@ fn network_source_unavailable(root: &Path, error: Option<&std::io::Error>) -> bo}// Opening and reading the first entry verifies enumeration, rather than// trusting cached metadata/exists() after a share disconnects.- std::fs::read_dir(root)+ std::fs::read_dir(crate::platform::preview_path(&root.to_string_lossy())).and_then(|mut entries| entries.next().transpose().map(|_| ())).is_err()}+struct ScanEntry {+ entry: walkdir::DirEntry,+ path: PathBuf,+}+impl ScanEntry {+ fn path(&self) -> &Path {+ &self.path+ }+ fn file_type(&self) -> std::fs::FileType {+ self.entry.file_type()+ }+ fn metadata(&self) -> walkdir::Result<std::fs::Metadata> {+ self.entry.metadata()+ }+}+fn scan_logical_path(path: &Path, physical: &Path, logical: &Path) -> PathBuf {+ path.strip_prefix(physical).map_or_else(+ |_| path.to_path_buf(),+ |p| {+ if p.as_os_str().is_empty() {+ logical.to_path_buf()+ } else {+ logical.join(p)+ }+ },+ )+}fn walker<'a>(root: &Path,s: &'a Settings,home: &'a Path,-) -> impl Iterator<Item = walkdir::Result<walkdir::DirEntry>> + 'a {- walkdir::WalkDir::new(root)+) -> impl Iterator<Item = walkdir::Result<ScanEntry>> + 'a {+ walker_paths(+ root.to_path_buf(),+ crate::platform::preview_path(&root.to_string_lossy()),+ s,+ home,+ )+}+fn walker_paths<'a>(+ logical: PathBuf,+ physical: PathBuf,+ s: &'a Settings,+ home: &'a Path,+) -> impl Iterator<Item = walkdir::Result<ScanEntry>> + 'a {+ let filter_physical = physical.clone();+ let filter_logical = logical.clone();+ walkdir::WalkDir::new(&physical).follow_links(false).max_open(16).into_iter().filter_entry(move |e| {- s.allowed(e.path()) && !e.path().starts_with(home) && !e.file_type().is_symlink()+ let path = scan_logical_path(e.path(), &filter_physical, &filter_logical);+ s.allowed(&path) && !path.starts_with(home) && !e.file_type().is_symlink()+ })+ .map(move |e| {+ e.map(|entry| {+ let path = scan_logical_path(entry.path(), &physical, &logical);+ ScanEntry { entry, path }+ })})}pub fn sensitive(text: &str) -> bool {@@ -4098,3 +4154,39 @@ mod monitoring_log_tests {);}}++#[cfg(test)]+mod network_scan_identity_tests {+ use super::*;+ #[test]+ fn mounted_source_enumerates_new_folders_with_logical_paths_and_real_metadata() {+ let disk = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let folder = disk.path().join("new folder");+ std::fs::create_dir(&folder).unwrap();+ std::fs::write(folder.join("new.txt"), b"new data").unwrap();+ let s = Settings::default();+ let entries = walker_paths(+ PathBuf::from(r"T:\"),+ disk.path().to_path_buf(),+ &s,+ home.path(),+ )+ .collect::<walkdir::Result<Vec<_>>>()+ .unwrap();+ let file = entries.iter().find(|e| e.file_type().is_file()).unwrap();+ assert_eq!(file.path(), Path::new(r"T:\new folder\new.txt"));+ assert_eq!(file.metadata().unwrap().len(), 8);+ }+ #[test]+ fn physical_scan_paths_preserve_index_and_source_identity() {+ assert_eq!(+ scan_logical_path(+ Path::new(r"\\nas\share\folder\a.txt"),+ Path::new(r"\\nas\share"),+ Path::new(r"T:\")+ ),+ PathBuf::from(r"T:\folder\a.txt")+ );+ }+}diff --git a/native/src/launcher.rs b/native/src/launcher.rsindex e580eb9..adbdf51 100644--- a/native/src/launcher.rs+++ b/native/src/launcher.rs@@ -130,6 +130,33 @@ pub fn paused() -> bool {pub fn ignore_next() {IGNORE_NEXT.store(true, std::sync::atomic::Ordering::Release);}+// Same-process captures/imports wake the semantic queues without database polling.+static CLIPBOARD_WORK_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);+fn clipboard_work_changed() {+ CLIPBOARD_WORK_REVISION.fetch_add(1, std::sync::atomic::Ordering::Release);+}+#[derive(Default)]+struct ClipboardWorkGate {+ signature: String,+ revision: u64,+ empty_until: Option<std::time::Instant>,+}+impl ClipboardWorkGate {+ fn observe(&mut self, signature: String, revision: u64) {+ if self.signature != signature || self.revision != revision {+ self.signature = signature;+ self.revision = revision;+ self.empty_until = None;+ }+ }+ fn ready(&self, now: std::time::Instant) -> bool {+ self.empty_until.is_none_or(|until| now >= until)+ }+ fn empty(&mut self, now: std::time::Instant) {+ self.empty_until = Some(now + std::time::Duration::from_secs(60));+ }+}+const NEXT_CLIP_IMAGE: &str = "SELECT id FROM clips WHERE kind='image' AND ((embedding='')=1 OR model_key!=?1) ORDER BY created DESC,id DESC LIMIT 1";#[derive(Clone)]pub struct Clipboard {file: PathBuf,@@ -148,9 +175,18 @@ impl Clipboard {}fn connect(&self) -> Result<Connection> {static MIGRATIONS: std::sync::Mutex<()> = std::sync::Mutex::new(());- let _migration = MIGRATIONS.lock().unwrap_or_else(|p| p.into_inner());let c = Connection::open(&self.file)?;c.busy_timeout(std::time::Duration::from_secs(2))?;+ c.execute_batch("PRAGMA secure_delete=ON")?;+ let version: i64 = c.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version >= 2 {+ return Ok(c);+ }+ let _migration = MIGRATIONS.lock().unwrap_or_else(|p| p.into_inner());+ let version: i64 = c.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version >= 2 {+ return Ok(c);+ }c.execute_batch("PRAGMA secure_delete=ON; CREATE TABLE IF NOT EXISTS clips(id INTEGER PRIMARY KEY,created INTEGER NOT NULL,payload TEXT NOT NULL,digest TEXT NOT NULL UNIQUE);")?;let columns: Vec<String> = c.prepare("PRAGMA table_info(clips)")?@@ -199,6 +235,11 @@ impl Clipboard {c.execute("UPDATE clips SET bytes=length(payload) WHERE bytes=0", [])?;c.execute_batch("PRAGMA user_version=1")?;}+ c.execute_batch("BEGIN IMMEDIATE;+ CREATE INDEX IF NOT EXISTS clips_embedding_queue ON clips(kind,created DESC,id DESC,model_key,(embedding=''));+ CREATE INDEX IF NOT EXISTS clips_ocr_queue ON clips(created DESC,id DESC) WHERE kind='image' AND ocr_done=0;+ CREATE INDEX IF NOT EXISTS clips_retention ON clips(pinned,created DESC,id DESC,bytes,kind);+ PRAGMA user_version=2;COMMIT;")?;Ok(c)}fn model_key(s: &crate::config::Settings) -> String {@@ -223,7 +264,10 @@ impl Clipboard {return Ok(false);}let key = Self::model_key(s);- let row:Option<i64>=self.connect()?.query_row("SELECT id FROM clips WHERE kind='image' AND (embedding='' OR model_key!=?1) ORDER BY created DESC LIMIT 1",[&key],|r|r.get(0)).optional()?;+ let row: Option<i64> = self+ .connect()?+ .query_row(NEXT_CLIP_IMAGE, [&key], |r| r.get(0))+ .optional()?;let Some(id) = row else { return Ok(false) };let media = self.image(id)?;let segment = crate::content::Segment {@@ -708,6 +752,7 @@ impl Clipboard {let c = self.connect()?;c.execute("INSERT INTO clips(created,payload,digest,kind,bytes) VALUES(?1,?2,?3,'image',?4) ON CONFLICT(digest) DO UPDATE SET created=excluded.created",params![now,payload,digest,payload.len() as i64])?;drop(c);+ clipboard_work_changed();self.purge(hours, now)}pub fn image(&self, id: i64) -> Result<Vec<u8>> {@@ -737,7 +782,7 @@ impl Clipboard {let id: Option<i64> = self.connect()?.query_row(- "SELECT id FROM clips WHERE kind='image' AND ocr_done=0 ORDER BY created DESC LIMIT 1",+ "SELECT id FROM clips INDEXED BY clips_ocr_queue WHERE kind='image' AND ocr_done=0 ORDER BY created DESC LIMIT 1",[],|r| r.get(0),)@@ -851,6 +896,7 @@ impl Clipboard {}}tx.commit()?;+ clipboard_work_changed();Ok(())}pub fn remove(&self, id: i64) -> Result<()> {@@ -881,11 +927,32 @@ pub fn monitor(std::thread::spawn(move || {let store = Clipboard::new(&semantic_home);let mut ocr_retry = std::time::Instant::now();+ let mut ocr_gate = ClipboardWorkGate::default();+ let mut image_gate = ClipboardWorkGate::default();while !semantic_stop.load(std::sync::atomic::Ordering::Relaxed) {let s = semantic_settings.lock().unwrap().clone();+ let revision = CLIPBOARD_WORK_REVISION.load(std::sync::atomic::Ordering::Acquire);+ let now = std::time::Instant::now();+ ocr_gate.observe(+ format!(+ "{}|{}|{}",+ s.clipboard_enabled, s.clipboard_options.ocr, s.ocr+ ),+ revision,+ );+ image_gate.observe(+ format!(+ "{}|{}|{}",+ s.clipboard_enabled,+ s.clipboard_image_embeddings,+ Clipboard::model_key(&s)+ ),+ revision,+ );if s.clipboard_enabled&& !paused()&& s.clipboard_options.ocr+ && ocr_gate.ready(now)&& std::time::Instant::now() >= ocr_retry&& crate::scheduling::idle_allowed(&s, crate::scheduling::metrics()).is_ok(){@@ -900,10 +967,12 @@ pub fn monitor(format!("Clipboard OCR paused for 60 seconds: {error}"),));}- _ => {}+ Ok(false) => ocr_gate.empty(now),}}if s.clipboard_enabled+ && !paused()+ && image_gate.ready(now)&& s.clipboard_image_embeddings&& crate::scheduling::idle_allowed(&s, crate::scheduling::metrics()).is_ok(){@@ -919,7 +988,7 @@ pub fn monitor(std::thread::sleep(std::time::Duration::from_secs(1));}}- _ => {}+ Ok(false) => image_gate.empty(now),}}std::thread::sleep(std::time::Duration::from_secs(2));@@ -1479,3 +1548,141 @@ mod image_query_tests {);}}++#[cfg(test)]+mod clipboard_idle_tests {+ use super::*;+ #[test]+ fn new_image_capture_wakes_an_empty_queue() {+ let home = tempfile::tempdir().unwrap();+ let store = Clipboard::new(home.path());+ let now = std::time::Instant::now();+ let revision = CLIPBOARD_WORK_REVISION.load(std::sync::atomic::Ordering::Acquire);+ let mut gate = ClipboardWorkGate::default();+ gate.observe("current".into(), revision);+ gate.empty(now);+ let mut bytes = std::io::Cursor::new(Vec::new());+ image::DynamicImage::new_rgba8(2, 2)+ .write_to(&mut bytes, image::ImageFormat::Png)+ .unwrap();+ store+ .record_image(bytes.get_ref(), 0, chrono::Utc::now().timestamp())+ .unwrap();+ gate.observe(+ "current".into(),+ CLIPBOARD_WORK_REVISION.load(std::sync::atomic::Ordering::Acquire),+ );+ assert!(gate.ready(now));+ assert!(+ store+ .connect()+ .unwrap()+ .query_row(NEXT_CLIP_IMAGE, ["current"], |r| r.get::<_, i64>(0))+ .optional()+ .unwrap()+ .is_some()+ );+ }+ #[test]+ fn empty_work_sleeps_until_capture_settings_change_or_safety_deadline() {+ let now = std::time::Instant::now();+ let mut gate = ClipboardWorkGate::default();+ gate.observe("local-model".into(), 5);+ assert!(gate.ready(now));+ gate.empty(now);+ for second in 1..60 {+ gate.observe("local-model".into(), 5);+ assert!(!gate.ready(now + std::time::Duration::from_secs(second)));+ }+ gate.observe("local-model".into(), 6);+ assert!(gate.ready(now));+ gate.empty(now);+ gate.observe("different-model".into(), 6);+ assert!(gate.ready(now));+ gate.empty(now);+ assert!(gate.ready(now + std::time::Duration::from_secs(60)));+ }+ #[test]+ fn existing_history_migrates_to_covering_work_indexes_without_reading_payloads() {+ let home = tempfile::tempdir().unwrap();+ let store = Clipboard::new(home.path());+ // Start with the oldest supported schema and preserve its existing row.+ let old = Connection::open(&store.file).unwrap();+ old.execute_batch("CREATE TABLE clips(id INTEGER PRIMARY KEY,created INTEGER NOT NULL,payload TEXT NOT NULL,digest TEXT NOT NULL UNIQUE); INSERT INTO clips VALUES(1,1,'retained payload','legacy');").unwrap();+ drop(old);+ let c = store.connect().unwrap();+ assert_eq!(+ c.query_row("PRAGMA user_version", [], |r| r.get::<_, i64>(0))+ .unwrap(),+ 2+ );+ assert_eq!(+ c.query_row("SELECT payload FROM clips WHERE id=1", [], |r| r+ .get::<_, String>(0))+ .unwrap(),+ "retained payload"+ );+ for (id, embedding, key) in [+ (2, "vector", "current"),+ (3, "", "current"),+ (4, "vector", "old"),+ ] {+ c.execute("INSERT INTO clips(id,created,payload,digest,kind,embedding,model_key) VALUES(?1,?1,?2,?3,'image',?4,?5)",params![id,"x".repeat(256*1024),format!("image-{id}"),embedding,key]).unwrap();+ }+ let plan = c+ .prepare(&format!("EXPLAIN QUERY PLAN {NEXT_CLIP_IMAGE}"))+ .unwrap()+ .query_map(["current"], |r| r.get::<_, String>(3))+ .unwrap()+ .collect::<rusqlite::Result<Vec<_>>>()+ .unwrap()+ .join(" ");+ assert!(plan.contains("clips_embedding_queue"), "{plan}");+ assert!(!plan.contains("TEMP B-TREE"), "{plan}");+ let bytecode = c+ .prepare(&format!("EXPLAIN {NEXT_CLIP_IMAGE}"))+ .unwrap()+ .query_map(["current"], |r| {+ Ok((+ r.get::<_, String>(1)?,+ r.get::<_, i64>(2)?,+ r.get::<_, i64>(3)?,+ ))+ })+ .unwrap()+ .collect::<rusqlite::Result<Vec<_>>>()+ .unwrap();+ assert!(+ !bytecode+ .iter()+ .any(|(op, cursor, _)| op == "Column" && *cursor == 0),+ "Candidate lookup must not read payload table columns: {bytecode:?}"+ );+ assert_eq!(+ c.query_row(NEXT_CLIP_IMAGE, ["current"], |r| r.get::<_, i64>(0))+ .unwrap(),+ 4+ );+ c.execute(+ "UPDATE clips SET embedding='vector',model_key='current' WHERE kind='image'",+ [],+ )+ .unwrap();+ assert!(+ c.query_row(NEXT_CLIP_IMAGE, ["current"], |r| r.get::<_, i64>(0))+ .optional()+ .unwrap()+ .is_none()+ );+ let ocr_plan=c.prepare("EXPLAIN QUERY PLAN SELECT id FROM clips INDEXED BY clips_ocr_queue WHERE kind='image' AND ocr_done=0 ORDER BY created DESC LIMIT 1").unwrap().query_map([],|r|r.get::<_,String>(3)).unwrap().collect::<rusqlite::Result<Vec<_>>>().unwrap().join(" ");+ assert!(ocr_plan.contains("clips_ocr_queue"), "{ocr_plan}");+ drop(c);+ let reopened = store.connect().unwrap();+ assert_eq!(+ reopened+ .query_row("SELECT count(*) FROM clips", [], |r| r.get::<_, i64>(0))+ .unwrap(),+ 4+ );+ }+}diff --git a/native/src/platform.rs b/native/src/platform.rsindex 438c17c..5814acc 100644--- a/native/src/platform.rs+++ b/native/src/platform.rs@@ -2534,6 +2534,30 @@ mod fullscreen_tests {}}+/// Native hit testing avoids stale renderer focus after a hidden audio process exits.+pub fn pointer_in_main_window() -> bool {+ #[cfg(windows)]+ unsafe {+ use windows::Win32::{+ Foundation::{HWND, POINT, RECT},+ UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect},+ };+ let hwnd = HWND(MAIN_WINDOW.load(std::sync::atomic::Ordering::Acquire) as *mut _);+ let mut point = POINT::default();+ let mut rect = RECT::default();+ if GetCursorPos(&mut point).is_err() || GetWindowRect(hwnd, &mut rect).is_err() {+ return true;+ }+ return point.x >= rect.left+ && point.x < rect.right+ && point.y >= rect.top+ && point.y < rect.bottom;+ }+ #[cfg(not(windows))]+ {+ true+ }+}pub fn main_window_visible() -> bool {#[cfg(windows)]unsafe {diff --git a/native/src/scheduling.rs b/native/src/scheduling.rsindex d3138a9..483a5a7 100644--- a/native/src/scheduling.rs+++ b/native/src/scheduling.rs@@ -127,15 +127,17 @@ fn due_impl(}Ok(slot)}-pub fn start_monitor() {+pub fn start_monitor(settings: std::sync::Arc<Mutex<Settings>>) {static STARTED: OnceLock<()> = OnceLock::new();STARTED.get_or_init(|| {- std::thread::spawn(|| {+ std::thread::spawn(move || {#[cfg(windows)]let mut sampler = Sampler::new();loop {#[cfg(windows)]- let mut value = sampler.sample();+ let monitor_settings = settings.lock().unwrap().clone();+ #[cfg(windows)]+ let mut value = sampler.sample(&monitor_settings);#[cfg(not(windows))]let mut value = Metrics::default();let (game, fullscreen) = crate::platform::game_or_fullscreen();@@ -166,6 +168,9 @@ struct Sampler {counter: windows::Win32::System::Performance::PDH_HCOUNTER,gpu_ready: bool,previous_pids: std::collections::HashSet<u32>,+ gpu_target: Option<(u32, u32)>,+ target_key: String,+ target_retry: std::time::Instant,}#[cfg(windows)]impl Sampler {@@ -192,9 +197,23 @@ impl Sampler {counter,gpu_ready: ready,previous_pids: Default::default(),+ gpu_target: None,+ target_key: String::new(),+ target_retry: std::time::Instant::now(),}}- fn sample(&mut self) -> Metrics {+ fn sample(&mut self, s: &Settings) -> Metrics {+ let key = format!("{}|{}|{}", s.gpu_idle_device, s.hardware, s.device);+ if key != self.target_key || std::time::Instant::now() >= self.target_retry {+ let target = selected_gpu(s);+ self.gpu_target = target.as_ref().map(|a| a.luid);+ *GPU_MONITOR_NAME+ .get_or_init(Default::default)+ .lock()+ .unwrap() = target.map(|a| a.name);+ self.target_key = key;+ self.target_retry = std::time::Instant::now() + std::time::Duration::from_secs(30);+ }use windows::Win32::{Foundation::FILETIME,System::{@@ -274,15 +293,25 @@ impl Sampler {)}).collect::<Vec<_>>();+ let counters = counters+ .into_iter()+ .filter(|(name, _)| {+ self.gpu_target+ .is_some_and(|target| gpu_luid(name) == Some(target))+ })+ .collect::<Vec<_>>();let other = counters.iter().filter(|(name, _)| {!gpu_pid(name).is_some_and(|pid| owned_pids.contains(&pid))});let owned = counters.iter().filter(|(name, _)| {gpu_pid(name).is_some_and(|pid| owned_pids.contains(&pid))});- m.gpu = Some(busiest_gpu_engine(other.map(|(n, v)| (n.as_str(), *v))));- m.owned_gpu =- Some(busiest_gpu_engine(owned.map(|(n, v)| (n.as_str(), *v))));+ m.gpu = self+ .gpu_target+ .map(|_| busiest_gpu_engine(other.map(|(n, v)| (n.as_str(), *v))));+ m.owned_gpu = self+ .gpu_target+ .map(|_| busiest_gpu_engine(owned.map(|(n, v)| (n.as_str(), *v))));}}}@@ -494,3 +523,200 @@ mod gpu_aggregation_tests {assert_eq!(super::busiest_gpu_engine(rows.into_iter()), 9.0);}}++#[derive(Clone, Debug)]+pub struct GpuAdapter {+ pub id: String,+ pub name: String,+ pub luid: (u32, u32),+}+static GPU_MONITOR_NAME: OnceLock<Mutex<Option<String>>> = OnceLock::new();+pub fn gpu_monitor_name() -> Option<String> {+ GPU_MONITOR_NAME+ .get_or_init(Default::default)+ .lock()+ .unwrap()+ .clone()+}+pub fn gpu_adapters() -> Vec<GpuAdapter> {+ static CACHE: OnceLock<Mutex<Option<(std::time::Instant, Vec<GpuAdapter>)>>> = OnceLock::new();+ let mut cache = CACHE.get_or_init(Default::default).lock().unwrap();+ if let Some((at, items)) = &*cache {+ if at.elapsed() < std::time::Duration::from_secs(5) {+ return items.clone();+ }+ }+ let items = detect_gpu_adapters();+ *cache = Some((std::time::Instant::now(), items.clone()));+ items+}+fn detect_gpu_adapters() -> Vec<GpuAdapter> {+ #[cfg(windows)]+ unsafe {+ use windows::Win32::Graphics::Dxgi::{+ CreateDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE, IDXGIFactory1,+ };+ let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory1>() else {+ return vec![];+ };+ return (0..32)+ .map_while(|i| factory.EnumAdapters1(i).ok().map(|a| (i, a)))+ .filter_map(|(i, a)| {+ let d = a.GetDesc1().ok()?;+ if d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {+ return None;+ }+ let end = d+ .Description+ .iter()+ .position(|c| *c == 0)+ .unwrap_or(d.Description.len());+ let name = String::from_utf16_lossy(&d.Description[..end]);+ Some(GpuAdapter {+ id: format!(+ "adapter:{i}:{:x}:{:x}:{:x}:{name}",+ d.VendorId, d.DeviceId, d.SubSysId+ ),+ name,+ luid: (d.AdapterLuid.HighPart as u32, d.AdapterLuid.LowPart),+ })+ })+ .collect();+ }+ #[cfg(not(windows))]+ {+ vec![]+ }+}+fn gpu_luid(name: &str) -> Option<(u32, u32)> {+ let tail = name.split_once("_luid_")?.1;+ let mut p = tail.split('_');+ Some((+ u32::from_str_radix(p.next()?.strip_prefix("0x")?, 16).ok()?,+ u32::from_str_radix(p.next()?.strip_prefix("0x")?, 16).ok()?,+ ))+}+fn selected_gpu(s: &Settings) -> Option<GpuAdapter> {+ let adapters = gpu_adapters();+ if s.gpu_idle_device != "model" {+ return adapters.into_iter().find(|a| a.id == s.gpu_idle_device);+ }+ if s.hardware == "CPU" || s.remote_embeddings() {+ return None;+ }+ #[cfg(windows)]+ if let Some(index) = s+ .device+ .strip_prefix("CUDA")+ .and_then(|n| n.parse::<i32>().ok())+ {+ let luid = cuda_luid(index)?;+ return adapters.into_iter().find(|a| a.luid == luid);+ }+ // Never guess that a compute API index is a Windows adapter index.+ if adapters.len() == 1 {+ return adapters.into_iter().next();+ }+ None+}+#[cfg(windows)]+fn cuda_luid(index: i32) -> Option<(u32, u32)> {+ unsafe {+ use windows::{+ Win32::{+ Foundation::FreeLibrary,+ System::LibraryLoader::{+ GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,+ },+ },+ core::{PCSTR, w},+ };+ let module = LoadLibraryExW(w!("nvcuda.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32).ok()?;+ struct Library(windows::Win32::Foundation::HMODULE);+ impl Drop for Library {+ fn drop(&mut self) {+ unsafe {+ let _ = FreeLibrary(self.0);+ }+ }+ }+ let _library = Library(module);+ let init: unsafe extern "system" fn(u32) -> i32 =+ std::mem::transmute(GetProcAddress(module, PCSTR(c"cuInit".as_ptr().cast()))?);+ let get: unsafe extern "system" fn(*mut i32, i32) -> i32 = std::mem::transmute(+ GetProcAddress(module, PCSTR(c"cuDeviceGet".as_ptr().cast()))?,+ );+ let luid: unsafe extern "system" fn(*mut u8, *mut u32, i32) -> i32 = std::mem::transmute(+ GetProcAddress(module, PCSTR(c"cuDeviceGetLuid".as_ptr().cast()))?,+ );+ let mut device = 0;+ let mut bytes = [0u8; 8];+ let mut mask = 0;+ if init(0) != 0+ || get(&mut device, index) != 0+ || luid(bytes.as_mut_ptr(), &mut mask, device) != 0+ {+ return None;+ }+ Some((+ u32::from_le_bytes(bytes[4..].try_into().ok()?),+ u32::from_le_bytes(bytes[..4].try_into().ok()?),+ ))+ }+}++#[cfg(test)]+mod selected_gpu_tests {+ use super::*;+ #[test]+ fn ignores_busy_igpu_and_preserves_selected_adapter_process_accounting() {+ let rows = [+ (+ "pid_1_luid_0x00000000_0x00000001_phys_0_eng_0_engtype_3D",+ 88.0,+ ),+ ("pid_2_luid_0x0_0x2_phys_0_eng_0_engtype_Compute", 3.0),+ ("pid_3_luid_0x0_0x2_phys_0_eng_0_engtype_Compute", 4.0),+ ];+ let selected = rows+ .into_iter()+ .filter(|(name, _)| gpu_luid(name) == Some((0, 2)));+ assert_eq!(busiest_gpu_engine(selected), 7.0);+ assert_eq!(+ gpu_luid("pid_1_luid_0xffffffff_0x1234_phys_0_eng_0_engtype_3D"),+ Some((u32::MAX, 0x1234))+ );+ assert_eq!(gpu_luid("invalid"), None);+ }+ #[test]+ fn gpu_selection_is_saved_and_old_settings_use_model_default() {+ let s: Settings = serde_json::from_str("{}").unwrap();+ assert_eq!(s.gpu_idle_device, "model");+ let mut s = s;+ s.gpu_idle_device = "adapter:1:10de:example".into();+ let restored: Settings = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();+ assert_eq!(restored.gpu_idle_device, s.gpu_idle_device);+ }+ #[test]+ #[ignore = "reads real GPU counters and selected CUDA identity without loading a model"]+ #[cfg(windows)]+ fn live_cuda_gpu_idle_selection() {+ let s = Settings {+ hardware: "Dedicated GPU".into(),+ device: "CUDA0".into(),+ ..Default::default()+ };+ let selected = selected_gpu(&s).expect("CUDA model GPU must map to DXGI");+ assert!(selected.name.to_lowercase().contains("nvidia"));+ println!("Selected {} {:?}", selected.name, selected.luid);+ let mut sampler = Sampler::new();+ std::thread::sleep(std::time::Duration::from_secs(2));+ let m = sampler.sample(&s);+ assert!(m.gpu.is_some());+ assert_eq!(gpu_monitor_name(), Some(selected.name));+ println!("Selected GPU external utilization: {:?}", m.gpu);+ let mut manual = s.clone();+ manual.gpu_idle_device = selected.id;+ assert_eq!(selected_gpu(&manual).unwrap().luid, selected.luid);+ }+}diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.issindex 6a06cdc..42615ba 100644--- a/packaging/VectorDash-Rust.iss+++ b/packaging/VectorDash-Rust.iss@@ -3,8 +3,8 @@ AppId={{C6AC1B4D-A119-4D73-B2C8-6C507DEFE923}AppName=VectorDashAppVerName=VectorDashUninstallDisplayName=VectorDash-AppVersion=0.3.44-VersionInfoVersion=0.3.44.0+AppVersion=0.3.45+VersionInfoVersion=0.3.45.0AppPublisher=VectorDash contributorsAppPublisherURL=https://github.com/ampersandru/VectorDashDefaultDirName={localappdata}\Programs\VectorDash@@ -14,7 +14,7 @@ ArchitecturesAllowed=x64compatibleArchitecturesInstallIn64BitMode=x64compatibleMinVersion=10.0.19041OutputDir=..\dist\installer-OutputBaseFilename=VectorDash-Rust-Setup-0.3.44-x64+OutputBaseFilename=VectorDash-Rust-Setup-0.3.45-x64SetupIconFile=VectorDash.icoUninstallDisplayIcon={app}\VectorDash.exeLicenseFile=..\LICENSE