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
Improve indexing fairness, cache controls and search feedback; beta Windows 10
ampersandru7016df7496c9
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1index 76d7902..1657b4f 100644--- a/Build-Rust.ps1+++ b/Build-Rust.ps1@@ -82,8 +82,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.25-beta.1-x64.zip' -Force-$taskInstaller='dist/installer/VectorDash-Beta-Setup-0.3.25-beta.1-x64.exe'-$taskZip='dist/installer/VectorDash-Rust-0.3.25-beta.1-x64.zip'+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.25-beta.2-x64.zip' -Force+$taskInstaller='dist/installer/VectorDash-Beta-Setup-0.3.25-beta.2-x64.exe'+$taskZip='dist/installer/VectorDash-Rust-0.3.25-beta.2-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 f5b70d9..1bf892e 100644--- a/README.md+++ b/README.md@@ -1,6 +1,6 @@# VectorDash-**A local, universal search and launcher for Windows 11. Built in Rust.**+**A local, universal search and launcher for Windows 11 and Windows 10 (beta). Built in Rust.**VectorDash is meant to be a **full Windows search replacement**: one search bar for files and folders, installed apps, Windows settings, and quick calculations. Press **Ctrl+Alt+Space** from any app to find what you need.@@ -20,6 +20,8 @@ Search by name or exact words, or describe what you remember. Google's **Embeddi| **Calculations** | `24*1.2`, `20% of 150`, `sqrt(81)` | Get an instant local answer; press **Enter** to copy it. |- **File search:** combine names, exact words and semantic matches. Read PDF, Word, Excel and PowerPoint content; optionally use OCR for screenshot text. Search across 100+ languages and opt into code search.+- **Indexing controls:** choose Quick or Full files first, prepare one batch ahead, and let long documents yield between chunk groups. Optional near-identical video frame skipping reduces repeated embeddings; learned estimates cover known queued work. Select FP32 or FP16 semantic caching without rebuilding your index, and optionally enable Rank Calibration at search time.+- **Picture grid:** browse Images or Videos as thumbnails, with keyboard navigation and a resizable preview.- **Update channels:** choose Release for full releases, or Beta to include pre-releases, in About → Updates.- **Quick search and previews:** a frosted popup with adjustable color, transparency and gradient. It stays compact until you type. Preview results, drag the divider to resize Search/Clipboard previews, inspect why they matched, and open, copy or reveal files in Explorer.- **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.@@ -75,6 +77,8 @@ Semantic search needs the model and a compatible llama-server. Image/audio searcCustomize hotkeys in **Settings → Search and dictation → Keyboard Shortcut**.+Windows 10 support is **beta**, targeting version 2004/build 19041 or newer, x64. Windows 11 remains the primary tested platform. Older visual effects fall back when unavailable.+## Models and toolsApproximate sizes vary by release. EmbeddingGemma sizes are individual files; Parakeet and runtime sizes are compressed downloads. Installed files, the index and RAM/VRAM use require additional space.diff --git a/native/Cargo.lock b/native/Cargo.lockindex 45a42e5..f3ee5b3 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -5716,7 +5716,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"[[package]]name = "vectordash"-version = "0.3.25-beta.1"+version = "0.3.25-beta.2"dependencies = ["anyhow","arboard",@@ -5729,6 +5729,7 @@ dependencies = ["egui_commonmark","egui_extras","embed-resource",+ "half","hound","image","jxl-oxide",diff --git a/native/Cargo.toml b/native/Cargo.tomlindex 3990bb1..fafd17e 100644--- a/native/Cargo.toml+++ b/native/Cargo.toml@@ -1,11 +1,12 @@[package]name = "vectordash"-version = "0.3.25-beta.1"+version = "0.3.25-beta.2"edition = "2024"license = "MIT"[dependencies]anyhow = "1"semver = "1"+half = "2"base64 = "0.22"chrono = { version = "0.4", features = ["serde"] }crossbeam-channel = "0.5"diff --git a/native/docs/0.3.25-beta.2.md b/native/docs/0.3.25-beta.2.mdnew file mode 100644index 0000000..2f506bf--- /dev/null+++ b/native/docs/0.3.25-beta.2.md@@ -0,0 +1,16 @@+# VectorDash 0.3.25 Beta 2 — Indexing controls and Windows 10 beta++This is a test build on PR #16. Windows 10 support is **beta**, targeting Windows 10 version 2004/build 19041 or newer, x64. The installer no longer requires Windows 11. Actual Windows 10 device validation is still needed; compatibility branches were exercised on Windows 11. Windows 10 uses a rounded tinted fallback rather than the Windows 11 host-backdrop effect.++- Prepare one bounded batch ahead while the current batch embeds. Common Rust-decoded images avoid per-image process startup; other image/OCR parsers retain process isolation.+- Long documents yield in slices starting at 32 new chunks so other files can progress. Non-PDF slices grow on later turns to limit repeated parsing. Saved slices stay staged until the complete file can replace its old searchable content atomically; PDF resumes at its saved page. Other document formats may re-extract earlier content while reusing saved embeddings. Audio/video retain one streaming pass to avoid repeatedly decoding earlier media.+- Choose **Quick first** or **Full first** in Sources. Deferred work is durable and resumes under current source/idle rules without a second drive crawl.+- Optionally skip near-identical sampled video frames, preserving scene changes and timestamps. This saves embedding requests; candidate frames still need decoding. An ordinary Update index refreshes affected Full-indexed videos after changing this setting.+- Browse **Images** and **Videos** in a thumbnail grid, with keyboard navigation, context actions and a resizable preview. Disable the grid in Settings if you prefer the list.+- Learned timing estimates cover known queued Full work after enough completed samples. They are approximate, backend-specific and exclude undiscovered files.+- Choose **FP32** (default) or **FP16** semantic cache precision in Settings. FP16 halves vector storage in RAM, with FP32 scoring; the on-disk index stays FP32. No index update is required. Low memory mode continues streaming FP32 from disk.+- Optional **Rank Calibration** in Sources adjusts cross-media semantic ranking at search time. It does not change the embedding model's output or stored vectors. **No index update is required**, including for already Full-indexed items.+- Search loading and EmbeddingGemma waits show a blue circulating outline. Search, dictation and AI notices share a centered footer and expire after completion or a few seconds. AI responses show elapsed request time; read-aloud Pause/Play/Stop controls stay in that footer.+- Search/Clipboard previews use the available vertical space and preserve media aspect ratios.++Measured results and limits: [BENCHMARKS.md](BENCHMARKS.md). FP16 is a memory option, not a guaranteed speed improvement. This generated test corpus does not establish broad relevance quality.diff --git a/native/docs/BENCHMARKS.md b/native/docs/BENCHMARKS.mdindex 0c4b0b9..093b9d4 100644--- a/native/docs/BENCHMARKS.md+++ b/native/docs/BENCHMARKS.md@@ -84,3 +84,41 @@ Reproduce with `native/scripts/stability_benchmark.py`; it creates disposable da`--convert-encryption on|off` creates a converted database and retains the original, matching the settings conversion behavior. Back up before using it on an important index. Resume checkpoints reuse embedding work but currently re-extract earlier pages/chunks. Interactive searches have priority between batches; an already-running server batch is not preempted. Without a usable NTFS journal, startup catch-up may still scan sources to recover offline changes.Validation for this build: 147 standard Rust tests passed, plus explicit PDF streaming/cancellation, native H.264 decoding, and real-server reference checks. End-to-end process interruption retained eight of 137 chunks and reduced restart requests from 35 to 33, without publishing partial content. HTTP 503 recovery completed on the next update; one rejected input did not prevent four valid files from indexing. A configured Git fsmonitor hook was not executed. Main/popup Search and AI and the Sources page passed isolated launch/render checks. Three package-validation tests passed. These checks do not replace broad file-format fuzzing or testing every hardware/backend combination.+++## 0.3.25 Beta 2 validation++Compared with PR #16's preceding preview-fill build (6174826) on the same machine. These are disposable generated indexes, never the user's index. Search timings use one cold query followed by seven warm repeats; OS caches were not flushed. All three memory profiles, Names/Semantic/Hybrid modes, and plain/encrypted storage were exercised.++### Cache precision: 20,000 vectors, 768 dimensions++| Balanced semantic cache | FP32 median / p95 | FP16 median / p95 | Peak process RSS FP32 / FP16 |+|---|---:|---:|---:|+| Plain index | 20.270 / 23.799 ms | 22.313 / 24.470 ms | 120.53 / 91.29 MiB |+| Encrypted index | 22.411 / 26.639 ms | 23.299 / 28.552 ms | 121.36 / 92.50 MiB |++Four seeded queries per semantic mode used exact prototypes, 800 close neighbors, and unrelated normalized vectors. Top-1 agreement and top-10 set overlap were 100% across both cached profiles and encryption modes; the maximum shared score difference was 0.00000221. Low memory mode ignores cache precision and produced identical scores. This is a cache/pipeline test with fixed mock query vectors, not a model-inference benchmark. FP16 normalization is cached per row; conversion/scoring stays FP32. Vector payload memory halves; total process memory does not.++On the configured real remote backend, 24 generated text files and three geometric images retained the expected top topic for all 18 Semantic/Hybrid queries with FP32 and FP16, and calibration off/on. The index was copied for each check; no embeddings were rewritten. This small corpus cannot establish general relevance improvements or guarantee unchanged close rankings on other data.++### Indexing and resilience++128 tiny text files with a fixed 5 ms mock service delay, median of three fresh runs: batch 1 1.0355 → 1.0129 s; batch 4 0.3264 → 0.3254 s; batch 16 0.1384 → 0.1488 s. For tiny files there is little preparation to overlap, and added scheduling can cost time. The 72-page PDF extraction control was 2.3995 → 2.4507 s, with 72 pages in both builds. Neither table is evidence of faster model inference.++A static two-scene, six-second video retained both scenes and the three-second transition with deduplication enabled. FFmpeg yielded six candidates and two retained frames; the native decoder yielded four candidates and two retained frames on this generated long-GOP fixture. Deduplication does not reduce candidate decoding. Native seek behavior is codec dependent; use the existing FFmpeg option when it misses desired moments. Flat scenes with different colors are not treated as duplicates.++Long-file tests verify that a small file embeds before the long file finishes, with unique final vectors and no pending jobs. Yielded chunks stay in durable staging; old complete content remains searchable until an atomic final replacement. PDF page resume, cancellation, transient 503 recovery, rejected-file isolation and Git-hook non-execution passed. Forced termination after eight staged chunks retained them, completed 137 vectors after restart, and used 33 requests versus 35 uninterrupted; no incomplete file content was published.++161 standard Rust tests passed, plus explicit PDF and native H.264 checks. Main/popup image/video grids rendered, selected row 20 scrolled into view, and simulated Windows 10/no-glass paths launched. These checks run on Windows 11; a real Windows 10 machine remains required before removing the beta label.++Reproduce cache measurements with `native/scripts/cache_precision_benchmark.py`; the before/after controls use `native/scripts/stability_benchmark.py` and interruption checks use `native/scripts/stability_faults.py`. RSS excludes model-server RAM and VRAM. Learned estimates cover known jobs only, require three samples per content kind, and can be affected by server load and idle waits.++The one-batch-ahead image fixture uses 24 generated 1600×1000 PNGs, batch 4 and an 80 ms mock embedding service. After removing per-image subprocess startup for bounded Rust-decoded images, median indexing over three runs was 1.4472 → 0.5908 s, with six requests and all 24 image vectors present in every run. This measures overlap and pipeline overhead, not GPU inference; OCR and other codecs retain isolated workers.++Fair scheduling slices PDFs at 32 new records with page resume. Other documents begin at 32 records and grow their turns as staged progress increases, limiting repeated extraction. Audio/video keep one streaming decode pass; they still yield model access between embedding batches, but do not interleave separate indexing files mid-media. Full timestamp-based media resume is not part of this build.++The compatibility audit guards Windows 11 DWM attributes and uses a rounded tinted fallback on Windows 10. See Microsoft's [DWM corner requirements](https://learn.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference) and [DWM attributes](https://learn.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute). Media Foundation remains delay-loaded with the existing FFmpeg alternative. Imported APIs and forced 19045 branches were checked on the development machine; this is not a Windows 10 device certification.++Footer validation used a deliberately slow embedding endpoint: the blue outline and waiting notice remained active until a response, then returned to the result count and measured search time. Main/popup checks covered three-second notice expiry, measured status centering, AI request elapsed time and real test-audio read-aloud controls. The compact popup footer now reserves a 40-point row for its 35-point Open full app button, with padding inside the rounded window.++The final candidate also recorded 0.0% process CPU in three consecutive four-second tray-idle samples after warm-up, with no sources, clipboard capture or background indexing enabled. This short idle observation does not cover every enabled background service. Final package checks verified installer/portable manifests and four release-gate tests passed.diff --git a/native/scripts/cache_precision_benchmark.py b/native/scripts/cache_precision_benchmark.pynew file mode 100644index 0000000..1e8e2d8--- /dev/null+++ b/native/scripts/cache_precision_benchmark.py@@ -0,0 +1,61 @@+"""Measure real release searches and FP16/FP32 ranking agreement in a disposable index."""+import argparse,json,math,os,random,sqlite3,statistics,struct,subprocess,tempfile,threading,time+from pathlib import Path+from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer+import psutil+p=argparse.ArgumentParser();p.add_argument('--exe',required=True);p.add_argument('--output',required=True);p.add_argument('--files',type=int,default=20000);args=p.parse_args();exe=Path(args.exe).resolve();root=Path(tempfile.mkdtemp(prefix='VectorDash-cache-bench-'));home=root/'home';home.mkdir();source=root/'catalog';source.mkdir();rng=random.Random(941)+def normalized(values):+ scale=math.sqrt(sum(x*x for x in values));return [x/scale for x in values]+probes=[normalized([rng.gauss(0,1)for _ in range(768)])for _ in range(8)]+class Handler(BaseHTTPRequestHandler):+ protocol_version='HTTP/1.1'+ def do_POST(self):+ import socket+ self.connection.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY,1)+ body=json.loads(self.rfile.read(int(self.headers['Content-Length'])));text=str(body['input']);index=next((i for i in range(8)if f'probe{i}'in text),0);data=json.dumps({'data':[{'index':0,'embedding':probes[index]}]}).encode();self.send_response(200);self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)+ def log_message(self,*a):pass+server=ThreadingHTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start()+settings={'encrypt_index':False,'roots':[{'path':str(source),'mode':'full'}],'embedding_server':'Remote','remote_url':f'http://127.0.0.1:{server.server_port}/v1','remote_model':'fixture','include_programs':False,'auto_check_updates':False,'watch_changes':False,'pause_for_game':False,'pause_for_fullscreen':False,'defer_search_model':False,'rank_calibration':False}+def save():(home/'settings.json').write_text(json.dumps(settings),encoding='utf-8')+def run(*argv):+ env=os.environ.copy();env['VECTORDASH_DATA_HOME']=str(home);process=subprocess.Popen([str(exe),*argv],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8');peak=0;stop=threading.Event()+ def sample():+ nonlocal peak+ while not stop.wait(.01):+ try:peak=max(peak,psutil.Process(process.pid).memory_info().rss)+ except psutil.Error:pass+ thread=threading.Thread(target=sample);thread.start()+ try:out,err=process.communicate(timeout=120)+ finally:stop.set();thread.join()+ assert process.returncode==0,err;return json.loads(out),round(peak/1048576,2)+save();run('--query','','--mode','Names');db=sqlite3.connect(home/'index.sqlite');db.execute('BEGIN');location=json.dumps({'page':0,'seconds':-1,'line':0,'embedding_source':'text'})+for i in range(args.files):+ # Most rows are unrelated; nearby candidates stress close-ranking precision without artificial ties.+ if i<8:vector=probes[i]+ elif i<808:vector=normalized([v+rng.gauss(0,.003)for v in probes[i%8]])+ else:vector=normalized([rng.gauss(0,1)for _ in range(768)])+ path=str(source/f'file-{i:06d}.txt');name=Path(path).name;blob=struct.pack('<768f',*vector)+ db.execute('INSERT INTO names VALUES(?,?,?,?,?,?,?,?,?)',(path,name,str(source),'file',path.lower(),name.lower(),1,2048,'full'));db.execute('INSERT INTO segments VALUES(?,?,?,?,?,?)',(path,'files','text','unrelated fixture document','[]',location));rid=db.execute('SELECT last_insert_rowid()').fetchone()[0];db.execute('INSERT INTO segment_vectors VALUES(?,?,?,?,?,?,?)',(rid,'files','text','text',768,blob,path))+db.execute("INSERT INTO name_words(name_words) VALUES('rebuild')");db.commit();db.close();report={'files':args.files,'dimensions':768,'rows':[],'comparisons':[],'limits':['Synthetic normalized vectors; pipeline and cache comparison, not an inference benchmark.','OS disk cache not flushed. RAM is backend process RSS, excludes server and VRAM.']};results={}+try:+ for encrypted in [False,True]:+ if encrypted:run('--convert-encryption','on');settings['encrypt_index']=True+ for profile in ['Low memory','Balanced','Fast search']:+ for precision in ['FP32','FP16']:+ settings.update(performance=profile,cache_precision=precision);save()+ for mode in ['Names','Semantic','Both']:+ times=[];peak=0;checks=[]+ for index in range(4 if mode!='Names' else 1):+ query='file-000000' if mode=='Names' else f'probe{index}'+ data,rss=run('--query',query,'--mode',mode,'--repeat','8');times+=data['search_times_ms'][1:];peak=max(peak,rss);checks.append(data['results']);results[(encrypted,profile,precision,mode,index)]=data['results']+ row={'encrypted':encrypted,'profile':profile,'precision':precision,'mode':mode,'warm_median_ms':round(statistics.median(times),3),'warm_p95_ms':round(sorted(times)[math.ceil(len(times)*.95)-1],3),'peak_rss_mib':peak};report['rows'].append(row);print(json.dumps(row),flush=True)+ for encrypted in [False,True]:+ for profile in ['Low memory','Balanced','Fast search']:+ for mode in ['Semantic','Both']:+ overlaps=[];same=0;errors=[]+ for i in range(4):+ a=results[(encrypted,profile,'FP32',mode,i)];b=results[(encrypted,profile,'FP16',mode,i)];same+=a[0]['path']==b[0]['path'];overlaps.append(len({x['path']for x in a[:10]}&{x['path']for x in b[:10]})/10);scores={x['path']:x['score']for x in a};errors.extend(abs(x['score']-scores[x['path']])for x in b if x['path']in scores)+ report['comparisons'].append({'encrypted':encrypted,'profile':profile,'mode':mode,'top1_agreement':same/4,'top10_overlap':statistics.mean(overlaps),'max_shared_score_error':max(errors)})+ assert same==4,'Top result changed on synthetic relevance probes'+finally:+ Path(args.output).write_text(json.dumps(report,indent=2),encoding='utf-8');server.shutdown()diff --git a/native/scripts/prefetch_benchmark.py b/native/scripts/prefetch_benchmark.pynew file mode 100644index 0000000..4bf948c--- /dev/null+++ b/native/scripts/prefetch_benchmark.py@@ -0,0 +1,26 @@+"""Disposable 24-image preparation/inference overlap benchmark; requires Pillow."""+import json,subprocess,os,tempfile,threading,time,statistics,argparse,sqlite3+from pathlib import Path+from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer+from PIL import Image+parser=argparse.ArgumentParser();parser.add_argument('--exe',required=True);parser.add_argument('--baseline',required=True);parser.add_argument('--output',required=True);args=parser.parse_args()+root=Path(tempfile.mkdtemp(prefix='VD-prefetch-'));source=root/'photos';source.mkdir()+for i in range(24):Image.new('RGB',(1600,1000),(i*10,80,120)).save(source/f'photo-{i}.png')+calls=0+class Handler(BaseHTTPRequestHandler):+ def log_message(self,*args):pass+ def do_POST(self):+ global calls+ calls+=1+ body=json.loads(self.rfile.read(int(self.headers['Content-Length'])));items=body['input'];items=items if isinstance(items,list)else[items];time.sleep(.08);b=json.dumps({'data':[{'index':i,'embedding':[1,0,0]}for i in range(len(items))]}).encode();self.send_response(200);self.send_header('Content-Length',str(len(b)));self.end_headers();self.wfile.write(b)+server=ThreadingHTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start();report=[]+baseline=Path(args.baseline).resolve()+try:+ for label,exe in [('before',baseline),('after',Path(args.exe).resolve())]:+ runs=[];requests=[]+ for i in range(3):+ calls=0+ home=root/f'{label}-{i}';home.mkdir();s={'encrypt_index':False,'embedding_server':'Remote','remote_url':f'http://127.0.0.1:{server.server_port}/v1','remote_model':'fixture','include_programs':False,'watch_changes':False,'check_cpu':False,'check_gpu':False,'check_user_idle':False,'pause_for_game':False,'pause_for_fullscreen':False,'ac_only':False,'defer_search_model':False,'batch_size':4,'ocr_enabled':False};(home/'settings.json').write_text(json.dumps(s));env=os.environ.copy();env['VECTORDASH_DATA_HOME']=str(home);p=subprocess.run([str(exe),'--index',str(source),'--unencrypted'],env=env,capture_output=True,text=True,timeout=90);assert p.returncode==0,p.stderr;d=json.loads(p.stdout);runs.append(d['index_seconds']);requests.append(calls)+ c=sqlite3.connect(home/'index.sqlite');assert c.execute('SELECT count(*) FROM segment_vectors').fetchone()[0]==24;assert c.execute("SELECT count(*) FROM native_content WHERE error<>''").fetchone()[0]==0;c.close()+ row={'build':label,'median_s':statistics.median(runs),'runs':runs,'requests':requests,'indexed_images':24};report.append(row);print(row,flush=True)+finally:server.shutdown();Path(args.output).write_text(json.dumps(report,indent=2))diff --git a/native/src/app.rs b/native/src/app.rsindex 4e355f0..7dcc8cd 100644--- a/native/src/app.rs+++ b/native/src/app.rs@@ -26,9 +26,10 @@ const PAGES: [&str; 8] = ["Logs","About",];-const CATEGORIES: [&str; 7] = [+const CATEGORIES: [&str; 8] = ["All files","Images",+ "Videos","Documents","Audio / video","Folders",@@ -143,6 +144,7 @@ pub struct App {qa_child_size: Option<[usize; 2]>,qa_selection: Option<usize>,result_scroll_offset: f32,+ grid_columns: usize,child_theme_key: String,search_visible: bool,model_warm_attempted: bool,@@ -214,6 +216,8 @@ pub struct App {qa_ai_followup_sent: bool,qa_ai_scroll_before: f32,ai_metrics: crate::ai::Metrics,+ ai_started: Option<Instant>,+ ai_elapsed: Option<f64>,ai_image_view: Option<String>,tts_models: Vec<String>,tts_voices: Vec<String>,@@ -230,7 +234,7 @@ pub struct App {tts_job: u64,tts_cancel: Arc<AtomicBool>,tts_paused: Arc<AtomicBool>,- status_clocks: [Option<(String, Instant)>; 3],+ status_clocks: [Option<(String, Instant)>; 6],connections: [ConnectionState; 2],remote_servers: [RemoteState; 4],hardware_open: bool,@@ -432,6 +436,7 @@ impl App {qa_child_size: None,qa_selection: None,result_scroll_offset: 0.0,+ grid_columns: 1,child_theme_key: String::new(),search_visible: !(std::env::args().any(|a| a == "--startup") && saved_start_hidden),model_warm_attempted: false,@@ -503,6 +508,8 @@ impl App {qa_ai_followup_sent: false,qa_ai_scroll_before: 0.0,ai_metrics: crate::ai::Metrics::default(),+ ai_started: None,+ ai_elapsed: None,ai_image_view: None,tts_models: vec![],tts_voices: vec![],@@ -519,7 +526,7 @@ impl App {tts_job: 0,tts_cancel: Arc::new(AtomicBool::new(false)),tts_paused: Arc::new(AtomicBool::new(false)),- status_clocks: [None, None, None],+ status_clocks: [None, None, None, None, None, None],connections: std::array::from_fn(|_| ConnectionState::default()),remote_servers: std::array::from_fn(|_| RemoteState::default()),hardware_open: false,@@ -577,12 +584,12 @@ impl App {app.mode = "Names".into();app.dirty = true;}+ if let Some(mode) = get("--smoke-mode") {+ app.mode = mode;+ }if args.iter().any(|a| a == "--smoke-indexing") {app.indexing = true;}- if args.iter().any(|a| a == "--smoke-tts-busy") {- app.tts_busy = true;- }if args.iter().any(|a| a == "--smoke-transcribing") {app.dictation_busy = true;app.dictation_status = "Transcribing...".into();@@ -608,6 +615,9 @@ impl App {if std::env::args().any(|a| a == "--smoke-tts-voices") {app.tts_voice_due = Some(Instant::now());}+ if let Some(category) = get("--smoke-category") {+ app.category = category;+ }if let Some(tool) = get("--smoke-tool") {app.switch_tool(&tool);}@@ -619,6 +629,9 @@ impl App {images: vec![],});}+ if args.iter().any(|a| a == "--smoke-tts-busy") {+ app.tts_busy = true;+ }if let Some(path) = get("--smoke-ai-image") {if let Ok(bytes) = std::fs::read(path) {if let Ok(url) = crate::capture::vision(&bytes, None) {@@ -682,6 +695,9 @@ impl App {self.s.setup_model = self.model_setup;self.s.setup_encoder = self.encoder_setup;self.s.setup_ocr = self.ocr_setup;+ if self.saved_settings.cache_precision != self.s.cache_precision {+ self.engine.vectors.clear();+ }let pages = match self.s.performance.as_str() {"Low memory" => 8192,"Fast search" => 65536,@@ -1129,6 +1145,10 @@ impl App {}Event::AiDone(id, result) => {if id == self.ai_job {+ self.ai_elapsed = self+ .ai_started+ .take()+ .map(|start| start.elapsed().as_secs_f64());self.ai_busy = false;match result {Ok(()) => {@@ -1602,58 +1622,6 @@ impl App {let _ = tx.send(Event::ModelReady(result));});}- fn model_search_panel(&mut self, ui: &mut egui::Ui) {- if self.mode == "Names" || self.s.remote_embeddings() {- 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. Hybrid/Semantic searches may need a few seconds to load it.".into() };- ui.label(RichText::new(notice).color(crate::appearance::component_color(ui.visuals().dark_mode,false,true)));- 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;@@ -2497,7 +2465,7 @@ impl App {{self.changed();}- self.model_search_panel(ui);+if self.quick&& self.hits.is_empty()&& ctx.animate_bool_with_time(egui::Id::new("popup-expansion"), false, 0.18) <= 0.0@@ -2520,14 +2488,6 @@ impl App {.color(self.accent()),);}- ui.label(- RichText::new(if self.searching {- "Searching…".into()- } else {- format!("{} results · {:.1} ms", self.hits.len(), self.search_ms)- })- .weak(),- );let available = ui.available_size();let mut columns = preview_columns(ui,@@ -2544,239 +2504,378 @@ impl App {}{let ui = &mut columns[0];- let mut scroll = egui::ScrollArea::vertical().id_salt("results");- if self.scroll_to_selection {- let current = egui::scroll_area::State::load(ctx, ui.make_persistent_id("results"))- .map(|s| s.offset.y)- .unwrap_or(0.0);- let offset = selection_offset(- self.selected,- 62.0 + ui.spacing().item_spacing.y,- current,- available.y.max(62.0),- );- scroll = scroll.vertical_scroll_offset(offset);- self.scroll_to_selection = false;- }- let output = scroll.show_rows(ui, 62.0, self.hits.len(), |ui, range| {- for i in range {- let hit = self.hits[i].clone();- let name = Path::new(&hit.path)- .file_name()- .unwrap_or_default()- .to_string_lossy()- .into_owned();- let title = if hit.kind == "calculator" {- hit.path.clone()- } else if hit.kind == "settings" || hit.kind == "application" {- hit.text.clone()- } else {- name- };- if !["settings", "calculator", "folder"].contains(&hit.kind.as_str())- && !self.thumbs.contains_key(&hit.path)- && !self.thumb_pending.contains(&hit.path)- && !self.thumb_failed.contains(&hit.path)- {- if crate::previews::thumbnail(- hit.path.clone(),- self.s.clone(),- self.engine.tx.clone(),- )- .is_ok()+ if self.s.picture_grid && matches!(self.category.as_str(), "Images" | "Videos") {+ self.picture_grid(ui, ctx);+ } else {+ let mut scroll = egui::ScrollArea::vertical().id_salt("results");+ if self.scroll_to_selection {+ let current =+ egui::scroll_area::State::load(ctx, ui.make_persistent_id("results"))+ .map(|s| s.offset.y)+ .unwrap_or(0.0);+ let offset = selection_offset(+ self.selected,+ 62.0 + ui.spacing().item_spacing.y,+ current,+ available.y.max(62.0),+ );+ scroll = scroll.vertical_scroll_offset(offset);+ self.scroll_to_selection = false;+ }+ let output = scroll.show_rows(ui, 62.0, self.hits.len(), |ui, range| {+ for i in range {+ let hit = self.hits[i].clone();+ let name = Path::new(&hit.path)+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned();+ let title = if hit.kind == "calculator" {+ hit.path.clone()+ } else if hit.kind == "settings" || hit.kind == "application" {+ hit.text.clone()+ } else {+ name+ };+ if !["settings", "calculator", "folder"].contains(&hit.kind.as_str())+ && !self.thumbs.contains_key(&hit.path)+ && !self.thumb_pending.contains(&hit.path)+ && !self.thumb_failed.contains(&hit.path){- self.thumb_pending.insert(hit.path.clone());+ if crate::previews::thumbnail(+ hit.path.clone(),+ self.s.clone(),+ self.engine.tx.clone(),+ )+ .is_ok()+ {+ self.thumb_pending.insert(hit.path.clone());+ }}- }- let row_width = ui.available_width();- let (rect, response) =- ui.allocate_exact_size(egui::vec2(row_width, 62.0), egui::Sense::click());- let selected = self.selected == i;- let dark = crate::appearance::dark(ctx, &self.s);- let accent = self.accent();- let fill = if selected {- Color32::from_rgba_unmultiplied(- self.s.accent[0],- self.s.accent[1],- self.s.accent[2],- if dark { 65 } else { 38 },- )- } else if response.hovered() {- Color32::from_rgba_unmultiplied(- self.s.accent[0],- self.s.accent[1],- self.s.accent[2],- if dark { 38 } else { 22 },- )- } else {- Color32::TRANSPARENT- };- ui.painter().rect_filled(- rect,- 14.0,- if selected || response.hovered() {- fill- } else if dark {- Color32::from_white_alpha(8)+ let row_width = ui.available_width();+ let (rect, response) = ui+ .allocate_exact_size(egui::vec2(row_width, 62.0), egui::Sense::click());+ let selected = self.selected == i;+ let dark = crate::appearance::dark(ctx, &self.s);+ let accent = self.accent();+ let fill = if selected {+ Color32::from_rgba_unmultiplied(+ self.s.accent[0],+ self.s.accent[1],+ self.s.accent[2],+ if dark { 65 } else { 38 },+ )+ } else if response.hovered() {+ Color32::from_rgba_unmultiplied(+ self.s.accent[0],+ self.s.accent[1],+ self.s.accent[2],+ if dark { 38 } else { 22 },+ )} else {- Color32::from_white_alpha(75)- },- );- if selected {- ui.painter().rect_stroke(+ Color32::TRANSPARENT+ };+ ui.painter().rect_filled(rect,14.0,- egui::Stroke::new(1.0, accent.gamma_multiply(0.7)),- egui::StrokeKind::Inside,+ if selected || response.hovered() {+ fill+ } else if dark {+ Color32::from_white_alpha(8)+ } else {+ Color32::from_white_alpha(75)+ },);- }- let icon_rect = egui::Rect::from_min_size(- rect.min + egui::vec2(10.0, 9.0),- egui::vec2(42.0, 42.0),- );- if let Some(texture) = self.thumbs.get(&hit.path) {- ui.put(- icon_rect,- egui::Image::new(texture).fit_to_exact_size(icon_rect.size()),+ if selected {+ ui.painter().rect_stroke(+ rect,+ 14.0,+ egui::Stroke::new(1.0, accent.gamma_multiply(0.7)),+ egui::StrokeKind::Inside,+ );+ }+ let icon_rect = egui::Rect::from_min_size(+ rect.min + egui::vec2(10.0, 9.0),+ egui::vec2(42.0, 42.0),);- } else {- ui.put(- icon_rect,- crate::icons::image(- crate::icons::result(&hit.kind, &hit.path),- accent,- 28.0,- ),+ if let Some(texture) = self.thumbs.get(&hit.path) {+ ui.put(+ icon_rect,+ egui::Image::new(texture).fit_to_exact_size(icon_rect.size()),+ );+ } else {+ ui.put(+ icon_rect,+ crate::icons::image(+ crate::icons::result(&hit.kind, &hit.path),+ accent,+ 28.0,+ ),+ );+ }+ let title_rect = egui::Rect::from_min_size(+ rect.min + egui::vec2(64.0, 8.0),+ egui::vec2((row_width - 76.0).max(1.0), 23.0),);- }- let title_rect = egui::Rect::from_min_size(- rect.min + egui::vec2(64.0, 8.0),- egui::vec2((row_width - 76.0).max(1.0), 23.0),- );- let mut title_ui = ui.new_child(- egui::UiBuilder::new()- .max_rect(title_rect)- .layout(egui::Layout::left_to_right(egui::Align::Min)),- );- title_ui.add(- egui::Label::new(- RichText::new(&title)- .strong()- .size(14.0)- .color(ui.visuals().text_color()),- )- .truncate()- .selectable(false)- .sense(egui::Sense::hover()),- );- let location = if hit.kind == "application" {- "Windows application".into()- } else if hit.kind == "settings" {- hit.path.clone()- } else {- Path::new(&hit.path)- .parent()- .unwrap_or(Path::new(""))- .display()- .to_string()- };- let tag = match hit.kind.as_str() {- "application" => "App",- "settings" => "Settings",- "folder" => "Folder",- _ => hit.kind.as_str(),- };- let mut job = egui::text::LayoutJob::default();- job.append(- tag,- 0.0,- egui::TextFormat {- font_id: egui::FontId::new(12.0, egui::FontFamily::Name("bold".into())),- color: accent,- ..Default::default()- },- );- job.append(- &format!(" · {location}"),- 0.0,- egui::TextFormat {- font_id: egui::FontId::proportional(12.0),- color: ui.visuals().weak_text_color(),- ..Default::default()- },- );- let metadata_rect = egui::Rect::from_min_size(- rect.min + egui::vec2(64.0, 33.0),- egui::vec2((row_width - 76.0).max(1.0), 20.0),- );- let mut metadata_ui = ui.new_child(- egui::UiBuilder::new()- .max_rect(metadata_rect)- .layout(egui::Layout::left_to_right(egui::Align::Min)),- );- metadata_ui.add(- egui::Label::new(job)+ let mut title_ui = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(title_rect)+ .layout(egui::Layout::left_to_right(egui::Align::Min)),+ );+ title_ui.add(+ egui::Label::new(+ RichText::new(&title)+ .strong()+ .size(14.0)+ .color(ui.visuals().text_color()),+ ).truncate().selectable(false).sense(egui::Sense::hover()),- );- if response.clicked() {- ctx.memory_mut(|m| m.surrender_focus(egui::Id::new("query")));- self.selected = i;- self.texture = None;- self.preview_error = None;- self.preview_pending = None;- }- if response.double_clicked() {- self.selected = i;- self.open_selected(ctx);- }- response.context_menu(|ui| {- if ui.button("Open").clicked() {+ );+ let location = if hit.kind == "application" {+ "Windows application".into()+ } else if hit.kind == "settings" {+ hit.path.clone()+ } else {+ Path::new(&hit.path)+ .parent()+ .unwrap_or(Path::new(""))+ .display()+ .to_string()+ };+ let tag = match hit.kind.as_str() {+ "application" => "App",+ "settings" => "Settings",+ "folder" => "Folder",+ _ => hit.kind.as_str(),+ };+ let mut job = egui::text::LayoutJob::default();+ job.append(+ tag,+ 0.0,+ egui::TextFormat {+ font_id: egui::FontId::new(+ 12.0,+ egui::FontFamily::Name("bold".into()),+ ),+ color: accent,+ ..Default::default()+ },+ );+ job.append(+ &format!(" · {location}"),+ 0.0,+ egui::TextFormat {+ font_id: egui::FontId::proportional(12.0),+ color: ui.visuals().weak_text_color(),+ ..Default::default()+ },+ );+ let metadata_rect = egui::Rect::from_min_size(+ rect.min + egui::vec2(64.0, 33.0),+ egui::vec2((row_width - 76.0).max(1.0), 20.0),+ );+ let mut metadata_ui = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(metadata_rect)+ .layout(egui::Layout::left_to_right(egui::Align::Min)),+ );+ metadata_ui.add(+ egui::Label::new(job)+ .truncate()+ .selectable(false)+ .sense(egui::Sense::hover()),+ );+ if response.clicked() {+ ctx.memory_mut(|m| m.surrender_focus(egui::Id::new("query")));self.selected = i;- self.open_selected(ctx);- ui.close();- }- if ui.button("Open file location").clicked() {- self.run(crate::platform::reveal(&hit.path));- ui.close();- }- if ui- .add_enabled(- !["calculator", "settings"].contains(&hit.kind.as_str()),- egui::Button::new("Copy file"),- )- .clicked()- {- self.run(crate::platform::copy_file(&hit.path));- ui.close();- }- if ui.button("Copy path").clicked() {- ctx.copy_text(hit.path.clone());- ui.close();- }- if ui.button("Exclude from future searches").clicked() {- self.s.exclusions.push(hit.path.clone());- self.save();- self.changed();- ui.close();+ self.texture = None;+ self.preview_error = None;+ self.preview_pending = None;}- if ui.button("Properties").clicked() {- self.run(crate::platform::properties(&hit.path));- ui.close();- }- if ui.button("Delete…").clicked() {- self.delete_confirm = Some(hit.clone());- ui.close();+ if response.double_clicked() {+ self.selected = i;+ self.open_selected(ctx);}- });- }- });- self.result_scroll_offset = output.state.offset.y;+ response.context_menu(|ui| {+ if ui.button("Open").clicked() {+ self.selected = i;+ self.open_selected(ctx);+ ui.close();+ }+ if ui.button("Open file location").clicked() {+ self.run(crate::platform::reveal(&hit.path));+ ui.close();+ }+ if ui+ .add_enabled(+ !["calculator", "settings"].contains(&hit.kind.as_str()),+ egui::Button::new("Copy file"),+ )+ .clicked()+ {+ self.run(crate::platform::copy_file(&hit.path));+ ui.close();+ }+ if ui.button("Copy path").clicked() {+ ctx.copy_text(hit.path.clone());+ ui.close();+ }+ if ui.button("Exclude from future searches").clicked() {+ self.s.exclusions.push(hit.path.clone());+ self.save();+ self.changed();+ ui.close();+ }+ if ui.button("Properties").clicked() {+ self.run(crate::platform::properties(&hit.path));+ ui.close();+ }+ if ui.button("Delete…").clicked() {+ self.delete_confirm = Some(hit.clone());+ ui.close();+ }+ });+ }+ });+ self.result_scroll_offset = output.state.offset.y;+ }}self.preview(&mut columns[1], ctx);}+ fn picture_grid(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {+ let columns = (ui.available_width() / 150.0).floor().max(1.0) as usize;+ if self.grid_columns != columns {+ self.scroll_to_selection = true;+ }+ self.grid_columns = columns;+ let row_height = 150.0;+ let width = (ui.available_width() - ui.spacing().item_spacing.x * (columns - 1) as f32)+ / columns as f32;+ let mut scroll = egui::ScrollArea::vertical().id_salt("picture-grid");+ if self.scroll_to_selection {+ let current =+ egui::scroll_area::State::load(ctx, ui.make_persistent_id("picture-grid"))+ .map(|s| s.offset.y)+ .unwrap_or(0.0);+ scroll = scroll.vertical_scroll_offset(selection_offset(+ self.selected / columns,+ row_height + ui.spacing().item_spacing.y,+ current,+ ui.available_height(),+ ));+ self.scroll_to_selection = false;+ }+ let output = scroll.show_rows(+ ui,+ row_height,+ self.hits.len().div_ceil(columns),+ |ui, rows| {+ for row in rows {+ ui.horizontal(|ui| {+ for index in row * columns..((row + 1) * columns).min(self.hits.len()) {+ let hit = self.hits[index].clone();+ if !self.thumbs.contains_key(&hit.path)+ && !self.thumb_pending.contains(&hit.path)+ && !self.thumb_failed.contains(&hit.path)+ {+ if crate::previews::thumbnail(+ hit.path.clone(),+ self.s.clone(),+ self.engine.tx.clone(),+ )+ .is_ok()+ {+ self.thumb_pending.insert(hit.path.clone());+ }+ }+ let (rect, response) = ui.allocate_exact_size(+ egui::vec2(width, row_height),+ egui::Sense::click(),+ );+ let fill = if self.selected == index {+ ui.visuals().selection.bg_fill+ } else if response.hovered() {+ ui.visuals().widgets.hovered.bg_fill+ } else {+ Color32::TRANSPARENT+ };+ ui.painter().rect(+ rect,+ 10.0,+ fill,+ ui.visuals().widgets.inactive.bg_stroke,+ egui::StrokeKind::Inside,+ );+ let photo = egui::Rect::from_min_size(+ rect.min + egui::vec2(6.0, 6.0),+ egui::vec2(width - 12.0, 108.0),+ );+ if let Some(texture) = self.thumbs.get(&hit.path) {+ let size = preview_image_size(texture.size_vec2(), photo.size());+ egui::Image::new(texture).corner_radius(8).paint_at(+ ui,+ egui::Rect::from_center_size(photo.center(), size),+ );+ } else {+ crate::icons::image(crate::icons::Icon::Image, self.accent(), 28.0)+ .paint_at(+ ui,+ egui::Rect::from_center_size(+ photo.center(),+ egui::vec2(28.0, 28.0),+ ),+ );+ }+ let title = Path::new(&hit.path)+ .file_name()+ .unwrap_or_default()+ .to_string_lossy();+ let label = egui::Rect::from_min_max(+ egui::pos2(rect.left() + 6.0, rect.top() + 119.0),+ rect.max - egui::vec2(6.0, 4.0),+ );+ let mut text = ui.new_child(egui::UiBuilder::new().max_rect(label));+ text.add(+ egui::Label::new(title.as_ref())+ .truncate()+ .selectable(false),+ );+ if response.clicked() {+ self.selected = index;+ self.texture = None;+ self.preview_pending = None;+ self.preview_error = None;+ }+ if response.double_clicked() {+ self.selected = index;+ self.open_selected(ctx);+ }+ response.context_menu(|ui| {+ if ui.button("Open").clicked() {+ self.selected = index;+ self.open_selected(ctx);+ ui.close();+ }+ if ui.button("Open file location").clicked() {+ self.run(crate::platform::reveal(&hit.path));+ ui.close();+ }+ if ui.button("Copy file").clicked() {+ self.run(crate::platform::copy_file(&hit.path));+ ui.close();+ }+ });+ response.on_hover_text(&hit.path);+ }+ });+ }+ },+ );+ self.result_scroll_offset = output.state.offset.y;+ }fn preview(&mut self, ui: &mut egui::Ui, _ctx: &egui::Context) {let Some(hit) = self.hits.get(self.selected).cloned() else {ui.allocate_ui_with_layout(@@ -3014,6 +3113,8 @@ impl App {if self.progress.session_completed+self.progress.session_pending>0 {ui.weak(format!("Session: {} content files complete · {} pending (checkpoints saved)",self.progress.session_completed,self.progress.session_pending));}+ if let Some(seconds)=self.progress.estimated_seconds {ui.weak(format!("Known queued work: about {}m {}s (learned from completed files)",seconds as u64/60,seconds as u64%60));}+ else {ui.weak("Learning indexing times; estimates appear after enough similar files complete.");}ui.label(&self.progress.current);}ui.horizontal(|ui| {@@ -3077,6 +3178,17 @@ impl App {&mut self.s.retry_failed,"Retry previously skipped files on the next update",);+ ui.horizontal(|ui| {+ ui.label("Indexing order");+ combo(+ ui,+ "index-order",+ &mut self.s.index_order,+ &["Quick first", "Full first"],+ );+ });+ ui.checkbox(&mut self.s.rank_calibration, "Rank Calibration");+ ui.weak("Adjusts semantic ranking across text, pictures and audio. Applies at search time to existing Full-indexed items; no index update is required. Does not change model embeddings.");ui.checkbox(&mut self.s.count_files,"Count files before indexing (off starts processing immediately)",@@ -3336,6 +3448,8 @@ impl App {ui.add_space(8.0);ui.group(|ui| {ui.strong("Video");+ ui.checkbox(&mut self.s.skip_similar_frames,"Skip near-identical video frames");+ ui.weak("Reduces repeated scene embeddings. Update the index to apply this to existing videos; disable for frame-by-frame recall.");ui.checkbox(&mut self.s.index_video, "Index video frames");if self.s.index_video {ui.label("Video decoder");@@ -3508,32 +3622,237 @@ impl App {);}}+ fn embedding_activity(&self) -> bool {+ self.page == 0+ && self.tool == "Search"+ && self.mode != "Names"+ && (self.searching || self.engine.models.loading.load(Ordering::Acquire))+ }fn footer_text(&self) -> String {- if self.quick {- if self.ai_busy {- "AI request in progress…".into()- } else if let Some(error) = &self.search_error {- error.clone()- } else if self.status == "Copied"- || self.status.starts_with("Playing from")- || self.status.starts_with("Playback")- {- self.status.clone()- } else if self.searching {- "Searching…".into()- } else if self.tool == "Search" && !self.query.trim().is_empty() {- format!("{} results · {:.1} ms", self.hits.len(), self.search_ms)- } else if self.tool == "Clipboard" {- format!("{} items", self.tool_items.len())- } else if self.tool == "Emoji" {- format!("{} emoji", self.tool_items.len())+ if self.page != 0 {+ return self.status.clone();+ }+ if self.dictation_busy {+ return "Transcribing…".into();+ }+ if crate::dictation::recording() {+ return "Listening…".into();+ }+ if self.ai_busy {+ return format!(+ "AI responding · {:.1} s",+ self.ai_started.map_or(0.0, |t| t.elapsed().as_secs_f64())+ );+ }+ if self.tts_busy {+ let state = if self.tts_paused.load(Ordering::Acquire) {+ "Read aloud paused"} else {- String::new()+ "Reading aloud"+ };+ return self+ .ai_elapsed+ .map(|s| format!("{state} · AI {s:.1} s"))+ .unwrap_or_else(|| state.into());+ }+ if self.tool == "Search" && self.mode != "Names" && !self.s.remote_embeddings() {+ if let Some(reason) = self.engine.models.search_hold(&self.s) {+ return format!("EmbeddingGemma 2 paused: {reason}");+ }+ if let Some(error) = &self.model_warm_error {+ return error.clone();}- } else if self.ai_busy {- "AI request in progress…".into()+ }+ if self.embedding_activity() {+ return if self.engine.models.loading.load(Ordering::Acquire) {+ format!(+ "Loading EmbeddingGemma 2 · {}",+ self.engine.models.loading_phase()+ )+ } else {+ "Waiting for EmbeddingGemma 2…".into()+ };+ }+ if self.searching {+ return "Searching…".into();+ }+ if let Some(error) = self.search_error.as_ref().filter(|_| self.tool != "AI") {+ return error.clone();+ }+ if self.tool == "AI" {+ if let Some(error) = &self.ai_error {+ return error.clone();+ }+ }+ for notice in [&self.dictation_status, &self.tts_status] {+ if !notice.is_empty() && !notice.starts_with("Recording") {+ return notice.clone();+ }+ }+ if !self.status.is_empty()+ && !self.status.contains(" results · ")+ && !self.status.starts_with("Targeted changes")+ && !self.status.starts_with("Recovery/")+ {+ return self.status.clone();+ }+ match self.tool.as_str() {+ "Search" => format!("{} results · {:.1} ms", self.hits.len(), self.search_ms),+ "AI" => self+ .ai_elapsed+ .map(|s| format!("AI response · {s:.1} s"))+ .unwrap_or_default(),+ "Clipboard" => format!("{} items", self.tool_items.len()),+ "Emoji" => format!("{} emoji", self.tool_items.len()),+ _ => String::new(),+ }+ }+ fn draw_footer(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {+ let (row, _) = ui.allocate_exact_size(+ egui::vec2(ui.available_width(), ui.spacing().interact_size.y.max(40.0)),+ egui::Sense::hover(),+ );+ if self.smoke.is_some() {+ ctx.data_mut(|d| {+ d.insert_temp(egui::Id::new("qa-footer-row"), row);+ });+ }+ let mut left = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(row)+ .layout(egui::Layout::left_to_right(egui::Align::Center)),+ );+ let start = if self.quick {+ let button = left.button("Open full app");+ if self.smoke.is_some() {+ ctx.data_mut(|d| {+ d.insert_temp(egui::Id::new("qa-open-full"), button.rect);+ });+ }+ if button.clicked() {+ let _ = self.engine.tx.send(Event::Full);+ }+ left.min_rect().right() + 8.0+ } else {+ row.left()+ };+ let mut right = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(row)+ .layout(egui::Layout::right_to_left(egui::Align::Center)),+ );+ right.spacing_mut().item_spacing.x = 5.0;+ for (key, action) in [+ ("Esc", if self.ai_busy { "stop" } else { "dismiss" }),+ (+ if self.saved_settings.search_tools().len() > 1 {+ "Tab"+ } else {+ ""+ },+ "cycle tools",+ ),+ ("Ctrl+C", "copy"),+ (if self.tool == "Search" { "Space" } else { "" }, "preview"),+ (+ "Enter",+ if self.tool == "AI" {+ "send"+ } else if self.tool == "Search" {+ "open"+ } else {+ "copy"+ },+ ),+ ("↑ ↓", if self.tool == "AI" { "page" } else { "select" }),+ ] {+ if key.is_empty() {+ continue;+ }+ right.label(RichText::new(action).size(11.0));+ right.label(RichText::new(key).size(11.0).strong().color(self.accent()));+ }+ let end = (right.min_rect().left() - 8.0).max(start);+ let center =+ egui::Rect::from_min_max(egui::pos2(start, row.top()), egui::pos2(end, row.bottom()));+ let footer = self.footer_text();+ let mut middle = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(center)+ .layout(egui::Layout::left_to_right(egui::Align::Center)),+ );+ let playback = self.page == 0 && self.tts_busy;+ let load_override = self.page == 0+ && self.tool == "Search"+ && self.mode != "Names"+ && !self.s.remote_embeddings()+ && (self.engine.models.search_hold(&self.s).is_some()+ || self.model_warm_error.is_some());+ let controls_width = if playback {+ 105.0+ } else if load_override {+ 95.0} else {- self.status.clone()+ 0.0+ };+ let text = footer.clone();+ let text_width = middle+ .painter()+ .layout_no_wrap(+ text.clone(),+ egui::FontId::proportional(12.0),+ middle.visuals().text_color(),+ )+ .size()+ .x+ .min((center.width() - controls_width).max(0.0));+ let needed = text_width + controls_width;+ let offset = (row.center().x - center.left() - needed / 2.0)+ .clamp(0.0, (center.width() - needed).max(0.0));+ middle.add_space(offset);+ let response = middle.add_sized(+ [text_width, 22.0],+ egui::Label::new(RichText::new(text).size(12.0)).truncate(),+ );+ if self.smoke.is_some() {+ ctx.data_mut(|d| d.insert_temp(egui::Id::new("qa-footer-text"), response.rect));+ }+ response.on_hover_text(&footer);+ if playback {+ let paused = self.tts_paused.load(Ordering::Acquire);+ if middle+ .small_button(if paused { "Play" } else { "Pause" })+ .clicked()+ {+ self.tts_paused.store(!paused, Ordering::Release);+ }+ if middle+ .small_button("Stop")+ .on_hover_text("Stop playback")+ .clicked()+ {+ self.stop_read_aloud();+ }+ }+ if load_override && middle.small_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 self.smoke.is_some() {+ ctx.data_mut(|d| {+ d.insert_temp(+ egui::Id::new("qa-footer-status"),+ egui::Rect::from_min_size(+ egui::pos2(center.left() + offset, center.top()),+ egui::vec2(needed, center.height()),+ ),+ );+ });}}fn refresh_microphones(&mut self) {@@ -4303,6 +4622,20 @@ impl App {&mut self.s.performance,&["Low memory", "Balanced", "Fast search"],);+ ui.horizontal(|ui| {+ ui.label("Semantic cache precision");+ combo(+ ui,+ "cache-precision",+ &mut self.s.cache_precision,+ &["FP32", "FP16"],+ );+ });+ ui.weak("FP16 halves vector-cache storage; calculations stay FP32. Very close results may swap places. No re-indexing is needed; Low memory still streams FP32 from disk.");+ ui.checkbox(+ &mut self.s.picture_grid,+ "Picture grid for Images and Videos searches",+ );ui.label("Database and filename catalog remain on disk. Low memory: 8 MiB pages and streamed vectors. Balanced: 32 MiB pages and up to 128 MiB compact vectors. Fast search: 64 MiB pages and up to 512 MiB vectors. These are caps, not reserved memory; models/workers use additional RAM.");ui.separator();ui.heading("Clipboard history");@@ -4406,6 +4739,7 @@ impl App {self.ai_messages.pop();}self.ai_busy = false;+ self.ai_started = None;self.ai_job += 1;}fn ask_ai(&mut self) {@@ -4415,6 +4749,7 @@ impl App {self.ai_error = None;self.ai_answer.clear();self.ai_metrics = crate::ai::Metrics::default();+ self.ai_elapsed = None;self.ai_follow_bottom = true;self.stop_read_aloud();self.markdown = egui_commonmark::CommonMarkCache::default();@@ -4432,6 +4767,9 @@ impl App {self.ai_images.clear();self.ai_attachment = None;self.ai_context_trimmed = messages.len() < self.ai_messages.len() + 1;+ if self.ai_context_trimmed {+ self.status = "Older turns removed to fit Max context.".into();+ }self.ai_messages = messages;}Err(error) => {@@ -4443,6 +4781,8 @@ impl App {let id = self.ai_job;self.ai_cancel = Arc::new(AtomicBool::new(false));self.ai_busy = true;+ self.ai_started = Some(Instant::now());+ self.ai_elapsed = None;let cancel = self.ai_cancel.clone();let s = selected_settings;let messages = self.ai_messages.clone();@@ -4518,6 +4858,7 @@ impl App {self.ai_error = None;self.ai_context_trimmed = false;self.ai_metrics = crate::ai::Metrics::default();+ self.ai_elapsed = None;self.markdown = egui_commonmark::CommonMarkCache::default();}fn resume_read_aloud(&mut self) {@@ -4771,10 +5112,6 @@ impl App {return;}if self.tool == "Clipboard" {- ui.weak(format!(- "{} items · Enter / Ctrl+C to copy",- self.tool_items.len()- ));if !self.saved_settings.clipboard_enabled {ui.weak("Capture is off · enable it in Settings");}@@ -5255,7 +5592,7 @@ impl App {fn about(&mut self, ui: &mut egui::Ui) {ui.heading("About VectorDash");ui.label(format!(- "Version {} · Native Rust · Windows 11 x64",+ "Version {} · Native Rust · Windows 10 (beta) / 11 x64",env!("CARGO_PKG_VERSION")));ui.label("Local universal file search and launcher, powered by EmbeddingGemma 2.");@@ -5929,6 +6266,24 @@ impl eframe::App for App {ctx.request_repaint_after(delay);}}+ for (index, notice) in [+ (3, &mut self.search_error),+ (4, &mut self.ai_error),+ (5, &mut self.model_warm_error),+ ] {+ if let Some(value) = notice.as_mut() {+ if let Some(delay) =+ expire_notice(value, &mut self.status_clocks[index], false, now)+ {+ ctx.request_repaint_after(delay);+ }+ if value.is_empty() {+ *notice = None;+ }+ } else {+ self.status_clocks[index] = None;+ }+ }if !self.saved_settings.tool_available(&self.tool) {if self.tool == "AI" {self.stop_ai();@@ -6104,86 +6459,7 @@ impl eframe::App for App {d.insert_temp(egui::Id::new("qa-footer-top"), ui.max_rect().top() - 9.0)});}- if self.page == 0 {- if !self.tts_status.is_empty() {- ui.label(&self.tts_status);- }- if self.tts_busy {- ui.horizontal(|ui| {- ui.label(if self.tts_paused.load(Ordering::Acquire) {- "Read aloud paused for dictation"- } else {- "Reading aloud…"- });- if ui.button("Stop playback").clicked() {- self.stop_read_aloud();- }- });- }- if !self.dictation_status.is_empty()- && !self.dictation_status.starts_with("Recording")- {- ui.label(&self.dictation_status);- }- if self.tool == "AI" {- if let Some(error) = &self.ai_error {- ui.colored_label(Color32::LIGHT_RED, error);- }- if self.ai_context_trimmed {- ui.weak("Older turns removed to fit Max context.");- }- }- }- let footer = self.footer_text();- ui.horizontal_wrapped(|ui| {- if self.quick && ui.button("Open full app").clicked() {- let _ = self.engine.tx.send(Event::Full);- }- ui.add_sized(- [(ui.available_width() - 550.0).max(120.0), 22.0],- egui::Label::new(&footer).truncate(),- )- .on_hover_text(&footer);- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- for (key, action) in [- ("Esc", if self.ai_busy { "stop" } else { "dismiss" }),- (- if self.saved_settings.search_tools().len() > 1 {- "Tab"- } else {- ""- },- "cycle tools",- ),- ("Ctrl+C", "copy"),- (if self.tool == "Search" { "Space" } else { "" }, "preview"),- (- "Enter",- if self.tool == "AI" {- "send"- } else if self.tool == "Search" {- "open"- } else {- "copy"- },- ),- ("↑ ↓", if self.tool == "AI" { "page" } else { "select" }),- ] {- if key.is_empty() {- continue;- }- ui.label(action);- ui.label(- RichText::new(key)- .font(egui::FontId::new(- 12.0,- egui::FontFamily::Name("bold".into()),- ))- .color(self.accent()),- );- }- });- });+ self.draw_footer(ui, ctx);});if !self.quick {egui::SidePanel::left("navigation")@@ -6281,6 +6557,7 @@ impl eframe::App for App {self.popup_had_focus = false;}if (self.popup_had_focus && !focused || outside_click)+ && !(self.smoke.is_some() && std::env::args().any(|a| a == "--smoke-keep-open"))&& !self.large_preview&& !self.ai_busy&& !self.tts_busy@@ -6309,14 +6586,7 @@ impl eframe::App for App {};let expansion =ctx.animate_bool_with_time(egui::Id::new("popup-expansion"), !empty, 0.18);- let panel = self.tool == "Search"- && self.mode != "Names"- && !self.s.remote_embeddings()- && (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)));+ let panel = false;if self.popup_size_state != Some(empty)|| self.popup_model_panel != panel|| (expansion > 0.0 && expansion < 1.0)@@ -6324,14 +6594,15 @@ impl eframe::App for App {self.popup_model_panel = panel;self.popup_size_state = Some(empty);ctx.send_viewport_cmd(egui::ViewportCommand::MinInnerSize(egui::vec2(- 780.0, 160.0,+ 780.0,+ if self.tool == "AI" { 254.0 } else { 194.0 },)));ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(940.0,if self.tool == "AI" {- 240.0 + 400.0 * expansion+ 254.0 + 386.0 * expansion} else {- 180.0 + 460.0 * expansion+ 194.0 + 446.0 * expansion} + if panel { 75.0 } else { 0.0 },)));}@@ -6395,6 +6666,32 @@ impl eframe::App for App {});}});+ if self.page == 0+ && self.tool == "Search"+ && self.s.picture_grid+ && matches!(self.category.as_str(), "Images" | "Videos")+ && !ctx.memory(|m| m.has_focus(egui::Id::new("query")))+ {+ let delta = ctx.input(|i| {+ if i.key_pressed(egui::Key::ArrowRight) {+ 1+ } else if i.key_pressed(egui::Key::ArrowLeft) {+ -1+ } else {+ 0+ }+ });+ if delta != 0 {+ self.selected = self+ .selected+ .saturating_add_signed(delta)+ .min(self.hits.len().saturating_sub(1));+ self.texture = None;+ self.preview_pending = None;+ self.preview_error = None;+ self.scroll_to_selection = true;+ }+ }if self.page == 0 && self.tool != "AI" && ctx.input(|i| i.key_pressed(egui::Key::ArrowDown)){ctx.memory_mut(|m| m.surrender_focus(egui::Id::new("query")));@@ -6411,6 +6708,11 @@ impl eframe::App for App {/ 62.0).floor().max(1.0) as usize+ } else if self.tool == "Search"+ && self.s.picture_grid+ && matches!(self.category.as_str(), "Images" | "Videos")+ {+ self.grid_columns.max(1)} else {1};@@ -6440,6 +6742,11 @@ impl eframe::App for App {/ 62.0).floor().max(1.0) as usize+ } else if self.tool == "Search"+ && self.s.picture_grid+ && matches!(self.category.as_str(), "Images" | "Videos")+ {+ self.grid_columns.max(1)} else {1};@@ -6509,6 +6816,12 @@ impl eframe::App for App {&& self.search_visible{paint_ai_outline(ctx);+ } else if (self.embedding_activity()+ || self.smoke.is_some()+ && std::env::args().any(|a| a == "--smoke-embedding-processing"))+ && self.search_visible+ {+ paint_activity_outline(ctx, ActivityTrail::Embedding);}self.capture_ui(ctx);if let Some(image) = self.ai_image_view.clone() {@@ -6800,7 +7113,7 @@ impl eframe::App for App {if self.startup.elapsed() > Duration::from_secs(self.smoke_seconds)&& (self.qa_screenshot.is_none() || self.qa_captured){- let mut data = serde_json::json!({"ok":true,"native_rust":true,"tool":self.tool,"tools":self.saved_settings.search_tools(),"footer":self.footer_text(),"dictation_status":self.dictation_status,"query":self.query,"ai_busy":self.ai_busy,"ai_answer":self.ai_answer,"model_loaded":self.engine.models.loaded.load(Ordering::Relaxed),"frames":self.frames,"max_frame_interval_ms":self.max_frame_ms,"dark_mode":ctx.style().visuals.dark_mode,"hidden_reopened":self.qa_hidden_reopened,"ocr_enabled":self.s.ocr_enabled,"ocr_setup_selected":self.ocr_setup,"results":self.hits.len(),"selected":self.selected,"result_scroll_offset":self.result_scroll_offset,"scope":self.scope,"quick_look":self.large_preview,"quick_look_size":self.qa_child_size,"cpu":crate::scheduling::metrics().cpu,"gpu":crate::scheduling::metrics().gpu,"query_focus":ctx.memory(|m|m.has_focus(egui::Id::new("query"))),"ai_metrics":self.ai_metrics.label(),"tts_busy":self.tts_busy,"tts_paused":self.tts_paused.load(Ordering::Acquire),"connection_results":self.connections.iter().map(|s|s.result.as_ref().map(|r|r.is_ok())).collect::<Vec<_>>(),"ai_scroll_offset":self.ai_scroll_offset,"qa_ai_scroll_before":self.qa_ai_scroll_before,"qa_ai_followup_sent":self.qa_ai_followup_sent,"tts_status":self.tts_status,"tts_notice":self.tts_notice,"tts_voices":self.tts_voices,"response_length":self.response_length,"toolbar_top":self.qa_toolbar_top,"filters_top":self.qa_filter_top,"query_selected":egui::text_edit::TextEditState::load(ctx,egui::Id::new("query")).and_then(|s|s.cursor.char_range()).map(|r|r.as_sorted_char_range().len()).unwrap_or(0)});+ let mut data = serde_json::json!({"ok":true,"native_rust":true,"tool":self.tool,"tools":self.saved_settings.search_tools(),"footer":self.footer_text(),"embedding_activity":self.embedding_activity(),"ai_elapsed":self.ai_elapsed,"dictation_status":self.dictation_status,"query":self.query,"ai_busy":self.ai_busy,"ai_answer":self.ai_answer,"model_loaded":self.engine.models.loaded.load(Ordering::Relaxed),"frames":self.frames,"max_frame_interval_ms":self.max_frame_ms,"dark_mode":ctx.style().visuals.dark_mode,"hidden_reopened":self.qa_hidden_reopened,"ocr_enabled":self.s.ocr_enabled,"ocr_setup_selected":self.ocr_setup,"results":self.hits.len(),"selected":self.selected,"result_scroll_offset":self.result_scroll_offset,"scope":self.scope,"quick_look":self.large_preview,"quick_look_size":self.qa_child_size,"cpu":crate::scheduling::metrics().cpu,"gpu":crate::scheduling::metrics().gpu,"query_focus":ctx.memory(|m|m.has_focus(egui::Id::new("query"))),"ai_metrics":self.ai_metrics.label(),"tts_busy":self.tts_busy,"tts_paused":self.tts_paused.load(Ordering::Acquire),"connection_results":self.connections.iter().map(|s|s.result.as_ref().map(|r|r.is_ok())).collect::<Vec<_>>(),"ai_scroll_offset":self.ai_scroll_offset,"qa_ai_scroll_before":self.qa_ai_scroll_before,"qa_ai_followup_sent":self.qa_ai_followup_sent,"tts_status":self.tts_status,"tts_notice":self.tts_notice,"tts_voices":self.tts_voices,"response_length":self.response_length,"toolbar_top":self.qa_toolbar_top,"filters_top":self.qa_filter_top,"query_selected":egui::text_edit::TextEditState::load(ctx,egui::Id::new("query")).and_then(|s|s.cursor.char_range()).map(|r|r.as_sorted_char_range().len()).unwrap_or(0)});data["source_list"] = serde_json::json!(ctx.data(|d| d.get_temp::<[f32; 2]>(egui::Id::new("qa-inclusion"))));@@ -6812,6 +7125,10 @@ impl eframe::App for App {);for (key, id) in [("preview_pane", "qa-preview-pane"),+ ("footer_status", "qa-footer-status"),+ ("footer_row", "qa-footer-row"),+ ("open_full_button", "qa-open-full"),+ ("footer_text_rect", "qa-footer-text"),("preview_image", "qa-preview-image"),("search_body", "qa-search-body"),] {@@ -7035,6 +7352,7 @@ const ACTIVITY_TRAIL_LENGTH: f32 = 0.34 * 1.5;enum ActivityTrail {Microphone,Ai,+ Embedding,}fn trail_style(kind: ActivityTrail, behind: f32) -> Option<(Color32, f32)> {if !(0.0..ACTIVITY_TRAIL_LENGTH).contains(&behind) {@@ -7048,6 +7366,7 @@ fn trail_style(kind: ActivityTrail, behind: f32) -> Option<(Color32, f32)> {((position - 0.5) * 2.0).clamp(0.0, 1.0),),ActivityTrail::Ai => ([155.0, 85.0, 255.0], [55.0, 135.0, 255.0], position),+ ActivityTrail::Embedding => ([55.0, 145.0, 255.0], [45.0, 210.0, 255.0], position),};let color = Color32::from_rgb((head[0] + (tail[0] - head[0]) * mix) as u8,@@ -7136,7 +7455,11 @@ mod activity_trail_tests {#[test]fn both_trails_have_the_same_fifty_percent_longer_span_and_distinct_gradients() {assert!((ACTIVITY_TRAIL_LENGTH / 0.34 - 1.5).abs() < 0.0001);- for kind in [ActivityTrail::Microphone, ActivityTrail::Ai] {+ for kind in [+ ActivityTrail::Microphone,+ ActivityTrail::Ai,+ ActivityTrail::Embedding,+ ] {assert!(trail_style(kind, 0.50).is_some());assert!(trail_style(kind, 0.52).is_none());assert!(trail_style(kind, 0.0).unwrap().1 > trail_style(kind, 0.4).unwrap().1);diff --git a/native/src/backdrop.rs b/native/src/backdrop.rsindex 4637c31..baf2e24 100644--- a/native/src/backdrop.rs+++ b/native/src/backdrop.rs@@ -243,6 +243,17 @@ mod windows_impl {}}pub fn sync(hwnd: isize, radius: f32) -> bool {+ // Enabling a host backdrop on a Win32 window requires the Windows 11 DWM+ // attribute. Keep the rounded, tinted UI on Windows 10 rather than creating+ // a black or rectangular host surface through unsupported attributes.+ if crate::platform::windows_build() < 22000 {+ return false;+ }+ if crate::platform::development_overrides()+ && std::env::var_os("VECTORDASH_TEST_NO_GLASS").is_some()+ {+ return false;+ }if FAILED.with(Cell::get) {return false;}diff --git a/native/src/config.rs b/native/src/config.rsindex b8cb08a..0486614 100644--- a/native/src/config.rs+++ b/native/src/config.rs@@ -27,6 +27,13 @@ pub struct Settings {pub exclusions: Vec<String>,pub excluded_types: String,pub count_files: bool,+ pub cache_precision: String,+ pub rank_calibration: bool,+ pub index_order: String,+ #[serde(skip)]+ pub(crate) index_phase: String,+ pub skip_similar_frames: bool,+ pub picture_grid: bool,pub watch_changes: bool,pub ntfs_journal: bool,pub saved_searches: Vec<SavedSearch>,@@ -166,6 +173,12 @@ impl Default for Settings {exclusions: vec![],excluded_types: String::new(),count_files: false,+ cache_precision: "FP32".into(),+ rank_calibration: false,+ index_order: "Quick first".into(),+ index_phase: String::new(),+ skip_similar_frames: true,+ picture_grid: true,watch_changes: false,ntfs_journal: false,saved_searches: vec![],diff --git a/native/src/content.rs b/native/src/content.rsindex cb974d0..4295914 100644--- a/native/src/content.rs+++ b/native/src/content.rs@@ -305,7 +305,7 @@ pub fn extract(}if ext == "pdf" {let mut records = vec![];- stream_pdf(path, s, checkpoint, &mut |record| {+ stream_pdf(path, 0, s, checkpoint, &mut |record| {anyhow::ensure!(records.len() < 2000,"PDF collection exceeds limit; use streaming extraction"@@ -494,6 +494,7 @@ pub struct PreviewRequest {}fn stream_pdf(path: &Path,+ start_page: u32,s: &Settings,checkpoint: &dyn Fn() -> Result<()>,emit: &mut dyn FnMut(Segment) -> Result<()>,@@ -503,8 +504,9 @@ fn stream_pdf("File exceeds configured parsing size limit");let mut emitted = 0usize;- let result = crate::pdf::visit(+ let result = crate::pdf::visit_from(path,+ start_page,s.pdf_visuals,s.ocr_enabled && !s.ocr.is_empty(),checkpoint,@@ -558,7 +560,7 @@ fn stream_pdf(doc.get_pages().len() <= 10000,"PDF page count exceeds limit");- for page in doc.get_pages().keys() {+ for page in doc.get_pages().keys().filter(|p| **p >= start_page) {checkpoint()?;for (text, line) in chunks(&doc.extract_text(&[*page])?, 1800) {emit(Segment::text("pdf", text, *page, line))?;@@ -574,10 +576,19 @@ pub fn stream(s: &Settings,checkpoint: &dyn Fn() -> Result<()>,emit: &mut dyn FnMut(Segment) -> Result<()>,+) -> Result<()> {+ stream_from(path, 0, s, checkpoint, emit)+}+pub fn stream_from(+ path: &Path,+ start_page: u32,+ s: &Settings,+ checkpoint: &dyn Fn() -> Result<()>,+ emit: &mut dyn FnMut(Segment) -> Result<()>,) -> Result<()> {let ext = extension(path);if ext == "pdf" {- return stream_pdf(path, s, checkpoint, emit);+ return stream_pdf(path, start_page, s, checkpoint, emit);}if !is_audio(&ext) && !is_video(&ext) {let records = extract(path, s, checkpoint)?;@@ -592,6 +603,7 @@ pub fn stream(return Ok(());}use std::process::Stdio;+ let mut dedupe = FrameDedupe::default();let mut native_frames = false;let mut native_audio = None;if is_video(&ext) && s.index_video && s.video_decoder != "FFmpeg" {@@ -609,6 +621,9 @@ pub fn stream(let Some((seconds, media)) = reader.frame(seconds, checkpoint)? else {break;};+ if s.skip_similar_frames && !dedupe.keep(&media)? {+ continue;+ }emit(Segment {kind: "video".into(),text: String::new(),@@ -678,16 +693,20 @@ pub fn stream(while let Some(end) = pending.windows(2).position(|b| b == [0xff, 0xd9]) {let rest = pending.split_off(end + 2);let media = std::mem::replace(&mut pending, rest);+ let seconds = frame as f32 * s.video_interval.clamp(1.0, 60.0);+ frame += 1;+ anyhow::ensure!(frame <= 100000, "Video sampling limit reached");+ if s.skip_similar_frames && !dedupe.keep(&media)? {+ continue;+ }emit(Segment {kind: "video".into(),text: String::new(),page: 0,- seconds: frame as f32 * s.video_interval.clamp(1.0, 60.0),+ seconds,line: 0,media,})?;- frame += 1;- anyhow::ensure!(frame <= 100000, "Video sampling limit reached");}}let status = child.wait()?;@@ -815,3 +834,54 @@ mod html_tests {assert_eq!(super::chunks(&text, 1800).len(), 1);}}++/// Compare luminance AND color/contrast so flat slides of different colors are not collapsed.+#[derive(Default)]+struct FrameDedupe {+ last: Option<[u8; 192]>,+}+impl FrameDedupe {+ fn keep(&mut self, jpeg: &[u8]) -> Result<bool> {+ let small = image::load_from_memory(jpeg)?+ .resize_exact(8, 8, image::imageops::FilterType::Triangle)+ .to_rgb8();+ let mut signature = [0u8; 192];+ signature.copy_from_slice(small.as_raw());+ if let Some(last) = &self.last {+ let sum: u32 = signature+ .iter()+ .zip(last)+ .map(|(a, b)| a.abs_diff(*b) as u32)+ .sum();+ let changed = signature+ .chunks_exact(3)+ .zip(last.chunks_exact(3))+ .filter(|(a, b)| a.iter().zip(*b).any(|(a, b)| a.abs_diff(*b) > 16))+ .count();+ if sum <= 192 * 3 && changed <= 2 {+ return Ok(false);+ }+ }+ self.last = Some(signature);+ Ok(true)+ }+}+#[cfg(test)]+mod frame_dedupe_tests {+ use super::*;+ #[test]+ fn repeated_frames_skip_but_color_and_scene_changes_survive() {+ let encode = |color| {+ let mut out = Cursor::new(Vec::new());+ image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(64, 64, image::Rgb(color)))+ .write_to(&mut out, image::ImageFormat::Png)+ .unwrap();+ out.into_inner()+ };+ let mut filter = FrameDedupe::default();+ assert!(filter.keep(&encode([180, 10, 10])).unwrap());+ assert!(!filter.keep(&encode([181, 10, 10])).unwrap());+ assert!(filter.keep(&encode([10, 10, 180])).unwrap());+ assert!(!filter.keep(&encode([10, 10, 180])).unwrap());+ }+}diff --git a/native/src/db.rs b/native/src/db.rsindex 123e750..23b6fa7 100644--- a/native/src/db.rs+++ b/native/src/db.rs@@ -77,6 +77,10 @@ impl Database {conn.execute_batch("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS names(path TEXT PRIMARY KEY,name TEXT,parent TEXT,kind TEXT,folded TEXT,base TEXT,mtime INTEGER DEFAULT -1,size INTEGER DEFAULT -1,index_mode TEXT DEFAULT 'full'); CREATE INDEX IF NOT EXISTS names_base ON names(base); CREATE VIRTUAL TABLE IF NOT EXISTS name_words USING fts5(folded,content='names',content_rowid='rowid',tokenize='trigram'); CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY,text TEXT,vector TEXT,mtime INTEGER,size INTEGER); CREATE TABLE IF NOT EXISTS segments(path TEXT,namespace TEXT,kind TEXT,text TEXT,vector TEXT,location TEXT); CREATE INDEX IF NOT EXISTS segments_path ON segments(path,namespace); CREATE VIRTUAL TABLE IF NOT EXISTS words USING fts5(path,text,tokenize='unicode61'); CREATE TABLE IF NOT EXISTS segment_vectors(id INTEGER PRIMARY KEY,namespace TEXT,kind TEXT,channel TEXT,dimension INTEGER,vector BLOB,path TEXT); CREATE INDEX IF NOT EXISTS vectors_path ON segment_vectors(namespace,dimension,path,channel); CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT); CREATE TABLE IF NOT EXISTS source_seen(path TEXT PRIMARY KEY,source TEXT,epoch INTEGER,added INTEGER); CREATE INDEX IF NOT EXISTS seen_source ON source_seen(source,epoch); CREATE TABLE IF NOT EXISTS native_content(path TEXT PRIMARY KEY,fingerprint TEXT,error TEXT); ")?;conn.execute_batch("CREATE TABLE IF NOT EXISTS native_jobs(path TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,token TEXT NOT NULL,error TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS native_staging(token TEXT,seq INTEGER,kind TEXT,text TEXT,location TEXT,dimension INTEGER,vector BLOB,PRIMARY KEY(token,seq)); CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL);")?;+ crate::index_costs::tables(&conn)?;+ conn.execute_batch(+ "CREATE TABLE IF NOT EXISTS native_quick_queue(path TEXT PRIMARY KEY);",+ )?;anyhow::ensure!(conn.query_row("PRAGMA cipher_version", [], |r| r.get::<_, String>(0)).is_ok(),@@ -171,6 +175,9 @@ impl Database {"native_staging","native_jobs","native_changes",+ "native_quick_queue",+ "index_costs",+ "index_job_time","metadata",] {let exists: bool = tx.query_row(@@ -456,6 +463,8 @@ impl Database {for table in ["native_jobs","native_changes",+ "native_quick_queue",+ "index_job_time","words","segments","segment_vectors",@@ -961,6 +970,7 @@ impl Database {if let Some((_, old)) = old {cached_execute(&c, "DELETE FROM native_staging WHERE token=?1", [old])?;}+ cached_execute(&c, "DELETE FROM index_job_time WHERE path=?1", [path])?;cached_execute(&c,"INSERT OR REPLACE INTO native_jobs(path,fingerprint,token,error) VALUES(?1,?2,?3,'')",diff --git a/native/src/engine.rs b/native/src/engine.rsindex c49f211..e7a4c8a 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -25,6 +25,7 @@ struct PendingDocument {records: Vec<crate::content::Segment>,size: u64,modified: Option<std::time::SystemTime>,+ prepared_seconds: f64,}#[derive(Clone, Debug, Default, Serialize, Deserialize)]pub struct Progress {@@ -41,6 +42,7 @@ pub struct Progress {pub session_pending: u64,pub requests: u64,pub started: i64,+ pub estimated_seconds: Option<f64>,}#[derive(Clone)]pub struct NotifySender {@@ -266,6 +268,10 @@ impl Control {Ok(())}pub fn check(&self) -> Result<()> {+ self.check_with(&|| false)+ }+ pub fn check_with(&self, stopped: &dyn Fn() -> bool) -> Result<()> {+ anyhow::ensure!(!stopped(), "Preparation stopped");if self.automatic.load(Ordering::Relaxed) {let settings = self.schedule.lock().unwrap();if self.watching.load(Ordering::Relaxed) && !settings.watch_changes {@@ -284,6 +290,7 @@ impl Control {}}loop {+ anyhow::ensure!(!stopped(), "Preparation stopped");anyhow::ensure!(!self.cancel.load(Ordering::Relaxed),"Indexing cancelled; completed files retained"@@ -296,6 +303,7 @@ impl Control {std::thread::sleep(Duration::from_millis(100));}while self.paused.load(Ordering::Relaxed) {+ anyhow::ensure!(!stopped(), "Preparation stopped");anyhow::ensure!(!self.cancel.load(Ordering::Relaxed),"Indexing cancelled; completed files retained"@@ -608,9 +616,7 @@ impl Engine {self.control.paused.store(false, Ordering::Relaxed);let owner = self.clone();std::thread::spawn(move || {- let result = owner- .index_paths(&s, force, paths)- .map_err(|e| e.to_string());+ let result = owner.run_index(&s, force, paths).map_err(|e| e.to_string());owner.control.last_run_success@@ -644,8 +650,81 @@ impl Engine {let _ = owner.tx.send(Event::IndexDone(result));});}- fn index_inner(&self, s: &Settings, force: bool) -> Result<String> {- self.index_paths(s, force, None)+ pub(crate) fn index_inner(&self, s: &Settings, force: bool) -> Result<String> {+ self.run_index(s, force, None)+ }+ fn run_index(&self, s: &Settings, force: bool, paths: Option<Vec<PathBuf>>) -> Result<String> {+ let mut first = s.clone();+ let has_quick = s.roots.iter().any(|r| r.mode.eq_ignore_ascii_case("quick"));+ let has_full = s+ .roots+ .iter()+ .any(|r| !r.mode.eq_ignore_ascii_case("quick"));+ first.index_phase = if !has_full {+ "quick-final"+ } else if s.index_order == "Full first" || !has_quick {+ "full"+ } else {+ "quick"+ }+ .into();+ let summary = self.index_paths(&first, force, paths)?;+ let c = self.db.connect(false)?;+ crate::db::register_search(&c, s, "All files", "", "", None)?;+ c.create_scalar_function(+ "vd_available",+ 1,+ rusqlite::functions::FunctionFlags::SQLITE_UTF8,+ |ctx| {+ let path = ctx.get::<String>(0)?;+ Ok(std::path::Path::new(&path).is_file())+ },+ )?;+ loop {+ self.control.file_checkpoint()?;+ let mut stmt=c.prepare_cached("SELECT path FROM native_jobs j WHERE error='' AND vd_match(path,'text',0,0) AND vd_available(path) ORDER BY (SELECT coalesce(max(seq),-1) FROM native_staging WHERE token=j.token),rowid LIMIT 64")?;+ let paths = stmt+ .query_map([], |r| r.get::<_, String>(0))?+ .collect::<rusqlite::Result<Vec<_>>>()?+ .into_iter()+ .filter(|p| {+ s.searched(Path::new(p)) && mode(p, s) == "full" && Path::new(p).is_file()+ })+ .map(PathBuf::from)+ .collect::<Vec<_>>();+ if paths.is_empty() {+ break;+ }+ let mut later = s.clone();+ later.count_files = false;+ later.index_phase = "resume".into();+ self.index_paths(&later, false, Some(paths))?;+ }+ loop {+ self.control.file_checkpoint()?;+ let mut stmt = c.prepare_cached("SELECT path FROM native_quick_queue LIMIT 256")?;+ let queued = stmt+ .query_map([], |r| r.get::<_, String>(0))?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ if queued.is_empty() {+ break;+ }+ let paths = queued+ .iter()+ .filter(|p| s.searched(Path::new(p)))+ .map(PathBuf::from)+ .collect::<Vec<_>>();+ if !paths.is_empty() {+ let mut later = s.clone();+ later.count_files = false;+ later.index_phase = "quick-final".into();+ self.index_paths(&later, false, Some(paths))?;+ }+ for path in queued {+ c.execute("DELETE FROM native_quick_queue WHERE path=?1", [path])?;+ }+ }+ Ok(summary)}fn index_paths(&self,@@ -719,7 +798,11 @@ impl Engine {.collect::<rusqlite::Result<Vec<_>>>()?;let resume_paths: HashSet<String> = pending.iter().cloned().collect();let mut resumed_done = HashSet::new();- for path in pending.into_iter().rev() {+ for path in pending+ .into_iter()+ .rev()+ .filter(|_| s.index_phase.is_empty())+ {let path = PathBuf::from(path);if s.searched(&path) && !selected.contains(&path) {selected.insert(0, path);@@ -766,6 +849,7 @@ impl Engine {progress.phase = "Indexing".into();}let mut last = Instant::now();+ let mut last_estimate = Instant::now() - Duration::from_secs(3);let mut tx_entries = 0u32;conn.execute_batch("BEGIN IMMEDIATE")?;let mut complete_roots = vec![];@@ -785,7 +869,6 @@ impl Engine {s.code_search);let mut documents: Vec<PendingDocument> = vec![];- let mut document_bytes = 0usize;let outcome = (|| -> Result<()> {for root in selected {self.control.file_checkpoint()?;@@ -892,6 +975,15 @@ impl Engine {.map(|t| t.as_nanos().min(i64::MAX as u128) as i64).unwrap_or(-1);let indexing_mode = mode(&path.to_string_lossy(), s);+ if is_file && indexing_mode == "quick" && s.index_phase == "full" {+ progress.found += 1;+ conn.execute(+ "INSERT OR IGNORE INTO native_quick_queue VALUES(?1)",+ [path.to_string_lossy().as_ref()],+ )?;+ conn.execute("INSERT INTO source_seen(path,source,epoch,added) SELECT ?1,?2,?3,0 WHERE EXISTS(SELECT 1 FROM names WHERE path=?1) ON CONFLICT(path) DO UPDATE SET source=excluded.source,epoch=excluded.epoch",params![path.to_string_lossy(),root_s,epoch])?;+ continue;+ }let reason = Database::touch_name_detail(&conn,path,@@ -973,6 +1065,9 @@ impl Engine {if extension == "pdf" && s.pdf_visuals {detail.push_str("|pdf:visual");}+ if content::is_video(&extension) && s.skip_similar_frames {+ detail.push_str("|dedupe:rgb-v1");+ }if content::is_video(&extension)&& (s.video_interval - 5.0).abs() > f32::EPSILON{@@ -1046,6 +1141,7 @@ impl Engine {}} else if !resumed_done.contains(&progress.current)&& (force+ || s.index_phase == "resume"|| resume_paths.contains(&progress.current)|| !legacy&& previous@@ -1078,6 +1174,11 @@ impl Engine {if resume_paths.contains(&progress.current) {resumed_done.insert(progress.current.clone());}+ if s.index_phase == "quick" {+ Database::prepare_job(&conn, &progress.current, &key)?;+ progress.completed += 1;+ continue;+ }let small_text = meta.len() <= 16 * 1024&& (["txt", "md", "csv", "log", "json", "yaml", "yml", "toml"].contains(&extension.as_str())@@ -1085,100 +1186,25 @@ impl Engine {let small_image =content::is_image(&extension) && meta.len() <= 16 * 1024 * 1024;if small_text || small_image {- let extracted = (|| -> Result<Vec<crate::content::Segment>> {- let records = if small_image {- let mut records = vec![];- let mut bytes = 0usize;- let mut warned = false;- crate::worker::visit(- path,- s,- &self.control,- &mut |record| {- if record.kind == "warning" {- warned = true;- self.log("Warning", &record.text);- return Ok(());- }- bytes += record.media.len() + record.text.len();- anyhow::ensure!(- records.len() < 128 && bytes <= 8 * 1024 * 1024,- "Image extraction exceeds bounded batch size"- );- records.push(record);- Ok(())- },- )?;- anyhow::ensure!(- !records.is_empty() || !warned,- "No readable image content; previous content retained"- );- records- } else {- content::extract(path, s, &|| {- self.control.file_checkpoint()- })?- };- Ok(records)- })()- .and_then(|records| {- anyhow::ensure!(- !s.excluded_sensitive- || !records.iter().any(|r| sensitive(&r.text)),- "Potential credentials detected; content excluded"- );- Ok(records)- });- let records = match extracted {- Ok(records) => records,- Err(error) => {- self.control.file_checkpoint()?;- conn.execute("INSERT OR REPLACE INTO native_content VALUES(?1,?2,?3)",params![progress.current,key,error.to_string()])?;- progress.skipped += 1;- progress.completed += 1;- self.log(- "Warning",- format!("Skipped {}: {error}", progress.current),- );- continue;- }- };- let bytes = records- .iter()- .map(|r| r.text.len() + r.media.len())- .sum::<usize>();- if document_bytes + bytes > 2 * 1024 * 1024 {- self.flush_documents(s, &conn, &mut documents, &mut progress)?;- document_bytes = 0;- }let (token, resume) =Database::prepare_job(&conn, &progress.current, &key)?;- document_bytes += bytes;documents.push(PendingDocument {path: progress.current.clone(),key,token,resume,- records,+ records: vec![],size: meta.len(),modified: meta.modified().ok(),+ prepared_seconds: 0.0,});progress.completed += 1;- if documents.len() >= 16- || document_bytes- >= if small_image {- 2 * 1024 * 1024- } else {- 32 * 1024- }- {+ if documents.len() >= 32 {self.flush_documents(s, &conn, &mut documents, &mut progress)?;- document_bytes = 0;}continue;}self.flush_documents(s, &conn, &mut documents, &mut progress)?;- document_bytes = 0;progress.phase = "Extracting Full content".into();// Commit names before potentially slow parsing/inference. No writer lock is// held while a GPU or remote model is working, and searches stay available.@@ -1190,7 +1216,26 @@ impl Engine {let file_result = (|| -> Result<usize> {let (token, resume) =Database::prepare_job(&conn, &progress.current, &key)?;- let mut seen = 0usize;+ let (start_page, prefix): (u32, usize) = if extension == "pdf"+ && resume > 0+ {+ let page:u32=conn.query_row("SELECT coalesce(max(cast(json_extract(location,'$.page') AS INTEGER)),0) FROM native_staging WHERE token=?1",[&token],|r|r.get(0))?;+ let prefix=conn.query_row("SELECT count(*) FROM native_staging WHERE token=?1 AND cast(json_extract(location,'$.page') AS INTEGER)<?2",params![token,page],|r|r.get(0))?;+ (page, prefix)+ } else {+ (0, 0)+ };+ // PDF can seek to its saved page. Media decoding must remain a+ // single stream until timestamp resume is available; restarting it+ // every few frames would multiply decoding work on long videos.+ let sliced = !content::is_video(&extension)+ && !content::is_audio(&extension);+ let turn_budget = if extension == "pdf" {+ 32+ } else {+ (resume / 4).max(32)+ };+ let mut seen = prefix;let mut batch = vec![];let mut count = resume;if resume > 0 {@@ -1230,13 +1275,23 @@ impl Engine {.segments(s, batch, &|| self.control.file_checkpoint())?;Database::stage(&conn, &token, *count, batch, &vectors)?;*count += batch.len();+ if last_estimate.elapsed() > Duration::from_secs(2) {+ file_progress.estimated_seconds =+ crate::index_costs::estimate(&conn, s).ok().flatten();+ last_estimate = Instant::now();+ }file_progress.content_chunks = *count as u64;let _ = self.tx.send(Event::Progress(file_progress.clone()));batch.clear();Ok(())};- let parsed =- crate::worker::visit(path, s, &self.control, &mut |record| {+ let parsed = crate::worker::visit_checked(+ path,+ s,+ &self.control,+ start_page,+ &|| false,+ &mut |record| {if record.kind == "warning" {had_warning = true;self.log("Warning", &record.text);@@ -1246,6 +1301,9 @@ impl Engine {if seen <= resume {return Ok(());}+ if sliced && seen > resume.saturating_add(turn_budget) {+ return Err(YieldFile.into());+ }let media = !record.media.is_empty();if batch.first().is_some_and(|r: &crate::content::Segment| {@@ -1266,10 +1324,13 @@ impl Engine {process(&mut batch, &mut count)?;}Ok(())- });- if let Err(error) = parsed {- return Err(error);- }+ },+ );+ let yielded = match parsed {+ Ok(()) => false,+ Err(error) if error.is::<YieldFile>() => true,+ Err(error) => return Err(error),+ };process(&mut batch, &mut count)?;anyhow::ensure!(seen >= resume,@@ -1282,9 +1343,36 @@ impl Engine {count > 0 || !had_warning,"No readable content was extracted; previous file content retained");- Database::finish_stage(&conn, &token, &progress.current, &key)?;- progress.requests +=- count.div_ceil(s.batch_size.clamp(1, 16)) as u64;+ let current = std::fs::metadata(path)?;+ anyhow::ensure!(+ current.len() == meta.len()+ && current.modified().ok() == meta.modified().ok(),+ "File changed while parsing; retry on next update"+ );+ // Yield durable staged work without exposing an incomplete file.+ // Replace its searchable content atomically only after extraction finishes.+ if !yielded {+ Database::finish_stage(&conn, &token, &progress.current, &key)?;+ }+ if yielded {+ crate::index_costs::add_time(+ &conn,+ &progress.current,+ file_start.elapsed().as_secs_f64(),+ )?;+ } else {+ crate::index_costs::finish(+ &conn,+ s,+ &progress.current,+ meta.len(),+ file_start.elapsed().as_secs_f64(),+ )?;+ }+ progress.requests += count+ .saturating_sub(resume)+ .div_ceil(s.batch_size.clamp(1, 16))+ as u64;Ok(count)})();progress.content_chunks = file_progress.content_chunks;@@ -1339,6 +1427,11 @@ impl Engine {tx_entries = 0;self.db.generation.fetch_add(1, Ordering::Relaxed);}+ if last_estimate.elapsed() > Duration::from_secs(2) {+ progress.estimated_seconds =+ crate::index_costs::estimate(&conn, s).ok().flatten();+ last_estimate = Instant::now();+ }if last.elapsed() > Duration::from_millis(100) {if let Ok((complete, pending)) = Database::session(&conn) {progress.session_completed = complete;@@ -1411,12 +1504,180 @@ impl Engine {start.elapsed().as_secs_f64()))}+ fn prepare_document(+ &self,+ s: &Settings,+ document: &mut PendingDocument,+ stop: &AtomicBool,+ ) -> Result<()> {+ let start = Instant::now();+ let path = Path::new(&document.path);+ let mut records = vec![];+ let mut bytes = 0usize;+ let mut warning = false;+ let ext = content::extension(path);+ let rust_image =+ ["png", "jpg", "jpeg", "webp", "bmp", "gif"].contains(&ext.as_str()) && !s.ocr_enabled;+ if content::is_image(&ext) && !rust_image {+ crate::worker::visit_checked(+ path,+ s,+ &self.control,+ 0,+ &|| stop.load(Ordering::Acquire),+ &mut |record| {+ if record.kind == "warning" {+ warning = true;+ self.log("Warning", &record.text);+ return Ok(());+ }+ bytes += record.media.len() + record.text.len();+ anyhow::ensure!(+ records.len() < 128 && bytes <= 8 * 1024 * 1024,+ "Image extraction exceeds bounded batch size"+ );+ records.push(record);+ Ok(())+ },+ )?;+ anyhow::ensure!(+ !records.is_empty() || !warning,+ "No readable image content; previous content retained"+ );+ } else {+ records = content::extract(path, s, &|| {+ anyhow::ensure!(!stop.load(Ordering::Acquire), "Preparation stopped");+ self.control.check_with(&|| stop.load(Ordering::Acquire))+ })?;+ }+ anyhow::ensure!(+ !s.excluded_sensitive || !records.iter().any(|r| sensitive(&r.text)),+ "Potential credentials detected; content excluded"+ );+ anyhow::ensure!(+ records.len() <= 128+ && records+ .iter()+ .map(|r| r.text.len() + r.media.len())+ .sum::<usize>()+ <= 8 * 1024 * 1024,+ "Prepared document exceeds bounded batch size"+ );+ document.records = records;+ document.prepared_seconds = start.elapsed().as_secs_f64();+ Ok(())+ }fn flush_documents(&self,s: &Settings,c: &rusqlite::Connection,documents: &mut Vec<PendingDocument>,progress: &mut Progress,+ ) -> Result<()> {+ if documents.is_empty() {+ return Ok(());+ }+ if !c.is_autocommit() {+ c.execute_batch("COMMIT")?;+ }+ let input = std::mem::take(documents);+ let stopped = AtomicBool::new(false);+ let (tx, rx) = crossbeam_channel::bounded(1);+ let (advance, requests) = crossbeam_channel::bounded(1);+ advance.send(()).unwrap();+ let result = std::thread::scope(|scope| {+ let stop = &stopped;+ scope.spawn(move || {+ let mut input = input.into_iter().peekable();+ while input.peek().is_some() && !stop.load(Ordering::Acquire) {+ loop {+ match requests.recv_timeout(Duration::from_millis(50)) {+ Ok(()) => break,+ Err(crossbeam_channel::RecvTimeoutError::Timeout)+ if !stop.load(Ordering::Acquire) =>+ {+ continue;+ }+ _ => return,+ }+ }+ let mut batch = vec![];+ let mut bytes = 0;+ while batch.len() < s.batch_size.clamp(1, 16) && bytes < 2 * 1024 * 1024 {+ let Some(mut document) = input.next() else {+ break;+ };+ let error = self+ .prepare_document(s, &mut document, stop)+ .err()+ .map(|e| e.to_string());+ bytes += document+ .records+ .iter()+ .map(|r| r.text.len() + r.media.len())+ .sum::<usize>();+ batch.push((document, error));+ }+ let mut pending = batch;+ loop {+ match tx.send_timeout(pending, Duration::from_millis(50)) {+ Ok(()) => break,+ Err(crossbeam_channel::SendTimeoutError::Timeout(value))+ if !stop.load(Ordering::Acquire) =>+ {+ pending = value+ }+ _ => return,+ }+ }+ }+ });+ let result = (|| -> Result<()> {+ loop {+ self.control.file_checkpoint()?;+ let batch = match rx.recv_timeout(Duration::from_millis(50)) {+ Ok(batch) => batch,+ Err(crossbeam_channel::RecvTimeoutError::Timeout) => continue,+ Err(_) => break,+ };+ let _ = advance.try_send(());+ let mut ready = vec![];+ for (document, error) in batch {+ if let Some(error) = error {+ c.execute(+ "UPDATE native_jobs SET error=?1 WHERE path=?2",+ params![error, document.path],+ )?;+ c.execute(+ "INSERT OR REPLACE INTO native_content VALUES(?1,?2,?3)",+ params![document.path, document.key, error],+ )?;+ progress.skipped += 1;+ self.log("Warning", format!("Skipped {}: {error}", document.path));+ } else {+ ready.push(document)+ }+ }+ self.commit_documents(s, c, &mut ready, progress)?;+ }+ Ok(())+ })();+ stopped.store(true, Ordering::Release);+ drop(advance);+ drop(rx);+ result+ });+ if c.is_autocommit() {+ c.execute_batch("BEGIN IMMEDIATE")?;+ }+ result+ }+ fn commit_documents(+ &self,+ s: &Settings,+ c: &rusqlite::Connection,+ documents: &mut Vec<PendingDocument>,+ progress: &mut Progress,) -> Result<()> {if documents.is_empty() {return Ok(());@@ -1434,6 +1695,8 @@ impl Engine {documents.len());let _ = self.tx.send(Event::Progress(progress.clone()));+ let started = Instant::now();+ let ready_before = self.models.loaded.load(Ordering::Acquire) || s.remote_embeddings();let result = self.models.segments(s, &records, &|| self.control.file_checkpoint());@@ -1447,6 +1710,7 @@ impl Engine {}};progress.requests += records.len().div_ceil(s.batch_size.clamp(1, 16)) as u64;+ let per_file = started.elapsed().as_secs_f64() / documents.len().max(1) as f64;let mut offset = 0usize;for document in documents.drain(..) {self.control.file_checkpoint()?;@@ -1475,6 +1739,15 @@ impl Engine {)?;self.control.file_checkpoint()?;Database::finish_stage(c, &document.token, &document.path, &document.key)?;+ if ready_before {+ crate::index_costs::finish(+ c,+ s,+ &document.path,+ document.size,+ document.prepared_seconds + per_file,+ )?;+ }Ok(())})();offset += remaining;@@ -1816,7 +2089,10 @@ impl Engine {let mut file_maxima: HashMap<(String, String), f32> = HashMap::new();let mut pool: Vec<(f32, i64)> = vec![];let mut channel_totals: HashMap<String, (f32, u64)> = HashMap::new();- if let Some(matrix) = self.vectors.get(&conn, vector.len(), &s.performance)? {+ if let Some(matrix) =+ self.vectors+ .get(&conn, vector.len(), &s.performance, &s.cache_precision)?+ {let mut metadata_allowed = vec![true; matrix.groups.len()];if filters.is_some_and(|f| f.active()) {let mut stmt=conn.prepare_cached("SELECT path FROM names WHERE path IN (SELECT value FROM json_each(?1)) AND vd_match(path,kind,mtime,size)")?;@@ -1842,12 +2118,12 @@ impl Engine {&& metadata_allowed[i]}).collect::<Vec<_>>();- for (i, values) in matrix.values.chunks_exact(matrix.dimension).enumerate() {+ for i in 0..matrix.ids.len() {let group = matrix.group_ids[i];if !permitted[group] {continue;}- let score = crate::vector_cache::dot(values, &vector);+ let score = matrix.score(i, &vector);let group = &matrix.groups[group];let maximum = file_maxima.entry((group.path.clone(), group.channel.clone()))@@ -1932,7 +2208,13 @@ impl Engine {}).map(|(sum, count)| sum / (*count).max(1) as f32).unwrap_or(0.0);- let ranking = score + (score - mean).clamp(-0.15, 0.15) + exact * 0.25;+ let ranking = score+ + if s.rank_calibration {+ (score - mean).clamp(-0.15, 0.15)+ } else {+ 0.0+ }+ + exact * 0.25;let media = location["embedding_source"] == "media";let h = Hit {path: path.clone(),@@ -2282,6 +2564,7 @@ fn rank_hits(hits: &mut [Hit], intent: Option<&str>) {matches(b).cmp(&matches(a)).then_with(|| b.score.total_cmp(&a.score))+ .then_with(|| a.path.cmp(&b.path))});}#[cfg(test)]@@ -2830,3 +3113,12 @@ mod scan_lifecycle_tests {assert!(c.automatic_hold.load(Ordering::Relaxed));}}++#[derive(Debug)]+struct YieldFile;+impl std::fmt::Display for YieldFile {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Continuing saved long-file work after other files")+ }+}+impl std::error::Error for YieldFile {}diff --git a/native/src/feature_tests.rs b/native/src/feature_tests.rsnew file mode 100644index 0000000..afdc3ee--- /dev/null+++ b/native/src/feature_tests.rs@@ -0,0 +1,412 @@+use crate::{+ config::{Settings, Source},+ db::Database,+ engine::{Control, Engine},+ models::Models,+};+use std::{+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+};+fn engine(home: &std::path::Path, s: &Settings) -> Engine {+ let (tx, _) = crossbeam_channel::unbounded();+ Engine {+ db: Database::new(home, s).unwrap(),+ models: Models::default(),+ control: Control::default(),+ tx: tx.into(),+ searching: Arc::new(AtomicBool::new(false)),+ vectors: Default::default(),+ }+}+struct Mock {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+ inputs: Arc<std::sync::Mutex<Vec<String>>>,+}+impl Mock {+ fn start(s: &mut Settings, observe: impl Fn(&str) + Send + 'static) -> Self {+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ s.embedding_server = "Remote".into();+ s.remote_url = format!("http://{}", server.server_addr());+ let stop = Arc::new(AtomicBool::new(false));+ let inputs = Arc::new(std::sync::Mutex::new(vec![]));+ let (done, log) = (stop.clone(), inputs.clone());+ let thread = std::thread::spawn(move || {+ while !done.load(Ordering::Acquire) {+ let Some(mut request) = server.recv_timeout(Duration::from_millis(50)).unwrap()+ else {+ continue;+ };+ let mut text = String::new();+ request.as_reader().read_to_string(&mut text).unwrap();+ let body: serde_json::Value = serde_json::from_str(&text).unwrap();+ observe(&text);+ log.lock().unwrap().push(text);+ let n = body["input"].as_array().map_or(1, Vec::len);+ let response = serde_json::json!({"data":(0..n).map(|i|serde_json::json!({"index":i,"embedding":[1.0,0.0]})).collect::<Vec<_>>()});+ let _ = request.respond(tiny_http::Response::from_string(response.to_string()));+ }+ });+ Self {+ stop,+ thread: Some(thread),+ inputs,+ }+ }+}+impl Drop for Mock {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Release);+ self.thread.take().unwrap().join().unwrap();+ }+}+fn settings() -> Settings {+ Settings {+ encrypt_index: false,+ include_programs: false,+ count_files: false,+ check_cpu: false,+ check_gpu: false,+ check_user_idle: false,+ pause_for_game: false,+ pause_for_fullscreen: false,+ ..Default::default()+ }+}+#[test]+fn quick_and_full_priorities_are_applied_before_embedding_and_do_not_lose_names() {+ for order in ["Quick first", "Full first"] {+ let home = tempfile::tempdir().unwrap();+ let source = tempfile::Builder::new()+ .prefix("VD-order-")+ .tempdir()+ .unwrap();+ let quick = source.path().join("quick");+ let full = source.path().join("full");+ std::fs::create_dir(&quick).unwrap();+ std::fs::create_dir(&full).unwrap();+ let quick_file = quick.join("ordinary.txt");+ std::fs::write(&quick_file, "quick").unwrap();+ std::fs::write(full.join("document.txt"), "full content").unwrap();+ let mut s = settings();+ s.index_order = order.into();+ s.roots = vec![+ Source {+ path: quick.to_string_lossy().into(),+ mode: "quick".into(),+ },+ Source {+ path: full.to_string_lossy().into(),+ mode: "full".into(),+ },+ ];+ let checked = Arc::new(AtomicBool::new(false));+ let marker = checked.clone();+ let dbpath = home.path().join("index.sqlite");+ let expected = order == "Quick first";+ let _mock = Mock::start(&mut s, move |_| {+ let c = rusqlite::Connection::open(&dbpath).unwrap();+ let found: i64 = c+ .query_row(+ "SELECT count(*) FROM names WHERE path=?1",+ [quick_file.to_string_lossy().as_ref()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(found > 0, expected);+ marker.store(true, Ordering::Release);+ });+ let e = engine(home.path(), &s);+ e.index_inner(&s, false).unwrap();+ assert!(checked.load(Ordering::Acquire));+ let c = e.db.connect(false).unwrap();+ let count: i64 = c+ .query_row("SELECT count(*) FROM names WHERE kind='file'", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(count, 2);+ let pending: i64 = c+ .query_row("SELECT count(*) FROM native_quick_queue", [], |r| r.get(0))+ .unwrap();+ assert_eq!(pending, 0);+ }+}+#[test]+fn long_file_yields_to_small_files_and_finishes_with_unique_vectors() {+ let home = tempfile::tempdir().unwrap();+ let source = tempfile::Builder::new()+ .prefix("VD-fair-")+ .tempdir()+ .unwrap();+ let long = source.path().join("long.txt");+ let short = source.path().join("short.txt");+ let body = "LONGMARKER seasonal garden plants and flowers. ".repeat(6000);+ std::fs::write(&long, &body).unwrap();+ std::fs::write(&short, "SMALLMARKER invoice document").unwrap();+ let mut s = settings();+ s.roots = vec![+ Source {+ path: long.to_string_lossy().into(),+ mode: "full".into(),+ },+ Source {+ path: short.to_string_lossy().into(),+ mode: "full".into(),+ },+ ];+ let visible = Arc::new(AtomicBool::new(false));+ let marker = visible.clone();+ let path = long.clone();+ let dbpath = home.path().join("index.sqlite");+ let mock = Mock::start(&mut s, move |input| {+ if input.contains("SMALLMARKER") {+ let c = rusqlite::Connection::open(&dbpath).unwrap();+ let count: i64 = c+ .query_row(+ "SELECT count(*) FROM native_staging WHERE token IN (SELECT token FROM native_jobs WHERE path=?1)",+ [path.to_string_lossy().as_ref()],+ |r| r.get(0),+ )+ .unwrap();+ assert!(count > 0 && count <= 32);+ let published: i64 = c+ .query_row(+ "SELECT count(*) FROM segments WHERE path=?1",+ [path.to_string_lossy().as_ref()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(published, 0);+ marker.store(true, Ordering::Release);+ }+ });+ let e = engine(home.path(), &s);+ e.index_inner(&s, false).unwrap();+ assert!(visible.load(Ordering::Acquire));+ let inputs = mock.inputs.lock().unwrap();+ let small = inputs+ .iter()+ .position(|x| x.contains("SMALLMARKER"))+ .unwrap();+ assert!(inputs[small + 1..].iter().any(|x| x.contains("LONGMARKER")));+ let c = e.db.connect(false).unwrap();+ let n: i64 = c+ .query_row(+ "SELECT count(*) FROM segment_vectors WHERE path=?1",+ [long.to_string_lossy().as_ref()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(n as usize, crate::content::chunks(&body, 1800).len());+ let pending: i64 = c+ .query_row("SELECT count(*) FROM native_jobs", [], |r| r.get(0))+ .unwrap();+ assert_eq!(pending, 0);+}+#[test]+fn fp16_cache_uses_half_storage_preserves_scores_and_does_not_rewrite_index() {+ let home = tempfile::tempdir().unwrap();+ let s = settings();+ let db = Database::new(home.path(), &s).unwrap();+ let c = db.connect(false).unwrap();+ let mut v = (0..768)+ .map(|i| ((i as f32 + 1.0) * 0.17).sin())+ .collect::<Vec<_>>();+ let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();+ for x in &mut v {+ *x /= norm+ }+ Database::save_segments(+ &c,+ "sample.txt",+ &[crate::content::Segment::text("text", "sample".into(), 0, 0)],+ &[v.clone()],+ "same",+ )+ .unwrap();+ let cache = crate::vector_cache::Cache::default();+ let full = cache.get(&c, 768, "Balanced", "FP32").unwrap().unwrap();+ let half = cache.get(&c, 768, "Balanced", "FP16").unwrap().unwrap();+ assert!(half.values.is_empty());+ assert_eq!(half.halves.len(), 768);+ assert_eq!(full.values.len(), 768);+ assert!((full.score(0, &v) - half.score(0, &v)).abs() < 0.0001);+ assert!(half.bytes < full.bytes);+ assert_eq!(half.revision, full.revision);+ assert!(cache.get(&c, 768, "Low memory", "FP16").unwrap().is_none());+}+#[test]+fn learned_estimates_are_backend_specific_and_clearable() {+ let home = tempfile::tempdir().unwrap();+ let source = tempfile::Builder::new()+ .prefix("VD-estimate-")+ .tempdir()+ .unwrap();+ let pending = source.path().join("pending.txt");+ std::fs::write(&pending, "fixture").unwrap();+ let mut s = settings();+ s.roots = vec![Source {+ path: source.path().to_string_lossy().into(),+ mode: "full".into(),+ }];+ let db = Database::new(home.path(), &s).unwrap();+ let c = db.connect(false).unwrap();+ for _ in 0..4 {+ crate::index_costs::finish(&c, &s, "done.txt", 1024, 0.2).unwrap();+ }+ Database::touch_name(&c, &pending, "file", 1, 2048, "full", "root", 1).unwrap();+ Database::prepare_job(&c, &pending.to_string_lossy(), "x").unwrap();+ let eta = crate::index_costs::estimate(&c, &s).unwrap().unwrap();+ assert!((eta - 0.4).abs() < 0.001);+ let mut other = s.clone();+ other.model = "different".into();+ assert!(crate::index_costs::estimate(&c, &other).unwrap().is_none());+ db.clear_index().unwrap();+ assert!(crate::index_costs::estimate(&c, &s).unwrap().is_none());+}++#[test]+fn rank_calibration_is_query_time_and_does_not_change_the_index() {+ let home = tempfile::tempdir().unwrap();+ let source = tempfile::Builder::new()+ .prefix("VD-calibration-")+ .tempdir()+ .unwrap();+ let mut s = settings();+ s.roots = vec![Source {+ path: source.path().to_string_lossy().into(),+ mode: "full".into(),+ }];+ let _mock = Mock::start(&mut s, |_| {});+ let e = engine(home.path(), &s);+ let c = e.db.connect(false).unwrap();+ for (name, score, image) in [+ ("picture.png", 0.81f32, true),+ ("strong.txt", 0.795, false),+ ("other1.txt", 0.1, false),+ ("other2.txt", 0.1, false),+ ] {+ let path = source.path().join(name);+ Database::touch_name(&c, &path, "file", 1, 100, "full", &s.roots[0].path, 1).unwrap();+ let mut segment = crate::content::Segment::text(+ if image { "image" } else { "text" },+ "indexed document".into(),+ 0,+ 0,+ );+ if image {+ segment.media = vec![1];+ }+ Database::save_segments(+ &c,+ &path.to_string_lossy(),+ &[segment],+ &[vec![score, (1.0 - score * score).sqrt()]],+ "unchanged",+ )+ .unwrap();+ }+ let before: i64 = c+ .query_row("SELECT sum(length(vector)) FROM segment_vectors", [], |r| {+ r.get(0)+ })+ .unwrap();+ let first = e+ .search_inner("semanticprobe", &s, "Semantic", "All files", "", "")+ .unwrap();+ assert!(first[0].path.ends_with("picture.png"));+ s.rank_calibration = true;+ let calibrated = e+ .search_inner("semanticprobe", &s, "Semantic", "All files", "", "")+ .unwrap();+ assert!(calibrated[0].path.ends_with("strong.txt"));+ let after: i64 = c+ .query_row("SELECT sum(length(vector)) FROM segment_vectors", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(before, after);+ assert_eq!(e.db.stats().unwrap().files, 4);+}++#[test]+fn staged_replacement_retains_old_content_until_the_whole_file_finishes() {+ let home = tempfile::tempdir().unwrap();+ let s = settings();+ let db = Database::new(home.path(), &s).unwrap();+ let c = db.connect(false).unwrap();+ Database::save_segments(+ &c,+ "long.txt",+ &[crate::content::Segment::text(+ "text",+ "old complete file".into(),+ 0,+ 0,+ )],+ &[vec![1.0, 0.0]],+ "old",+ )+ .unwrap();+ let (token, _) = Database::prepare_job(&c, "long.txt", "new").unwrap();+ Database::stage(+ &c,+ &token,+ 0,+ &[crate::content::Segment::text("text", "first".into(), 0, 0)],+ &[vec![1.0, 0.0]],+ )+ .unwrap();+ assert_eq!(+ "old complete file",+ c.query_row::<String, _, _>("SELECT text FROM segments", [], |r| r.get(0))+ .unwrap()+ );+ Database::stage(+ &c,+ &token,+ 1,+ &[crate::content::Segment::text("text", "second".into(), 0, 0)],+ &[vec![0.0, 1.0]],+ )+ .unwrap();+ Database::finish_stage(&c, &token, "long.txt", "new").unwrap();+ assert_eq!(+ 2,+ c.query_row::<i64, _, _>("SELECT count(*) FROM segments", [], |r| r.get(0))+ .unwrap()+ );+ assert_eq!(+ 0,+ c.query_row::<i64, _, _>(+ "SELECT count(*) FROM segments WHERE text='old complete file'",+ [],+ |r| r.get(0)+ )+ .unwrap()+ );+}+#[test]+fn preparation_stop_interrupts_a_paused_pipeline() {+ let control = Control::default();+ control.paused.store(true, Ordering::Relaxed);+ let stop = AtomicBool::new(false);+ std::thread::scope(|scope| {+ scope.spawn(|| {+ std::thread::sleep(Duration::from_millis(30));+ stop.store(true, Ordering::Release);+ });+ let start = std::time::Instant::now();+ assert!(+ control+ .check_with(&|| stop.load(Ordering::Acquire))+ .is_err()+ );+ assert!(start.elapsed() < Duration::from_millis(500));+ });+}diff --git a/native/src/index_costs.rs b/native/src/index_costs.rsnew file mode 100644index 0000000..431dee1--- /dev/null+++ b/native/src/index_costs.rs@@ -0,0 +1,109 @@+use crate::{config::Settings, content};+use anyhow::Result;+use rusqlite::{Connection, OptionalExtension, params};+use sha2::{Digest, Sha256};+use std::path::Path;+fn bucket(s: &Settings) -> String {+ format!(+ "{:x}",+ Sha256::digest(+ format!(+ "{}|{}|{}|{}|{}|{}",+ s.model,+ s.remote_url,+ s.remote_model,+ s.hardware,+ s.device,+ s.backend()+ )+ .as_bytes()+ )+ )+}+fn kind(path: &str) -> &'static str {+ let e = content::extension(Path::new(path));+ if content::is_image(&e) {+ "image"+ } else if content::is_video(&e) {+ "video"+ } else if content::is_audio(&e) {+ "audio"+ } else if e == "pdf" {+ "pdf"+ } else {+ "text"+ }+}+fn units(kind: &str, size: u64) -> f64 {+ if kind == "image" {+ 1.0+ } else {+ (size as f64 / 1024.0).max(1.0)+ }+}+pub fn tables(c: &Connection) -> Result<()> {+ c.execute_batch("CREATE TABLE IF NOT EXISTS index_costs(backend TEXT,kind TEXT,seconds REAL,units REAL,samples INTEGER,PRIMARY KEY(backend,kind));CREATE TABLE IF NOT EXISTS index_job_time(path TEXT PRIMARY KEY,seconds REAL);")?;+ Ok(())+}+pub fn add_time(c: &Connection, path: &str, seconds: f64) -> Result<()> {+ c.execute("INSERT INTO index_job_time VALUES(?1,?2) ON CONFLICT(path) DO UPDATE SET seconds=seconds+excluded.seconds",params![path,seconds.max(0.0)])?;+ Ok(())+}+pub fn finish(c: &Connection, s: &Settings, path: &str, size: u64, seconds: f64) -> Result<()> {+ let previous: f64 = c+ .query_row(+ "SELECT seconds FROM index_job_time WHERE path=?1",+ [path],+ |r| r.get(0),+ )+ .optional()?+ .unwrap_or(0.0);+ let time = previous + seconds;+ let kind = kind(path);+ if time.is_finite() && time > 0.0 {+ c.execute("INSERT INTO index_costs VALUES(?1,?2,?3,?4,1) ON CONFLICT(backend,kind) DO UPDATE SET seconds=seconds*0.95+excluded.seconds,units=units*0.95+excluded.units,samples=samples+1",params![bucket(s),kind,time,units(kind,size)])?;+ }+ c.execute("DELETE FROM index_job_time WHERE path=?1", [path])?;+ Ok(())+}+pub fn estimate(c: &Connection, s: &Settings) -> Result<Option<f64>> {+ let mut rates = std::collections::HashMap::new();+ let mut q = c.prepare_cached(+ "SELECT kind,seconds/units FROM index_costs WHERE backend=?1 AND samples>=3 AND units>0",+ )?;+ for row in q.query_map([bucket(s)], |r| {+ Ok((r.get::<_, String>(0)?, r.get::<_, f64>(1)?))+ })? {+ let (k, v) = row?;+ rates.insert(k, v);+ }+ if rates.is_empty() {+ return Ok(None);+ }+ crate::db::register_search(c, s, "All files", "", "", None)?;+ let mut q=c.prepare_cached("SELECT n.path,n.size,coalesce(t.seconds,0) FROM native_jobs j JOIN names n ON n.path=j.path LEFT JOIN index_job_time t ON t.path=j.path WHERE j.error='' AND n.index_mode='full' AND vd_match(n.path,'text',n.mtime,n.size) LIMIT 2048")?;+ let mut total = 0.0;+ let mut count = 0;+ for row in q.query_map([], |r| {+ Ok((+ r.get::<_, String>(0)?,+ r.get::<_, i64>(1)?,+ r.get::<_, f64>(2)?,+ ))+ })? {+ let (path, size, spent) = row?;+ let k = kind(&path);+ let Some(rate) = rates.get(k) else {+ return Ok(None);+ };+ total += (units(k, size.max(0) as u64) * rate - spent).max(rate * 0.1);+ count += 1;+ }+ if count == 0 {+ return Ok(None);+ }+ let all: u64 = c.query_row("SELECT count(*) FROM native_jobs j JOIN names n ON n.path=j.path WHERE j.error='' AND n.index_mode='full' AND vd_match(n.path,'text',n.mtime,n.size)", [], |r| {+ r.get(0)+ })?;+ Ok(Some(total * all as f64 / count as f64))+}diff --git a/native/src/main.rs b/native/src/main.rsindex 9363064..2715739 100644--- a/native/src/main.rs+++ b/native/src/main.rs@@ -12,7 +12,10 @@ mod content;mod db;mod dictation;mod engine;+#[cfg(test)]+mod feature_tests;mod icons;+mod index_costs;mod journal;mod launcher;mod mcp;diff --git a/native/src/pdf.rs b/native/src/pdf.rsindex 794b012..88fbef1 100644--- a/native/src/pdf.rs+++ b/native/src/pdf.rs@@ -237,11 +237,21 @@ pub fn visit(scanned_images: bool,checkpoint: &dyn Fn() -> Result<()>,emit: &mut dyn FnMut(u32, String, Option<Vec<u8>>) -> Result<()>,+) -> Result<()> {+ visit_from(path, 0, visuals, scanned_images, checkpoint, emit)+}+pub fn visit_from(+ path: &Path,+ start_page: u32,+ visuals: bool,+ scanned_images: bool,+ checkpoint: &dyn Fn() -> Result<()>,+ emit: &mut dyn FnMut(u32, String, Option<Vec<u8>>) -> Result<()>,) -> Result<()> {with_pdf(path, |pdf, document| unsafe {let count = (pdf.count)(document);anyhow::ensure!((0..=10000).contains(&count), "PDF page count exceeds limit");- for index in 0..count {+ for index in (start_page.saturating_sub(1) as i32).min(count)..count {checkpoint()?;let page = (pdf.load_page)(document, index);anyhow::ensure!(!page.is_null(), "PDF page unavailable");diff --git a/native/src/platform.rs b/native/src/platform.rsindex d7156e8..490a8e9 100644--- a/native/src/platform.rs+++ b/native/src/platform.rs@@ -1089,8 +1089,10 @@ pub fn material(value: isize, popup: bool, dark: bool, _: [u8; 3], _: f32) {SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,);}- let no_border = 0xfffffffeu32;- let _ = DwmSetWindowAttribute(hwnd, DWMWA_BORDER_COLOR, &no_border as *const _ as _, 4);+ if windows_build() >= 22000 {+ let no_border = 0xfffffffeu32;+ let _ = DwmSetWindowAttribute(hwnd, DWMWA_BORDER_COLOR, &no_border as *const _ as _, 4);+ }let mode = dark as i32;let _ = DwmSetWindowAttribute(hwnd,@@ -1105,20 +1107,22 @@ pub fn material(value: isize, popup: bool, dark: bool, _: [u8; 3], _: f32) {// frame/shadow uses a different outline and leaks behind those corners.let policy = DWMNCRP_DISABLED;let _ = DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &policy as *const _ as _, 4);- let corners = DWMWCP_DONOTROUND;- let _ = DwmSetWindowAttribute(- hwnd,- DWMWA_WINDOW_CORNER_PREFERENCE,- &corners as *const _ as _,- 4,- );- let backdrop = DWMSBT_NONE;- let _ = DwmSetWindowAttribute(- hwnd,- DWMWA_SYSTEMBACKDROP_TYPE,- &backdrop as *const _ as _,- 4,- );+ if windows_build() >= 22000 {+ let corners = DWMWCP_DONOTROUND;+ let _ = DwmSetWindowAttribute(+ hwnd,+ DWMWA_WINDOW_CORNER_PREFERENCE,+ &corners as *const _ as _,+ 4,+ );+ let backdrop = DWMSBT_NONE;+ let _ = DwmSetWindowAttribute(+ hwnd,+ DWMWA_SYSTEMBACKDROP_TYPE,+ &backdrop as *const _ as _,+ 4,+ );+ }let empty = windows::Win32::Graphics::Gdi::CreateRectRgn(0, 0, 0, 0);let alpha = DWM_BLURBEHIND {dwFlags: DWM_BB_ENABLE | DWM_BB_BLURREGION,@@ -2224,3 +2228,59 @@ pub fn main_window_visible() -> bool {true}}++/// Read the real build without manifest-sensitive GetVersionEx behavior.+#[cfg(windows)]+pub fn windows_build() -> u32 {+ static BUILD: std::sync::OnceLock<u32> = std::sync::OnceLock::new();+ if development_overrides() {+ if let Ok(value) = std::env::var("VECTORDASH_TEST_WINDOWS_BUILD") {+ if let Ok(build) = value.parse() {+ return build;+ }+ }+ }+ *BUILD.get_or_init(|| unsafe {+ use windows::{+ Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress},+ core::{PCSTR, w},+ };+ #[repr(C)]+ struct Version {+ size: u32,+ major: u32,+ minor: u32,+ build: u32,+ platform: u32,+ service: [u16; 128],+ }+ let Ok(module) = GetModuleHandleW(w!("ntdll.dll")) else {+ return 0;+ };+ let Some(function) = GetProcAddress(module, PCSTR(c"RtlGetVersion".as_ptr().cast())) else {+ return 0;+ };+ let function: unsafe extern "system" fn(*mut Version) -> i32 =+ std::mem::transmute(function);+ let mut version = Version {+ size: std::mem::size_of::<Version>() as u32,+ major: 0,+ minor: 0,+ build: 0,+ platform: 0,+ service: [0; 128],+ };+ if function(&mut version) >= 0 {+ version.build+ } else {+ 0+ }+ })+}+#[cfg(not(windows))]+pub fn windows_build() -> u32 {+ 0+}+pub fn development_overrides() -> bool {+ cfg!(debug_assertions) || std::env::args().any(|a| a == "--allow-development-overrides")+}diff --git a/native/src/stability_tests.rs b/native/src/stability_tests.rsindex 189356b..e0dce77 100644--- a/native/src/stability_tests.rs+++ b/native/src/stability_tests.rs@@ -384,6 +384,13 @@ fn pdf_metadata_streaming_and_cancellation_preserve_readable_pages() {}).unwrap();assert_eq!(again.len(), 2);+ let mut resumed = vec![];+ crate::pdf::visit_from(&path, 2, false, false, &|| Ok(()), &mut |page, _, _| {+ resumed.push(page);+ Ok(())+ })+ .unwrap();+ assert_eq!(resumed, vec![2]);}#[test]diff --git a/native/src/vector_cache.rs b/native/src/vector_cache.rsindex 0c60419..7aecebb 100644--- a/native/src/vector_cache.rs+++ b/native/src/vector_cache.rs@@ -18,6 +18,9 @@ pub struct Matrix {pub groups: Vec<Group>,pub group_ids: Vec<usize>,pub values: Vec<f32>,+ pub halves: Vec<half::f16>,+ pub fp16: bool,+ inverse_norms: Vec<f32>,pub bytes: usize,}#[derive(Clone, Default)]@@ -35,7 +38,9 @@ impl Cache {db: &Connection,dimension: usize,profile: &str,+ precision: &str,) -> Result<Option<Arc<Matrix>>> {+ let fp16 = precision == "FP16";let limit = match profile {"Low memory" => 0,"Fast search" => 512 * 1024 * 1024,@@ -57,13 +62,12 @@ impl Cache {.inner.lock().map_err(|_| anyhow::anyhow!("Vector cache unavailable"))?;- if let Some(matrix) = lock- .as_ref()- .filter(|m| m.revision == revision && m.dimension == dimension && m.bytes <= limit)- {+ if let Some(matrix) = lock.as_ref().filter(|m| {+ m.revision == revision && m.dimension == dimension && m.bytes <= limit && m.fp16 == fp16+ }) {return Ok(Some(matrix.clone()));}- let(count,estimated):(usize,usize)=db.query_row("SELECT count(*),coalesce(sum(length(vector)+length(path)+length(kind)+length(channel)+64),0) FROM segment_vectors WHERE dimension=?1",[dimension],|r|Ok((r.get(0)?,r.get(1)?)))?;+ let(count,estimated):(usize,usize)=db.query_row("SELECT count(*),coalesce(sum(length(vector)/?2+length(path)+length(kind)+length(channel)+128),0) FROM segment_vectors WHERE dimension=?1",rusqlite::params![dimension, if fp16 {2} else {1}],|r|Ok((r.get(0)?,r.get(1)?)))?;if count == 0 || estimated > limit {return Ok(None);}@@ -73,7 +77,10 @@ impl Cache {ids: Vec::with_capacity(count),groups: vec![],group_ids: Vec::with_capacity(count),- values: Vec::with_capacity(count * dimension),+ values: Vec::with_capacity(if fp16 { 0 } else { count * dimension }),+ halves: Vec::with_capacity(if fp16 { count * dimension } else { 0 }),+ fp16,+ inverse_norms: Vec::with_capacity(if fp16 { count } else { 0 }),bytes: 0,};let mut lookup = HashMap::new();@@ -107,13 +114,24 @@ impl Cache {blob.len() == dimension * 4,"Invalid vector length in index");- matrix.values.extend(- blob.chunks_exact(4)- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])),- );+ let values = blob+ .chunks_exact(4)+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]));+ if fp16 {+ matrix.halves.extend(values.map(half::f16::from_f32));+ let norm = matrix.halves[matrix.halves.len() - dimension..]+ .iter()+ .map(|x| x.to_f32().powi(2))+ .sum::<f32>()+ .sqrt();+ anyhow::ensure!(norm.is_finite() && norm > 0.0, "Invalid cached embedding");+ matrix.inverse_norms.push(1.0 / norm);+ } else {+ matrix.values.extend(values);+ }matrix.ids.push(id);matrix.group_ids.push(group);- matrix.bytes += dimension * 4 + 16;+ matrix.bytes += dimension * if fp16 { 2 } else { 4 } + if fp16 { 20 } else { 16 };if matrix.bytes > limit {return Ok(None);}@@ -177,16 +195,41 @@ mod cache_tests {).unwrap();let cache = Cache::default();- assert!(cache.get(&c, 2, "Low memory").unwrap().is_none());- let a = cache.get(&c, 2, "Balanced").unwrap().unwrap();+ assert!(cache.get(&c, 2, "Low memory", "FP32").unwrap().is_none());+ let a = cache.get(&c, 2, "Balanced", "FP32").unwrap().unwrap();assert_eq!(a.ids.len(), 1);assert!(a.bytes <= 128 * 1024 * 1024);- let again = cache.get(&c, 2, "Balanced").unwrap().unwrap();+ let again = cache.get(&c, 2, "Balanced", "FP32").unwrap().unwrap();assert!(Arc::ptr_eq(&a, &again));Database::save_segments(&c, "C:\\note.txt", &[segment], &[vec![0.0, 1.0]], "second").unwrap();- let b = cache.get(&c, 2, "Balanced").unwrap().unwrap();+ let b = cache.get(&c, 2, "Balanced", "FP32").unwrap().unwrap();assert_ne!(a.revision, b.revision);assert_eq!(b.values, vec![0.0, 1.0]);}}++impl Matrix {+ pub fn score(&self, row: usize, query: &[f32]) -> f32 {+ let start = row * self.dimension;+ if self.fp16 {+ dot_half(&self.halves[start..start + self.dimension], query) * self.inverse_norms[row]+ } else {+ dot(&self.values[start..start + self.dimension], query)+ }+ }+}+pub fn dot_half(a: &[half::f16], b: &[f32]) -> f32 {+ use half::slice::HalfFloatSliceExt;+ let mut converted = [0.0f32; 1024];+ let mut result = 0.0;+ for (i, chunk) in a.chunks(1024).enumerate() {+ chunk.convert_to_f32_slice(&mut converted[..chunk.len()]);+ let start = i * 1024;+ result += dot(+ &converted[..chunk.len()],+ &b[start..(start + chunk.len()).min(b.len())],+ );+ }+ result+}diff --git a/native/src/worker.rs b/native/src/worker.rsindex 02004cc..88f648a 100644--- a/native/src/worker.rs+++ b/native/src/worker.rs@@ -12,6 +12,8 @@ use std::{pub struct Request {pub path: String,pub settings: Settings,+ #[serde(default)]+ pub start_page: u32,}pub fn worker_main() -> Result<()> {crate::platform::lower_integrity()?;@@ -19,8 +21,9 @@ pub fn worker_main() -> Result<()> {std::io::stdin().lock().read_line(&mut line)?;anyhow::ensure!(line.len() < 1024 * 1024, "Worker request too large");let request: Request = serde_json::from_str(&line)?;- let result = crate::content::stream(+ let result = crate::content::stream_from(Path::new(&request.path),+ request.start_page,&request.settings,&|| Ok(()),&mut |segment| {@@ -40,11 +43,30 @@ pub fn visit(s: &Settings,control: &Control,consume: &mut dyn FnMut(Segment) -> Result<()>,+) -> Result<()> {+ visit_checked(path, s, control, 0, &|| false, consume)+}+pub fn visit_checked(+ path: &Path,+ s: &Settings,+ control: &Control,+ start_page: u32,+ stopped: &dyn Fn() -> bool,+ consume: &mut dyn FnMut(Segment) -> Result<()>,) -> Result<()> {// Unit tests run a harness EXE, not the worker-capable application EXE.#[cfg(test)]{- return crate::content::stream(path, s, &|| control.file_checkpoint(), consume);+ return crate::content::stream_from(+ path,+ start_page,+ s,+ &|| {+ anyhow::ensure!(!stopped(), "Preparation stopped");+ control.file_checkpoint()+ },+ consume,+ );}let mut settings = s.clone();settings.llm_key.clear();@@ -66,6 +88,7 @@ pub fn visit(let request = Request {path: path.to_string_lossy().into_owned(),settings,+ start_page,};let mut input = child.stdin.take().context("Worker input unavailable")?;input.write_all(serde_json::to_string(&request)?.as_bytes())?;@@ -103,7 +126,8 @@ pub fn visit(let result = (|| -> Result<()> {loop {- control.check()?;+ anyhow::ensure!(!stopped(), "Preparation stopped");+ control.check_with(stopped)?;anyhow::ensure!(started.elapsed() < Duration::from_secs(900),"Parser exceeded 15-minute limit"diff --git a/packaging/README.md b/packaging/README.mdindex 43a02e1..45535f5 100644--- a/packaging/README.md+++ b/packaging/README.md@@ -1,11 +1,7 @@# Building the Windows installer-Run `./Build-Windows.ps1` in PowerShell on Windows with Python 3.14 installed. The script creates a build environment, bundles the application and its dependencies, verifies and sets up a portable Inno Setup compiler, and creates `dist/installer/VectorDash-Setup-0.2.23-x64.exe` plus its SHA-256 checksum.+Run `./Build-Rust.ps1` in PowerShell with the Rust MSVC toolchain and Visual Studio C++ build tools. It stages the native application and PDF runtime, builds the Inno Setup installer, and creates a portable ZIP and SHA-256 manifest under `dist/installer`.-For an existing Python environment, pass `-Python PATH`. Use `-SkipDependencies` only when its dependencies are already installed.+The current installer supports Windows 11 x64 and **Windows 10 version 2004/build 19041 or newer (beta)**. It installs per user and preserves settings, downloaded models and the index on uninstall. Models and optional tools are downloaded separately.-The installer targets Windows 11 x64, installs for the current user without administrator access, and includes Python, Qt and the media decoder. AI models and optional OCR tools are downloaded separately from Models & hardware. Uninstalling preserves downloaded models, settings and the search index.--For a packaged smoke test, run `dist/VectorDash/VectorDash.exe --smoke-test --smoke-report PATH/report.json`. This checks the bundled UI, image/PDF previews, indexing, search, startup command and media decoder without downloading models.--Build outputs are ignored by Git. Publish the installer and checksum as release assets.+Use `-SkipBuild` only after building the current native source. Validate artifacts with `native/scripts/release_gate.py --verify-only` before publication. Published release assets are authoritative; legacy Python packaging files are retained for migration/reference.diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.issindex 0141eb1..09e564c 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.25-beta.1+AppVersion=0.3.25-beta.2VersionInfoVersion=0.3.25.0AppPublisher=VectorDash contributorsAppPublisherURL=https://github.com/ampersandru/VectorDash@@ -12,9 +12,9 @@ DefaultGroupName=VectorDashPrivilegesRequired=lowestArchitecturesAllowed=x64compatibleArchitecturesInstallIn64BitMode=x64compatible-MinVersion=10.0.22000+MinVersion=10.0.19041OutputDir=..\dist\installer-OutputBaseFilename=VectorDash-Beta-Setup-0.3.25-beta.1-x64+OutputBaseFilename=VectorDash-Beta-Setup-0.3.25-beta.2-x64SetupIconFile=VectorDash.icoUninstallDisplayIcon={app}\VectorDash.exeLicenseFile=..\LICENSE