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
Prepare independent VectorDash Windows app with previews and local semantic search
ampersandrud83da3bcacfd
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..1cee19c--- /dev/null+++ b/.gitignore@@ -0,0 +1,9 @@+__pycache__/+*.py[cod]+.venv/+windows/.venv/+windows/.smoke/+*.local.png+*.local.json+.DS_Store+Thumbs.dbdiff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.mdnew file mode 100644index 0000000..c4fcac9--- /dev/null+++ b/ACKNOWLEDGEMENTS.md@@ -0,0 +1,15 @@+# Acknowledgements++VectorDash is inspired by [DigUp](https://github.com/ARahim3/DigUp), created by+Abdur Rahim. DigUp established the local semantic file-search approach that+inspired this Windows application. Thank you for publishing the project under+an open-source license.++VectorDash's Windows application is written in Python and Qt. It does not compile+or import DigUp's macOS Swift application. The original MIT copyright notice is+preserved in LICENSE. The earlier repository and development history are retained+in the [archived fork](https://github.com/ampersandru/VectorDash-legacy-fork).++VectorDash also uses EmbeddingGemma 2, llama.cpp, Qt/PySide6, NumPy, Pillow,+PyMuPDF, Tesseract, FFmpeg and imageio-ffmpeg. These projects, model downloads and+runtime distributions retain their own licenses and notices.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..3f0d374--- /dev/null+++ b/LICENSE@@ -0,0 +1,22 @@+MIT License++Copyright (c) 2026 Abdur Rahim+Copyright (c) 2026 VectorDash contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..e7c6f44--- /dev/null+++ b/README.md@@ -0,0 +1,162 @@+# VectorDash++**Find files on Windows 11 by describing what you remember.**++VectorDash searches the contents of your files, rather than relying only on their+names. Search for a dog in a photo, a topic in a podcast, a clause in a PDF, or an+error shown in a screenshot. Exact words, names and invoice numbers work too.++VectorDash is an independent Windows project inspired by+[DigUp](https://github.com/ARahim3/DigUp), created by Abdur Rahim. The Windows app+is written in Python and Qt. See [ACKNOWLEDGEMENTS.md](ACKNOWLEDGEMENTS.md) for credit.++## What you can find++| Search example | What opens |+| --- | --- |+| `images of dogs` | Photos matched by what is in the image |+| `payment declined error` | A screenshot, including text read from the image |+| `the clause about pets in the lease` | The matching PDF page, with matching words highlighted |+| `where they talk about sleep` | The matching part of a podcast or recording |+| `zebra in a video` | A sampled video moment showing the zebra |+| `INV-2026-00891` | Files containing that exact invoice number |+| `code: retry a failed call with backoff` | A function or source passage in an enabled project |++You can also search across languages. For example, an English description can+find a Bengali or Arabic note. The model supports more than 100 languages;+results depend on the language and the content.++## Get started++1. Install Python 3.12 or later if it is not already installed.+2. Run **Setup-VectorDash.cmd** once to install the app's dependencies.+3. Run **Run-VectorDash.cmd** to open VectorDash.+4. In **Models & hardware → Status**, choose the features you want. Choose your+ hardware and model quantization below, then click **Download, install and start**.+5. In **Sources**, add a drive or folder and click **Update index**.+6. Search for a file. Start with a small test folder to check the results.++The app can download llama-server, EmbeddingGemma 2, its image/audio encoder,+OCR tools and language packs. The media decoder is included with the app's+Python dependencies. Downloads can be resumed, and supplied checksums are verified.+A Windows permission prompt may appear when installing OCR.++**Q8_0** is the default model choice. You can select another available quantization+from the download list. Image and audio search need the matching encoder file.+You can use existing model and tool files instead of downloading them again.++## Search and preview++Select a result to see its preview on the right. Images, PDF pages, text, code and+media moments are supported in both the full app and the popup search window.+Media previews wait for you to press Play.++| Shortcut | Action |+| --- | --- |+| `Ctrl+Shift+Space` | Show quick search; change this shortcut in Settings |+| `Down`, then `Up` / `Down` | Move through search results |+| `Space` while a result is focused | Open a larger preview |+| `Enter` | Open the selected result |+| `Ctrl+C` while a result is focused | Copy the file for pasting into Explorer or apps that accept files |+| `Esc` | Dismiss quick search or close the larger preview |++**Show in Explorer** opens the folder and selects the actual file. **Copy path**+copies its location as text. Typing spaces in the search box still works normally.+If another app owns the shortcut, search and indexing still work; choose another+combination in Settings.++## Choose where and how to search++- Add individual folders or whole drives in **Sources**.+- Use a dedicated GPU, integrated GPU, or CPU and system memory.+- Choose an adapter from the detected device list. GPU support needs a compatible+ llama.cpp build; available adapters depend on your runtime and drivers.+- Enable code search only for project folders you choose. Git-ignored and common+ generated files are excluded. Source previews do not execute the code.+- Use **Scheduling** to update at a selected time, while the computer is idle, or+ when both conditions are met. CPU/GPU activity, user inactivity and AC power+ can be used as conditions. VectorDash must be running; it does not wake your PC.+- Start with Windows and choose whether closing the window hides it to the tray,+ minimizes it, or exits the app.++## Understand Status++The Status panel shows a right-aligned indicator for each component:++- **Green:** loaded or checked and ready to use.+- **Yellow:** installed, but not loaded or checked yet.+- **Red:** missing or unavailable.++Select exactly which components to set up. When they are already installed,+the main button becomes **Start**. It is disabled when the selected components+are ready. **Stop** unloads the local model and its encoder. **Cancel setup**+appears only while setup is running.++OCR adds exact text matching inside screenshots and scanned PDFs. It is separate+from the image encoder, which searches by what the image shows. Select OCR+language packs such as `eng`, `ben` or `ara` for the text you want to read.++## Local or remote models++In local mode, selected file content and queries stay on your computer. Internet+access is used for setup downloads. VectorDash uses EmbeddingGemma 2 through+llama-server for text, image and audio embeddings.++You can also connect to a remote llama-server. Select **Remote**, enter the server+URL, optional API key and the model identifier reported by that server, then save+and connect. The server needs EmbeddingGemma 2 in embedding mode and the matching+encoder for images/audio. Remote mode sends selected file content and queries to+that host. Install and stop remote models on the host itself.++## Indexing, speed and limits++Sources shows the number of indexed files and the current indexing activity.+Pause keeps the current job's progress. Cancel keeps the last completed index.+A red animated magnifying glass means indexing is active; purple means it is idle+or paused. File-specific errors are logged and skipped so other files can finish.++The index is stored in SQLite. Search combines meaning, full-text matches and+exact strings. Decoded vectors are cached in memory, and repeated searches reuse+query embeddings. New semantic searches still take time to run through the model.+An indexing request that is already using the model can also delay a new query.++Video search samples frames and scene changes, so a very brief event can be missed.+Audio search uses overlapping 30-second windows, so the match is an approximate+moment. OCR, multilingual matching and semantic results are not always exact.+Unsupported formats remain searchable by filename. Password-protected or damaged+files may be skipped. PDF and image highlights are preview overlays; originals+are not changed.++If you previously indexed with semantic search off, start the model and run+**Full rebuild** once. Rebuild after changing the model or encoder.++## Logs and troubleshooting++Open **Logs** to filter messages by Verbose, Info, Warning or Error. Open the app+log or model output from there when diagnosing a problem. Settings includes a+button to open the local data folder.++Settings, downloads and the index normally live in `%LOCALAPPDATA%\VectorDash`.+Older DigUp data is migrated automatically. Exit the old app before upgrading.+**Exit VectorDash** stops its model and helper processes. Closing to the tray keeps+background search and schedules available. Verified matching local servers are+also stopped on exit; remote servers continue running.++## Development and license++The app is in `windows/`. Install `windows/requirements.txt`, then run+`python windows/desktop.py`. Run the automated tests with:++```text+python -m unittest discover -s windows -p "test_*.py" -q+```++Native desktop checks are in `windows/qa_*.py`. Some media checks require their+optional local fixtures. `qa_search_benchmark.py` measures database/vector search+with 1,500 synthetic files; it excludes model inference and UI time.++VectorDash is available under the [MIT license](LICENSE). Credit also goes to+[DigUp](https://github.com/ARahim3/DigUp),+[EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2),+[llama.cpp](https://github.com/ggml-org/llama.cpp), Qt/PySide6, Tesseract and FFmpeg.+Downloaded tools and models keep their own licenses.diff --git a/Run-VectorDash.cmd b/Run-VectorDash.cmdnew file mode 100644index 0000000..6530f26--- /dev/null+++ b/Run-VectorDash.cmd@@ -0,0 +1,2 @@+@echo off+call "%~dp0windows\Run-VectorDash.cmd"diff --git a/Setup-VectorDash.cmd b/Setup-VectorDash.cmdnew file mode 100644index 0000000..7397c5e--- /dev/null+++ b/Setup-VectorDash.cmd@@ -0,0 +1,2 @@+@echo off+call "%~dp0windows\Setup-VectorDash.cmd"diff --git a/windows/README.md b/windows/README.mdnew file mode 100644index 0000000..b5796f2--- /dev/null+++ b/windows/README.md@@ -0,0 +1,3 @@+# VectorDash for Windows 11++See the [main README](../README.md) for setup, features, keyboard shortcuts and troubleshooting.diff --git a/windows/Run-VectorDash.cmd b/windows/Run-VectorDash.cmdnew file mode 100644index 0000000..a09e8fe--- /dev/null+++ b/windows/Run-VectorDash.cmd@@ -0,0 +1,14 @@+@echo off+cd /d "%~dp0"+if not exist ".venv\Scripts\pythonw.exe" (+ echo Run Setup-VectorDash.cmd once to install the desktop dependencies.+ pause+ exit /b 1+)+.venv\Scripts\python.exe -c "import numpy, PySide6.QtWidgets, PySide6.QtMultimedia, psutil, PIL, pymupdf, imageio_ffmpeg" >nul 2>&1+if errorlevel 1 (+ echo Desktop dependencies are missing. Run Setup-VectorDash.cmd.+ pause+ exit /b 1+)+start "" ".venv\Scripts\pythonw.exe" "%~dp0desktop.py"diff --git a/windows/Setup-VectorDash.cmd b/windows/Setup-VectorDash.cmdnew file mode 100644index 0000000..d7e1295--- /dev/null+++ b/windows/Setup-VectorDash.cmd@@ -0,0 +1,15 @@+@echo off+cd /d "%~dp0"+if not exist ".venv\Scripts\python.exe" (+ python -m venv .venv+ if errorlevel 1 goto failed+)+.venv\Scripts\python.exe -m pip install -r requirements.txt+if errorlevel 1 goto failed+echo Setup complete. Open Run-VectorDash.cmd to launch the app.+pause+exit /b 0+:failed+echo Setup failed. Install Python 3.12 or later and try again.+pause+exit /b 1diff --git a/windows/assets/check.png b/windows/assets/check.pngnew file mode 100644index 0000000..a3016ebBinary files /dev/null and b/windows/assets/check.png differdiff --git a/windows/content.py b/windows/content.pynew file mode 100644index 0000000..0bcfef5--- /dev/null+++ b/windows/content.py@@ -0,0 +1,325 @@+"""Local document, visual, audio and code segments with navigable locations."""+from dataclasses import dataclass, field+from pathlib import Path+from array import array+import math+import csv+import ast+import io+import json+import os+import re+import shutil+import subprocess+import process_lifecycle+import tempfile+import threading+import wave+from PIL import Image, ImageOps+import pymupdf+import imageio_ffmpeg++IMAGE = {'.jpg','.jpeg','.png','.webp','.bmp','.tif','.tiff','.gif'}+AUDIO = {'.mp3','.wav','.flac','.m4a','.aac','.ogg','.opus','.wma'}+VIDEO = {'.mp4','.mkv','.mov','.avi','.webm','.m4v','.wmv','.mpeg','.mpg'}+CODE = {'.py','.js','.jsx','.ts','.tsx','.java','.kt','.go','.rs','.c','.h','.cpp','.hpp','.cs','.swift','.rb','.php','.sh','.ps1','.sql','.ipynb'}+EXCLUDE = {'node_modules','vendor','dist','build','target','.git','.venv','venv','__pycache__','bin','obj'}++@dataclass+class Segment:+ kind: str = 'text'+ text: str = ''+ page: int = 0+ seconds: float = -1+ end: float = -1+ line: int = 0+ end_line: int = 0+ symbol: str = ''+ boxes: list = field(default_factory=list)+ media: bytes = b''+ def location(self):+ if self.page:+ return f'Page {self.page}'+ if self.seconds >= 0:+ return f'{int(self.seconds)//60}:{int(self.seconds)%60:02d}'+ if self.line:+ return f'{self.symbol + " · " if self.symbol else ""}Lines {self.line}–{self.end_line}'+ return {'image':'Photo / screenshot','filename':'Filename only'}.get(self.kind,'Document text')+ def metadata(self):+ return json.dumps({k:v for k,v in vars(self).items() if k not in ('media','text','kind')},ensure_ascii=False)++def chunks(text, size=2400, overlap=240):+ text=text.strip()+ for offset in range(0,len(text),size-overlap):+ yield text[offset:offset+size]+ if offset+size >= len(text):+ break++def ocr_program(settings):+ configured=settings.get('ocr_path','').strip()+ if configured:+ return configured if Path(configured).is_file() else None+ found=shutil.which('tesseract')+ if found:+ return found+ for root in (os.environ.get('LOCALAPPDATA',''),os.environ.get('ProgramFiles','C:/Program Files')):+ for folder in ('Programs/Tesseract-OCR','Tesseract-OCR'):+ candidate=Path(root)/folder/'tesseract.exe'+ if candidate.is_file():+ return str(candidate)+ return None++def ocr(image, settings):+ program=ocr_program(settings)+ if not program:+ return '',[]+ buffer=io.BytesIO()+ image.save(buffer,format='PNG')+ args=[program,'stdin','stdout','-l',settings.get('ocr_languages','eng') or 'eng','-c','tessedit_create_tsv=1']+ if settings.get('ocr_data'):+ args+=['--tessdata-dir',str(Path(settings['ocr_data']))]+ # Use literal subprocess arguments; wrappers can leave quotes inside Windows+ # data paths containing spaces. PNG stdin also avoids temporary image files.+ result=process_lifecycle.run(args,input=buffer.getvalue(),capture_output=True,timeout=90,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if result.returncode:+ raise RuntimeError('OCR failed: '+result.stderr.decode('utf-8',errors='replace')[-1000:])+ words=[]+ boxes=[]+ rows=csv.DictReader(io.StringIO(result.stdout.decode('utf-8',errors='replace')),delimiter='\t',quoting=csv.QUOTE_NONE)+ for row in rows:+ word=row.get('text','') or ''+ if word.strip() and float(row['conf'])>=0:+ words.append(word)+ boxes.append([word,int(row['left']),int(row['top']),int(row['width']),int(row['height'])])+ return ' '.join(words),boxes++def image_bytes(image):+ image=ImageOps.exif_transpose(image).convert('RGB')+ image.thumbnail((1024,1024))+ buffer=io.BytesIO()+ image.save(buffer,format='JPEG',quality=90)+ return buffer.getvalue()++def ffmpeg(settings):+ configured=settings.get('ffmpeg_path','').strip()+ return configured or shutil.which('ffmpeg') or imageio_ffmpeg.get_ffmpeg_exe()++def process(args):+ return process_lifecycle.popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))++def audio_segments(path,settings,checkpoint):+ """Decode one bounded PCM stream; overlapping windows retain speech context."""+ proc=process([ffmpeg(settings),'-nostdin','-v','error','-i',str(path),'-vn','-ac','1','-ar','16000','-f','s16le','pipe:1'])+ errors=[]+ reader=threading.Thread(target=lambda:errors.append(proc.stderr.read()),daemon=True)+ reader.start()+ window=30*16000*2+ step=25*16000*2+ buffer=b''+ start=0.0+ try:+ while True:+ checkpoint()+ chunk=proc.stdout.read(min(65536,window-len(buffer)))+ if chunk:+ buffer+=chunk+ if len(buffer)==window or (not chunk and buffer):+ output=io.BytesIO()+ with wave.open(output,'wb') as wav:+ wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(16000); wav.writeframes(buffer)+ samples=array('h',buffer[:len(buffer)//2*2])+ rms=math.sqrt(sum(sample*sample for sample in samples)/max(1,len(samples)))+ if rms>=20:+ yield Segment(kind='audio',seconds=start,end=start+len(buffer)/32000,media=output.getvalue())+ if not chunk:+ break+ buffer=buffer[step:]+ start+=25+ elif not chunk:+ break+ proc.wait(timeout=15)+ reader.join(timeout=2)+ if proc.returncode:+ raise RuntimeError('Audio decode failed: '+b''.join(errors).decode(errors='replace')[-1000:])+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.stdout.close(); proc.stderr.close(); proc.wait()++def video_segments(path,settings,checkpoint):+ """Frames every three seconds and on scene changes, retaining original PTS."""+ import queue+ stamps=queue.Queue()+ errors=[]+ interval=max(1,int(settings.get('video_interval',3)))+ filters=f"select='isnan(prev_selected_t)+gte(t-prev_selected_t,{interval})+gt(scene,0.35)',scale='min(1024,iw)':-2,showinfo"+ proc=process([ffmpeg(settings),'-nostdin','-v','info','-i',str(path),'-an','-vf',filters,'-fps_mode','vfr','-f','image2pipe','-vcodec','mjpeg','pipe:1'])+ def stderr():+ for raw in iter(proc.stderr.readline,b''):+ line=raw.decode(errors='replace')+ if 'showinfo' in line and (match:=re.search(r'pts_time:([\d.eE+-]+)',line)):+ stamps.put(float(match[1]))+ errors.append(line)+ if len(errors)>40:+ errors.pop(0)+ reader=threading.Thread(target=stderr,daemon=True)+ reader.start()+ buffer=b''+ try:+ while True:+ checkpoint()+ chunk=proc.stdout.read(65536)+ buffer+=chunk+ while True:+ start=buffer.find(b'\xff\xd8')+ end=buffer.find(b'\xff\xd9',max(0,start+2))+ if start<0 or end<0:+ break+ frame=buffer[start:end+2]+ buffer=buffer[end+2:]+ checkpoint()+ try:+ seconds=stamps.get(timeout=10)+ except queue.Empty:+ raise RuntimeError('Video frame timestamp unavailable; refusing an inaccurate location')+ yield Segment(kind='video',seconds=max(0,seconds),end=max(0,seconds)+interval,media=frame)+ if not chunk:+ break+ if len(buffer)>32*1024*1024:+ raise RuntimeError('Video decoder frame exceeds the supported buffer')+ proc.wait(timeout=15)+ reader.join(timeout=2)+ if proc.returncode:+ raise RuntimeError('Video decode failed: '+''.join(errors)[-1000:])+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.stdout.close(); proc.stderr.close(); proc.wait()++def extract(path,settings,read_text,checkpoint):+ suffix=path.suffix.lower()+ if suffix in CODE:+ # Code content is never included unless its separate search is enabled.+ yield Segment(kind='filename')+ elif suffix in IMAGE and settings.get('index_images',True):+ with Image.open(path) as original:+ image=ImageOps.exif_transpose(original).convert('RGB')+ text,boxes=ocr(image,settings) if settings.get('ocr_enabled',True) else ('',[])+ yield Segment(kind='image',text=text,boxes=boxes,media=image_bytes(image) if settings['semantic'] else b'')+ elif suffix=='.pdf':+ with pymupdf.open(path) as doc:+ if doc.needs_pass:+ raise ValueError('Password-protected PDF')+ for number,page in enumerate(doc):+ checkpoint()+ text=page.get_text(sort=True)+ if not text.strip():+ scale=min(2,2048/max(page.rect.width,page.rect.height,1))+ pixmap=page.get_pixmap(matrix=pymupdf.Matrix(scale,scale),alpha=False)+ image=Image.frombytes('RGB',[pixmap.width,pixmap.height],pixmap.samples)+ text,boxes=ocr(image,settings) if settings.get('ocr_enabled',True) else ('',[])+ # Store OCR rectangles in PDF points for highlights.+ boxes=[[word,x/scale,y/scale,w/scale,h/scale] for word,x,y,w,h in boxes]+ yield Segment(kind='pdf',text=text,page=number+1,boxes=boxes,media=image_bytes(image) if settings['semantic'] else b'')+ else:+ for passage in chunks(text):+ yield Segment(kind='pdf',text=passage,page=number+1)+ elif suffix in AUDIO and settings.get('index_audio',True) and settings['semantic']:+ yield from audio_segments(path,settings,checkpoint)+ elif suffix in VIDEO and settings.get('index_video',True) and settings['semantic']:+ yield from video_segments(path,settings,checkpoint)+ if settings.get('index_audio',True):+ # Silent videos legitimately have no audio stream.+ probe=process([ffmpeg(settings),'-nostdin','-i',str(path)])+ _,info=probe.communicate(timeout=30)+ if b'Audio:' in info:+ for segment in audio_segments(path,settings,checkpoint):+ segment.kind='video_audio'+ yield segment+ else:+ text=read_text(path)+ for passage in chunks(text):+ yield Segment(text=passage)+ if not text:+ yield Segment(kind='filename')++def project_files(root):+ root=Path(root).resolve()+ try:+ top=process_lifecycle.run(['git','-C',str(root),'rev-parse','--show-toplevel'],capture_output=True,timeout=10,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if top.returncode==0:+ repo=Path(top.stdout.decode().strip()).resolve()+ result=process_lifecycle.run(['git','-C',str(repo),'ls-files','--cached','--others','--exclude-standard','-z'],capture_output=True,timeout=30,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if result.returncode:+ raise RuntimeError('Cannot read project files with Git')+ for name in result.stdout.decode('utf-8',errors='replace').split('\0'):+ if name:+ path=(repo/name).resolve()+ if path.is_relative_to(root) and path.is_file() and not path.is_symlink():+ yield path+ return+ except FileNotFoundError:+ pass+ for base,dirs,names in os.walk(root,followlinks=False):+ dirs[:]=[d for d in dirs if d.lower() not in EXCLUDE and not d.startswith('.') and not (Path(base)/d).is_symlink() and not (Path(base)/d).is_junction()]+ for name in names:+ yield Path(base)/name++def code_segments(path):+ if path.suffix.lower() not in CODE or path.stat().st_size>2*1024*1024:+ return+ text=path.read_text(encoding='utf-8',errors='replace')+ if path.suffix.lower()=='.ipynb':+ notebook=json.loads(text)+ for index,cell in enumerate(notebook.get('cells',[])):+ if cell.get('cell_type')=='code':+ source=''.join(cell.get('source',[]))+ for passage in chunks(source):+ yield Segment(kind='code',text=passage,symbol=f'Notebook cell {index+1}')+ return+ lines=text.splitlines()+ if path.suffix.lower()=='.py':+ try:+ tree=ast.parse(text)+ nodes=[node for node in ast.walk(tree) if isinstance(node,(ast.FunctionDef,ast.AsyncFunctionDef))]+ if nodes:+ for node in nodes:+ start=min([node.lineno]+[d.lineno for d in node.decorator_list])+ for passage in chunks('\n'.join(lines[start-1:node.end_lineno])):+ yield Segment(kind='code',text=passage,line=start,end_line=node.end_lineno,symbol=node.name)+ return+ except SyntaxError:+ pass+ if path.suffix.lower() in {'.js','.jsx','.ts','.tsx','.java','.kt','.go','.rs','.c','.h','.cpp','.hpp','.cs','.swift','.php'}:+ # Mask comments and strings without moving source offsets. Balanced braces+ # locate named functions/methods rather than returning the entire file.+ masked=re.sub(r'//[^\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|`(?:\\.|[^`\\])*`',lambda m:re.sub(r'[^\n]',' ',m.group()),text)+ pattern=r'(?:\b(?:function|fn|func|fun)\s+([\w]+)\s*\([^)]*\)[^{;]*|\b(?:const|let|var)\s+([\w]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>\s*|\b([\w]+)\s*\([^;{}]*\)\s*(?:async\s*)?(?:throws\s+[\w., ]+)?\s*)\{'+ found=False+ for match in re.finditer(pattern,masked):+ symbol=next(name for name in match.groups() if name)+ if symbol in {'if','for','while','switch','catch','with','synchronized'}:+ continue+ start=match.start()+ opening=match.end()-1+ depth=1+ end=opening+1+ while end<len(masked) and depth:+ depth+=(masked[end]=='{')-(masked[end]=='}')+ end+=1+ if depth:+ continue+ first=text.count('\n',0,start)+1+ last=text.count('\n',0,end)+1+ for passage in chunks('\n'.join(lines[first-1:last])):+ yield Segment(kind='code',text=passage,line=first,end_line=last,symbol=symbol)+ found=True+ if found:+ return+ # Keep source positions even in languages without a local parser.+ for start in range(0,len(lines),50):+ end=min(len(lines),start+60)+ body='\n'.join(lines[start:end])+ match=re.search(r'(?:function\s+|fn\s+|func\s+|def\s+)([\w]+)',body)+ for passage in chunks(body):+ yield Segment(kind='code',text=passage,line=start+1,end_line=end,symbol=match[1] if match else '')diff --git a/windows/desktop.py b/windows/desktop.pynew file mode 100644index 0000000..9307bea--- /dev/null+++ b/windows/desktop.py@@ -0,0 +1,1755 @@+"""Modern VectorDash Windows desktop, quick search, setup and scheduling."""+import logging+import math+import ctypes+from ctypes import wintypes+from datetime import datetime+import hashlib+import socket as net_socket+import json+import os+from pathlib import Path+import subprocess+import process_lifecycle+import sys+import threading+import time+import urllib.request+import psutil+from PySide6.QtCore import Qt, QObject, Signal, QTimer, QTime, QAbstractNativeEventFilter, QFileInfo, QEvent, QRectF, QMimeData, QUrl+from PySide6.QtGui import QIcon, QKeySequence, QShortcut, QCursor, QPainter, QColor, QPen, QPixmap+from PySide6.QtNetwork import QLocalServer, QLocalSocket+from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QLineEdit, QListWidget, QListWidgetItem, QStackedWidget, QComboBox, QCheckBox, QSpinBox, QTimeEdit, QFileDialog, QMessageBox, QFrame, QSystemTrayIcon, QMenu, QProgressBar, QScrollArea, QFileIconProvider, QAbstractItemView, QPlainTextEdit, QSplitter)+from engine import Engine, Settings, SearchResult, verify_server_model+from previews import Preview, SelectionPreview+from vectordash_core import command, embed, embedding_request, server_url+from windows_integration import GlobalHotkey, HOTKEY_ID, set_startup, reveal_in_explorer, parse_devices, idle_seconds, gpu_utilization+from scheduling import schedule_due, idle_allowed, next_run+from setup_runtime import catalogs, install_runtime, install_model+from setup_tools import install_ocr, install_ffmpeg+from content import ocr_program, ffmpeg++class Events(QObject):+ status = Signal(str)+ indexed = Signal(str, str, bool, str)+ searched = Signal(int, object, str)+ devices = Signal(object, str)+ catalog = Signal(object, object, str)+ installed = Signal(str, str, str)+ progress = Signal(str, object, object)+ metrics = Signal(object)+ model = Signal(str)+ log = Signal(str, str)+ tools_ready = Signal(object)++def app_icon(active=False, phase=0):+ pixmap=QPixmap(64,64)+ pixmap.fill(Qt.GlobalColor.transparent)+ painter=QPainter(pixmap)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ painter.setBrush(QColor('#d83b50' if active else '#6757e8'))+ painter.setPen(Qt.PenStyle.NoPen)+ painter.drawRoundedRect(2,2,60,60,17,17)+ if active:+ painter.translate(32,32)+ painter.rotate(math.sin(phase)*18)+ painter.translate(-32,-32)+ painter.setPen(QPen(QColor('white'),5))+ painter.setBrush(Qt.BrushStyle.NoBrush)+ painter.drawEllipse(17,14,25,25)+ painter.drawLine(38,37,49,49)+ painter.end()+ return QIcon(pixmap)++def search_icon():+ pixmap=QPixmap(24,24)+ pixmap.fill(Qt.GlobalColor.transparent)+ painter=QPainter(pixmap)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ painter.setPen(QPen(QColor('#8573ff'),3))+ painter.setBrush(Qt.BrushStyle.NoBrush)+ painter.drawEllipse(3,3,12,12)+ painter.drawLine(14,14,21,21)+ painter.end()+ return QIcon(pixmap)++def label(text, style=''):+ result=QLabel(text)+ result.setTextFormat(Qt.TextFormat.PlainText)+ result.setWordWrap(True)+ if style:+ result.setObjectName(style)+ return result++def button(text, callback, primary=False):+ result=QPushButton(text)+ result.clicked.connect(callback)+ if primary:+ result.setObjectName('primary')+ return result++def row(*widgets):+ frame=QWidget()+ layout=QHBoxLayout(frame)+ layout.setContentsMargins(0,0,0,0)+ for widget in widgets:+ layout.addWidget(widget)+ return frame++def card(title, subtitle=''):+ frame=QFrame()+ frame.setObjectName('card')+ layout=QVBoxLayout(frame)+ layout.setContentsMargins(22,18,22,18)+ layout.setSpacing(12)+ layout.addWidget(label(title,'cardTitle'))+ if subtitle:+ layout.addWidget(label(subtitle,'muted'))+ return frame,layout++def scroll_settings(widget,event):+ event.ignore()+ parent=widget.parentWidget()+ while parent is not None and not isinstance(parent,QScrollArea):+ parent=parent.parentWidget()+ if parent is not None:+ QApplication.sendEvent(parent.viewport(),event)++class ScrollSafeSpinBox(QSpinBox):+ def wheelEvent(self,event):+ scroll_settings(self,event)++class ScrollSafeTimeEdit(QTimeEdit):+ def wheelEvent(self,event):+ scroll_settings(self,event)++class ScrollSafeComboBox(QComboBox):+ def wheelEvent(self,event):+ scroll_settings(self,event)++class SearchEdit(QLineEdit):+ def __init__(self, results):+ super().__init__()+ self.results=results+ self.setPlaceholderText('Describe a file, or search for exact words…')+ self.setObjectName('searchInput')+ def keyPressEvent(self,event):+ if event.key()==Qt.Key.Key_Down and self.results.count():+ self.results.setCurrentRow(0)+ self.results.setFocus()+ else:+ super().keyPressEvent(event)++class Results(QListWidget):+ def __init__(self, owner):+ super().__init__()+ self.owner=owner+ self.setObjectName('results')+ self.setSpacing(6)+ self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)+ self.icons=QFileIconProvider()+ self.itemActivated.connect(lambda item:owner.open_file(item.data(Qt.ItemDataRole.UserRole)))+ def keyPressEvent(self,event):+ if event.key()==Qt.Key.Key_Space and event.modifiers()==Qt.KeyboardModifier.NoModifier:+ self.owner.preview_result(self.selected_result())+ event.accept()+ elif event.matches(QKeySequence.StandardKey.Copy):+ self.owner.copy_file(self.selected_path())+ event.accept()+ else:+ super().keyPressEvent(event)++ def populate(self, results):+ self.clear()+ for result in results:+ score,path,snippet = result+ item=QListWidgetItem()+ item.setData(Qt.ItemDataRole.UserRole,result if isinstance(result,SearchResult) else path)+ item.setToolTip(path)+ widget=QWidget()+ layout=QHBoxLayout(widget)+ layout.setContentsMargins(12,10,12,10)+ icon=QLabel()+ icon.setPixmap(self.icons.icon(QFileInfo(path)).pixmap(32,32))+ layout.addWidget(icon)+ content=QVBoxLayout()+ content.setSpacing(3)+ content.addWidget(label(Path(path).name,'resultTitle'))+ content.addWidget(label((result.location()+' · ' if isinstance(result,SearchResult) else '')+path,'muted'))+ if snippet:+ content.addWidget(label(snippet,'snippet'))+ layout.addLayout(content,1)+ item.setSizeHint(widget.sizeHint())+ self.addItem(item)+ self.setItemWidget(item,widget)+ if self.count():+ self.setCurrentRow(0)+ def selected_path(self):+ item=self.currentItem()+ value=item.data(Qt.ItemDataRole.UserRole) if item else None+ return value.path if isinstance(value,SearchResult) else value+ def selected_result(self):+ item=self.currentItem()+ return item.data(Qt.ItemDataRole.UserRole) if item else None++class HotkeyFilter(QAbstractNativeEventFilter):+ def __init__(self, callback):+ super().__init__()+ self.callback=callback+ def nativeEventFilter(self,event_type,message):+ if os.name=='nt':+ msg=wintypes.MSG.from_address(int(message))+ if msg.message==0x0312 and msg.wParam==HOTKEY_ID:+ self.callback()+ return True,0+ return False,0++class QuickSearch(QWidget):+ def __init__(self, owner):+ super().__init__(None,Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint)+ self.owner=owner+ self.setWindowTitle('VectorDash Quick Search')+ self.setWindowIcon(owner.windowIcon())+ self.setObjectName('quickSearch')+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)+ self.setAutoFillBackground(False)+ self.resize(1060,570)+ layout=QVBoxLayout(self)+ layout.setContentsMargins(20,20,20,16)+ layout.addWidget(row(label('VectorDash','cardTitle'),button('Open full app',self.full)))+ self.results=Results(owner)+ self.input=SearchEdit(self.results)+ self.input.addAction(search_icon(),QLineEdit.ActionPosition.LeadingPosition)+ layout.addWidget(self.input)+ self.preview=SelectionPreview(self)+ split=QSplitter(Qt.Orientation.Horizontal)+ split.addWidget(self.results)+ split.addWidget(self.preview)+ split.setSizes([600,420])+ layout.addWidget(split,1)+ self.results.currentItemChanged.connect(lambda current,previous:self.preview.show_result(self.results.selected_result()))+ self.hint=label('↑ ↓ select Space preview Ctrl+C copy file Enter open Esc dismiss','muted')+ layout.addWidget(self.hint)+ self.timer=QTimer(self)+ self.timer.setSingleShot(True)+ self.timer.setInterval(120)+ self.timer.timeout.connect(lambda:owner.request_search(self.input.text()))+ self.input.textChanged.connect(lambda:self.changed())+ self.input.returnPressed.connect(lambda:owner.open_file(self.results.selected_result()) if self.results.count() else owner.request_search(self.input.text()))+ QShortcut(QKeySequence('Escape'),self,activated=self.hide)+ def paintEvent(self,event):+ painter=QPainter(self)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ dark=self.owner.settings['theme']=='Dark' or (self.owner.settings['theme']=='System' and QApplication.styleHints().colorScheme()==Qt.ColorScheme.Dark)+ painter.setBrush(QColor('#20212c' if dark else '#ffffff'))+ painter.setPen(QPen(QColor('#8573ff'),5))+ painter.drawRoundedRect(QRectF(self.rect()).adjusted(3,3,-3,-3),20,20)++ def hideEvent(self,event):+ self.preview.clear()+ super().hideEvent(event)++ def changed(self):+ self.results.clear()+ self.owner.search_sequence+=1+ self.timer.start()++ def full(self):+ self.owner.query.setText(self.input.text())+ self.hide()+ self.owner.show_main()+ def summon(self):+ screen=QApplication.screenAt(QCursor.pos()) or QApplication.primaryScreen()+ area=screen.availableGeometry()+ self.resize(min(1060,area.width()-40),min(570,area.height()-80))+ self.move(area.center().x()-self.width()//2,area.top()+max(40,int(area.height()*.22)))+ self.show()+ self.raise_()+ self.activateWindow()+ self.input.setFocus()+ self.input.selectAll()+ self.owner.request_search(self.input.text())+ def event(self,event):+ if event.type()==QEvent.Type.WindowDeactivate and self.isVisible():+ self.hide()+ return super().event(event)++class UiLogHandler(logging.Handler):+ def __init__(self, events):+ super().__init__()+ self.events=events+ def emit(self, record):+ self.events.log.emit(record.levelname,self.format(record))++class Desktop(QMainWindow):+ def __init__(self, settings, ipc=None):+ super().__init__()+ self.store=settings+ process_lifecycle.reopen()+ self.settings=settings.values+ self.settings['semantic']=True+ self.model_generation=0+ self.model_loaded=False+ self.loaded_modalities={}+ self.tool_ready={}+ self.engine=Engine(settings.home)+ self.events=Events()+ self.indexing=False+ self.automatic_active=False+ self.installing=False+ self.collecting=False+ self.metrics={'cpu':None,'gpu':None,'idle':None,'on_ac':None}+ self.metrics_time=0+ self.schedule_retry=0+ self.attached_server=None+ self.model_process=None+ self.model_log=None+ self.download_cancel=threading.Event()+ self.search_sequence=0+ self.pending_search=None+ self.search_running=False+ self.log_records=[]+ existing_log=self.store.home/'vectordash.log'+ if existing_log.exists():+ for line in existing_log.read_text(encoding='utf-8',errors='replace')[-100000:].splitlines():+ level=next((name for name in ('DEBUG','INFO','WARNING','ERROR','CRITICAL') if ' '+name+' ' in line),'INFO')+ self.log_records.append((level,line))+ self.log_records=self.log_records[-2000:]+ self.probing_model=False+ self.icon_phase=0+ self.widgets={}+ self.runtimes=[]+ self.models=[]+ self.shutting_down=False+ self.setWindowTitle('VectorDash')+ self.setWindowIcon(app_icon())+ self.resize(1120,820)+ self.setMinimumSize(850,620)+ self.events.tools_ready.connect(self.tools_status_finished)+ self.events.log.connect(self.append_log)+ self.logger=logging.getLogger('vectordash')+ self.logger.setLevel(logging.DEBUG)+ self.log_handler=UiLogHandler(self.events)+ self.log_file_handler=logging.FileHandler(self.store.home/'vectordash.log',encoding='utf-8')+ self.log_file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))+ self.logger.addHandler(self.log_handler)+ self.logger.addHandler(self.log_file_handler)+ self.events.status.connect(self.set_status)+ self.events.indexed.connect(self.index_finished)+ self.events.searched.connect(self.search_finished)+ self.events.devices.connect(self.devices_finished)+ self.events.catalog.connect(self.catalog_finished)+ self.events.installed.connect(self.install_finished)+ self.events.progress.connect(self.download_progress)+ self.events.metrics.connect(self.metrics_finished)+ self.events.model.connect(self.model_status)+ self.build()+ self.launch(self.warm_search_cache)+ self.quick=QuickSearch(self)+ self.hotkey=GlobalHotkey()+ self.hotkey_filter=HotkeyFilter(self.toggle_quick)+ QApplication.instance().installNativeEventFilter(self.hotkey_filter)+ self.tray=QSystemTrayIcon(self.windowIcon(),self)+ menu=QMenu()+ menu.addAction('Quick search',self.toggle_quick)+ menu.addAction('Open VectorDash',lambda:self.show_main())+ menu.addSeparator()+ menu.addAction('Pause / resume indexing',self.pause_index)+ menu.addAction('Update index',lambda:self.start_index())+ menu.addAction('Settings',lambda:self.show_main(4))+ menu.addSeparator()+ menu.addAction('Exit VectorDash',self.exit_app)+ self.tray.setContextMenu(menu)+ self.tray.setToolTip('VectorDash • local file search')+ self.tray.activated.connect(lambda reason:self.toggle_quick() if reason==QSystemTrayIcon.ActivationReason.Trigger else None)+ self.tray.show()+ if ipc:+ ipc.newConnection.connect(lambda:self.accept_ipc(ipc))+ self.apply_theme()+ try:+ self.hotkey.register(self.settings['hotkey'])+ if self.settings['startup']:+ set_startup(True)+ except (OSError,ValueError) as error:+ self.set_status('Quick-search shortcut unavailable. You can still use VectorDash; choose another shortcut in Settings.')+ self.update_hotkey_status()+ self.clock=QTimer(self)+ self.clock.setInterval(15000)+ self.clock.timeout.connect(self.tick)+ self.clock.start()+ self.process_timer=QTimer(self)+ self.process_timer.setInterval(2000)+ self.process_timer.timeout.connect(self.check_model_exit)+ self.process_timer.start()+ self.icon_timer=QTimer(self)+ self.icon_timer.setInterval(120)+ self.icon_timer.timeout.connect(self.animate_index_icon)+ self.icon_timer.start()+ QApplication.instance().aboutToQuit.connect(self.cleanup)+ QTimer.singleShot(1000,self.refresh_component_status)+ QApplication.styleHints().colorSchemeChanged.connect(lambda:self.apply_theme() if self.settings['theme']=='System' else None)+ QTimer.singleShot(500,self.tick)+ if self.settings['auto_model']:+ QTimer.singleShot(800,self.start_model)++ def launch(self, work):+ threading.Thread(target=work,daemon=True).start()++ def warm_search_cache(self):+ try:+ self.engine.cached_index('files')+ if self.settings.get('code_enabled'):+ self.engine.cached_index('code')+ except Exception as error:+ self.logger.debug('Search cache warm-up: %s',error)++ def build(self):+ central=QWidget()+ root=QHBoxLayout(central)+ root.setContentsMargins(0,0,0,0)+ root.setSpacing(0)+ sidebar=QFrame()+ sidebar.setObjectName('sidebar')+ sidebar.setFixedWidth(205)+ nav=QVBoxLayout(sidebar)+ nav.setContentsMargins(20,30,16,18)+ nav.setSpacing(12)+ nav.addWidget(label('VectorDash','brand'))+ nav.addWidget(label('Find what you remember.','muted'))+ nav.addSpacing(28)+ self.navigation=QListWidget()+ self.navigation.setObjectName('navigation')+ self.navigation.addItems(['Search','Sources','Models & hardware','Scheduling','Settings','Logs'])+ self.navigation.setSpacing(6)+ nav.addWidget(self.navigation,1)+ nav.addWidget(label('On your PC.\nYour files stay local.','muted'))+ root.addWidget(sidebar)+ body=QWidget()+ layout=QVBoxLayout(body)+ layout.setContentsMargins(28,26,28,16)+ layout.setSpacing(18)+ self.stack=QStackedWidget()+ layout.addWidget(self.stack,1)+ self.status=label('Ready','muted')+ layout.addWidget(self.status)+ root.addWidget(body,1)+ self.setCentralWidget(central)+ self.navigation.currentRowChanged.connect(self.stack.setCurrentIndex)+ self.search_page()+ self.sources_page()+ self.models_page()+ self.schedule_page()+ self.settings_page()+ self.logs_page()+ self.navigation.setCurrentRow(0)++ def page(self,title,description):+ page=QWidget()+ layout=QVBoxLayout(page)+ layout.setContentsMargins(0,0,0,0)+ layout.setSpacing(18)+ layout.addWidget(label(title,'heading'))+ layout.addWidget(label(description,'muted'))+ scroll=QScrollArea()+ scroll.setWidgetResizable(True)+ scroll.setFrameShape(QFrame.Shape.NoFrame)+ content=QWidget()+ inner=QVBoxLayout(content)+ inner.setContentsMargins(0,0,8,0)+ inner.setSpacing(18)+ scroll.setWidget(content)+ layout.addWidget(scroll,1)+ self.stack.addWidget(page)+ return inner++ def field(self,layout,key,title,kind='text',options=None,minimum=0,maximum=100):+ if kind!='check':+ layout.addWidget(label(title))+ value=self.settings.get(key)+ if kind=='combo':+ widget=ScrollSafeComboBox()+ widget.addItems(options)+ widget.setCurrentText(value)+ elif kind=='check':+ widget=QCheckBox(title)+ widget.setChecked(bool(value))+ elif kind=='spin':+ widget=ScrollSafeSpinBox()+ widget.setRange(minimum,maximum)+ widget.setValue(value)+ elif kind=='time':+ widget=ScrollSafeTimeEdit(QTime.fromString(value,'HH:mm'))+ widget.setDisplayFormat('hh:mm AP')+ else:+ widget=QLineEdit(str(value or ''))+ layout.addWidget(widget)+ self.widgets[key]=widget+ return widget++ def search_page(self):+ page=QWidget()+ layout=QVBoxLayout(page)+ layout.setContentsMargins(0,0,0,0)+ layout.setSpacing(16)+ layout.addWidget(label('What are you looking for?','heading'))+ self.shortcut_hint=label(f'Describe a file, or press {self.settings["hotkey"]} from any app.','muted')+ layout.addWidget(self.shortcut_hint)+ self.results=Results(self)+ self.query=SearchEdit(self.results)+ layout.addWidget(self.query)+ self.search_hint=label('Type to search your indexed files.','muted')+ layout.addWidget(self.search_hint)+ self.result_preview=SelectionPreview(self)+ split=QSplitter(Qt.Orientation.Horizontal)+ split.addWidget(self.results)+ split.addWidget(self.result_preview)+ split.setSizes([560,400])+ layout.addWidget(split,1)+ self.results.currentItemChanged.connect(lambda current,previous:self.result_preview.show_result(self.results.selected_result()))+ layout.addWidget(row(button('Open',lambda:self.open_file(self.results.selected_result()),True),button('Show in Explorer',self.reveal),button('Copy path',self.copy_path)))+ self.stack.addWidget(page)+ self.search_timer=QTimer(self)+ self.search_timer.setSingleShot(True)+ self.search_timer.setInterval(120)+ self.search_timer.timeout.connect(lambda:self.request_search(self.query.text()))+ self.query.textChanged.connect(self.query_changed)+ self.query.returnPressed.connect(lambda:self.open_file(self.results.selected_result()) if self.results.count() else self.request_search(self.query.text()))++ def sources_page(self):+ layout=self.page('Your sources','Choose the drives and folders VectorDash can read.')+ frame,inside=card('Index status','Pause keeps your progress. Cancel keeps the previous completed index.')+ self.index_count=label(f'{self.engine.indexed_file_count():,} indexed files','cardTitle')+ inside.addWidget(self.index_count)+ self.source_status=label('Ready','muted')+ self.source_progress=QProgressBar()+ self.source_progress.setValue(0)+ inside.addWidget(self.source_status)+ inside.addWidget(self.source_progress)+ inside.addWidget(row(button('Pause / resume',self.pause_index),button('Cancel indexing',self.engine.cancel.set)))+ layout.addWidget(frame)+ frame,inside=card('Drives and folders','Hidden/system folders, cloud placeholders and common secrets are skipped.')+ self.sources=QListWidget()+ self.sources.setMinimumHeight(180)+ self.sources.addItems(self.settings['roots'])+ inside.addWidget(self.sources)+ self.drives=ScrollSafeComboBox()+ if os.name=='nt':+ mask=ctypes.windll.kernel32.GetLogicalDrives()+ self.drives.addItems([f'{chr(65+i)}:\\' for i in range(26) if mask & (1<<i)])+ inside.addWidget(row(button('Add folder…',self.add_folder,True),self.drives,button('Add drive',lambda:self.add_source(self.drives.currentText())),button('Remove',self.remove_source)))+ layout.addWidget(frame)+ frame,inside=card('Search file contents','Photos, audio and video require semantic search and the matching vision + audio encoder. PDFs retain their page numbers.')+ for key,title in [('index_images','Photos and screenshots'),('index_audio','Audio and video soundtracks'),('index_video','Video frames')]:+ self.field(inside,key,title,'check')+ self.field(inside,'video_interval','Seconds between sampled video frames','spin',minimum=1,maximum=30)+ inside.addWidget(label('Scene changes are also sampled. A brief event between frames can be missed; use 1 second for finer coverage. Audio uses overlapping 30-second windows.','muted'))+ inside.addWidget(label('OCR, decoder and encoder setup are in Models & hardware.','muted'))+ layout.addWidget(frame)+ frame,inside=card('Code search','Opt in, choose project folders, then prefix your query with code:. Git ignored files are excluded.')+ self.field(inside,'code_enabled','Enable code search','check')+ self.code_sources=QListWidget()+ self.code_sources.addItems(self.settings.get('code_roots',[]))+ self.code_sources.setMinimumHeight(100)+ inside.addWidget(self.code_sources)+ inside.addWidget(row(button('Add project…',self.add_project),button('Remove project',lambda:self.code_sources.takeItem(self.code_sources.currentRow()))))+ inside.addWidget(button('Save content settings',self.save,True))+ layout.addWidget(frame)+ frame,inside=card('Indexing','Updates reuse unchanged files. A full rebuild recalculates every vector.')+ inside.addWidget(row(button('Update index',lambda:self.start_index(),True),button('Full rebuild',lambda:self.start_index(force=True)),button('Pause / resume',self.pause_index),button('Stop',self.engine.cancel.set)))+ self.index_status=label('No indexing task running.','muted')+ inside.addWidget(self.index_status)+ layout.addWidget(frame)+ layout.addStretch()++ def add_project(self):+ path=QFileDialog.getExistingDirectory(self,'Choose a project folder')+ if path and path not in [self.code_sources.item(i).text() for i in range(self.code_sources.count())]:+ self.code_sources.addItem(path)++ def models_page(self):+ layout=self.page('Models & hardware','Choose the features you want, then start your local or remote model.')+ frame,inside=card('Status','Downloads and installs the selected runtime, model, encoder, OCR language packs and media decoder. Choose hardware and quantization below first.')+ self.setup_progress=QProgressBar()+ self.setup_progress.setValue(0)+ inside.addWidget(self.setup_progress)+ self.setup_choices={}+ self.component_status={}+ components=[('server','Local model runtime',True),('model','Text search model',True),('projector','Photos, audio and video encoder',True),('ocr','Exact text in screenshots and scanned PDFs',self.settings.get('ocr_enabled',True)),('ffmpeg','Audio and video decoder',True)]+ saved=self.settings.get('setup_components',{})+ for key,title,default in components:+ choice=QCheckBox(title)+ choice.setChecked(saved.get(key,default))+ status=label('Checking…')+ status.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)+ self.setup_choices[key]=choice+ self.component_status[key]=status+ inside.addWidget(row(choice,status))+ choice.toggled.connect(self.update_tool_state)+ self.setup_button=button('Download, install and start',self.setup_all,True)+ self.setup_stop=button('Stop',self.stop_model)+ self.setup_cancel=button('Cancel setup',self.download_cancel.set)+ self.setup_cancel.hide()+ inside.addWidget(row(self.setup_button,self.setup_stop,button('Refresh status',self.refresh_component_status),self.setup_cancel))+ layout.addWidget(frame)+ frame,inside=card('Server connection','Remote mode sends indexed content and search queries to your chosen server.')+ self.field(inside,'server_mode','Embedding server','combo',['Local','Remote'])+ self.field(inside,'remote_url','Remote server URL, e.g. http://192.168.1.10:8787')+ self.field(inside,'remote_model_id','Remote model identifier (as reported by /props)')+ self.field(inside,'remote_key','Remote API key (optional)')+ self.widgets['remote_key'].setEchoMode(QLineEdit.EchoMode.Password)+ inside.addWidget(row(button('Save connection',self.save),button('Connect / check status',self.start_model)))+ layout.addWidget(frame)+ frame,inside=card('Local inference','Keep your existing runtime and model, or download them below.')+ self.field(inside,'mode','Run on','combo',['CPU / system RAM','Dedicated GPU','Integrated GPU'])+ self.devices=ScrollSafeComboBox()+ self.devices.addItem(self.settings['device'] or 'Select an adapter',self.settings['device'])+ inside.addWidget(label('Inference device'))+ inside.addWidget(row(self.devices,button('Refresh devices',self.refresh_devices)))+ for key,title in [('server','llama-server executable'),('model','Embedding model (GGUF)'),('projector','Vision + audio encoder (matching mmproj GGUF)')]:+ self.field(inside,key,title)+ inside.addWidget(button('Browse…',lambda checked=False,k=key:self.browse(k)))+ self.field(inside,'auto_model','Start model automatically when VectorDash starts','check')+ inside.addWidget(row(button('Save hardware settings',self.save,True),button('Start model',self.start_model),button('Stop model',self.stop_model),button('Test embedding',self.test_model)))+ self.model_state=label('Model readiness is checked when starting or testing.','muted')+ inside.addWidget(self.model_state)+ layout.addWidget(frame)+ frame,inside=card('Download and set up','Runtime: ggml-org/llama.cpp · Model: ggml-org/embeddinggemma-2-GGUF')+ inside.addWidget(button('Load available downloads',self.load_catalog))+ self.runtime_choice=ScrollSafeComboBox()+ self.quant_choice=ScrollSafeComboBox()+ self.quant_choice.addItem('Q8_0 (recommended)','Q8_0')+ self.quant_choice.addItem('BF16','BF16')+ if 'BF16' in Path(self.settings.get('model','')).name.upper():+ self.quant_choice.setCurrentIndex(1)+ inside.addWidget(label('Windows runtime'))+ inside.addWidget(self.runtime_choice)+ inside.addWidget(label('EmbeddingGemma 2 quantization'))+ inside.addWidget(self.quant_choice)+ self.download_summary=label('Choose a quantization and click download; catalogs load automatically. Load available downloads to choose a runtime build.','muted')+ inside.addWidget(self.download_summary)+ self.runtime_choice.currentIndexChanged.connect(self.catalog_summary)+ self.quant_choice.currentIndexChanged.connect(self.catalog_summary)+ self.quant_choice.currentIndexChanged.connect(self.update_tool_state)+ self.download_bar=QProgressBar()+ self.download_bar.setValue(0)+ inside.addWidget(self.download_bar)+ inside.addWidget(row(button('Install runtime',lambda:self.install('server'),True),button('Download model + encoder',lambda:self.install('model'),True),button('Encoder only',lambda:self.install('projector')),button('Cancel download',self.download_cancel.set)))+ inside.addWidget(label('Downloads are resumable. Models are checked against SHA-256. Runtime checksums are verified when supplied by GitHub. Existing paths remain available.','muted'))+ layout.addWidget(frame)+ frame,inside=card('OCR and media tools','Optional OCR provides exact screenshot text. FFmpeg decodes audio/video and is included with VectorDash.')+ self.field(inside,'ocr_enabled','Extract exact text from screenshots and scanned PDFs','check')+ self.field(inside,'ocr_path','Tesseract executable (blank = detect installed copy)')+ inside.addWidget(button('Browse OCR executable…',lambda:self.browse('ocr_path')))+ self.field(inside,'ocr_languages','OCR language packs, e.g. eng+ben+ara')+ self.field(inside,'ocr_data','OCR language data folder (set automatically during setup)')+ inside.addWidget(button('Download and set up OCR + languages',lambda:self.install_tool('ocr'),True))+ self.field(inside,'ffmpeg_path','FFmpeg executable (blank = installed or included copy)')+ inside.addWidget(row(button('Browse FFmpeg…',lambda:self.browse('ffmpeg_path')),button('One-click FFmpeg setup',lambda:self.install_tool('ffmpeg'),True)))+ inside.addWidget(row(button('Save tool settings',self.save),button('Cancel remaining downloads',self.download_cancel.set)))+ self.tool_state=label('','muted')+ inside.addWidget(self.tool_state)+ inside.addWidget(label('The model GGUF handles text. Its mmproj file supplies EmbeddingGemma’s own image/audio encoders. Tesseract is optional for exact OCR; FFmpeg is only needed for audio/video.','muted'))+ layout.addWidget(frame)+ self.update_tool_state()+ layout.addStretch()++ def schedule_page(self):+ layout=self.page('Scheduling','Keep your index current while VectorDash runs in the background.')+ frame,inside=card('When to update','Scheduled updates reuse unchanged files and never overlap.')+ self.field(inside,'schedule_mode','Schedule','combo',['Manual','At selected time','When idle','Time + idle'])+ self.field(inside,'schedule_time','Time (this PC’s local time)','time')+ dayrow=QWidget()+ days=QHBoxLayout(dayrow)+ days.setContentsMargins(0,0,0,0)+ self.day_checks=[]+ for i,name in enumerate(['Mon','Tue','Wed','Thu','Fri','Sat','Sun']):+ check=QCheckBox(name)+ check.setChecked(i in self.settings['schedule_days'])+ self.day_checks.append(check)+ days.addWidget(check)+ inside.addWidget(dayrow)+ self.field(inside,'idle_interval','Minimum minutes between idle updates','spin',minimum=5,maximum=1440)+ inside.addWidget(button('Save schedule',self.save,True))+ layout.addWidget(frame)+ frame,inside=card('Idle and power conditions','Idle conditions apply to When idle and Time + idle. AC power applies to every automatic run.')+ self.field(inside,'check_user_idle','Require keyboard and mouse inactivity','check')+ self.field(inside,'idle_minutes','Keyboard/mouse inactive for minutes','spin',minimum=1,maximum=120)+ self.field(inside,'check_cpu','Require low CPU usage','check')+ self.field(inside,'cpu_limit','CPU usage below (%)','spin',minimum=1,maximum=100)+ self.field(inside,'check_gpu','Require low GPU usage (all monitored GPU engines)','check')+ self.field(inside,'gpu_limit','GPU usage below (%)','spin',minimum=1,maximum=100)+ self.field(inside,'ac_only','Automatic indexing only on AC power','check')+ self.field(inside,'max_run_minutes','Maximum automatic run duration (minutes)','spin',minimum=5,maximum=1440)+ inside.addWidget(label('GPU monitoring depends on Windows performance counters. If unavailable, a GPU-conditioned schedule waits and explains why. Idle jobs pause between chunks when activity resumes.','muted'))+ inside.addWidget(button('Save conditions',self.save,True))+ layout.addWidget(frame)+ frame,inside=card('Schedule status')+ self.schedule_status=label('Checking conditions…','muted')+ self.telemetry=label('Collecting usage…','muted')+ self.next_status=label('Next run: manual only','muted')+ self.last_status=label('Last successful update: '+(self.settings['last_success'] or 'Never'),'muted')+ inside.addWidget(self.schedule_status)+ inside.addWidget(self.telemetry)+ inside.addWidget(self.next_status)+ inside.addWidget(self.last_status)+ self.history=QListWidget()+ self.history.setMinimumHeight(100)+ self.history.addItems(self.settings.get('schedule_history',[]))+ inside.addWidget(self.history)+ inside.addWidget(button('Update now',lambda:self.start_index()))+ inside.addWidget(label('Missed runs are handled once after resume. VectorDash must be running; it does not wake a sleeping PC.','muted'))+ layout.addWidget(frame)+ layout.addStretch()++ def settings_page(self):+ layout=self.page('Settings','Make VectorDash fit the way you use Windows.')+ frame,inside=card('Model status')+ self.settings_model_state=label(self.model_state.text(),'muted')+ inside.addWidget(self.settings_model_state)+ inside.addWidget(button('Refresh model status',self.probe_model))+ layout.addWidget(frame)+ frame,inside=card('Appearance and shortcut')+ self.field(inside,'theme','Appearance','combo',['System','Light','Dark'])+ self.field(inside,'hotkey','Global quick-search shortcut')+ self.shortcut_state=label('','muted')+ inside.addWidget(self.shortcut_state)+ inside.addWidget(label('Use Ctrl, Alt, Shift or Win plus Space, a letter, digit or function key. Conflicts are reported.','muted'))+ layout.addWidget(frame)+ frame,inside=card('Startup and window behavior')+ self.field(inside,'startup','Start VectorDash when I sign in to Windows','check')+ self.field(inside,'start_hidden','Start hidden in the system tray at sign-in','check')+ self.field(inside,'close_behavior','When I close the window','combo',['Hide to tray','Minimize to taskbar','Exit'])+ self.field(inside,'minimize_behavior','When I minimize the window','combo',['Taskbar','Tray'])+ inside.addWidget(label('The tray icon provides Search, Pause/resume, Settings and Exit. Closing to tray keeps schedules and the hotkey available.','muted'))+ layout.addWidget(frame)+ layout.addWidget(button('Apply settings',self.save,True))+ frame,inside=card('Local data')+ inside.addWidget(label(str(self.store.home),'muted'))+ inside.addWidget(button('Open data folder',lambda:self.open_file(str(self.store.home))))+ inside.addWidget(button('Exit VectorDash',self.exit_app))+ layout.addWidget(frame)+ layout.addStretch()++ def read_widgets(self):+ values=dict(self.settings)+ for key,widget in self.widgets.items():+ if isinstance(widget,QCheckBox):+ values[key]=widget.isChecked()+ elif isinstance(widget,QComboBox):+ values[key]=widget.currentText()+ elif isinstance(widget,QSpinBox):+ values[key]=widget.value()+ elif isinstance(widget,QTimeEdit):+ values[key]=widget.time().toString('HH:mm')+ else:+ values[key]=widget.text().strip()+ values['semantic']=True+ values['setup_components']={key:choice.isChecked() for key,choice in self.setup_choices.items()}+ values['roots']=[self.sources.item(i).text() for i in range(self.sources.count())]+ values['code_roots']=[self.code_sources.item(i).text() for i in range(self.code_sources.count())]+ values['device']=self.devices.currentData() or ''+ values['schedule_days']=[i for i,check in enumerate(self.day_checks) if check.isChecked()]+ return values++ def save(self, quiet=False):+ values=self.read_widgets()+ if values.get('server_mode')=='Remote':+ from urllib.parse import urlparse+ endpoint=urlparse(values.get('remote_url',''))+ if endpoint.scheme not in ('http','https') or not endpoint.hostname:+ self.error('Enter a complete http:// or https:// remote server URL.')+ return False+ if values['schedule_mode'] in ('At selected time','Time + idle') and not values['schedule_days']:+ self.error('Select at least one scheduling day.')+ return False+ old_shortcut=self.settings['hotkey']+ try:+ if values['hotkey']!=old_shortcut:+ self.hotkey.register(values['hotkey'])+ if values['startup']!=self.settings['startup']:+ set_startup(values['startup'])+ except (ValueError,OSError) as error:+ if self.hotkey.current!=old_shortcut:+ try:+ self.hotkey.register(old_shortcut)+ except (OSError,ValueError):+ pass+ self.error(str(error))+ return False+ schedule_keys=['schedule_mode','schedule_time','schedule_days']+ if any(values[key]!=self.settings[key] for key in schedule_keys):+ values['schedule_enabled_at']=datetime.now().isoformat()+ values['last_schedule_slot']=''+ self.schedule_retry=0+ if self.automatic_active:+ self.engine.cancel.set()+ self.settings=values+ self.store.values=values+ self.store.save()+ self.apply_theme()+ self.update_tool_state()+ self.update_hotkey_status()+ if not quiet:+ self.set_status('Settings saved')+ return True++ def update_hotkey_status(self):+ if self.hotkey.current:+ self.shortcut_state.setText('Shortcut active: '+self.hotkey.current)+ self.shortcut_hint.setText('Describe a file, or press '+self.hotkey.current+' from any app.')+ else:+ self.shortcut_state.setText('Shortcut unavailable: another app is using it. Choose a different combination and Apply settings. Search and indexing still work.')+ self.shortcut_hint.setText('Describe a file. Quick-search shortcut unavailable; change it in Settings.')++ def apply_theme(self):+ theme=self.settings['theme']+ dark=theme=='Dark' or (theme=='System' and QApplication.styleHints().colorScheme()==Qt.ColorScheme.Dark)+ bg='#14151d' if dark else '#f5f6fa'+ surface='#20212c' if dark else '#ffffff'+ side='#191a24' if dark else '#eceef6'+ text='#eceef8' if dark else '#202239'+ muted='#a8acc2' if dark else '#646b85'+ border='#35384b' if dark else '#dfe3ef'+ hover='#2c2f42' if dark else '#e8e7fd'+ tick_icon=(Path(__file__).parent/'assets'/'check.png').as_posix()+ css=f'''+ QWidget {{font-family: 'Segoe UI'; font-size: 13px; color: {text};}}+ QMainWindow, QScrollArea, QStackedWidget {{background: {bg};}}+ QScrollArea > QWidget > QWidget {{background: {bg};}}+ #sidebar {{background: {side}; border-right: 1px solid {border};}}+ #brand {{font-size: 29px; font-weight: 700; color: #8573ff;}}+ #heading {{font-size: 28px; font-weight: 600;}}+ #cardTitle {{font-size: 17px; font-weight: 600;}}+ #muted {{color: {muted}; font-size: 12px;}}+ #card {{background: {surface}; border: 1px solid {border}; border-radius: 12px;}}+ #card QWidget {{background: transparent;}}+ QPushButton {{background: {surface}; border: 1px solid {border}; padding: 9px 14px; border-radius: 7px;}}+ QPushButton:hover {{background: {hover};}}+ QPushButton#primary {{background: #6757e8; color: white; border-color: #6757e8;}}+ QPushButton#primary:hover {{background: #7868f2;}}+ QPushButton:disabled, QPushButton#primary:disabled {{background: {border}; color: {muted}; border-color: {border};}}+ QLineEdit, QComboBox, QSpinBox, QTimeEdit {{background: {surface}; border: 1px solid {border}; border-radius: 7px; padding: 8px; selection-background-color: #6757e8;}}+ QLineEdit:focus {{border-color: #8573ff;}}+ QComboBox QAbstractItemView {{background: {surface}; color: {text}; selection-background-color: {hover}; border: 1px solid {border};}}+ #searchInput {{font-size: 18px; padding: 16px; border-radius: 11px;}}+ QListWidget {{background: {surface}; border: 1px solid {border}; border-radius: 8px; outline: none;}}+ QListWidget::item {{padding: 7px; border-radius: 6px;}}+ QListWidget::item:selected {{background: {hover}; color: {text};}}+ #navigation {{background: transparent; border: none; font-size: 14px;}}+ #navigation::item {{padding: 13px 10px;}}+ #navigation::item:selected {{background: {hover}; color: #8573ff;}}+ #results {{background: transparent; border: none;}}+ #results::item {{background: {surface}; border: 1px solid {border}; padding: 0;}}+ #results::item:selected {{border-color: #8573ff; background: {hover};}}+ #resultTitle {{font-weight: 600; font-size: 14px;}}+ #snippet {{color: {muted}; font-size: 12px;}}+ #quickSearch {{background: transparent; border: none;}}+ QCheckBox {{spacing: 8px; padding: 3px;}}+ QCheckBox::indicator {{width: 16px; height: 16px; border: 1px solid {border}; border-radius: 4px; background: {surface};}}+ QCheckBox::indicator:checked {{background: #6757e8; border-color: #6757e8; image: url("{tick_icon}");}}+ QProgressBar {{border: 1px solid {border}; border-radius: 6px; text-align: center; height: 18px;}}+ QProgressBar::chunk {{background: #6757e8; border-radius: 5px;}}+ QScrollBar:vertical {{background: transparent; width: 10px; margin: 2px;}}+ QScrollBar:horizontal {{background: transparent; height: 10px; margin: 2px;}}+ QScrollBar::handle:vertical {{background: #8573ff; border-radius: 4px; min-height: 32px;}}+ QScrollBar::handle:horizontal {{background: #8573ff; border-radius: 4px; min-width: 32px;}}+ QScrollBar::handle:hover {{background: #6757e8;}}+ QScrollBar::add-line, QScrollBar::sub-line {{width: 0px; height: 0px; border: none;}}+ QScrollBar::add-page, QScrollBar::sub-page {{background: transparent;}}+ QMenu {{background: {surface}; border: 1px solid {border}; padding: 6px;}}+ QMenu::item {{padding: 8px 20px;}}+ QMenu::item:selected {{background: {hover};}}+ '''+ QApplication.instance().setStyleSheet(css)++ def error(self,text):+ self.set_status(text)+ QMessageBox.warning(self,'VectorDash',text)++ def set_status(self,text):+ self.status.setText(text)+ if self.indexing:+ self.index_status.setText(text)+ self.source_status.setText(text)+ self.logger.log(logging.WARNING if text.startswith('Skipped ') else logging.ERROR if 'failed' in text.lower() else logging.DEBUG if text.startswith('Reading ') else logging.INFO,text)++ def show_main(self,index=None):+ if index is not None:+ self.navigation.setCurrentRow(index)+ self.showNormal()+ self.raise_()+ self.activateWindow()+ if index in (None,0):+ self.query.setFocus()++ def toggle_quick(self):+ if self.quick.isVisible():+ self.quick.hide()+ else:+ self.quick.summon()++ def accept_ipc(self,server):+ socket=server.nextPendingConnection()+ if socket:+ def received():+ if socket.readAll().data()!=b'startup':+ self.quick.summon()+ socket.disconnectFromServer()+ socket.readyRead.connect(received)+ if socket.bytesAvailable():+ received()+ socket.disconnected.connect(socket.deleteLater)++ def add_folder(self):+ self.add_source(QFileDialog.getExistingDirectory(self,'Choose a folder'))++ def add_source(self,path):+ if path and path.casefold() not in [self.sources.item(i).text().casefold() for i in range(self.sources.count())]:+ self.sources.addItem(str(Path(path).absolute()))+ self.settings['roots']=[self.sources.item(i).text() for i in range(self.sources.count())]+ self.store.save()++ def remove_source(self):+ index=self.sources.currentRow()+ if index>=0:+ self.sources.takeItem(index)+ self.settings['roots']=[self.sources.item(i).text() for i in range(self.sources.count())]+ self.store.save()+ self.set_status('Source removed. Update the index to remove its results.')++ def start_index(self,force=False,scheduled=False,slot=''):+ if self.installing:+ self.set_status('Finish setup before indexing')+ return+ if self.indexing:+ self.set_status('An indexing task is already running')+ return+ if not scheduled and not self.save(quiet=True):+ return+ if not self.settings['roots'] and not (self.settings.get('code_enabled') and self.settings.get('code_roots')):+ self.set_status('Add a folder, drive or enabled code project before indexing')+ return+ self.engine.cancel.clear()+ self.engine.paused.clear()+ self.indexing=True+ self.source_progress.setRange(0,0)+ self.automatic_active=scheduled+ snapshot=dict(self.settings)+ self.set_status('Checking selected sources…')+ started=time.monotonic()+ def condition():+ if scheduled:+ rules=self.settings+ if rules['schedule_mode']=='Manual':+ raise InterruptedError('Automatic schedule disabled; previous index retained')+ if time.monotonic()-started>rules['max_run_minutes']*60:+ raise InterruptedError('Automatic run reached its time limit; previous index retained')+ if time.monotonic()-self.metrics_time>45:+ return False+ if rules['schedule_mode'] in ('When idle','Time + idle'):+ return idle_allowed(rules,self.metrics)[0]+ if rules['ac_only']:+ return self.metrics.get('on_ac') is True+ return True+ def work():+ try:+ result=self.engine.index(snapshot,self.events.status.emit,condition,force)+ self.events.indexed.emit(result,slot,True,'Scheduled' if scheduled else 'Manual')+ except Exception as error:+ self.events.indexed.emit(str(error),slot,False,'Scheduled' if scheduled else 'Manual')+ self.launch(work)++ def index_finished(self,message,slot,success,origin):+ self.indexing=False+ self.source_progress.setRange(0,100)+ self.source_progress.setValue(100 if success else 0)+ self.source_status.setText(message)+ self.index_count.setText(f'{self.engine.indexed_file_count():,} indexed files')+ if success:+ self.launch(self.warm_search_cache)+ self.automatic_active=False+ self.engine.paused.clear()+ self.index_status.setText(message)+ self.set_status(message)+ if not success:+ self.logger.error('Indexing stopped: %s',message)+ now=datetime.now().isoformat(timespec='seconds')+ if success:+ self.settings['last_success']=now+ if slot:+ self.settings['last_schedule_slot']=slot+ self.last_status.setText('Last successful update: '+now)+ else:+ self.schedule_retry=time.monotonic()+300+ entry=f'{now} · {origin} · {"Complete" if success else "Stopped/failed"} · {message}'+ self.settings['schedule_history']=[entry]+self.settings.get('schedule_history',[])[:19]+ self.history.clear()+ self.history.addItems(self.settings['schedule_history'])+ self.store.save()+ if self.query.text():+ self.request_search(self.query.text())++ def pause_index(self):+ if not self.indexing:+ self.set_status('No indexing task running')+ return+ if self.engine.paused.is_set():+ self.engine.paused.clear()+ self.set_status('Indexing resumed')+ else:+ self.engine.paused.set()+ self.set_status('Indexing paused; search remains available')++ def query_changed(self):+ self.results.clear()+ self.search_sequence+=1+ self.search_timer.start()++ def request_search(self,query):+ self.search_sequence+=1+ self.pending_search=(self.search_sequence,query,dict(self.settings))+ if not self.search_running:+ self.run_search()++ def run_search(self):+ if not self.pending_search:+ return+ sequence,query,settings=self.pending_search+ self.pending_search=None+ self.search_running=True+ self.search_hint.setText('Searching…')+ self.quick.hint.setText('Searching…')+ def work():+ try:+ self.events.searched.emit(sequence,self.engine.search(query,settings),'')+ except Exception as error:+ self.events.searched.emit(sequence,[],str(error))+ self.launch(work)++ def search_finished(self,sequence,results,error):+ self.search_running=False+ if sequence==self.search_sequence:+ self.results.populate(results)+ self.quick.results.populate(results)+ self.search_hint.setText(error or f'{len(results)} results · Enter to open')+ self.quick.hint.setText(error or f'{len(results)} results · ↑ ↓ select · Enter open · Esc dismiss')+ if error:+ self.set_status(error)+ self.run_search()++ def open_file(self,path):+ if not path:+ return+ try:+ if isinstance(path,SearchResult):+ result=path+ from content import CODE+ if Path(result.path).suffix.lower() in CODE and result.kind!='code':+ result.kind='code'+ result.line=result.end_line=1+ if result.page or result.seconds>=0 or result.kind in ('image','code'):+ preview=Preview(result,self)+ preview.show()+ self.quick.hide()+ return+ path=result.path+ os.startfile(path)+ self.quick.hide()+ except Exception as error:+ self.error(str(error))++ def preview_result(self,result):+ if not result:+ return+ try:+ if not isinstance(result,SearchResult):+ result=SearchResult(0,str(result),'')+ preview=Preview(result,self)+ preview.show()+ self.quick.hide()+ except Exception as error:+ self.error('Preview unavailable: '+str(error))++ def copy_file(self,path):+ if not path:+ return+ if not Path(path).is_file():+ self.set_status('This file is no longer available to copy.')+ return+ mime=QMimeData()+ mime.setUrls([QUrl.fromLocalFile(str(Path(path).resolve()))])+ # Windows drop effect COPY; Qt supplies CF_HDROP for these file URLs.+ mime.setData('application/x-qt-windows-mime;value="Preferred DropEffect"',(1).to_bytes(4,'little'))+ QApplication.clipboard().setMimeData(mime)+ self.set_status('File copied. Paste it in Explorer or another app that accepts files.')++ def reveal(self):+ if path:=self.results.selected_path():+ try:+ reveal_in_explorer(path)+ except OSError as error:+ self.error(str(error))++ def copy_path(self):+ if path:=self.results.selected_path():+ QApplication.clipboard().setText(path)+ self.set_status('Path copied')++ def browse(self,key):+ path,_=QFileDialog.getOpenFileName(self,'Choose '+key,'','Executable (*.exe)' if key in ('server','ocr_path','ffmpeg_path') else 'GGUF model (*.gguf)')+ if path:+ self.widgets[key].setText(path)++ def refresh_devices(self):+ path=self.widgets['server'].text().strip()+ self.set_status('Detecting inference devices…')+ def work():+ try:+ result=subprocess.run([path,'--list-devices'],capture_output=True,text=True,timeout=30,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if result.returncode:+ raise RuntimeError((result.stderr or result.stdout)[-1500:])+ output=result.stdout+'\n'+result.stderr+ self.events.devices.emit(parse_devices(output),output)+ except Exception as error:+ self.events.devices.emit([],str(error))+ self.launch(work)++ def devices_finished(self,devices,output):+ previous=self.devices.currentData()+ self.devices.clear()+ self.devices.addItem('CPU / system RAM (no GPU offload)','')+ for identifier,description in devices:+ self.devices.addItem(f'{identifier} — {description}',identifier)+ index=self.devices.findData(previous)+ self.devices.setCurrentIndex(max(0,index))+ self.set_status(f'{len(devices)} device(s) detected. Select an adapter and save.' if devices else 'No GPU devices detected: '+output[-500:])++ def start_model(self):+ if self.indexing:+ self.set_status('Stop indexing before changing the running model')+ return+ if not self.save(quiet=True):+ return+ if self.settings.get('server_mode')=='Remote':+ self.probe_model()+ return+ if self.model_process and self.model_process.poll() is None:+ if self.model_process.args==command(self.settings):+ self.set_status('The model is already running')+ return+ self.stop_model()+ try:+ if not Path(self.settings['server']).is_file() or not Path(self.settings['model']).is_file():+ raise ValueError('Choose or download a runtime and model first.')+ if self.settings.get('projector') and not Path(self.settings['projector']).is_file():+ raise ValueError('The selected vision/audio encoder does not exist. Download it or choose its mmproj GGUF file.')+ with net_socket.socket() as probe:+ occupied=probe.connect_ex(('127.0.0.1',8787))==0+ if occupied:+ try:+ verify_server_model(dict(self.settings,semantic=True))+ self.attach_local_server()+ self.model_status('Model: loaded · connected to existing local server')+ return+ except Exception as error:+ raise ValueError('Port 8787 is already occupied. Stop the existing server before starting a new model. '+str(error)) from error+ self.model_log=open(self.store.home/'model.log','w',encoding='utf-8')+ self.model_process=process_lifecycle.popen(command(self.settings),stdout=self.model_log,stderr=self.model_log,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ self.model_state.setText('Loading the model…')+ process=self.model_process+ def wait_ready():+ for _ in range(90):+ if self.model_process is not process:+ return+ if process.poll() is not None:+ self.events.model.emit('Model exited. Open the data folder and inspect model.log.')+ return+ try:+ with urllib.request.urlopen('http://127.0.0.1:8787/health',timeout=1) as response:+ if json.load(response).get('status')=='ok':+ self.events.model.emit('loaded · local embedding server ready')+ return+ except Exception:+ pass+ time.sleep(1)+ self.events.model.emit('Model still loading or port unavailable. Inspect model.log.')+ self.launch(wait_ready)+ except (OSError,ValueError) as error:+ self.error(str(error))++ def model_status(self,message):+ previous=self.model_state.text()+ self.model_loaded=message.startswith('loaded') or 'test passed' in message.lower() or 'Model: loaded' in message+ if not self.model_loaded:+ self.loaded_modalities={}+ self.model_state.setText(message)+ if hasattr(self,'settings_model_state'):+ self.settings_model_state.setText(message)+ if previous!=message:+ self.set_status(message)+ self.update_tool_state()++ def check_model_exit(self):+ if self.model_process and self.model_process.poll() is not None:+ code=self.model_process.returncode+ self.model_process=None+ if self.model_log:+ self.model_log.close()+ self.model_log=None+ self.model_status(f'Model process exited ({code}). See model.log for details.')++ def stop_model(self):+ self.model_generation+=1+ if self.indexing:+ self.engine.cancel.set()+ self.engine.clear_query_cache()+ if self.attached_server:+ try:+ self.attached_server.terminate()+ self.attached_server.wait(timeout=3)+ except psutil.TimeoutExpired:+ try: self.attached_server.kill()+ except psutil.Error: pass+ except psutil.Error:+ pass+ self.attached_server=None+ process=self.model_process+ self.model_process=None+ if process and process.poll() is None:+ try:+ root=psutil.Process(process.pid)+ children=root.children(recursive=True)+ for child in children:+ try: child.terminate()+ except psutil.Error: pass+ root.terminate()+ _,alive=psutil.wait_procs(children+[root],timeout=3)+ for child in alive:+ try: child.kill()+ except psutil.Error: pass+ process.wait(timeout=3)+ except (psutil.Error,subprocess.TimeoutExpired):+ if process.poll() is None:+ process.kill()+ if self.model_log:+ self.model_log.close()+ self.model_log=None+ self.model_status('Model: stopped' if process else 'No local model started by VectorDash is running')++ def test_model(self):+ if not self.save(quiet=True):+ return+ snapshot=dict(self.settings,semantic=True)+ self.model_state.setText('Testing a local embedding request…')+ def work():+ try:+ verify_server_model(snapshot)+ with self.engine.inference:+ vector=embed('task: search result | query: A document about Windows desktop search',request=lambda text:embedding_request(text,snapshot))+ with urllib.request.urlopen(urllib.request.Request(server_url(snapshot)+'/props',headers={'Authorization':'Bearer '+snapshot['remote_key']} if snapshot.get('remote_key') else {}),timeout=5) as response:+ modalities=json.load(response).get('modalities',{})+ self.loaded_modalities=modalities+ ready=modalities.get('vision') and modalities.get('audio')+ if snapshot.get('server_mode')!='Remote' and snapshot.get('projector') and not ready:+ raise ValueError('The running server has no vision/audio encoder. Stop it and start the model with the selected encoder.')+ self.events.model.emit(f'Embedding test passed · {len(vector)} dimensions · '+('text + vision + audio ready' if ready else 'text only; download/select an encoder and restart for media search'))+ except Exception as error:+ self.events.model.emit('Embedding test failed: '+str(error))+ self.launch(work)++ def load_catalog(self):+ self.set_status('Loading official runtime and model catalogs…')+ def work():+ try:+ runtimes,models=catalogs()+ self.events.catalog.emit(runtimes,models,'')+ except Exception as error:+ self.events.catalog.emit([],[],str(error))+ self.launch(work)++ def catalog_finished(self,runtimes,models,error):+ if error:+ self.error('Catalog unavailable: '+error)+ return+ selected_quant=self.quant_choice.currentData() or 'Q8_0'+ self.runtimes,self.models=runtimes,models+ self.runtime_choice.clear()+ self.quant_choice.clear()+ for item in runtimes:+ self.runtime_choice.addItem(f'{item["label"]} · {item["size"]/1024**2:.0f} MB')+ for item in models:+ self.quant_choice.addItem(f'{item["label"]} · {item["size"]/1024**2:.0f} MB',item['label'])+ self.quant_choice.setCurrentIndex(next((i for i,item in enumerate(models) if item['label']==selected_quant),0))+ preferred=next((i for i,item in enumerate(runtimes) if item['backend']=='vulkan'),0)+ if self.settings['mode']=='Dedicated GPU' and self.settings['device'].upper().startswith('CUDA'):+ preferred=next((i for i,item in enumerate(runtimes) if item['backend'].startswith('cuda-12')),preferred)+ elif self.settings['mode']=='CPU / system RAM':+ preferred=next((i for i,item in enumerate(runtimes) if item['backend']=='cpu'),preferred)+ self.runtime_choice.setCurrentIndex(preferred)+ self.catalog_summary()+ self.set_status('Downloads available. Select a runtime and quantization.')++ def catalog_summary(self):+ r=self.runtime_choice.currentIndex()+ q=self.quant_choice.currentIndex()+ if 0<=r<len(self.runtimes) and 0<=q<len(self.models):+ total=self.runtimes[r]['size']+self.models[q]['size']+self.models[q].get('projector',{}).get('size',0)+ self.download_summary.setText(f'Total download: {total/1024**2:.0f} MB. Model SHA-256 verified. Choose the runtime for your hardware; existing installations are retained.')++ def component_installed(self,key):+ try:+ if key=='ocr':+ program=ocr_program(self.settings)+ if not program:+ return False+ data=Path(self.settings['ocr_data']) if self.settings.get('ocr_data') else Path(program).parent/'tessdata'+ return all((data/(code+'.traineddata')).is_file() for code in self.settings.get('ocr_languages','eng').split('+'))+ if key=='ffmpeg':+ return Path(ffmpeg(self.settings)).is_file()+ path=Path(self.settings.get(key,''))+ installed=path.is_file()+ if key in ('model','projector') and installed:+ quant=self.quant_choice.currentData() if hasattr(self,'quant_choice') else None+ if quant and any(token in path.name.upper() for token in ('Q8_0','BF16')):+ installed=quant in path.name.upper()+ return installed+ except Exception:+ return False++ def update_tool_state(self,*args):+ if not hasattr(self,'setup_choices'):+ return+ for key,status in self.component_status.items():+ installed=self.component_installed(key)+ if self.settings.get('server_mode')=='Remote' and key in ('server','model','projector'):+ installed=self.model_loaded+ loaded=installed and (self.model_loaded if key in ('server','model') else bool(self.loaded_modalities.get('vision') or self.loaded_modalities.get('audio')) if key=='projector' else self.tool_ready.get(key,False))+ text,color=('Loaded' if key in ('server','model','projector') else 'Ready','#16834a') if loaded else ('Installed · not loaded','#aa7900') if installed else ('Not installed','#c73545')+ status.setText(text)+ status.setStyleSheet('color: '+color+'; font-weight: 600;')+ selected=[key for key,choice in self.setup_choices.items() if choice.isChecked()]+ ready=all(self.component_installed(key) for key in set(selected)|{'server','model'})+ self.setup_button.setText('Start' if ready else 'Download, install and start')+ loaded=ready and self.model_loaded and all(('Loaded' if key in ('server','model','projector') else 'Ready')==self.component_status[key].text() for key in selected)+ self.setup_button.setEnabled(not self.installing and not loaded)+ self.setup_stop.setEnabled(self.settings.get('server_mode')!='Remote' and (self.model_loaded or bool(self.model_process) or bool(self.attached_server)))+ self.setup_cancel.setVisible(self.installing)+ if hasattr(self,'tool_state'):+ self.tool_state.setText('OCR: '+self.component_status['ocr'].text()+' · Media decoder: '+self.component_status['ffmpeg'].text())++ def refresh_component_status(self):+ if not self.save(quiet=True):+ return+ self.probe_model()+ snapshot=dict(self.settings)+ def work():+ ready={}+ for key,args in [('ocr',[ocr_program(snapshot),'--version']),('ffmpeg',[ffmpeg(snapshot),'-version'])]:+ try:+ if args[0]:+ result=process_lifecycle.run(args,capture_output=True,timeout=10,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ ready[key]=result.returncode==0+ if key=='ocr' and ready[key]:+ languages=[args[0],'--list-langs']+ if snapshot.get('ocr_data'):+ languages+=['--tessdata-dir',snapshot['ocr_data']]+ packs=process_lifecycle.run(languages,capture_output=True,text=True,timeout=10,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ ready[key]=packs.returncode==0 and all(code in packs.stdout.splitlines() for code in snapshot.get('ocr_languages','eng').split('+'))+ except Exception:+ ready[key]=False+ if not self.shutting_down:+ self.events.tools_ready.emit(ready)+ self.launch(work)++ def tools_status_finished(self,ready):+ self.tool_ready=ready+ self.update_tool_state()++ def install_tool(self,key):+ if self.installing or self.indexing:+ self.set_status('Finish the current download/indexing task before setting up tools')+ return+ if not self.save(quiet=True):+ return+ snapshot=dict(self.settings)+ self.download_cancel.clear()+ self.installing=True+ self.update_tool_state()+ self.download_bar.setValue(0)+ self.set_status('Setting up '+('OCR and selected languages' if key=='ocr' else 'included FFmpeg'))+ def work():+ try:+ paths=install_ocr(snapshot,self.store.home,self.download_cancel,self.events.progress.emit) if key=='ocr' else install_ffmpeg(self.store.home,self.download_cancel,self.events.progress.emit)+ self.events.installed.emit('tools',json.dumps(paths),'')+ except Exception as error:+ self.events.installed.emit('tools','',str(error))+ self.launch(work)++ def install(self,key):+ if self.installing:+ self.set_status('A download is already running')+ return+ quant=self.quant_choice.currentData() or 'Q8_0'+ runtime_index=self.runtime_choice.currentIndex()+ model_index=self.quant_choice.currentIndex()+ available_runtimes=list(self.runtimes)+ available_models=list(self.models)+ mode=self.widgets['mode'].currentText()+ device=self.devices.currentData() or ''+ self.download_cancel.clear()+ self.installing=True+ self.update_tool_state()+ self.download_bar.setValue(0)+ self.set_status('Preparing '+('vision/audio encoder' if key=='projector' else 'download'))+ def work():+ try:+ runtimes,models=available_runtimes,available_models+ if not runtimes or not models:+ runtimes,models=catalogs()+ self.events.catalog.emit(runtimes,models,'')+ preferred='cpu' if mode=='CPU / system RAM' else ('cuda-' if str(device).upper().startswith('CUDA') else 'vulkan')+ runtime_index_local=next((i for i,item in enumerate(runtimes) if item['backend'].startswith(preferred)),0)+ model_index_local=next((i for i,item in enumerate(models) if item['label']==quant),-1)+ if model_index_local<0:+ raise ValueError('The selected quantization is unavailable. Load the catalog and select an available model.')+ else:+ runtime_index_local=runtime_index+ model_index_local=model_index+ item=runtimes[runtime_index_local] if key=='server' else models[model_index_local]+ if key=='projector':+ item=item.get('projector')+ if not item:+ raise ValueError('No matching vision/audio encoder is available for this model.')+ function=install_runtime if key=='server' else install_model+ path=function(item,self.store.home,self.download_cancel,self.events.progress.emit)+ if key=='model' and item.get('projector'):+ encoder=install_model(item['projector'],self.store.home,self.download_cancel,self.events.progress.emit)+ path=json.dumps({'model':path,'projector':encoder})+ self.events.installed.emit(key,path,'')+ except Exception as error:+ self.events.installed.emit(key,'',str(error))+ self.launch(work)++ def download_progress(self,title,done,total):+ self.download_bar.setValue(round(done/total*100) if total else 0)+ self.setup_progress.setValue(self.download_bar.value())+ self.set_status(f'{title}: {done/1024**2:.0f} / {total/1024**2:.0f} MB' if total else title)++ def install_finished(self,key,path,error):+ self.installing=False+ self.update_tool_state()+ if error:+ self.set_status(error)+ return+ paths=json.loads(path) if path.startswith('{') else {key:path}+ for name,value in paths.items():+ if name=='device':+ self.devices.clear()+ self.devices.addItem(value,value)+ else:+ self.widgets[name].setText(value)+ self.settings[name]=value+ self.store.save()+ self.download_bar.setValue(100)+ self.setup_progress.setValue(100)+ self.set_status('Installed. Refresh devices, select hardware, then start/test the model.' if key=='server' else 'Model downloaded and verified. Start/test the model, then update your index.')+ self.update_tool_state()+ if key=='tools':+ self.set_status('Tools installed, verified and configured. Update the index to apply OCR changes.')+ if key=='setup':+ self.settings['semantic']=True+ self.store.save()+ self.start_model()+ self.refresh_component_status()+ if key=='server':+ self.refresh_devices()++ def setup_all(self):+ if self.installing or self.indexing:+ self.set_status('Wait for the current setup or indexing task to finish')+ return+ selection={key:choice.isChecked() for key,choice in self.setup_choices.items()}+ self.widgets['ocr_enabled'].setChecked(selection['ocr'])+ self.widgets['index_images'].setChecked(selection['projector'])+ for key in ('index_audio','index_video'):+ self.widgets[key].setChecked(selection['projector'] and selection['ffmpeg'])+ if not self.save(quiet=True):+ return+ if self.settings.get('server_mode')=='Remote':+ self.probe_model()+ self.set_status('Remote models are installed on their host. Use local setup for downloads on this PC.')+ return+ if all(self.component_installed(key) for key in {key for key,value in selection.items() if value}|{'server','model'}):+ self.start_model()+ self.refresh_component_status()+ return+ for key in ('server','model'):+ if not selection[key] and not self.component_installed(key):+ self.set_status('Select the runtime and text model, or choose existing files before starting.')+ return+ if self.model_process:+ self.stop_model()+ snapshot=dict(self.settings)+ quant=self.quant_choice.currentData() or 'Q8_0'+ runtime_index=self.runtime_choice.currentIndex()+ selected=self.runtimes[runtime_index] if 0<=runtime_index<len(self.runtimes) else None+ self.installing=True+ self.update_tool_state()+ self.download_cancel.clear()+ self.set_status('Preparing one-click setup…')+ def work():+ paths={}+ try:+ need_model=any(selection[key] and not self.component_installed(key) for key in ('server','model','projector'))+ runtimes,models=catalogs() if need_model else ([],[])+ preferred='cpu' if snapshot['mode']=='CPU / system RAM' else ('cuda-' if str(snapshot['device']).upper().startswith('CUDA') else 'vulkan')+ runtime=(selected if isinstance(selected,dict) else next(item for item in runtimes if item['backend'].startswith(preferred))) if need_model else None+ model=next(item for item in models if item['label']==quant) if need_model else {}+ for key,item,installer in [('server',runtime,install_runtime),('model',model,install_model),('projector',model.get('projector'),install_model)]:+ if not selection[key]:+ if snapshot.get(key):+ paths[key]=snapshot[key]+ continue+ if self.download_cancel.is_set():+ raise InterruptedError('Setup cancelled')+ if not Path(snapshot.get(key,'')).is_file() or (key!='server' and quant not in Path(snapshot.get(key,'')).name):+ if not item:+ raise ValueError('No downloadable component is available for '+key)+ paths[key]=installer(item,self.store.home,self.download_cancel,self.events.progress.emit)+ else:+ paths[key]=snapshot[key]+ if snapshot['mode']!='CPU / system RAM' and not snapshot.get('device'):+ result=process_lifecycle.run([paths['server'],'--list-devices'],capture_output=True,text=True,timeout=30,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ adapters=[item for item in parse_devices(result.stdout+'\n'+result.stderr) if not item[0].upper().startswith('CPU')]+ if not adapters:+ raise ValueError('No compatible GPU was found. Select CPU / system RAM and retry setup.')+ if snapshot['mode']=='Integrated GPU':+ integrated=[item for item in adapters if any(term in item[1].lower() for term in ('integrated','intel','radeon graphics','apu'))]+ if not integrated:+ raise ValueError('Select your integrated GPU from Refresh devices before starting the model.')+ adapters=integrated+ paths['device']=adapters[0][0]+ if selection['ffmpeg']:+ paths.update(install_ffmpeg(self.store.home,self.download_cancel,self.events.progress.emit))+ if selection['ocr']:+ paths.update(install_ocr(snapshot,self.store.home,self.download_cancel,self.events.progress.emit))+ self.events.installed.emit('setup',json.dumps(paths),'')+ except Exception as error:+ # Preserve successfully installed components so retry does not repeat work.+ if paths:+ self.events.installed.emit('tools',json.dumps(paths),'')+ self.events.installed.emit('setup','',str(error))+ self.launch(work)++ def probe_model(self):+ if self.probing_model or self.shutting_down:+ return+ self.probing_model=True+ generation=self.model_generation+ snapshot=dict(self.settings,semantic=True)+ def work():+ try:+ verify_server_model(snapshot)+ request=urllib.request.Request(server_url(snapshot)+'/props',headers={'Authorization':'Bearer '+snapshot['remote_key']} if snapshot.get('remote_key') else {})+ with urllib.request.urlopen(request,timeout=3) as response:+ props=json.load(response)+ modes=props.get('modalities',{})+ self.loaded_modalities=modes+ message='loaded · text: ready · images: '+('ready' if modes.get('vision') else 'unavailable')+' · audio: '+('ready' if modes.get('audio') else 'unavailable')+ except Exception as error:+ self.logger.debug('Model status check: %s',error)+ message='not loaded · '+(str(error) if isinstance(error,ValueError) else 'Start the local model or check the server connection.')+ finally:+ self.probing_model=False+ if not self.shutting_down and generation==self.model_generation:+ if snapshot.get('server_mode')!='Remote' and message.startswith('loaded'):+ self.attach_local_server()+ self.events.model.emit(message)+ self.launch(work)++ def animate_index_icon(self):+ active=self.indexing and not self.engine.paused.is_set() and not self.engine.cancel.is_set()+ self.icon_phase+=.3+ icon=app_icon(active,self.icon_phase)+ self.setWindowIcon(icon)+ self.tray.setIcon(icon)+ self.tray.setToolTip('VectorDash · '+('Indexing' if active else 'Paused' if self.indexing else 'Ready'))++ def logs_page(self):+ layout=self.page('Logs','Indexing skips, setup messages and model status. Full history is saved in vectordash.log.')+ self.log_filter=ScrollSafeComboBox()+ self.log_filter.addItems(['All','Verbose','Info','Warning','Error'])+ self.log_filter.currentTextChanged.connect(self.render_logs)+ layout.addWidget(row(self.log_filter,button('Open log file',lambda:os.startfile(str(self.store.home/'vectordash.log'))),button('Open model output',lambda:self.open_model_log())))+ self.log_view=QPlainTextEdit()+ self.log_view.setReadOnly(True)+ self.log_view.setMaximumBlockCount(2000)+ layout.addWidget(self.log_view)+ if (self.store.home/'vectordash.log').exists():+ self.render_logs()++ def open_model_log(self):+ path=self.store.home/'model.log'+ if path.exists():+ os.startfile(str(path))+ else:+ self.set_status('No local model log yet. Start a local model first.')++ def append_log(self,level,message):+ self.log_records.append((level,datetime.now().strftime('%H:%M:%S')+' '+level+' '+message))+ self.log_records=self.log_records[-2000:]+ if hasattr(self,'log_view'):+ wanted={'Verbose':'DEBUG','Info':'INFO','Warning':'WARNING','Error':'ERROR'}.get(self.log_filter.currentText())+ if not wanted or level==wanted:+ self.log_view.appendPlainText(self.log_records[-1][1])++ def render_logs(self):+ wanted={'Verbose':'DEBUG','Info':'INFO','Warning':'WARNING','Error':'ERROR'}.get(self.log_filter.currentText())+ self.log_view.setPlainText('\n'.join(text for level,text in self.log_records if not wanted or level==wanted))+ bar=self.log_view.verticalScrollBar()+ bar.setValue(bar.maximum())++ def tick(self):+ self.probe_model()+ self.next_status.setText('Next run: '+next_run(self.settings,datetime.now()))+ if self.collecting:+ return+ self.collecting=True+ check_gpu=self.settings['check_gpu']+ def work():+ try:+ cpu=psutil.cpu_percent(interval=.2)+ battery=psutil.sensors_battery()+ metrics={'cpu':cpu,'gpu':gpu_utilization() if check_gpu else None,'idle':idle_seconds(),'on_ac':battery is None or battery.power_plugged}+ except Exception:+ metrics={'cpu':None,'gpu':None,'idle':None,'on_ac':None}+ self.events.metrics.emit(metrics)+ self.launch(work)++ def metrics_finished(self,metrics):+ self.collecting=False+ self.metrics=metrics+ self.metrics_time=time.monotonic()+ def number(value,suffix):+ return f'{value:.0f}{suffix}' if value is not None else 'unavailable'+ self.telemetry.setText(f'CPU {number(metrics["cpu"],"%")} · GPU {number(metrics["gpu"],"%") if self.settings["check_gpu"] else "not required"} · User idle {number(metrics["idle"],"s")} · Power {"AC" if metrics["on_ac"] else "battery/unknown"}')+ due,slot,reason=schedule_due(self.settings,datetime.now(),metrics)+ if self.indexing:+ allowed,condition=idle_allowed(self.settings,metrics)+ self.schedule_status.setText('Indexing in progress · '+(condition if self.settings['schedule_mode'] in ('When idle','Time + idle') else 'running'))+ else:+ self.schedule_status.setText(reason)+ if due and not self.indexing and time.monotonic()>=self.schedule_retry and self.settings['roots']:+ self.start_index(scheduled=True,slot=slot)++ def changeEvent(self,event):+ super().changeEvent(event)+ if event.type()==QEvent.Type.WindowStateChange and self.isMinimized() and self.settings['minimize_behavior']=='Tray' and QSystemTrayIcon.isSystemTrayAvailable():+ QTimer.singleShot(0,self.hide)++ def closeEvent(self,event):+ if self.shutting_down:+ event.accept()+ return+ behavior=self.settings['close_behavior']+ if behavior=='Exit':+ event.ignore()+ self.exit_app()+ elif behavior=='Hide to tray' and QSystemTrayIcon.isSystemTrayAvailable():+ self.hide()+ event.ignore()+ else:+ self.showMinimized()+ event.ignore()++ def attach_local_server(self):+ if self.model_process or self.attached_server or self.shutting_down:+ return+ expected=Path(self.settings.get('server','')).resolve()+ model=self.settings.get('model','')+ if not model:+ return+ for process in psutil.process_iter(['exe','cmdline']):+ try:+ if not process.info['exe'] or Path(process.info['exe']).resolve()!=expected:+ continue+ args=process.info['cmdline'] or []+ matching=any(args[i] in ('-m','--model') and os.path.normcase(str(Path(args[i+1]).resolve()))==os.path.normcase(str(Path(model).resolve())) for i in range(len(args)-1))+ if matching and any(connection.laddr.port==8787 and connection.status==psutil.CONN_LISTEN for connection in process.net_connections(kind='tcp')):+ self.attached_server=process+ return+ except (psutil.Error,OSError):+ pass++ def cleanup(self):+ if self.shutting_down:+ return+ self.shutting_down=True+ process_lifecycle.close()+ self.clock.stop()+ self.process_timer.stop()+ self.icon_timer.stop()+ self.engine.cancel.set()+ self.engine.paused.clear()+ self.download_cancel.set()+ self.hotkey.unregister()+ self.stop_model()+ if self.attached_server:+ try:+ self.attached_server.terminate()+ self.attached_server.wait(timeout=3)+ except psutil.TimeoutExpired:+ try: self.attached_server.kill()+ except psutil.Error: pass+ except psutil.Error:+ pass+ self.attached_server=None+ # Decoder, OCR, setup and helper processes belong to this app's process tree.+ children=psutil.Process().children(recursive=True)+ for child in children:+ try: child.terminate()+ except psutil.Error: pass+ _,alive=psutil.wait_procs(children,timeout=3)+ for child in alive:+ try: child.kill()+ except psutil.Error: pass+ self.tray.hide()+ self.quick.hide()+ self.logger.removeHandler(self.log_handler)+ self.logger.removeHandler(self.log_file_handler)+ self.log_file_handler.close()++ def exit_app(self):+ self.cleanup()+ self.close()+ QApplication.instance().quit()+++def main():+ app=QApplication(sys.argv)+ app.setApplicationName('VectorDash')+ app.setOrganizationName('VectorDash')+ app.setStyle('Fusion')+ app.setQuitOnLastWindowClosed(False)+ settings=Settings()+ name='VectorDash-'+hashlib.sha256(str(settings.home.resolve()).encode()).hexdigest()[:16]+ socket=QLocalSocket()+ socket.connectToServer(name)+ if socket.waitForConnected(400):+ socket.write(b'startup' if '--startup' in sys.argv else b'show')+ socket.waitForBytesWritten(500)+ socket.disconnectFromServer()+ return 0+ QLocalServer.removeServer(name)+ server=QLocalServer()+ if not server.listen(name):+ QMessageBox.critical(None,'VectorDash','Could not establish single-instance communication.')+ return 1+ window=Desktop(settings,server)+ hidden='--startup' in sys.argv and settings.values['start_hidden'] and QSystemTrayIcon.isSystemTrayAvailable()+ if not hidden:+ window.show()+ return app.exec()++if __name__=='__main__':+ raise SystemExit(main())diff --git a/windows/engine.py b/windows/engine.pynew file mode 100644index 0000000..8977256--- /dev/null+++ b/windows/engine.py@@ -0,0 +1,436 @@+"""Persistent settings, incremental index, and search shared by the desktop UI."""+from contextlib import contextmanager+from dataclasses import dataclass+import numpy as np+from collections import OrderedDict+import re+import shutil+import logging+import json+import os+from pathlib import Path+import sqlite3+import threading+import time+import urllib.request+import zipfile+import xml.etree.ElementTree as ET+from vectordash_core import safe, read_text, embed, cosine, embedding_request, server_url+from content import Segment, extract, project_files, code_segments, ocr_program, IMAGE, AUDIO, VIDEO++DEFAULTS = {+ 'server_mode': 'Local', 'remote_url': '', 'remote_key': '', 'remote_model_id': 'embeddinggemma-2',+ 'projector': '', 'index_images': True, 'index_audio': True, 'index_video': True,+ 'ocr_enabled': True, 'ocr_path': '', 'ocr_data': '', 'ocr_languages': 'eng', 'ffmpeg_path': '',+ 'video_interval': 3, 'code_enabled': False, 'code_roots': [],+ 'roots': [], 'mode': 'CPU / system RAM', 'server': '', 'model': '', 'device': '',+ 'semantic': False, 'theme': 'System', 'hotkey': 'Ctrl+Shift+Space',+ 'startup': False, 'start_hidden': True, 'close_behavior': 'Hide to tray',+ 'minimize_behavior': 'Taskbar', 'auto_model': False,+ 'schedule_mode': 'Manual', 'schedule_time': '02:00', 'schedule_days': [0,1,2,3,4,5,6],+ 'idle_minutes': 5, 'cpu_limit': 25, 'gpu_limit': 20, 'check_cpu': True,+ 'check_gpu': False, 'check_user_idle': True, 'ac_only': True, 'idle_interval': 60, 'last_success': '',+ 'last_schedule_slot': '', 'schedule_history': [], 'max_run_minutes': 120+}++def data_home():+ override = os.environ.get('VECTORDASH_DATA_HOME') or os.environ.get('DIGUP_DATA_HOME')+ base = Path(os.environ.get('LOCALAPPDATA') or str(Path.home()))+ if override:+ return Path(override)+ target=base/'VectorDash'+ legacy=base/'DigUp'+ if not target.exists() and (legacy/'settings.json').exists():+ shutil.move(str(legacy),str(target))+ settings_file=target/'settings.json'+ values=json.loads(settings_file.read_text(encoding='utf-8-sig'))+ for key in ('server','model','projector','ocr_path','ocr_data','ffmpeg_path'):+ value=values.get(key,'')+ if value and Path(value).is_relative_to(legacy):+ values[key]=str(target/Path(value).relative_to(legacy))+ settings_file.write_text(json.dumps(values,indent=2),encoding='utf-8')+ return target++class Settings:+ def __init__(self, home=None):+ self.home = Path(home) if home else data_home()+ self.home.mkdir(parents=True, exist_ok=True)+ self.path = self.home/'settings.json'+ self.values = dict(DEFAULTS)+ if self.path.exists():+ self.values.update(json.loads(self.path.read_text(encoding='utf-8-sig')))+ def save(self):+ temp = self.path.with_suffix('.tmp')+ temp.write_text(json.dumps(self.values, indent=2), encoding='utf-8')+ temp.replace(self.path)+++def model_signature(settings):+ if not settings['semantic']:+ return ''+ if settings.get('server_mode')=='Remote':+ return json.dumps(['remote',server_url(settings),settings.get('remote_model_id','embeddinggemma-2'),4])+ path = Path(settings['model'])+ stat = path.stat()+ # Include the extraction/embedding algorithm version to invalidate old vectors.+ projection = Path(settings['projector']) if settings.get('projector') else None+ encoder = [str(projection.resolve()), projection.stat().st_size, projection.stat().st_mtime_ns] if projection else []+ return json.dumps([str(path.resolve()), stat.st_size, stat.st_mtime_ns, encoder, 4])+++def verify_server_model(settings):+ if not settings['semantic']:+ return+ with urllib.request.urlopen(urllib.request.Request(server_url(settings)+'/props',headers={'Authorization':'Bearer '+settings['remote_key']} if settings.get('remote_key') else {}),timeout=5) as response:+ props=json.load(response)+ running=props.get('model_path')+ if settings.get('server_mode')=='Remote':+ expected=settings.get('remote_model_id','embeddinggemma-2').casefold()+ if expected and expected not in str(running or props.get('model_alias','')).casefold():+ raise ValueError('Remote server model does not match the configured model identifier.')+ return+ if not running or os.path.normcase(str(Path(running).resolve())) != os.path.normcase(str(Path(settings['model']).resolve())):+ raise ValueError('The running server uses a different model. Stop it, then start the selected model before indexing/searching.')+++@dataclass+class SearchResult:+ score: float+ path: str+ snippet: str+ kind: str = 'text'+ page: int = 0+ seconds: float = -1+ end: float = -1+ line: int = 0+ end_line: int = 0+ symbol: str = ''+ boxes: list = None+ query: str = ''+ def __iter__(self):+ return iter((self.score,self.path,self.snippet))+ def location(self):+ return Segment(kind=self.kind,page=self.page,seconds=self.seconds,line=self.line,end_line=self.end_line,symbol=self.symbol).location()++class Engine:+ def __init__(self, home):+ self.db = Path(home)/'index.sqlite'+ self.cancel = threading.Event()+ self.paused = threading.Event()+ self.inference = threading.Lock()+ self.query_waiting = threading.Event()+ self.search_cache_lock=threading.RLock()+ self.search_cache={}+ self.query_vectors=OrderedDict()+ with self.connect() as db:+ db.execute('PRAGMA journal_mode=WAL')+ db.execute('CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, text TEXT, vector TEXT)')+ db.execute('CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT)')+ columns = {row[1] for row in db.execute('PRAGMA table_info(files)')}+ for name in ('mtime','size'):+ if name not in columns:+ db.execute(f'ALTER TABLE files ADD COLUMN {name} INTEGER DEFAULT -1')+ db.execute('CREATE TABLE IF NOT EXISTS segments(path TEXT, namespace TEXT, kind TEXT, text TEXT, vector TEXT, location TEXT)')+ db.execute('CREATE INDEX IF NOT EXISTS segments_path ON segments(path,namespace)')+ db.execute("CREATE VIRTUAL TABLE IF NOT EXISTS words USING fts5(path,text,tokenize='unicode61')")+ # Preserve readable legacy results until a successful replacement.+ if not db.execute('SELECT 1 FROM segments LIMIT 1').fetchone():+ db.execute("INSERT INTO segments SELECT path,'files','text',text,vector,'{}' FROM files")+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')++ def indexed_file_count(self):+ with self.connect() as db:+ return db.execute('SELECT count(DISTINCT path) FROM segments').fetchone()[0]++ def cached_index(self,namespace):+ with self.search_cache_lock:+ # Include WAL changes as well as checkpointed database changes.+ version=tuple((path.stat().st_mtime_ns,path.stat().st_size) if path.exists() else None for path in (self.db,Path(str(self.db)+'-wal')))+ key=(version,namespace)+ if key in self.search_cache:+ return self.search_cache[key]+ with self.connect() as db:+ db.execute('BEGIN')+ metadata=dict(db.execute('SELECT key,value FROM metadata'))+ rows=list(db.execute('SELECT rowid,path,kind,text,vector,location FROM segments WHERE namespace=?',(namespace,)))+ records=[]+ groups={}+ for i,(rowid,path,kind,text,stored,location) in enumerate(rows):+ vector=json.loads(stored)+ if vector:+ groups.setdefault(len(vector),[]).append((i,vector))+ records.append((rowid,path,kind,text,(path+'\n'+text).casefold(),location))+ matrices={}+ for dimension,entries in groups.items():+ matrix=np.asarray([vector for i,vector in entries],dtype=np.float32)+ norms=np.linalg.norm(matrix,axis=1,keepdims=True)+ matrix/=np.maximum(norms,1e-30)+ matrices[dimension]=([i for i,vector in entries],matrix)+ value=(records,matrices,metadata)+ self.search_cache={k:v for k,v in self.search_cache.items() if k[0]==version}+ self.search_cache[key]=value+ return value++ def clear_query_cache(self):+ with self.search_cache_lock:+ self.query_vectors.clear()++ @contextmanager+ def connect(self):+ connection=sqlite3.connect(self.db,timeout=30)+ try:+ with connection:+ yield connection+ finally:+ connection.close()++ def checkpoint(self, condition=lambda: True, wait_query=True):+ while True:+ if self.cancel.is_set():+ raise InterruptedError('Indexing stopped; previous index retained')+ if condition() and not self.paused.is_set() and not (wait_query and self.query_waiting.is_set()):+ return+ self.cancel.wait(.25)++ def infer(self,segment,path,condition,settings=None):+ def request(text):+ with self.inference:+ return embedding_request('title: '+path.name+' | text: '+text,settings) if settings and settings.get('server_mode')=='Remote' else embedding_request('title: '+path.name+' | text: '+text)+ checkpoint=lambda:self.checkpoint(condition)+ if segment.media:+ checkpoint()+ with self.inference:+ # Media must be embedded alone; a filename would contaminate its meaning.+ visual=embedding_request(segment.media,settings) if settings and settings.get('server_mode')=='Remote' else embedding_request(segment.media)+ if segment.text:+ # Separate text and media vectors retain both retrieval spaces.+ textual=embed(segment.text,checkpoint=checkpoint,request=request)+ return [visual,textual]+ return [visual]+ return [embed(segment.text or path.name,checkpoint=checkpoint,request=request)]++ def index(self, settings, progress=lambda text: None, condition=lambda: True, force=False):+ signature=model_signature(settings)+ verify_server_model(settings)+ content_options={key:settings.get(key) for key in ('index_images','index_audio','index_video','ocr_enabled','ocr_path','ocr_data','ocr_languages','video_interval','code_enabled','code_roots')}+ detected_ocr=ocr_program(settings)+ content_options['detected_ocr']=detected_ocr+ if settings.get('ocr_enabled',True):+ candidates=[Path(detected_ocr)] if detected_ocr else []+ if settings.get('ocr_data'):+ candidates.extend(Path(settings['ocr_data'])/(code+'.traineddata') for code in settings.get('ocr_languages','eng').split('+'))+ content_options['ocr_files']=[[str(path),path.stat().st_size,path.stat().st_mtime_ns] for path in candidates if path.is_file()]+ content_options['ffmpeg_path']=settings.get('ffmpeg_path','')+ configuration=json.dumps(content_options,sort_keys=True)+ warnings=[]+ if settings.get('ocr_enabled',True) and not ocr_program(settings):+ warnings.append('OCR unavailable: install Tesseract or set its path; screenshot exact text is not indexed')+ count=reused=skipped=segment_count=0+ kinds={}+ seen=set()+ checked_media=False+ with self.connect() as db:+ metadata=dict(db.execute('SELECT key,value FROM metadata'))+ previous={row[0]:row[1:] for row in db.execute('SELECT path,text,vector,mtime,size FROM files')}+ compatible=metadata.get('signature')==signature and metadata.get('content_options')==configuration and metadata.get('segments_version')=='4' and not force+ db.execute('CREATE TEMP TABLE replacement(path TEXT PRIMARY KEY,text TEXT,vector TEXT,mtime INTEGER,size INTEGER)')+ db.execute('CREATE TEMP TABLE new_segments(path TEXT,namespace TEXT,kind TEXT,text TEXT,vector TEXT,location TEXT)')+ def add(path,namespace):+ nonlocal count,reused,skipped,segment_count,checked_media+ self.checkpoint(condition)+ path=Path(path)+ key=(str(path),namespace)+ if key in seen:+ return+ seen.add(key)+ try:+ stat=path.stat()+ roots=settings.get('code_roots',[]) if namespace=='code' else settings['roots']+ relative=next((path.relative_to(Path(root)) for root in roots if path.is_relative_to(Path(root))),Path(path.name))+ if not safe(relative) or path.is_symlink() or getattr(stat,'st_file_attributes',0)&(0x1000|0x40000|0x400000):+ return+ old=previous.get(str(path))+ if compatible and old and old[2:]==(stat.st_mtime_ns,stat.st_size):+ db.execute('INSERT OR REPLACE INTO replacement VALUES(?,?,?,?,?)',(str(path),old[0],old[1],stat.st_mtime_ns,stat.st_size))+ db.execute('INSERT INTO new_segments SELECT * FROM segments WHERE path=? AND namespace=?',key)+ reused+=1+ else:+ progress(f'Reading {path.name} · {segment_count} content segments')+ if namespace=='code':+ segments=code_segments(path)+ else:+ media_kind=path.suffix.lower() in IMAGE|AUDIO|VIDEO+ if settings['semantic'] and media_kind and not checked_media:+ with urllib.request.urlopen(urllib.request.Request(server_url(settings)+'/props',headers={'Authorization':'Bearer '+settings['remote_key']} if settings.get('remote_key') else {}),timeout=5) as response:+ modalities=json.load(response).get('modalities',{})+ needs_vision=(settings.get('index_images',True) or settings.get('index_video',True))+ needs_audio=settings.get('index_audio',True)+ if (settings.get('server_mode')!='Remote' and not settings.get('projector')) or needs_vision and not modalities.get('vision') or needs_audio and not modalities.get('audio'):+ raise RuntimeError('Photos/audio/video require the matching vision + audio encoder (mmproj). Download it in Models & hardware, restart the model, then rebuild the index.')+ checked_media=True+ segments=extract(path,settings,read_text,lambda:self.checkpoint(condition))+ file_text=[]+ file_segments=0+ for segment in segments:+ self.checkpoint(condition)+ vectors=self.infer(segment,path,condition,settings) if settings['semantic'] else [[]]+ for vector in vectors:+ db.execute('INSERT INTO new_segments VALUES(?,?,?,?,?,?)',(str(path),namespace,segment.kind,segment.text,json.dumps(vector),segment.metadata()))+ segment_count+=1+ file_segments+=1+ kinds[segment.kind]=kinds.get(segment.kind,0)+1+ if file_segments%10==0:+ progress(f'{path.name} · {file_segments} segments · {segment.location()}')+ file_text.append(segment.text[:100])+ if not file_segments:+ db.execute('INSERT INTO new_segments VALUES(?,?,?,?,?,?)',(str(path),namespace,'filename','','[]','{}'))+ db.execute('INSERT OR REPLACE INTO replacement VALUES(?,?,?,?,?)',(str(path),' '.join(file_text[:10]),'[]',stat.st_mtime_ns,stat.st_size))+ count+=1+ except Exception as error:+ if isinstance(error,(InterruptedError,sqlite3.Error)):+ raise+ db.execute('DELETE FROM new_segments WHERE path=? AND namespace=?',key)+ skipped+=1+ warnings.append(f'{path}: {error}')+ logging.getLogger('vectordash').warning('Skipped %s: %s',path,error)+ logging.getLogger('vectordash').debug('File failure details: %s',path,exc_info=True)+ progress(f'Skipped {path.name}: {error}')+ db.execute('INSERT INTO new_segments VALUES(?,?,?,?,?,?)',(str(path),namespace,'filename','','[]','{}'))+ for source in settings['roots']:+ if not Path(source).is_dir():+ raise ValueError(f'Source unavailable: {source}; previous index retained')+ errors=[]+ for base,dirs,names in os.walk(source,followlinks=False,onerror=errors.append):+ self.checkpoint(condition)+ allowed=[]+ for directory in dirs:+ path=Path(base)/directory+ try:+ attrs=getattr(path.stat(),'st_file_attributes',0)+ if safe(path.relative_to(Path(source))) and not path.is_symlink() and not path.is_junction() and not attrs&(0x1000|0x40000|0x400000):+ allowed.append(directory)+ except OSError:+ skipped+=1+ dirs[:]=allowed+ for name in names:+ add(Path(base)/name,'files')+ if errors:+ for error in errors:+ skipped+=1+ logging.getLogger('vectordash').warning('Skipped inaccessible folder: %s',error)+ if settings.get('code_enabled'):+ for root in settings.get('code_roots',[]):+ if not Path(root).is_dir():+ raise ValueError(f'Project unavailable: {root}; previous index retained')+ for path in project_files(root):+ from content import CODE+ if path.suffix.lower() in CODE:+ add(path,'code')+ self.checkpoint(condition)+ db.execute('DELETE FROM files')+ db.execute('INSERT INTO files SELECT * FROM replacement')+ db.execute('DELETE FROM segments')+ db.execute('INSERT INTO segments SELECT * FROM new_segments')+ db.execute('DELETE FROM words')+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')+ for key,value in [('signature',signature),('model',settings['model'] if settings['semantic'] else ''),('segments_version','4'),('content_options',configuration),('warnings',json.dumps(warnings,ensure_ascii=False))]:+ db.execute('INSERT OR REPLACE INTO metadata VALUES(?,?)',(key,value))+ total=db.execute('SELECT count(*) FROM segments').fetchone()[0]+ summary=', '.join(f'{n} {kind}' for kind,n in db.execute('SELECT kind,count(*) FROM segments GROUP BY kind'))+ result=f'{count} files indexed · {reused} reused · {skipped} skipped · {total} segments ({summary})'+ if warnings:+ result+=' · '+warnings[0]+(f' (+{len(warnings)-1} warnings)' if len(warnings)>1 else '')+ return result++ def search(self, query, settings):+ started=time.perf_counter()+ query=query.strip()+ if not query:+ return []+ code=query.lower().startswith('code:')+ if code:+ if not settings.get('code_enabled'):+ raise ValueError('Enable code search and choose project folders in Sources first.')+ query=query[5:].strip()+ if not query:+ return []+ records,matrices,metadata=self.cached_index('code' if code else 'files')+ vector=[]+ if settings['semantic']:+ verify_server_model(settings)+ signature=metadata.get('signature')+ if signature!=model_signature(settings):+ raise ValueError('Rebuild the index with the selected model and encoder before semantic search.')+ subject=re.sub(r'^(?:images?|photos?|pictures?)\s+(?:of\s+)?','',query,flags=re.I).strip() or query+ prompt=('task: code retrieval | query: ' if code else 'task: search result | query: ')+subject+ cache_key=(signature,server_url(settings),prompt)+ vector=self.query_vectors.get(cache_key)+ if vector is None:+ self.query_waiting.set()+ try:+ with self.inference:+ vector=embed(prompt,request=lambda text:embedding_request(text,settings)) if settings.get('server_mode')=='Remote' else embed(prompt)+ self.query_vectors[cache_key]=vector+ if len(self.query_vectors)>64:+ self.query_vectors.popitem(last=False)+ finally:+ self.query_waiting.clear()+ tokens=re.findall(r'[\w]+(?:[-./:][\w]+)*',query.casefold())+ stop={'a','an','the','in','on','at','of','to','and','or','where','they','about','find','shows','show','me','with','is','it'}+ tokens=[token for token in tokens if token not in stop] or tokens+ format_words={'image','images','photo','photos','picture','pictures','video','videos','clip','clips','audio','podcast','podcasts','document','documents','file','files'}+ subjects=[token for token in tokens if token not in format_words]+ if subjects:+ tokens=subjects+ if not tokens:+ return []+ scores=np.zeros(len(records),dtype=np.float32)+ if vector and len(vector) in matrices:+ indices,matrix=matrices[len(vector)]+ query_vector=np.asarray(vector,dtype=np.float32)+ query_vector/=max(float(np.linalg.norm(query_vector)),1e-30)+ scores[indices]=matrix@query_vector+ token_patterns=[re.compile(r'(?<!\w)'+re.escape(token)+r'(?!\w)') for token in tokens]+ identifier=bool(re.search(r'\d|[_:/-]',query))+ lowered=query.casefold()+ results=[]+ with self.connect() as db:+ # FTS handles Unicode token boundaries; literal scoring additionally retains punctuation in IDs.+ expression=' OR '.join('"'+token.replace('"','""')+'"' for token in tokens)+ exact={row[0] for row in db.execute('SELECT rowid FROM words WHERE words MATCH ?', (expression,))}+ for index,(rowid,path,kind,text,haystack,location) in enumerate(records):+ matches=sum(bool(pattern.search(haystack)) for pattern in token_patterns)+ literal=query.casefold() in haystack+ lexical=matches/len(tokens)+ semantic=float(scores[index]) if vector else 0+ score=((2 if identifier else .65) if literal else 0)+((.35 if identifier else .15)*lexical if vector else lexical)+(.05 if rowid in exact else 0)+semantic+ lowered=query.casefold()+ if vector:+ if ('video' in lowered or 'clip' in lowered) and kind in ('video','video_audio'):+ score+=.2+ elif any(phrase in lowered for phrase in ('podcast','talk about','talks about','talking about','they talk','recording')) and kind in ('audio','video_audio'):+ score+=.3+ elif any(word in lowered for word in ('photo','picture','image')) and kind=='image':+ score+=.2+ if matches or semantic>.12:+ lower=text.casefold()+ offset=min((lower.find(token) for token in tokens if token in lower),default=0)+ snippet=' '.join(text[max(0,offset-50):offset+220].split())+ meta=json.loads(location)+ result=SearchResult(score,path,snippet,kind=kind,query=query,**meta)+ result.semantic_score=semantic+ result.lexical_match=bool(matches or literal)+ results.append(result)+ if vector and results:+ floor=max(.3,max(result.semantic_score for result in results)-.13)+ results=[result for result in results if result.lexical_match or result.semantic_score>=floor]+ results.sort(key=lambda item:(-item.score,item.path,item.seconds,item.page))+ selected=[]+ for result in results:+ if any(old.path==result.path and old.kind==result.kind and old.page==result.page and old.line==result.line and (old.seconds<0 and result.seconds<0 or abs(old.seconds-result.seconds)<10) for old in selected):+ continue+ selected.append(result)+ if len(selected)==100:+ break+ logging.getLogger('vectordash').debug('Search completed in %.1f ms: %d results from %d segments',(time.perf_counter()-started)*1000,len(selected),len(records))+ return selecteddiff --git a/windows/previews.py b/windows/previews.pynew file mode 100644index 0000000..fcb1446--- /dev/null+++ b/windows/previews.py@@ -0,0 +1,281 @@+"""Read-only native previews for the exact page, moment, image or code location."""+from pathlib import Path+import re+from PIL import Image,ImageOps+import pymupdf+from PySide6.QtCore import Qt,QUrl,QTimer+from PySide6.QtGui import QImage,QPixmap,QPainter,QColor,QTextCursor,QTextCharFormat+from PySide6.QtWidgets import QApplication,QDialog,QWidget,QVBoxLayout,QHBoxLayout,QLabel,QPushButton,QScrollArea,QSpinBox,QSlider,QPlainTextEdit,QTextEdit,QSizePolicy+from PySide6.QtMultimedia import QMediaPlayer,QAudioOutput+from PySide6.QtMultimediaWidgets import QVideoWidget+++def query_words(query):+ stop={'the','a','an','in','on','about','where','they','of','to','and','is','with'}+ return [word for word in re.findall(r'[\w]+(?:[-./:][\w]+)*',query.casefold()) if word not in stop]++def matches(text,query):+ words=query_words(query)+ return any(word in text.casefold() for word in words)++class FitPicture(QLabel):+ def __init__(self):+ super().__init__()+ self.original=QPixmap()+ self.setMinimumSize(1,1)+ self.setSizePolicy(QSizePolicy.Policy.Ignored,QSizePolicy.Policy.Ignored)+ def setPixmap(self,pixmap):+ self.original=pixmap+ self.fit()+ def fit(self):+ if not self.original.isNull():+ super().setPixmap(self.original.scaled(self.size(),Qt.AspectRatioMode.KeepAspectRatio,Qt.TransformationMode.SmoothTransformation))+ def resizeEvent(self,event):+ self.fit()+ super().resizeEvent(event)++class Preview(QDialog):+ def __init__(self,result,parent=None,embedded=False):+ super().__init__(parent)+ self.embedded=embedded+ if embedded:+ self.setWindowFlags(Qt.WindowType.Widget)+ self.result=result+ self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)+ self.setWindowTitle(Path(result.path).name+' — '+result.location()+' — VectorDash')+ self.resize(980,760)+ self.layout=QVBoxLayout(self)+ self.caption=QLabel(result.location()+' · '+result.path)+ self.caption.setTextFormat(Qt.TextFormat.PlainText)+ self.caption.setWordWrap(True)+ self.layout.addWidget(self.caption)+ self.doc=None+ self.player=None+ self.released=False+ self.finished.connect(self.release)+ QApplication.instance().aboutToQuit.connect(self.release)+ if result.page:+ self.pdf()+ elif result.seconds>=0:+ self.media()+ elif result.kind=='code':+ self.code()+ else:+ from content import IMAGE+ if Path(result.path).suffix.lower() in IMAGE:+ self.image()+ else:+ self.text()++ def canvas(self):+ self.scroll=QScrollArea()+ self.scroll.setWidgetResizable(True)+ self.picture=FitPicture() if self.embedded else QLabel()+ self.picture.setAlignment(Qt.AlignmentFlag.AlignCenter)+ self.scroll.setWidget(self.picture)+ self.layout.addWidget(self.scroll,1)++ def pdf(self):+ self.doc=pymupdf.open(self.result.path)+ self.canvas()+ controls=QHBoxLayout()+ previous=QPushButton('Previous page')+ following=QPushButton('Next page')+ self.page=QSpinBox()+ self.page.setRange(1,len(self.doc))+ self.page.setValue(self.result.page)+ controls.addWidget(previous); controls.addWidget(self.page); controls.addWidget(QLabel(f'/ {len(self.doc)} pages')); controls.addWidget(following)+ self.layout.addLayout(controls)+ previous.clicked.connect(lambda:self.page.setValue(self.page.value()-1))+ following.clicked.connect(lambda:self.page.setValue(self.page.value()+1))+ self.page.valueChanged.connect(self.render_pdf)+ self.render_pdf()++ def render_pdf(self):+ page=self.doc[self.page.value()-1]+ rectangles=[]+ if self.page.value()==self.result.page:+ for word in query_words(self.result.query):+ rectangles.extend(page.search_for(word))+ if not rectangles:+ # Semantic queries need not share any words with the document.+ for phrase in re.split(r'[.!?\n]',self.result.snippet):+ if len(phrase.strip())>12:+ rectangles.extend(page.search_for(phrase.strip()))+ if not rectangles:+ rectangles=[pymupdf.Rect(x,y,x+w,y+h) for word,x,y,w,h in (self.result.boxes or []) if matches(word,self.result.query)]+ if not rectangles and self.result.boxes:+ rectangles=[pymupdf.Rect(x,y,x+w,y+h) for word,x,y,w,h in self.result.boxes if word.casefold() in self.result.snippet.casefold()]+ self.highlight_count=len(rectangles)+ scale=min(1.4,380/max(page.rect.width,1)) if self.embedded else 1.4+ pixmap=page.get_pixmap(matrix=pymupdf.Matrix(scale,scale),alpha=False)+ image=QImage(pixmap.samples,pixmap.width,pixmap.height,pixmap.stride,QImage.Format.Format_RGB888).copy()+ painter=QPainter(image)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(255,215,40,100))+ for rect in rectangles:+ painter.drawRect(int(rect.x0*scale),int(rect.y0*scale),max(1,int(rect.width*scale)),max(1,int(rect.height*scale)))+ painter.end()+ self.picture.setPixmap(QPixmap.fromImage(image))+ if not self.embedded:+ self.picture.setMinimumSize(image.size())+ self.caption.setText(f'Page {self.page.value()} · {len(rectangles)} highlights · {self.result.path}')++ def image(self):+ self.canvas()+ with Image.open(self.result.path) as source:+ image=ImageOps.exif_transpose(source).convert('RGB')+ original=image.size+ image.thumbnail((380,480) if self.embedded else (1600,1200))+ pixels=image.tobytes()+ display=QImage(pixels,image.width,image.height,image.width*3,QImage.Format.Format_RGB888).copy()+ painter=QPainter(display)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(255,215,40,100))+ for word,x,y,w,h in self.result.boxes or []:+ if matches(word,self.result.query):+ sx,sy=image.width/original[0],image.height/original[1]+ painter.drawRect(int(x*sx),int(y*sy),int(w*sx),int(h*sy))+ painter.end()+ self.picture.setPixmap(QPixmap.fromImage(display))+ if not self.embedded:+ self.picture.setMinimumSize(display.size())++ def media(self):+ self.player=QMediaPlayer(self)+ self.audio=QAudioOutput(self)+ self.player.setAudioOutput(self.audio)+ self.audio.setVolume(.7)+ self.video=QVideoWidget()+ self.player.setVideoOutput(self.video)+ self.layout.addWidget(self.video,1)+ controls=QHBoxLayout()+ play=QPushButton('Pause / play')+ play.clicked.connect(lambda:self.player.pause() if self.player.playbackState()==QMediaPlayer.PlaybackState.PlayingState else self.player.play())+ self.seek=QSlider(Qt.Orientation.Horizontal)+ self.seek.setRange(0,0)+ self.seek.sliderMoved.connect(self.player.setPosition)+ self.player.durationChanged.connect(lambda duration:self.seek.setRange(0,duration))+ self.player.positionChanged.connect(self.position)+ self.player.errorOccurred.connect(lambda error,message:self.caption.setText('Playback error: '+message))+ controls.addWidget(play); controls.addWidget(self.seek,1)+ self.layout.addLayout(controls)+ self.pending_seek=max(0,round(self.result.seconds*1000))+ self.player.mediaStatusChanged.connect(self.loaded)+ self.player.setSource(QUrl.fromLocalFile(self.result.path))+ if not self.embedded:+ self.player.play()++ def loaded(self,status):+ if status in (QMediaPlayer.MediaStatus.LoadedMedia,QMediaPlayer.MediaStatus.BufferedMedia) and self.pending_seek is not None:+ self.player.setPosition(self.pending_seek)+ self.opened_position=self.pending_seek+ self.pending_seek=None++ def position(self,milliseconds):+ if not self.seek.isSliderDown():+ self.seek.setValue(milliseconds)+ seconds=milliseconds//1000+ self.caption.setText(f'{seconds//60}:{seconds%60:02d} · match at {self.result.location()} · {self.result.path}')++ def code(self):+ viewer=QPlainTextEdit()+ viewer.setReadOnly(True)+ viewer.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)+ viewer.setPlainText(Path(self.result.path).read_text(encoding='utf-8',errors='replace'))+ viewer.setStyleSheet('font-family: Consolas; font-size: 13px;')+ self.layout.addWidget(viewer,1)+ block=viewer.document().findBlockByLineNumber(max(0,self.result.line-1))+ cursor=QTextCursor(block)+ cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock)+ start=cursor.position()+ endblock=viewer.document().findBlockByLineNumber(max(0,self.result.end_line-1))+ endcursor=QTextCursor(endblock)+ endcursor.movePosition(QTextCursor.MoveOperation.EndOfBlock)+ cursor.setPosition(endcursor.position(),QTextCursor.MoveMode.KeepAnchor)+ selection=QTextEdit.ExtraSelection()+ selection.cursor=cursor+ selection.format.setBackground(QColor(103,87,232,65))+ viewer.setExtraSelections([selection])+ cursor.setPosition(start)+ viewer.setTextCursor(cursor)+ viewer.centerCursor()+ self.code_viewer=viewer++ def text(self):+ from vectordash_core import read_text+ viewer=QPlainTextEdit()+ viewer.setReadOnly(True)+ text=read_text(Path(self.result.path)) or self.result.snippet or 'No text preview available for this file.'+ viewer.setPlainText(text[:100000])+ selections=[]+ for word in query_words(self.result.query):+ cursor=viewer.document().find(word)+ while not cursor.isNull() and len(selections)<200:+ selection=QTextEdit.ExtraSelection()+ selection.cursor=cursor+ selection.format.setBackground(QColor(255,215,40,100))+ selections.append(selection)+ cursor=viewer.document().find(word,cursor)+ viewer.setExtraSelections(selections)+ self.layout.addWidget(viewer,1)++ def release(self,*args):+ if self.released:+ return+ self.released=True+ if self.player:+ self.player.blockSignals(True)+ self.player.stop()+ self.player.setAudioOutput(None)+ self.player.setVideoOutput(None)+ self.player.setSource(QUrl())+ if self.doc:+ self.doc.close()+ self.doc=None++ def closeEvent(self,event):+ self.release()+ super().closeEvent(event)+++class SelectionPreview(QWidget):+ """Shared right-hand preview; replaces and releases the previous selection."""+ def __init__(self,parent=None):+ super().__init__(parent)+ self.setMinimumWidth(260)+ self.layout=QVBoxLayout(self)+ self.layout.setContentsMargins(0,0,0,0)+ self.placeholder=QLabel('Select a result to preview it.')+ self.placeholder.setWordWrap(True)+ self.layout.addWidget(self.placeholder)+ self.current=None+ def show_result(self,result):+ self.clear()+ if not result:+ return+ from engine import SearchResult+ if not isinstance(result,SearchResult):+ result=SearchResult(0,str(result),'')+ try:+ self.current=Preview(result,self,embedded=True)+ self.layout.addWidget(self.current,1)+ self.current.show()+ self.placeholder.hide()+ except Exception as error:+ for child in self.findChildren(Preview,options=Qt.FindChildOption.FindDirectChildrenOnly):+ child.release()+ child.close()+ if self.current:+ self.current.release()+ self.current.deleteLater()+ self.current=None+ self.placeholder.setText('Preview unavailable: '+str(error))+ def clear(self):+ if self.current:+ self.current.release()+ self.layout.removeWidget(self.current)+ self.current.close()+ self.current=None+ self.placeholder.setText('Select a result to preview it.')+ self.placeholder.show()diff --git a/windows/process_lifecycle.py b/windows/process_lifecycle.pynew file mode 100644index 0000000..3d144ca--- /dev/null+++ b/windows/process_lifecycle.py@@ -0,0 +1,47 @@+"""Gate helper process creation during application shutdown."""+import subprocess+import threading++_lock=threading.RLock()+_closing=False++def reopen():+ global _closing+ with _lock:+ _closing=False++def close():+ global _closing+ with _lock:+ _closing=True++def popen(*args,**kwargs):+ with _lock:+ if _closing:+ raise InterruptedError('VectorDash is exiting')+ return subprocess.Popen(*args,**kwargs)++def run(*args,**kwargs):+ # subprocess.run enters Popen immediately. Holding this lock for its entire+ # wait would block shutdown, so use its native wait/timeout through a guarded+ # Popen context, preserving capture_output, input and check semantics.+ input_data=kwargs.pop('input',None)+ capture=kwargs.pop('capture_output',False)+ timeout=kwargs.pop('timeout',None)+ check=kwargs.pop('check',False)+ if capture:+ kwargs['stdout']=subprocess.PIPE+ kwargs['stderr']=subprocess.PIPE+ if input_data is not None:+ kwargs['stdin']=subprocess.PIPE+ with popen(*args,**kwargs) as process:+ try:+ stdout,stderr=process.communicate(input_data,timeout=timeout)+ except BaseException:+ process.kill()+ process.wait()+ raise+ result=subprocess.CompletedProcess(process.args,process.returncode,stdout,stderr)+ if check:+ result.check_returncode()+ return resultdiff --git a/windows/qa_desktop.py b/windows/qa_desktop.pynew file mode 100644index 0000000..25d3e90--- /dev/null+++ b/windows/qa_desktop.py@@ -0,0 +1,117 @@+"""Interactive Windows smoke checks; uses isolated settings and no startup registry writes."""+import ctypes, json, os, subprocess, sys, tempfile, time+from pathlib import Path+from unittest.mock import patch+sys.path.insert(0,str(Path(__file__).parent))+from PySide6.QtCore import QEvent, QTimer, Qt+from PySide6.QtTest import QTest+from PySide6.QtWidgets import QApplication+from engine import Settings+from desktop import Desktop+from windows_integration import GlobalHotkey, HOTKEY_ID++app=QApplication([])+app.setQuitOnLastWindowClosed(False)+root=Path(__file__).parent/'.smoke'/'interaction-data'+store=Settings(root)+store.values.update({'hotkey':'Ctrl+Alt+Shift+F24','theme':'Light','startup':False,'schedule_mode':'Manual'})+window=Desktop(store)+window.clock.stop()+window.process_timer.stop()+window.show()+app.processEvents()+# Allow the one-time startup telemetry request to finish before injecting test metrics.+QTest.qWait(800)+app.processEvents()++def wait_for(condition,seconds=5):+ until=time.monotonic()+seconds+ while time.monotonic()<until:+ app.processEvents()+ if condition(): return True+ QTest.qWait(20)+ return False++# Verify the real Windows message pump delivers WM_HOTKEY into Qt.+window.quick.hide()+assert ctypes.windll.user32.PostThreadMessageW(ctypes.windll.kernel32.GetCurrentThreadId(),0x0312,HOTKEY_ID,0)+assert wait_for(lambda:window.quick.isVisible()), 'Native shortcut did not summon search'+QTest.keyClick(window.quick,Qt.Key.Key_Escape)+assert wait_for(lambda:not window.quick.isVisible()),'Escape did not dismiss search'+print('Native global shortcut message and Escape passed')++# Another app reserving the combination must fail rather than silently replace it.+other=GlobalHotkey()+try:+ other.register('Ctrl+Alt+Shift+F24')+ raise AssertionError('Shortcut conflict was not detected')+except OSError:+ pass+print('Global shortcut conflict detection passed')++window.devices_finished([('CUDA0','NVIDIA RTX'),('Vulkan1','Intel UHD')],'')+window.devices.setCurrentIndex(2)+window.widgets['mode'].setCurrentText('Integrated GPU')+assert window.save(quiet=True)+assert store.values['device']=='Vulkan1'+print('Selectable device saved the exact runtime identifier')++with patch('desktop.set_startup') as startup:+ window.widgets['startup'].setChecked(True)+ assert window.save(quiet=True)+ startup.assert_called_once_with(True)+window.widgets['startup'].setChecked(False)+with patch('desktop.set_startup'):+ window.save(quiet=True)+print('Startup preference integration passed (isolated, no registry changes)')++window.settings['close_behavior']='Hide to tray'+window.close()+assert not window.isVisible()+window.show_main()+assert window.isVisible()+window.settings['close_behavior']='Minimize to taskbar'+window.close()+assert window.isMinimized()+window.show_main()+window.settings['minimize_behavior']='Tray'+window.showMinimized()+assert wait_for(lambda:not window.isVisible())+window.show_main()+print('Close to tray, close to taskbar, restore and minimize-to-tray passed')++window.quick.summon()+window.quick.results.populate([(1.0,'C:/example.txt','A searchable example')])+with patch('desktop.os.startfile') as opened:+ QTest.keyClick(window.quick.input,Qt.Key.Key_Return)+ opened.assert_called_once_with('C:/example.txt')+print('Quick-search Enter opens the selected result')++# Drive the actual scheduler controller/worker with a synthetic source.+assert wait_for(lambda:not window.collecting), 'Startup telemetry did not finish'+with tempfile.TemporaryDirectory(prefix='digup-ui-',dir=Path(__file__).parents[1]) as directory:+ source=Path(directory)+ (source/'notes.txt').write_text('Scheduling a local Windows index',encoding='utf-8')+ window.settings.update(roots=[str(source)],semantic=False,schedule_mode='When idle',check_user_idle=False,check_gpu=False,check_cpu=True,last_success='',cpu_limit=25)+ window.metrics={'cpu':5,'gpu':None,'idle':0,'on_ac':True}+ window.metrics_time=time.monotonic()+ window.metrics_finished(window.metrics)+ assert wait_for(lambda:not window.indexing), 'Scheduled indexing did not finish'+ assert window.settings['last_success'], 'Scheduled success was not recorded'+ assert window.engine.search('Scheduling',window.settings)+ window.metrics={'cpu':95,'gpu':None,'idle':0,'on_ac':True}+ window.metrics_time=time.monotonic()+ window.start_index(scheduled=True,slot='test-slot')+ QTest.qWait(100)+ assert window.indexing, 'Resource-conditioned indexing did not wait'+ window.widgets['schedule_mode'].setCurrentText('Manual')+ assert window.save(quiet=True)+ assert wait_for(lambda:not window.indexing), 'Disabling schedule did not stop the waiting job'+ print('Automatic scheduling, result commit, CPU waiting and schedule-disable cancellation passed')++window.shutting_down=True+window.hotkey.unregister()+window.tray.hide()+window.quick.hide()+window.close()+print('Desktop interaction checks passed')diff --git a/windows/qa_features.py b/windows/qa_features.pynew file mode 100644index 0000000..5653c45--- /dev/null+++ b/windows/qa_features.py@@ -0,0 +1,60 @@+"""Native checklist, logging, indexing icon and process shutdown checks."""+import json+from pathlib import Path+import subprocess+import sys+from unittest.mock import patch+import psutil+from PySide6.QtWidgets import QApplication+from PySide6.QtCore import Qt+from PySide6.QtTest import QTest+from engine import Settings,DEFAULTS+from desktop import Desktop+from vectordash_core import server_url+import process_lifecycle++app=QApplication([]);app.setQuitOnLastWindowClosed(False)+home=Path(__file__).parent/'.smoke/new-ui';home.mkdir(parents=True,exist_ok=True)+store=Settings(home);store.values=dict(DEFAULTS,hotkey='Ctrl+Alt+Shift+F21',theme='Light',ocr_enabled=False)+window=Desktop(store);window.clock.stop();window.process_timer.stop();window.show();QTest.qWait(100)+assert window.navigation.item(5).text()=='Logs'+# A shortcut held by another app must not block setup/indexing settings saves.+window.hotkey.unregister()+with patch.object(window.hotkey,'register',side_effect=OSError('Shortcut in use')) as register:+ assert window.save(quiet=True)+ register.assert_not_called()+assert 'unavailable' in window.shortcut_state.text()+window.hotkey.register(window.settings['hotkey'])+window.update_hotkey_status()+window.logger.warning('Skipped sample image: too many pixels');QTest.qWait(30)+window.log_filter.setCurrentText('Warning');assert 'sample image' in window.log_view.toPlainText()+window.log_filter.setCurrentText('Error');assert 'sample image' not in window.log_view.toPlainText()+window.indexing=True;window.animate_index_icon()+red=window.windowIcon().pixmap(64,64).toImage().pixelColor(6,30)+window.engine.paused.set();window.animate_index_icon()+purple=window.windowIcon().pixmap(64,64).toImage().pixelColor(6,30)+assert red.red()>red.blue() and purple.blue()>purple.red(),(red.name(),purple.name())+window.engine.paused.clear();window.index_finished('2 files indexed', '',True,'Manual')+assert window.source_progress.value()==100 and window.source_status.text()=='2 files indexed'+# Master setup uses the chosen model + projector, configures paths and starts.+window.launch=lambda work:work()+model={'label':'Q8_0','projector':{'label':'encoder'}};runtime={'backend':'cpu'}+with patch('desktop.catalogs',return_value=([runtime],[model])),patch('desktop.install_runtime',return_value='H:/managed/llama-server.exe'),patch('desktop.install_model',side_effect=['H:/managed/model-Q8_0.gguf','H:/managed/mmproj-Q8_0.gguf']),patch('desktop.install_ffmpeg',return_value={'ffmpeg_path':'H:/managed/ffmpeg.exe'}),patch.object(window,'start_model') as start:+ window.setup_all()+ assert window.settings['semantic'] and window.settings['projector'].endswith('mmproj-Q8_0.gguf')+ start.assert_called_once()+window.navigation.setCurrentRow(2);QTest.qWait(50)+window.grab().save(str(home/'models-status.png'))+# Real child process cleanup, with a separate helper still running.+window.model_process=process_lifecycle.popen([sys.executable,'-c','import time;time.sleep(120)'],creationflags=subprocess.CREATE_NO_WINDOW)+helper=process_lifecycle.popen([sys.executable,'-c','import time;time.sleep(120)'],creationflags=subprocess.CREATE_NO_WINDOW)+model_pid=window.model_process.pid;helper_pid=helper.pid+window.cleanup()+assert not psutil.pid_exists(model_pid) and not psutil.pid_exists(helper_pid)+with patch('process_lifecycle.subprocess.Popen') as spawn:+ try:process_lifecycle.popen(['new-helper'])+ except InterruptedError:pass+ else:raise AssertionError('Shutdown allowed another helper process')+ spawn.assert_not_called()+window.close()+print('Setup checklist, automatic start, log filters, indexing status/icon and real model/helper shutdown passed.')diff --git a/windows/qa_multimedia.py b/windows/qa_multimedia.pynew file mode 100644index 0000000..281012e--- /dev/null+++ b/windows/qa_multimedia.py@@ -0,0 +1,57 @@+"""Opt-in real model QA. Requires the isolated server on port 8788 and local fixtures."""+import os+os.environ['VECTORDASH_SERVER_URL']='http://127.0.0.1:8788'+import json+from pathlib import Path+import subprocess+import sys+sys.stdout.reconfigure(encoding="utf-8")+import pymupdf+from engine import Engine,DEFAULTS+from content import ffmpeg++root=Path(__file__).parent.resolve()/'.smoke/multimedia'+source=root/'source'+project=root/'project'+project.mkdir(exist_ok=True)+if not (project/'.git').exists():+ subprocess.run(['git','init',str(project)],check=True,capture_output=True,creationflags=subprocess.CREATE_NO_WINDOW)+source.mkdir(exist_ok=True)+managed=Path(__file__).parent.resolve()/'.smoke/managed'+info=json.loads((managed/'result.json').read_text())+settings=dict(DEFAULTS,roots=[str(source)],semantic=True,model=info['model'],projector=str(managed/'models/mmproj-embeddinggemma-2-Q8_0.gguf'),code_enabled=True,code_roots=[str(project)])+flags={'check':True,'capture_output':True,'creationflags':subprocess.CREATE_NO_WINDOW}+if not (source/'004.mp4').exists():+ subprocess.run([ffmpeg(settings),'-y','-loop','1','-i',str(root/'blank.png'),'-loop','1','-i',str(root/'scene.png'),'-filter_complex','[0:v]trim=duration=6,setpts=PTS-STARTPTS[a];[1:v]trim=duration=6,setpts=PTS-STARTPTS[b];[a][b]concat=n=2:v=1:a=0[out]','-map','[out]','-r','10','-c:v','libx264','-pix_fmt','yuv420p',str(source/'004.mp4')],**flags)+if not (source/'005.wav').exists():+ subprocess.run([ffmpeg(settings),'-y','-i',str(root/'speech.wav'),'-af','adelay=32000:all=1','-ac','1','-ar','16000',str(source/'005.wav')],**flags)+(source/'006.txt').write_text('ঘুম ভালো হলে শরীর ও মন সুস্থ থাকে। প্রতিদিন নিয়মিত সময়ে ঘুমানো উচিত।',encoding='utf-8')+(source/'007.txt').write_text('يجب شرب الماء بانتظام للحفاظ على صحة الجسم وتجنب الجفاف.',encoding='utf-8')+(source/'008.txt').write_text('Healthy sleep improves memory and helps the body recover overnight.',encoding='utf-8')+with pymupdf.open() as doc:+ page=doc.new_page(); page.insert_text((72,72),'Lease agreement. Rent is due on the first day of each month.')+ page=doc.new_page(); page.insert_text((72,72),'Pets clause: Dogs and cats are permitted with written landlord approval.')+ doc.save(source/'009.pdf')+(project/'retry.py').write_text('import time\n\ndef retry_request(call, attempts=4):\n """Retry a failed network call with exponential backoff."""\n for attempt in range(attempts):\n try:\n return call()\n except ConnectionError:\n if attempt == attempts - 1:\n raise\n time.sleep(2 ** attempt)\n',encoding='utf-8')+engine=Engine(root)+print(engine.index(settings,progress=lambda text:print(text,flush=True),force=True),flush=True)+queries=['zebra in a video','where they talk about sleep','the clause about pets in the lease','a dog','a dog on the beach','cellphone','payment declined error','INV-2026-00891','E_PAYMENT_402','regular bedtime','drink water to avoid dehydration','ঘুম শরীর সুস্থ রাখে','code: retry a failed call with backoff']+report={}+for query in queries:+ results=engine.search(query,settings)+ report[query]=[{'file':Path(r.path).name,'score':round(r.score,4),'kind':r.kind,'page':r.page,'seconds':r.seconds,'line':r.line,'snippet':r.snippet} for r in results[:5]]+ print(query,json.dumps(report[query],ensure_ascii=False),flush=True)+(root/'report.json').write_text(json.dumps(report,indent=2,ensure_ascii=False),encoding='utf-8')+assert report['zebra in a video'][0]['file']=='004.mp4' and report['zebra in a video'][0]['seconds']>=6+assert any(r['file']=='005.wav' and r['seconds']>=25 for r in report['where they talk about sleep'])+assert report['the clause about pets in the lease'][0]['page']==2+assert report['a dog'][0]['file'] in ('002.jpg','011.jpg')+assert report['a dog on the beach'][0]['file']=='011.jpg'+assert report['cellphone'][0]['file']=='010.jpg'+assert report['payment declined error'][0]['file']=='003.png'+assert report['INV-2026-00891'][0]['file']=='003.png'+assert report['E_PAYMENT_402'][0]['file']=='003.png'+assert report['drink water to avoid dehydration'][0]['file']=='007.txt'+assert any(r['file']=='008.txt' for r in report['ঘুম শরীর সুস্থ রাখে'])+assert report['code: retry a failed call with backoff'][0]['line']==3+print('Real multimodal retrieval checks passed.',flush=True)diff --git a/windows/qa_previews.py b/windows/qa_previews.pynew file mode 100644index 0000000..46724c3--- /dev/null+++ b/windows/qa_previews.py@@ -0,0 +1,67 @@+import os+# Use the native Windows multimedia backend during this interaction check.+os.environ['VECTORDASH_SERVER_URL']='http://127.0.0.1:8788'+import hashlib,json,time,faulthandler+faulthandler.dump_traceback_later(20,repeat=True)+from pathlib import Path+from PySide6.QtWidgets import QApplication+from PySide6.QtCore import Qt+from PySide6.QtTest import QTest+from engine import Engine,DEFAULTS+from previews import Preview+from desktop import Results+app=QApplication([])+root=Path(__file__).parent.resolve()/'.smoke/multimedia'+managed=Path(__file__).parent.resolve()/'.smoke/managed'+info=json.loads((managed/'result.json').read_text())+settings=dict(DEFAULTS,semantic=True,model=info['model'],projector=str(managed/'models/mmproj-embeddinggemma-2-Q8_0.gguf'),code_enabled=True)+engine=Engine(root)+class Owner:+ def open_file(self,value): self.opened=value+owner=Owner()+results=Results(owner)+pdf=engine.search('the clause about pets in the lease',settings)[0]+original=hashlib.sha256(Path(pdf.path).read_bytes()).hexdigest()+results.populate([pdf])+assert results.selected_path()==pdf.path+assert results.selected_result().page==2+preview=Preview(pdf)+preview.show(); QTest.qWait(100)+assert preview.page.value()==2 and preview.highlight_count>=1+preview.grab().save(str(root/'pdf-preview.png'))+preview.close(); QTest.qWait(30)+assert hashlib.sha256(Path(pdf.path).read_bytes()).hexdigest()==original+image=engine.search('E_PAYMENT_402',settings)[0]+preview=Preview(image)+preview.show(); QTest.qWait(100)+assert not preview.picture.pixmap().isNull()+preview.grab().save(str(root/'image-preview.png'))+preview.close(); QTest.qWait(30)+code=engine.search('code: retry a failed call with backoff',settings)[0]+preview=Preview(code)+preview.show(); QTest.qWait(100)+assert preview.code_viewer.textCursor().blockNumber()==2+assert 'retry_request' in preview.code_viewer.toPlainText()+preview.grab().save(str(root/'code-preview.png'))+preview.close(); QTest.qWait(30)+for query in ('zebra in a video','where they talk about sleep'):+ result=engine.search(query,settings)[0]+ preview=Preview(result)+ preview.show()+ deadline=time.monotonic()+12+ while not hasattr(preview,'opened_position') and time.monotonic()<deadline:+ QTest.qWait(100)+ assert hasattr(preview,'opened_position'),preview.caption.text()+ assert abs(preview.opened_position-result.seconds*1000)<1+ preview.player.pause()+ assert preview.player.position()>=preview.opened_position-500,(query,preview.player.position(),preview.opened_position)+ print(query,'opened at',preview.opened_position,'ms',flush=True)+ print('Closing preview',flush=True)+ if result.kind=='audio':+ QTest.keyClick(preview,Qt.Key.Key_Escape)+ else:+ preview.close()+ QTest.qWait(100)+ assert preview.released+faulthandler.cancel_dump_traceback_later()+print('Native PDF highlights, image/code previews and real media seeking passed.',flush=True)diff --git a/windows/qa_search_benchmark.py b/windows/qa_search_benchmark.pynew file mode 100644index 0000000..769781d--- /dev/null+++ b/windows/qa_search_benchmark.py@@ -0,0 +1,22 @@+"""Synthetic search benchmark; excludes model and UI latency."""+import json,random,time,statistics,sys+from pathlib import Path+from unittest.mock import patch+from engine import Engine,DEFAULTS,model_signature+home=Path(__file__).parent/'.smoke/search-benchmark';home.mkdir(parents=True,exist_ok=True)+model=home/'model.gguf';model.write_bytes(b'fixture')+settings=dict(DEFAULTS,semantic=True,model=str(model),ocr_enabled=False)+engine=Engine(home)+r=random.Random(43)+with engine.connect() as db:+ if not db.execute('SELECT 1 FROM segments LIMIT 1').fetchone():+ for i in range(1500):+ vector=[r.random() for _ in range(768)]+ db.execute('INSERT INTO segments VALUES(?,?,?,?,?,?)',(f'C:/photos/dog_{i}.jpg','files','image','photo',json.dumps(vector),'{}'))+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')+ db.execute("INSERT OR REPLACE INTO metadata VALUES('signature',?)",(model_signature(settings),))+with patch('engine.verify_server_model'),patch('engine.embed',return_value=[.5]*768):+ timings=[]+ for query in ('images of dogs','photos of dogs','a dog on the beach','images of dogs'):+ start=time.perf_counter();engine.search(query,settings);timings.append((time.perf_counter()-start)*1000)+ print(json.dumps({'files':1500,'segments':1500,'dimension':768,'ms':timings,'warm_median_ms':statistics.median(timings[1:])}))diff --git a/windows/qa_selection.py b/windows/qa_selection.pynew file mode 100644index 0000000..5c826dc--- /dev/null+++ b/windows/qa_selection.py@@ -0,0 +1,107 @@+"""Native selection preview, selective setup, status colors and Explorer checks."""+from pathlib import Path+from unittest.mock import patch+from PIL import Image+from PySide6.QtWidgets import QApplication,QPlainTextEdit+from PySide6.QtCore import Qt+from PySide6.QtTest import QTest+from engine import Settings,DEFAULTS,SearchResult+from desktop import Desktop+app=QApplication([]);app.setQuitOnLastWindowClosed(False)+home=Path(__file__).parent/'.smoke/selection-ui';home.mkdir(parents=True,exist_ok=True)+image=home/'dog photo.png';Image.new('RGB',(640,400),'tan').save(image)+text=home/'notes.txt';text.write_text('Invoice INV-99 and payment declined')+store=Settings(home);store.values=dict(DEFAULTS,hotkey='Ctrl+Alt+Shift+F20',theme='Light',ocr_enabled=False)+window=Desktop(store);window.clock.stop();window.process_timer.stop();window.show();QTest.qWait(60)+assert 'semantic' not in window.widgets and window.settings['semantic']+assert window.quick.input.actions() and not window.quick.input.actions()[0].icon().isNull()+assert 'QScrollBar::handle:vertical' in app.styleSheet() and 'border-radius: 4px' in app.styleSheet()+photo=SearchResult(1,str(image),'',kind='image',query='dogs')+note=SearchResult(.8,str(text),'Invoice INV-99',query='INV-99')+window.results.populate([photo,note]);QTest.qWait(40)+preview=window.result_preview.current+assert preview and not preview.picture.pixmap().isNull()+assert window.result_preview.geometry().left()>window.results.geometry().left()+window.results.setCurrentRow(1);QTest.qWait(30)+assert preview.released+viewer=window.result_preview.current.findChild(QPlainTextEdit)+assert viewer and 'INV-99' in viewer.toPlainText() and viewer.isReadOnly()+fixtures=Path(__file__).parent/'.smoke/multimedia/source'+if (fixtures/'009.pdf').exists():+ pdf=SearchResult(1,str((fixtures/'009.pdf').resolve()),'pets',kind='pdf',page=2,query='pets')+ window.results.populate([pdf]);QTest.qWait(30)+ assert window.result_preview.current.page.value()==2+ assert window.result_preview.current.highlight_count>0+if (fixtures/'004.mp4').exists():+ from PySide6.QtMultimedia import QMediaPlayer+ media=SearchResult(1,str((fixtures/'004.mp4').resolve()),'',kind='video',seconds=9.2)+ window.results.populate([media])+ player_preview=window.result_preview.current+ for _ in range(100):+ QTest.qWait(30)+ if hasattr(player_preview,'opened_position'):break+ assert player_preview.opened_position==9200+ assert player_preview.player.playbackState()!=QMediaPlayer.PlaybackState.PlayingState+ window.results.populate([photo,note]);QTest.qWait(30)+ assert player_preview.released+window.results.populate([photo,note]);QTest.qWait(30)+window.results.setCurrentRow(0);QTest.qWait(30)+window.results.setFocus()+QTest.keyClick(window.results,Qt.Key.Key_C,Qt.KeyboardModifier.ControlModifier)+clipboard=app.clipboard().mimeData()+assert clipboard.hasUrls() and Path(clipboard.urls()[0].toLocalFile())==image.resolve()+import ctypes+assert ctypes.windll.user32.IsClipboardFormatAvailable(15), 'Missing Windows file-copy format CF_HDROP'+from previews import Preview+QTest.keyClick(window.results,Qt.Key.Key_Space);QTest.qWait(30)+large=window.findChildren(Preview,options=Qt.FindChildOption.FindDirectChildrenOnly)+assert large and large[-1].isVisible() and not large[-1].embedded+large[-1].close();QTest.qWait(20)+window.grab().save(str(home/'search-preview.png'))+with patch.object(window,'request_search'):+ window.quick.summon()+ window.quick.results.populate([photo,note]);QTest.qWait(30)+ assert window.quick.preview.current and not window.quick.preview.current.picture.pixmap().isNull()+ popup=window.quick.grab()+ popup.save(str(home/'quick-preview.png'))+ assert popup.toImage().pixelColor(0,0).alpha()==0+ border=popup.toImage().pixelColor(3,popup.height()//2)+ assert border.blue()>border.red() and border.alpha()>200, border.name()+ with patch.object(window,'preview_result') as preview_action:+ QTest.keyClick(window.quick.results,Qt.Key.Key_Space)+ preview_action.assert_called_once_with(photo)+ QTest.keyClick(window.quick.results,Qt.Key.Key_C,Qt.KeyboardModifier.ControlModifier)+ assert Path(app.clipboard().mimeData().urls()[0].toLocalFile())==image.resolve()+ quick_preview=window.quick.preview.current+ window.quick.hide();QTest.qWait(30)+ assert quick_preview.released and window.quick.preview.current is None+with patch('desktop.reveal_in_explorer') as reveal:+ window.reveal();reveal.assert_called_once_with(str(image))+for key,name in [('server','llama-server.exe'),('model','embeddinggemma-2-Q8_0.gguf')]:+ path=home/name;path.write_bytes(b'fixture')+ window.settings[key]=str(path);window.widgets[key].setText(str(path))+for key in ('ocr','projector','ffmpeg'):window.setup_choices[key].setChecked(False)+window.update_tool_state()+assert window.setup_button.text()=='Start'+assert window.setup_cancel.isHidden()+window.installing=True;window.update_tool_state();assert not window.setup_cancel.isHidden()+window.installing=False;window.update_tool_state()+assert '#aa7900' in window.component_status['model'].styleSheet()+assert window.component_status['model'].alignment() & Qt.AlignmentFlag.AlignRight+window.model_status('loaded · text: ready')+assert '#16834a' in window.component_status['model'].styleSheet()+assert not window.setup_button.isEnabled()+assert 'indexed files' in window.index_count.text()+assert '#c73545' in window.component_status['projector'].styleSheet()+with patch.object(window,'start_model') as start,patch.object(window,'refresh_component_status'),patch('desktop.catalogs') as catalogs:+ window.setup_all();start.assert_called_once();catalogs.assert_not_called()+window.settings['ffmpeg_path']=str(home/'missing-ffmpeg.exe');window.widgets['ffmpeg_path'].setText(window.settings['ffmpeg_path'])+window.setup_choices['ffmpeg'].setChecked(True)+window.launch=lambda work:work()+with patch('desktop.catalogs') as catalogs,patch('desktop.install_model') as model,patch('desktop.install_runtime') as runtime,patch('desktop.install_ocr') as ocr,patch('desktop.install_ffmpeg',return_value={'ffmpeg_path':str(home/'ffmpeg.exe')}) as decoder,patch.object(window,'start_model'),patch.object(window,'refresh_component_status'):+ window.setup_all()+ decoder.assert_called_once();catalogs.assert_not_called();model.assert_not_called();runtime.assert_not_called();ocr.assert_not_called()+window.navigation.setCurrentRow(2);QTest.qWait(30)+window.grab().save(str(home/'setup-options.png'))+window.cleanup();window.close()+print('Main and quick previews, text highlights, exact Explorer dispatch, status colors, Start button and selective setup passed.')diff --git a/windows/qa_tool_settings.py b/windows/qa_tool_settings.pynew file mode 100644index 0000000..bd98606--- /dev/null+++ b/windows/qa_tool_settings.py@@ -0,0 +1,61 @@+"""Native settings checks for scrolling and automatic setup workflow."""+import json+from pathlib import Path+from unittest.mock import patch+from PySide6.QtCore import Qt,QPoint,QPointF,QTime+from PySide6.QtGui import QWheelEvent+from PySide6.QtWidgets import QApplication,QAbstractSpinBox,QScrollArea,QPushButton+from PySide6.QtTest import QTest+from engine import Settings,DEFAULTS+from desktop import Desktop,ScrollSafeSpinBox,ScrollSafeTimeEdit++app=QApplication([]);app.setQuitOnLastWindowClosed(False)+home=Path(__file__).parent/'.smoke/tool-ui';home.mkdir(parents=True,exist_ok=True)+store=Settings(home);store.values=dict(DEFAULTS,hotkey='Ctrl+Alt+Shift+F22',theme='Light')+window=Desktop(store);window.clock.stop();window.process_timer.stop();window.show()+QTest.qWait(100)+model_page=window.stack.widget(2)+for key in ('ocr_enabled','ocr_path','ocr_data','ocr_languages','ffmpeg_path','projector'):+ assert model_page.isAncestorOf(window.widgets[key]),key++for page,key in [(1,'video_interval'),(3,'cpu_limit'),(3,'gpu_limit'),(3,'idle_minutes'),(3,'schedule_time')]:+ window.navigation.setCurrentRow(page);QTest.qWait(20)+ widget=window.widgets[key]+ scroll=window.stack.widget(page).findChild(QScrollArea)+ scroll.ensureWidgetVisible(widget)+ widget.setFocus()+ before=widget.time() if isinstance(widget,ScrollSafeTimeEdit) else widget.value()+ for amount in (120,-120):+ local=QPoint(5,5)+ event=QWheelEvent(QPointF(local),QPointF(widget.mapToGlobal(local)),QPoint(),QPoint(0,amount),Qt.MouseButton.NoButton,Qt.KeyboardModifier.NoModifier,Qt.ScrollPhase.NoScrollPhase,False)+ app.sendEvent(widget.lineEdit(),event)+ assert (widget.time() if isinstance(widget,ScrollSafeTimeEdit) else widget.value())==before,key+print('Focused numeric/time fields keep their values when wheel scrolling through settings.')+widget=window.widgets['cpu_limit'];scroll=window.stack.widget(3).findChild(QScrollArea)+scroll.ensureWidgetVisible(widget);bar=scroll.verticalScrollBar()+bar.setValue(bar.maximum()//2);before=bar.value()+event=QWheelEvent(QPointF(5,5),QPointF(widget.mapToGlobal(QPoint(5,5))),QPoint(),QPoint(0,-120),Qt.MouseButton.NoButton,Qt.KeyboardModifier.NoModifier,Qt.ScrollPhase.NoScrollPhase,False)+app.sendEvent(widget,event)+assert bar.value()!=before,(before,bar.value())+print('Wheel scrolling over a numeric field still scrolls the settings page.')+# Keyboard editing remains available.+widget.setFocus();value=widget.value();QTest.keyClick(widget,Qt.Key.Key_Up)+assert widget.value()==min(widget.maximum(),value+1)+print('Keyboard arrows still change numeric values intentionally.')+# No catalog needs to be loaded before an encoder setup button works.+window.models=[];window.runtimes=[]+window.quant_choice.setCurrentIndex(1)+model={'label':'BF16','name':'model.gguf','size':1,'projector':{'name':'mmproj.gguf','label':'Vision/audio'}}+runtime={'label':'CPU','backend':'cpu','size':1}+with patch('desktop.catalogs',return_value=([runtime],[model])),patch('desktop.install_model',return_value='H:/verified/mmproj.gguf') as install:+ window.launch=lambda work:work()+ window.install('projector')+ assert install.call_args.args[0]['name']=='mmproj.gguf'+ assert window.settings['projector']=='H:/verified/mmproj.gguf'+ assert window.quant_choice.currentData()=='BF16'+print('One-click encoder setup loads its catalog, preserves quant selection and saves its path.')+with patch('desktop.install_ffmpeg',return_value={'ffmpeg_path':'H:/verified/ffmpeg.exe'}):+ window.install_tool('ffmpeg')+ assert window.settings['ffmpeg_path']=='H:/verified/ffmpeg.exe'+print('One-click tool setup saves its configured executable path.')+window.hotkey.unregister();window.tray.hide();window.shutting_down=True;window.close()diff --git a/windows/requirements.txt b/windows/requirements.txtnew file mode 100644index 0000000..e20caea--- /dev/null+++ b/windows/requirements.txt@@ -0,0 +1,7 @@+PySide6-Essentials>=6.10,<7+PySide6-Addons>=6.10,<7+psutil>=7,<8+Pillow>=12,<13+PyMuPDF>=1.26,<2+imageio-ffmpeg>=0.6,<1+numpy>=2,<3diff --git a/windows/scheduling.py b/windows/scheduling.pynew file mode 100644index 0000000..5c40ba2--- /dev/null+++ b/windows/scheduling.py@@ -0,0 +1,75 @@+"""Pure scheduling policy: telemetry is supplied by the desktop controller."""+from datetime import datetime, timedelta++def idle_allowed(settings, metrics):+ idle = metrics.get('idle')+ if settings.get('check_user_idle',True) and idle is None:+ return False, 'User idle monitoring unavailable'+ if settings.get('check_user_idle',True) and idle < settings['idle_minutes']*60:+ return False, 'Waiting for keyboard and mouse to be idle'+ if settings['check_cpu']:+ cpu = metrics.get('cpu')+ if cpu is None:+ return False, 'CPU monitoring unavailable'+ if cpu > settings['cpu_limit']:+ return False, 'Waiting for CPU usage to fall'+ if settings['check_gpu']:+ gpu = metrics.get('gpu')+ if gpu is None:+ return False, 'GPU monitoring unavailable; disable GPU condition to proceed'+ if gpu > settings['gpu_limit']:+ return False, 'Waiting for GPU usage to fall'+ if settings['ac_only'] and metrics.get('on_ac') is not True:+ return False, 'Waiting for AC power'+ return True, 'Idle conditions met'+++def latest_slot(settings, now):+ hour, minute = map(int,settings['schedule_time'].split(':'))+ for offset in range(8):+ date = now.date() - timedelta(days=offset)+ candidate = datetime.combine(date,datetime.min.time()).replace(hour=hour,minute=minute)+ if date.weekday() in settings['schedule_days'] and candidate <= now:+ return candidate+ return None+++def schedule_due(settings, now, metrics):+ mode = settings['schedule_mode']+ if mode == 'Manual':+ return False, '', 'Automatic indexing is off'+ if mode == 'When idle':+ last = settings.get('last_success')+ if last and now < datetime.fromisoformat(last)+timedelta(minutes=settings['idle_interval']):+ return False, '', 'Waiting for the next idle indexing interval'+ allowed, reason = idle_allowed(settings,metrics)+ return allowed, now.isoformat(), reason+ slot = latest_slot(settings,now)+ if not slot:+ return False, '', 'Waiting for the selected day and time'+ # On first enabling, avoid running a schedule from yesterday immediately.+ enabled = settings.get('schedule_enabled_at')+ if enabled and slot < datetime.fromisoformat(enabled):+ return False, '', 'Waiting for the selected day and time'+ previous = settings.get('last_schedule_slot')+ if previous and slot <= datetime.fromisoformat(previous):+ return False, '', 'Waiting for the next scheduled time'+ if settings['ac_only'] and metrics.get('on_ac') is not True:+ return False, '', 'Waiting for AC power'+ if mode == 'Time + idle':+ allowed, reason = idle_allowed(settings,metrics)+ return allowed, slot.isoformat(), reason+ return True, slot.isoformat(), 'Scheduled indexing is due'+++def next_run(settings, now):+ if settings['schedule_mode'] == 'Manual':+ return 'Manual only'+ if settings['schedule_mode'] == 'When idle':+ return 'When idle conditions are met'+ hour,minute=map(int,settings['schedule_time'].split(':'))+ for offset in range(8):+ candidate=(now+timedelta(days=offset)).replace(hour=hour,minute=minute,second=0,microsecond=0)+ if candidate.weekday() in settings['schedule_days'] and candidate>now:+ return candidate.strftime('%a %b %d, %I:%M %p')+ return 'No days selected'diff --git a/windows/setup_runtime.py b/windows/setup_runtime.pynew file mode 100644index 0000000..b336024--- /dev/null+++ b/windows/setup_runtime.py@@ -0,0 +1,171 @@+"""Download pinned official catalogs and install user-selected local assets."""+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import platform+import shutil+import threading+import urllib.request+import zipfile++MODEL_REPO = 'ggml-org/embeddinggemma-2-GGUF'+HEADERS = {'User-Agent': 'VectorDash-Windows/0.3', 'Accept': 'application/json'}+++def fetch_json(url):+ with urllib.request.urlopen(urllib.request.Request(url,headers=HEADERS),timeout=30) as response:+ return json.load(response)+++def catalogs():+ arch = 'arm64' if platform.machine().lower() in ('arm64','aarch64') else 'x64'+ releases=fetch_json('https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=20')+ runtimes=[]+ for release in releases:+ if release.get('draft'):+ continue+ assets=release['assets']+ for asset in assets:+ name=asset['name']+ if not name.startswith('llama-') or not name.endswith(f'-{arch}.zip') or '-bin-win-' not in name:+ continue+ backend=name.split('-bin-win-',1)[1].removesuffix(f'-{arch}.zip')+ if not (backend in ('cpu','vulkan') or backend.startswith('cuda-')):+ continue+ bundle=[asset]+ if backend.startswith('cuda-'):+ companion=next((a for a in assets if a['name']==f'cudart-llama-bin-win-{backend}-{arch}.zip'),None)+ if companion:+ bundle.append(companion)+ runtimes.append({'label':f'{backend.upper()} · {release["tag_name"]} · {arch}', 'version':release['tag_name'], 'backend':backend, 'assets':bundle,'size':sum(a['size'] for a in bundle)})+ if runtimes:+ break+ model=fetch_json(f'https://huggingface.co/api/models/{MODEL_REPO}?blobs=true')+ models=[]+ projectors={file['rfilename']: file for file in model.get('siblings',[]) if file['rfilename'].startswith('mmproj-')}+ for file in model.get('siblings',[]):+ name=file['rfilename']+ if not name.startswith('embeddinggemma-2-') or not name.endswith('.gguf'):+ continue+ info=file.get('lfs',{})+ models.append({'label':name.removeprefix('embeddinggemma-2-').removesuffix('.gguf'), 'name':name,'size':info.get('size',file.get('size',0)), 'sha256':info.get('sha256'), 'url':f'https://huggingface.co/{MODEL_REPO}/resolve/{model["sha"]}/{name}'})+ for item in models:+ name='mmproj-embeddinggemma-2-'+item['label']+'.gguf'+ file=projectors.get(name) or projectors.get('mmproj-embeddinggemma-2-Q8_0.gguf')+ if file:+ info=file.get('lfs',{})+ item['projector']={'label':'Vision + audio encoder','name':file['rfilename'],'size':info.get('size',file.get('size',0)),'sha256':info.get('sha256'),'url':f'https://huggingface.co/{MODEL_REPO}/resolve/{model["sha"]}/{file["rfilename"]}'}+ if not runtimes or not models:+ raise RuntimeError('No compatible Windows runtime/model assets were found in the official catalogs.')+ return runtimes,models+++def download(url, destination, size, checksum, cancel, progress):+ if cancel.is_set():+ raise InterruptedError('Download cancelled')+ destination=Path(destination)+ destination.parent.mkdir(parents=True,exist_ok=True)+ partial=destination.with_name(destination.name+'.part')+ offset=partial.stat().st_size if partial.exists() else 0+ if size and offset>size:+ partial.unlink()+ offset=0+ if not size or offset<size:+ headers={'User-Agent':HEADERS['User-Agent']}+ if offset:+ headers['Range']=f'bytes={offset}-'+ request=urllib.request.Request(url,headers=headers)+ with urllib.request.urlopen(request,timeout=30) as response:+ if offset and response.status != 206:+ offset=0+ if offset and not response.headers.get('Content-Range','').startswith(f'bytes {offset}-'):+ raise RuntimeError('Download server returned an unexpected resume range.')+ with partial.open('ab' if offset else 'wb') as output:+ while True:+ if cancel.is_set():+ raise InterruptedError('Download cancelled; partial file retained for resume')+ chunk=response.read(1024*1024)+ if not chunk:+ break+ output.write(chunk)+ offset+=len(chunk)+ if size and offset>size:+ raise RuntimeError('Download exceeds the expected file size.')+ progress(offset,size)+ if size and partial.stat().st_size != size:+ raise RuntimeError('Incomplete download; retry to resume.')+ if checksum:+ git_hash=checksum.startswith('git-sha1:')+ digest=hashlib.sha1() if git_hash else hashlib.sha256()+ if git_hash:+ digest.update(b'blob '+str(partial.stat().st_size).encode()+b'\0')+ with partial.open('rb') as stream:+ while chunk:=stream.read(1024*1024):+ if cancel.is_set():+ raise InterruptedError('Verification cancelled; partial file retained')+ digest.update(chunk)+ if digest.hexdigest().lower() != checksum.removeprefix('sha256:').removeprefix('git-sha1:').lower():+ partial.unlink()+ raise RuntimeError('Checksum mismatch; corrupt download discarded. Retry the download.')+ if cancel.is_set():+ raise InterruptedError('Download cancelled; partial file retained')+ partial.replace(destination)+ return destination+++def extract_archive(archive, target):+ target=Path(target).resolve()+ with zipfile.ZipFile(archive) as bundle:+ if sum(info.file_size for info in bundle.infolist())>4*1024**3:+ raise RuntimeError('Runtime archive expands beyond the allowed size.')+ for info in bundle.infolist():+ name=info.filename.replace('\\','/')+ path=PurePosixPath(name)+ if path.is_absolute() or '..' in path.parts or ':' in name or (info.external_attr >> 16) & 0o170000 == 0o120000:+ raise RuntimeError('Unsafe path in runtime archive.')+ resolved=(target/name).resolve()+ if not resolved.is_relative_to(target):+ raise RuntimeError('Archive entry escapes the installation folder.')+ bundle.extractall(target)+++def install_runtime(item, home, cancel, progress):+ home=Path(home)+ target=home/'runtimes'/f'{item["version"]}-{item["backend"]}'+ if target.exists():+ found=list(target.rglob('llama-server.exe'))+ if found:+ return str(found[0])+ staging=target.with_name(target.name+'.staging')+ staging.mkdir(parents=True,exist_ok=True)+ assets=item['assets']+ for index,asset in enumerate(assets):+ free=shutil.disk_usage(home).free+ if free<asset['size']*3:+ raise RuntimeError('Not enough disk space to download and unpack the runtime.')+ archive=download(asset['browser_download_url'],home/'downloads'/asset['name'],asset['size'],asset.get('digest'),cancel,lambda done,total:progress(f'Runtime {index+1}/{len(assets)}',done,total))+ if cancel.is_set():+ raise InterruptedError('Setup cancelled')+ extract_archive(archive,staging)+ found=list(staging.rglob('llama-server.exe'))+ if not found:+ raise RuntimeError('Downloaded runtime does not contain llama-server.exe.')+ # Put runtime dependencies next to the executable even if companion ZIP layouts differ.+ server=found[0]+ for dll in list(staging.rglob('*.dll')):+ if dll.parent != server.parent and not (server.parent/dll.name).exists():+ shutil.copy2(dll,server.parent/dll.name)+ if target.exists():+ raise RuntimeError('An incomplete install already exists; choose another runtime version.')+ relative=server.relative_to(staging)+ staging.rename(target)+ return str(target/relative)+++def install_model(item,home,cancel,progress):+ home=Path(home)+ if shutil.disk_usage(home).free<item['size']:+ raise RuntimeError('Not enough free disk space for the model.')+ target=home/'models'/item['name']+ return str(download(item['url'],target,item['size'],item.get('sha256'),cancel,lambda done,total:progress('EmbeddingGemma 2',done,total)))diff --git a/windows/setup_tools.py b/windows/setup_tools.pynew file mode 100644index 0000000..92a36e9--- /dev/null+++ b/windows/setup_tools.py@@ -0,0 +1,92 @@+"""One-click Windows OCR, verified language packs and bundled media decoder setup."""+import hashlib+import os+from pathlib import Path+import re+import shutil+import subprocess+import process_lifecycle+import threading+import imageio_ffmpeg+from content import ocr_program+from setup_runtime import download,fetch_json+++def check_program(path,argument='--version'):+ result=process_lifecycle.run([str(path),argument],capture_output=True,text=True,timeout=20,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if result.returncode:+ raise RuntimeError(f'{Path(path).name} failed its readiness check: '+(result.stderr or result.stdout)[-500:])+ return str(path)+++def install_ffmpeg(home,cancel,progress):+ if cancel.is_set():+ raise InterruptedError('Setup cancelled')+ # imageio-ffmpeg downloads the platform binary with VectorDash's dependencies.+ source=Path(imageio_ffmpeg.get_ffmpeg_exe())+ check_program(source,'-version')+ target=Path(home)/'tools/ffmpeg/ffmpeg.exe'+ target.parent.mkdir(parents=True,exist_ok=True)+ staging=target.with_suffix('.tmp')+ progress('Setting up included FFmpeg',0,0)+ shutil.copy2(source,staging)+ if hashlib.sha256(staging.read_bytes()).digest()!=hashlib.sha256(source.read_bytes()).digest():+ staging.unlink()+ raise RuntimeError('FFmpeg copy verification failed')+ if cancel.is_set():+ staging.unlink()+ raise InterruptedError('Setup cancelled')+ staging.replace(target)+ return {'ffmpeg_path':check_program(target,'-version')}+++def language_codes(value):+ codes=list(dict.fromkeys((value or 'eng').split('+')))+ if any(not re.fullmatch(r'[a-z][a-z0-9_]{1,20}',code) for code in codes):+ raise ValueError('Use OCR language codes separated by +, such as eng+ben+ara.')+ return codes+++def install_ocr(settings,home,cancel,progress):+ codes=language_codes(settings.get('ocr_languages','eng'))+ if cancel.is_set():+ raise InterruptedError('Setup cancelled')+ program=ocr_program(settings) or ocr_program(dict(settings,ocr_path=''))+ if not program:+ winget=shutil.which('winget')+ if not winget:+ raise RuntimeError('Windows App Installer (winget) is missing. Install/update App Installer from Microsoft Store, then retry OCR setup.')+ progress('Windows is installing Tesseract OCR; approve its Windows permission prompt if shown',0,0)+ log=Path(home)/'ocr-setup.log'+ # WinGet downloads and verifies the community-maintained Windows package.+ # CurrentUser is the installer's documented per-user mode.+ args=[winget,'install','--id','UB-Mannheim.TesseractOCR','--exact','--source','winget','--silent','--accept-package-agreements','--accept-source-agreements','--disable-interactivity','--override','/S /CurrentUser']+ with log.open('w',encoding='utf-8') as output:+ process=process_lifecycle.popen(args,stdout=output,stderr=output,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ # Do not interrupt a Windows installer halfway through writing files.+ process.wait()+ program=ocr_program(dict(settings,ocr_path=''))+ if not program:+ detail=log.read_text(encoding='utf-8',errors='replace')[-1200:]+ raise RuntimeError(f'Tesseract setup did not complete (exit {process.returncode}). {detail}')+ check_program(program)+ if cancel.is_set():+ raise InterruptedError('OCR engine setup finished; remaining downloads cancelled')+ progress('Loading official OCR language packs',0,0)+ repo='tesseract-ocr/tessdata_fast'+ revision=fetch_json(f'https://api.github.com/repos/{repo}/commits/main')['sha']+ tree=fetch_json(f'https://api.github.com/repos/{repo}/git/trees/{revision}')['tree']+ files={entry['path']:entry for entry in tree if entry['type']=='blob'}+ target=Path(home)/'tools/tessdata'+ target.mkdir(parents=True,exist_ok=True)+ for code in codes:+ name=code+'.traineddata'+ item=files.get(name)+ if not item:+ raise ValueError(f'OCR language {code} is not present in the official language catalog.')+ download(f'https://raw.githubusercontent.com/{repo}/{revision}/{name}',target/name,item['size'],'git-sha1:'+item['sha'],cancel,lambda done,total:progress('OCR language '+code,done,total))+ # Check the exact managed data folder, not just the engine executable.+ result=process_lifecycle.run([program,'--tessdata-dir',str(target),'--list-langs'],capture_output=True,text=True,timeout=20,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if result.returncode or any(code not in result.stdout.splitlines() for code in codes):+ raise RuntimeError('The selected OCR languages did not pass verification.')+ return {'ocr_path':program,'ocr_data':str(target),'ocr_languages':'+'.join(codes)}diff --git a/windows/test_content.py b/windows/test_content.pynew file mode 100644index 0000000..ab4a242--- /dev/null+++ b/windows/test_content.py@@ -0,0 +1,198 @@+"""Content retrieval, exact identifiers, atomic index and project isolation checks."""+import io+import json+from pathlib import Path+import subprocess+import tempfile+import unittest+from unittest.mock import patch+from PIL import Image,ImageDraw,ImageFont+import pymupdf+from content import Segment,extract,code_segments,project_files,ocr_program,chunks+from engine import Engine,DEFAULTS,model_signature+from vectordash_core import read_text,embedding_request,command++ROOT=Path(__file__).resolve().parents[1]++class ContentTests(unittest.TestCase):+ def setUp(self):+ self.temp=tempfile.TemporaryDirectory(dir=ROOT,prefix='vectordash-content-')+ self.addCleanup(self.temp.cleanup)+ self.home=Path(self.temp.name)+ self.source=self.home/'source'; self.source.mkdir()+ self.engine=Engine(self.home)+ self.settings=dict(DEFAULTS,roots=[str(self.source)],ocr_enabled=False)++ def pdf(self):+ path=self.source/'agreement.pdf'+ with pymupdf.open() as document:+ page=document.new_page(); page.insert_text((72,72),'Rent payment terms and the landlord address.')+ page=document.new_page(); page.insert_text((72,72),'Pets clause: dogs require written approval. Invoice INV-77891.')+ document.save(path)+ return path++ def test_pdf_result_has_matching_page_and_exact_identifier(self):+ self.pdf(); self.engine.index(self.settings)+ result=self.engine.search('INV-77891',self.settings)[0]+ self.assertEqual(result.page,2)+ self.assertEqual(result.kind,'pdf')+ self.assertIn('INV-77891',result.snippet)++ def test_scanned_pdf_ocr_retains_page_rectangles(self):+ path=self.source/'scan.pdf'+ with pymupdf.open() as doc:+ doc.new_page(); doc.save(path)+ with patch('content.ocr',return_value=('Invoice 88321',[['88321',20,40,80,20]])):+ result=list(extract(path,dict(self.settings,ocr_enabled=True),read_text,lambda:None))[0]+ self.assertEqual(result.page,1)+ self.assertEqual(result.boxes,[['88321',10,20,40,10]])++ def test_exact_text_at_end_of_long_document_is_not_discarded(self):+ path=self.source/'long.txt'+ path.write_text('ordinary document prose '*2400+' END-992817',encoding='utf-8')+ self.engine.index(self.settings)+ self.assertIn('END-992817',self.engine.search('END-992817',self.settings)[0].snippet)++ def test_disabled_code_content_never_enters_general_search(self):+ (self.source/'module.py').write_text('def very_unique_retry():\n return "HIDDEN_SENTINEL_12451"\n')+ self.engine.index(self.settings)+ self.assertEqual(self.engine.search('HIDDEN_SENTINEL_12451',self.settings),[])+ with self.assertRaisesRegex(ValueError,'Enable code'):+ self.engine.search('code: retry',self.settings)++ def test_opt_in_code_only_projects_and_function_location(self):+ (self.source/'module.py').write_text('import time\n\ndef backoff_call():\n """Retry failed requests with backoff."""\n time.sleep(2)\n')+ settings=dict(self.settings,roots=[],code_enabled=True,code_roots=[str(self.source)])+ self.engine.index(settings)+ result=self.engine.search('code: backoff',settings)[0]+ self.assertEqual((result.symbol,result.line,result.end_line),('backoff_call',3,5))+ self.assertEqual(self.engine.search('backoff',settings),[])++ def test_javascript_named_function_handles_braces_in_strings(self):+ path=self.source/'client.js'+ path.write_text('const unrelated = 1;\nasync function retryCall(request) {\n const text = "}";\n // } comment\n return request();\n}\nfunction other() { return 4; }\n')+ segments=list(code_segments(path))+ self.assertEqual(segments[0].symbol,'retryCall')+ self.assertEqual((segments[0].line,segments[0].end_line),(2,6))+ self.assertEqual(segments[1].symbol,'other')++ def test_notebook_indexes_only_code_cells(self):+ path=self.source/'analysis.ipynb'+ path.write_text(json.dumps({'cells':[{'cell_type':'markdown','source':['PRIVATE MARKDOWN']},{'cell_type':'code','source':['def retry(): pass'],'outputs':[{'text':['PRIVATE OUTPUT']}]}]}))+ segments=list(code_segments(path))+ self.assertEqual(segments[0].text,'def retry(): pass')+ self.assertNotIn('PRIVATE',segments[0].text)++ def test_gitignore_and_nested_project_boundaries(self):+ subprocess.run(['git','init',str(self.source)],capture_output=True,check=True,creationflags=subprocess.CREATE_NO_WINDOW)+ (self.source/'.gitignore').write_text('ignored.py\n')+ (self.source/'ignored.py').write_text('def ignored(): pass')+ (self.source/'included.py').write_text('def included(): pass')+ paths=list(project_files(self.source))+ self.assertIn(self.source/'included.py',paths)+ self.assertNotIn(self.source/'ignored.py',paths)++ def test_source_parent_names_do_not_exclude_explicit_selection(self):+ nested=self.source/'windows'; nested.mkdir()+ (nested/'notes.txt').write_text('explicitly selected application sources')+ self.engine.index(dict(self.settings,roots=[str(nested)]))+ self.assertTrue(self.engine.search('application',self.settings))++ def test_changed_content_options_reextract_unchanged_files(self):+ (self.source/'notes.txt').write_text('first text')+ self.engine.index(self.settings)+ with patch('engine.read_text',return_value='updated OCR configuration'):+ self.engine.index(dict(self.settings,ocr_languages='eng+ara'))+ self.assertTrue(self.engine.search('updated',self.settings))++ def test_file_failure_skips_partial_content_and_continues(self):+ path=self.source/'notes.txt'; path.write_text('old invoice INV-1299')+ self.engine.index(self.settings)+ path.write_text('bad replacement')+ (self.source/'good.txt').write_text('healthy content after failure')+ from content import Segment+ original=__import__('engine').extract+ def extract(path,*args):+ if path.name=='notes.txt':+ yield Segment(text='partial text that must not commit')+ raise RuntimeError('decode failed')+ yield from original(path,*args)+ with patch('engine.extract',side_effect=extract),self.assertLogs('vectordash',level='WARNING') as logs:+ summary=self.engine.index(self.settings)+ self.assertIn('1 skipped',summary)+ self.assertIn('decode failed',logs.output[0])+ self.assertTrue(self.engine.search('healthy',self.settings))+ self.assertEqual(self.engine.search('partial',self.settings),[])+ self.assertTrue(self.engine.search('notes',self.settings))++ def test_duplicate_source_selection_does_not_duplicate_segments(self):+ (self.source/'notes.txt').write_text('selected twice')+ self.engine.index(dict(self.settings,roots=[str(self.source),str(self.source)]))+ with self.engine.connect() as db:+ self.assertEqual(db.execute('SELECT count(*) FROM segments').fetchone()[0],1)++ def test_multilingual_literal_text_and_punctuation(self):+ (self.source/'notes.txt').write_text('مرحبا رقم الفاتورة INV-5532. বাংলা নোট।',encoding='utf-8')+ self.engine.index(self.settings)+ for query in ('مرحبا','INV-5532','বাংলা'):+ self.assertTrue(self.engine.search(query,self.settings),query)++ def test_ocr_screenshot_exact_identifiers(self):+ if not ocr_program(self.settings):+ self.skipTest('Tesseract unavailable')+ image=Image.new('RGB',(1000,350),'white')+ draw=ImageDraw.Draw(image)+ draw.text((30,50),'Payment declined error',font=ImageFont.truetype('C:/Windows/Fonts/arial.ttf',40),fill='black')+ draw.text((30,150),'Invoice INV-2026-00891',font=ImageFont.truetype('C:/Windows/Fonts/arial.ttf',40),fill='black')+ image.save(self.source/'123.png')+ self.engine.index(dict(self.settings,ocr_enabled=True))+ result=self.engine.search('INV-2026-00891',self.settings)[0]+ self.assertEqual(result.kind,'image')+ self.assertTrue(result.boxes)++ def test_projector_fingerprint_invalidates_vectors(self):+ model=self.home/'model.gguf'; model.write_bytes(b'model')+ projector=self.home/'mmproj.gguf'; projector.write_bytes(b'encoder')+ settings=dict(self.settings,semantic=True,model=str(model),projector=str(projector))+ before=model_signature(settings)+ projector.write_bytes(b'a different encoder')+ self.assertNotEqual(before,model_signature(settings))++ def test_cpu_encoder_and_pooling_configuration(self):+ args=command(dict(self.settings,server='server.exe',model='model.gguf',projector='mmproj.gguf'))+ self.assertIn('--no-mmproj-offload',args)+ self.assertEqual(args[args.index('--pooling')+1],'mean')+ self.assertEqual(args[args.index('--mmproj')+1],'mmproj.gguf')++ def test_media_request_contains_raw_payload_without_filename(self):+ props=io.BytesIO(json.dumps({'media_marker':'MEDIA'}).encode())+ vector=io.BytesIO(json.dumps({'data':[{'embedding':[.3,.4]}]}).encode())+ with patch('vectordash_core.urllib.request.urlopen',side_effect=[props,vector]) as requests:+ embedding_request(b'actual image bytes')+ request=requests.call_args_list[1].args[0]+ payload=json.loads(request.data)['input']+ self.assertEqual(payload['prompt_string'],'MEDIA')+ self.assertEqual(payload['multimodal_data'],['YWN0dWFsIGltYWdlIGJ5dGVz'])++ def test_prompted_text_and_media_are_indexed_as_separate_vectors(self):+ path=self.source/'photo.jpg'; path.write_bytes(b'fixture')+ segment=Segment(kind='image',text='Invoice 234',media=b'image')+ requests=[]+ def runtime(value):+ requests.append(value)+ return [1.,0.]+ with patch('engine.embedding_request',side_effect=runtime):+ vectors=self.engine.infer(segment,path,lambda:True)+ self.assertEqual(len(vectors),2)+ self.assertEqual(requests[0],b'image')+ self.assertEqual(requests[1],'title: photo.jpg | text: Invoice 234')++ def test_chunks_cover_complete_text(self):+ text=''.join(str(i%10) for i in range(20000))+ passages=list(chunks(text))+ self.assertEqual(passages[0],text[:2400])+ self.assertTrue(passages[-1].endswith(text[-100:]))+ self.assertEqual(len(passages),10)++if __name__=='__main__':+ unittest.main()diff --git a/windows/test_features.py b/windows/test_features.pynew file mode 100644index 0000000..85be80f--- /dev/null+++ b/windows/test_features.py@@ -0,0 +1,152 @@+"""Remote endpoint, migration and failed-image behavior regressions."""+import io+import json+import os+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch+from PIL import Image+from engine import Engine,DEFAULTS,Settings,data_home,model_signature,verify_server_model+from vectordash_core import embedding_request,server_url+import process_lifecycle++class Response(io.BytesIO):+ def __init__(self,data):+ super().__init__(json.dumps(data).encode())++class FeatureTests(unittest.TestCase):+ def setUp(self):+ self.temp=tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.home=Path(self.temp.name)+ process_lifecycle.reopen()+ self.addCleanup(process_lifecycle.reopen)++ def test_remote_text_and_media_use_endpoint_and_auth(self):+ settings=dict(DEFAULTS,server_mode='Remote',remote_url='https://example.invalid:8787/',remote_key='test-key')+ calls=[]+ def request(req,**kwargs):+ calls.append(req)+ return Response({'media_marker':'<media>'}) if req.full_url.endswith('/props') else Response({'data':[{'embedding':[1,2,3]}]})+ with patch('vectordash_core.urllib.request.urlopen',side_effect=request):+ self.assertEqual(embedding_request('hello',settings),[1,2,3])+ self.assertEqual(embedding_request(b'image',settings),[1,2,3])+ self.assertEqual(len(calls),3)+ for req in calls:+ self.assertTrue(req.full_url.startswith('https://example.invalid:8787/'))+ self.assertEqual(req.headers['Authorization'],'Bearer test-key')+ media=json.loads(calls[-1].data)['input']+ self.assertEqual(media['multimodal_data'],['aW1hZ2U='])++ def test_remote_signature_requires_no_local_model_and_checks_identity(self):+ settings=dict(DEFAULTS,semantic=True,server_mode='Remote',remote_url='http://remote:8787')+ self.assertIn('remote',model_signature(settings))+ with patch('engine.urllib.request.urlopen',return_value=Response({'model_path':'/models/embeddinggemma-2-Q8_0.gguf'})):+ verify_server_model(settings)+ with patch('engine.urllib.request.urlopen',return_value=Response({'model_path':'/models/unrelated.gguf'})):+ with self.assertRaises(ValueError):verify_server_model(settings)++ def test_legacy_folder_migrates_with_download_paths_and_index(self):+ legacy=self.home/'DigUp';legacy.mkdir()+ (legacy/'models').mkdir()+ model=legacy/'models/model.gguf';model.write_bytes(b'model')+ (legacy/'settings.json').write_text(json.dumps({'model':str(model),'roots':['C:/Documents']}))+ (legacy/'index.sqlite').write_bytes(b'index')+ with patch.dict(os.environ,{'LOCALAPPDATA':str(self.home)},clear=True):+ target=data_home()+ self.assertEqual(target,self.home/'VectorDash')+ values=Settings().values+ self.assertFalse(legacy.exists())+ self.assertTrue(Path(values['model']).is_file())+ self.assertEqual((target/'index.sqlite').read_bytes(),b'index')+ self.assertEqual(values['roots'],['C:/Documents'])++ def test_large_image_is_skipped_without_losing_other_files(self):+ source=self.home/'source';source.mkdir()+ Image.new('RGB',(20,20),'white').save(source/'huge.png')+ (source/'good.txt').write_text('healthy invoice INV-99')+ settings=dict(DEFAULTS,roots=[str(source)],ocr_enabled=False)+ engine=Engine(self.home)+ with patch.object(Image,'MAX_IMAGE_PIXELS',100),self.assertLogs('vectordash',level='WARNING'):+ result=engine.index(settings)+ self.assertIn('1 skipped',result)+ self.assertTrue(engine.search('INV-99',settings))+ self.assertTrue(engine.search('huge',settings))++ def test_remote_index_and_search_over_http(self):+ from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer+ import threading+ calls=[]+ class Handler(BaseHTTPRequestHandler):+ def log_message(self,*args):pass+ def do_GET(self):+ calls.append((self.path,self.headers.get('Authorization')))+ self.send_response(200);self.end_headers()+ self.wfile.write(json.dumps({'model_path':'/remote/embeddinggemma-2-Q8_0.gguf','modalities':{}}).encode())+ def do_POST(self):+ calls.append((self.path,self.headers.get('Authorization')))+ json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.send_response(200);self.end_headers()+ self.wfile.write(json.dumps({'data':[{'embedding':[1.0,0.0,0.0]}]}).encode())+ server=ThreadingHTTPServer(('127.0.0.1',0),Handler)+ worker=threading.Thread(target=server.serve_forever,daemon=True);worker.start()+ try:+ source=self.home/'source';source.mkdir()+ (source/'remote.txt').write_text('remote transport invoice INV-43')+ settings=dict(DEFAULTS,semantic=True,roots=[str(source)],ocr_enabled=False,server_mode='Remote',remote_url='http://127.0.0.1:'+str(server.server_port),remote_key='secret')+ engine=Engine(self.home)+ self.assertIn('1 files indexed',engine.index(settings))+ self.assertTrue(engine.search('INV-43',settings))+ self.assertTrue(any(path=='/v1/embeddings' for path,key in calls))+ self.assertTrue(all(key=='Bearer secret' for path,key in calls))+ finally:+ server.shutdown();server.server_close();worker.join()++ def test_picture_query_ranks_subject_above_generic_ocr_words(self):+ settings=dict(DEFAULTS,semantic=True,model=str(self.home/'model.gguf'))+ Path(settings['model']).write_bytes(b'model')+ engine=Engine(self.home)+ with engine.connect() as db:+ db.execute("INSERT OR REPLACE INTO metadata VALUES('signature',?)",(model_signature(settings),))+ for name,text,vector in [('compatibility.png','Image upload: pasted images stay inline',[.2,.98]),('dogs.jpg','',[1,0]),('error.png','Payment declined E_PAYMENT_402',[.3,.95])]:+ db.execute('INSERT INTO segments VALUES(?,?,?,?,?,?)',(str(self.home/name),'files','image',text,json.dumps(vector),'{}'))+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')+ with patch('engine.verify_server_model'),patch('engine.embed',return_value=[1,0]) as embed:+ images=engine.search('images of dogs',settings)+ self.assertEqual(Path(images[0].path).name,'dogs.jpg')+ self.assertFalse(any(Path(result.path).name=='compatibility.png' for result in images))+ self.assertIn('query: dogs',embed.call_args.args[0])+ exact=engine.search('E_PAYMENT_402',settings)+ self.assertEqual(Path(exact[0].path).name,'error.png')++ def test_query_embedding_is_reused_and_index_cache_invalidates(self):+ settings=dict(DEFAULTS,semantic=True,model=str(self.home/'model.gguf'))+ Path(settings['model']).write_bytes(b'model')+ engine=Engine(self.home)+ with engine.connect() as db:+ db.execute("INSERT INTO metadata VALUES('signature',?)",(model_signature(settings),))+ db.execute('INSERT INTO segments VALUES(?,?,?,?,?,?)',('first.txt','files','text','first','[1,0]','{}'))+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')+ with patch('engine.verify_server_model'),patch('engine.embed',return_value=[1,0]) as embed:+ self.assertEqual(engine.search('test subject',settings)[0].path,'first.txt')+ engine.search('test subject',settings)+ embed.assert_called_once()+ with engine.connect() as db:+ db.execute('DELETE FROM segments')+ db.execute('INSERT INTO segments VALUES(?,?,?,?,?,?)',('second.txt','files','text','second','[1,0]','{}'))+ db.execute('DELETE FROM words')+ db.execute('INSERT INTO words(rowid,path,text) SELECT rowid,path,text FROM segments')+ self.assertEqual(engine.search('test subject',settings)[0].path,'second.txt')+ engine.clear_query_cache()+ engine.search('test subject',settings)+ self.assertEqual(embed.call_count,2)+ self.assertEqual(engine.indexed_file_count(),1)++ def test_shutdown_blocks_new_helpers(self):+ process_lifecycle.close()+ with patch('process_lifecycle.subprocess.Popen') as spawn:+ with self.assertRaises(InterruptedError):process_lifecycle.popen(['anything'])+ spawn.assert_not_called()++if __name__=='__main__':unittest.main()diff --git a/windows/test_tools.py b/windows/test_tools.pynew file mode 100644index 0000000..7e88db5--- /dev/null+++ b/windows/test_tools.py@@ -0,0 +1,95 @@+"""Tool setup integrity, input validation and Windows installer regression checks."""+import hashlib+import io+from pathlib import Path+import tempfile+import threading+import unittest+from unittest.mock import patch,Mock+from setup_runtime import download+from setup_tools import install_ocr,install_ffmpeg,language_codes++ROOT=Path(__file__).resolve().parents[1]+class Response(io.BytesIO):+ status=200+ headers={}++class ToolTests(unittest.TestCase):+ def setUp(self):+ self.temp=tempfile.TemporaryDirectory(dir=ROOT,prefix='vectordash-tools-')+ self.addCleanup(self.temp.cleanup)+ self.home=Path(self.temp.name)+ self.cancel=threading.Event()++ def test_language_codes_reject_path_traversal_before_setup(self):+ for value in ('../eng','eng+../../file','eng+','eng;command'):+ with self.assertRaises(ValueError):+ language_codes(value)+ self.assertEqual(language_codes('eng+ben+ara+eng'),['eng','ben','ara'])++ def test_git_blob_hash_verified_before_replacing_language(self):+ content=b'valid official language data'+ digest=hashlib.sha1(b'blob '+str(len(content)).encode()+b'\0'+content).hexdigest()+ target=self.home/'eng.traineddata'+ target.write_bytes(b'previous language')+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(content)):+ download('https://official/file',target,len(content),'git-sha1:'+digest,self.cancel,lambda *args:None)+ self.assertEqual(target.read_bytes(),content)+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(b'corrupt data')):+ with self.assertRaisesRegex(RuntimeError,'Checksum'):+ download('https://official/file',target,len(b'corrupt data'),'git-sha1:'+digest,self.cancel,lambda *args:None)+ self.assertEqual(target.read_bytes(),content)++ def test_cancelled_setup_never_starts_installer(self):+ self.cancel.set()+ with patch('setup_tools.subprocess.Popen') as process:+ with self.assertRaises(InterruptedError):+ install_ocr({'ocr_languages':'eng'},self.home,self.cancel,lambda *args:None)+ process.assert_not_called()+ with self.assertRaises(InterruptedError):+ install_ffmpeg(self.home,self.cancel,lambda *args:None)++ def test_windows_install_then_pinned_language_setup(self):+ program='C:/Programs/Tesseract-OCR/tesseract.exe'+ process=Mock(returncode=0)+ data={'tree':[{'type':'blob','path':'eng.traineddata','size':10,'sha':'abc123'}]}+ with patch('setup_tools.ocr_program',side_effect=[None,None,program]),patch('setup_tools.shutil.which',return_value='winget.exe'),patch('setup_tools.subprocess.Popen',return_value=process) as launch,patch('setup_tools.check_program'),patch('setup_tools.fetch_json',side_effect=[{'sha':'pinned-revision'},data]),patch('setup_tools.download') as get,patch('setup_tools.process_lifecycle.run',return_value=Mock(returncode=0,stdout='List of languages:\neng\n')):+ result=install_ocr({'ocr_languages':'eng'},self.home,self.cancel,lambda *args:None)+ args=launch.call_args.args[0]+ self.assertIn('UB-Mannheim.TesseractOCR',args)+ self.assertEqual(args[-1],'/S /CurrentUser')+ process.wait.assert_called_once()+ self.assertIn('/pinned-revision/eng.traineddata',get.call_args.args[0])+ self.assertEqual(get.call_args.args[3],'git-sha1:abc123')+ self.assertEqual(result['ocr_path'],program)+ self.assertEqual(result['ocr_data'],str(self.home/'tools/tessdata'))++ def test_ocr_managed_path_with_spaces_and_exact_tsv_text(self):+ from PIL import Image+ from content import ocr+ header='level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n'+ row='5\t1\t1\t1\t1\t1\t20\t30\t80\t15\t96\tINV-2026_8832\n'+ data=(header+row).encode()+ settings={'ocr_path':'C:/OCR/tesseract.exe','ocr_data':'C:/Users/A User/OCR data','ocr_languages':'eng'}+ with patch('content.ocr_program',return_value=settings['ocr_path']),patch('content.process_lifecycle.run',return_value=Mock(returncode=0,stdout=data)) as run:+ text,boxes=ocr(Image.new('RGB',(100,100),'white'),settings)+ self.assertEqual(text,'INV-2026_8832')+ self.assertEqual(boxes,[['INV-2026_8832',20,30,80,15]])+ args=run.call_args.args[0]+ self.assertEqual(args[args.index('--tessdata-dir')+1],str(Path(settings['ocr_data'])))+ self.assertTrue(run.call_args.kwargs['input'].startswith(b'\x89PNG'))++ def test_missing_winget_reports_actionable_error(self):+ with patch('setup_tools.ocr_program',return_value=None),patch('setup_tools.shutil.which',return_value=None):+ with self.assertRaisesRegex(RuntimeError,'App Installer'):+ install_ocr({'ocr_languages':'eng'},self.home,self.cancel,lambda *args:None)++ def test_invalid_manual_path_reuses_detected_existing_ocr(self):+ program='C:/Programs/tesseract.exe'+ with patch('setup_tools.ocr_program',side_effect=[None,program]),patch('setup_tools.check_program'),patch('setup_tools.fetch_json',side_effect=[{'sha':'rev'},{'tree':[{'type':'blob','path':'eng.traineddata','size':1,'sha':'abc'}]}]),patch('setup_tools.download'),patch('setup_tools.process_lifecycle.run',return_value=Mock(returncode=0,stdout='eng\n')),patch('setup_tools.subprocess.Popen') as launch:+ result=install_ocr({'ocr_path':'invalid.exe','ocr_languages':'eng'},self.home,self.cancel,lambda *args:None)+ launch.assert_not_called()+ self.assertEqual(result['ocr_path'],program)++if __name__=='__main__':+ unittest.main()diff --git a/windows/test_upgrade.py b/windows/test_upgrade.pynew file mode 100644index 0000000..41dd568--- /dev/null+++ b/windows/test_upgrade.py@@ -0,0 +1,220 @@+"""Regression checks for the Windows desktop upgrade."""+from datetime import datetime+import hashlib+import io+import json+from pathlib import Path+import sqlite3+import tempfile+import threading+import unittest+from unittest.mock import patch+import zipfile+from engine import DEFAULTS, Engine, Settings, verify_server_model+from scheduling import schedule_due, idle_allowed, next_run+from windows_integration import hotkey_parts, parse_devices+from setup_runtime import download, extract_archive, catalogs++WORKSPACE=Path(__file__).resolve().parents[1]++def temporary():+ return tempfile.TemporaryDirectory(prefix='digup-test-',dir=WORKSPACE)++class IndexTests(unittest.TestCase):+ def setUp(self):+ self.temp=temporary()+ self.addCleanup(self.temp.cleanup)+ self.home=Path(self.temp.name)+ self.source=self.home/'source'+ self.source.mkdir()+ self.file=self.source/'notes.txt'+ self.file.write_text('Windows search with a remembered phrase',encoding='utf-8')+ self.settings=dict(DEFAULTS,roots=[str(self.source)])+ self.engine=Engine(self.home)++ def test_incremental_reuse_and_deleted_files(self):+ self.engine.index(self.settings)+ with patch('engine.read_text',side_effect=AssertionError('unchanged file re-read')):+ result=self.engine.index(self.settings)+ self.assertIn('1 reused',result)+ self.assertEqual(len(self.engine.search('remembered',self.settings)),1)+ self.file.unlink()+ self.engine.index(self.settings)+ self.assertEqual(self.engine.search('remembered',self.settings),[])++ def test_changed_file_is_reindexed(self):+ self.engine.index(self.settings)+ self.file.write_text('A different, much longer text describing solar panels',encoding='utf-8')+ self.engine.index(self.settings)+ self.assertEqual(len(self.engine.search('solar',self.settings)),1)+ self.assertEqual(self.engine.search('remembered',self.settings),[])++ def test_cancel_retains_previous_index(self):+ self.engine.index(self.settings)+ self.engine.cancel.set()+ with self.assertRaises(InterruptedError):+ self.engine.index(self.settings)+ self.assertEqual(len(self.engine.search('remembered',self.settings)),1)++ def test_missing_drive_retains_previous_index(self):+ self.engine.index(self.settings)+ settings=dict(self.settings,roots=[str(self.home/'disconnected')])+ with self.assertRaises(ValueError):+ self.engine.index(settings)+ self.assertEqual(len(self.engine.search('remembered',self.settings)),1)++ def test_migrates_original_schema(self):+ old=self.home/'legacy'+ old.mkdir()+ with sqlite3.connect(old/'index.sqlite') as db:+ db.execute('CREATE TABLE files(path TEXT PRIMARY KEY,text TEXT,vector TEXT)')+ db.execute('INSERT INTO files VALUES(?,?,?)',(str(self.file),'legacy notes','[]'))+ db.close()+ engine=Engine(old)+ self.assertEqual(len(engine.search('legacy',self.settings)),1)+ with engine.connect() as db:+ self.assertTrue({'mtime','size'}.issubset({row[1] for row in db.execute('PRAGMA table_info(files)')}))++ def test_search_while_index_paused(self):+ self.engine.index(self.settings)+ self.engine.paused.set()+ done=threading.Event()+ def work():+ try:+ self.engine.index(self.settings)+ except InterruptedError:+ pass+ finally:+ done.set()+ thread=threading.Thread(target=work)+ thread.start()+ try:+ self.assertEqual(len(self.engine.search('remembered',self.settings)),1)+ finally:+ self.engine.cancel.set()+ self.assertTrue(done.wait(3))+ thread.join()++ def test_atomic_settings_preserve_existing_paths(self):+ (self.home/'settings.json').write_text(json.dumps({'server':'H:/llama/server.exe','model':'C:/models/model.gguf','device':'CUDA0'}))+ settings=Settings(self.home)+ settings.save()+ self.assertEqual(Settings(self.home).values['device'],'CUDA0')+ self.assertEqual(Settings(self.home).values['server'],'H:/llama/server.exe')++class ScheduleTests(unittest.TestCase):+ def setUp(self):+ self.settings=dict(DEFAULTS,schedule_mode='At selected time',schedule_enabled_at='2026-10-10T01:00:00')+ self.metrics={'cpu':10,'gpu':5,'idle':600,'on_ac':True}++ def test_daily_run_only_once(self):+ now=datetime(2026,10,10,3)+ due,slot,_=schedule_due(self.settings,now,self.metrics)+ self.assertTrue(due)+ self.settings['last_schedule_slot']=slot+ self.assertFalse(schedule_due(self.settings,now,self.metrics)[0])++ def test_no_immediate_historical_run_on_enabling(self):+ self.settings['schedule_enabled_at']='2026-10-10T12:00:00'+ self.assertFalse(schedule_due(self.settings,datetime(2026,10,10,12,1),self.metrics)[0])++ def test_sleep_resume_catches_one_latest_slot(self):+ self.settings['last_schedule_slot']='2026-10-10T02:00:00'+ due,slot,_=schedule_due(self.settings,datetime(2026,10,13,12),self.metrics)+ self.assertTrue(due)+ self.assertEqual(slot,'2026-10-13T02:00:00')++ def test_cpu_gpu_and_user_idle_conditions(self):+ self.settings.update(schedule_mode='When idle',check_gpu=True)+ self.assertTrue(schedule_due(self.settings,datetime(2026,10,10,3),self.metrics)[0])+ for key,value in [('cpu',90),('gpu',90),('idle',0),('on_ac',False),('gpu',None)]:+ self.assertFalse(idle_allowed(self.settings,dict(self.metrics,**{key:value}))[0])++ def test_idle_repeat_interval(self):+ self.settings.update(schedule_mode='When idle',last_success='2026-10-10T02:30:00')+ self.assertFalse(schedule_due(self.settings,datetime(2026,10,10,3),self.metrics)[0])++ def test_time_plus_idle(self):+ self.settings['schedule_mode']='Time + idle'+ self.assertFalse(schedule_due(self.settings,datetime(2026,10,10,1,30),self.metrics)[0])+ self.assertFalse(schedule_due(self.settings,datetime(2026,10,10,3),dict(self.metrics,idle=0))[0])+ self.assertTrue(schedule_due(self.settings,datetime(2026,10,10,3),self.metrics)[0])++ def test_resources_only_idle_mode(self):+ self.settings.update(schedule_mode='When idle',check_user_idle=False)+ self.assertTrue(schedule_due(self.settings,datetime(2026,10,10,3),dict(self.metrics,idle=0))[0])++ def test_weekday_selection(self):+ self.settings['schedule_days']=[0]+ self.assertIn('Mon',next_run(self.settings,datetime(2026,10,10,3)))++class IntegrationTests(unittest.TestCase):+ def test_hotkey_validation(self):+ self.assertEqual(hotkey_parts('Ctrl+Shift+Space'),(0x4006,0x20))+ for invalid in ('Space','Ctrl+Unknown','Ctrl+Ctrl++','Ctrl+F25'):+ with self.assertRaises(ValueError):+ hotkey_parts(invalid)++ def test_running_model_must_match_selection(self):+ class Response(io.BytesIO):+ pass+ with patch('engine.urllib.request.urlopen',return_value=Response(b'{"model_path":"C:/models/wrong.gguf"}')):+ with self.assertRaisesRegex(ValueError,'different model'):+ verify_server_model(dict(DEFAULTS,semantic=True,model='C:/models/chosen.gguf'))++ def test_device_selection_preserves_identifiers(self):+ devices=parse_devices('ggml: init\nAvailable devices:\n CUDA0: NVIDIA RTX (16000 MiB)\n Vulkan1: Intel UHD (8000 MiB)\n')+ self.assertEqual([item[0] for item in devices],['CUDA0','Vulkan1'])++ def test_archive_traversal_blocked(self):+ with temporary() as directory:+ root=Path(directory)+ archive=root/'bad.zip'+ with zipfile.ZipFile(archive,'w') as bundle:+ bundle.writestr('../escape.exe','bad')+ with self.assertRaises(RuntimeError):+ extract_archive(archive,root/'install')+ self.assertFalse((root/'escape.exe').exists())++ def test_download_checksum_and_cancel(self):+ class Response(io.BytesIO):+ status=200+ headers={}+ data=b'verified model bytes'+ with temporary() as directory:+ target=Path(directory)/'model.gguf'+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(data)):+ download('https://example.invalid/model',target,len(data),hashlib.sha256(data).hexdigest(),threading.Event(),lambda *args:None)+ self.assertEqual(target.read_bytes(),data)+ cancel=threading.Event()+ cancel.set()+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(data)):+ with self.assertRaises(InterruptedError):+ download('https://example.invalid/model',target,len(data),None,cancel,lambda *args:None)++ def test_corrupt_download_not_installed(self):+ class Response(io.BytesIO):+ status=200+ headers={}+ with temporary() as directory:+ target=Path(directory)/'model.gguf'+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(b'wrong')):+ with self.assertRaisesRegex(RuntimeError,'Checksum mismatch'):+ download('https://example.invalid/model',target,5,'0'*64,threading.Event(),lambda *args:None)+ self.assertFalse(target.exists())+ self.assertFalse(target.with_name(target.name+'.part').exists())++ def test_download_resume(self):+ class Response(io.BytesIO):+ status=206+ headers={'Content-Range':'bytes 3-5/6'}+ with temporary() as directory:+ target=Path(directory)/'model.gguf'+ target.with_name(target.name+'.part').write_bytes(b'abc')+ with patch('setup_runtime.urllib.request.urlopen',return_value=Response(b'def')) as request:+ download('https://example.invalid/model',target,6,hashlib.sha256(b'abcdef').hexdigest(),threading.Event(),lambda *args:None)+ self.assertEqual(request.call_args.args[0].headers['Range'],'bytes=3-')+ self.assertEqual(target.read_bytes(),b'abcdef')++if __name__=='__main__':+ unittest.main()diff --git a/windows/test_windows.py b/windows/test_windows.pynew file mode 100644index 0000000..ac000b8--- /dev/null+++ b/windows/test_windows.py@@ -0,0 +1,72 @@+import tempfile+import unittest+from unittest.mock import patch+import io+import urllib.error+from pathlib import Path+from vectordash_core import safe, read_text, cosine, command, embed, embedding_request, InputTooLarge++class WindowsTests(unittest.TestCase):+ def test_exclusions(self):+ for name in ['C:/Users/me/.ssh/id_rsa', 'C:/Windows/file.txt', 'C:/files/passwords.txt', 'C:/files/key.pem']:+ self.assertFalse(safe(Path(name)))+ self.assertTrue(safe(Path('C:/Users/me/Documents/notes.txt')))++ def test_cpu_is_explicit(self):+ args = command({'server': 'server.exe', 'model': 'model.gguf', 'mode': 'CPU / system RAM'})+ self.assertEqual(args[-4:], ['--device', 'none', '--gpu-layers', '0'])++ def test_gpu_requires_device(self):+ with self.assertRaises(ValueError):+ command({'server': 'server.exe', 'model': 'model.gguf', 'mode': 'Integrated GPU'})+ args = command({'server': 'server.exe', 'model': 'model.gguf', 'mode': 'Integrated GPU', 'device': 'Vulkan1'})+ self.assertEqual(args[-4:], ['--device', 'Vulkan1', '--gpu-layers', 'all'])++ def test_server_batch_sizes_match(self):+ args = command({'server': 'server.exe', 'model': 'model.gguf', 'mode': 'CPU / system RAM'})+ for flag in ('--batch-size', '--ubatch-size', '-c'):+ self.assertEqual(args[args.index(flag)+1], '2048')+ self.assertEqual(args[args.index('--parallel')+1], '1')++ def test_oversized_inputs_split_without_content_loss(self):+ accepted = []+ def runtime(text):+ if len(text) > 512:+ raise InputTooLarge('input too large; physical batch size 512')+ accepted.append(text)+ return [1.0, 0.0]+ text = '\u65e5\u672c\u8a9e sample ' * 2000+ with patch('vectordash_core.embedding_request', side_effect=runtime):+ self.assertEqual(embed(text), [1.0, 0.0])+ self.assertEqual(sum(map(len, accepted)), len(text))+ self.assertTrue(all(len(chunk) <= 512 for chunk in accepted))++ def test_unrelated_server_error_is_not_retried(self):+ error = urllib.error.HTTPError('local', 500, 'error', {}, io.BytesIO(b'{"error":"device out of memory"}'))+ with patch('vectordash_core.urllib.request.urlopen', side_effect=error) as request:+ with self.assertRaisesRegex(RuntimeError, 'out of memory'):+ embed('sample')+ self.assertEqual(request.call_count, 1)++ def test_size_error_body_is_recognized(self):+ error = urllib.error.HTTPError('local', 500, 'error', {}, io.BytesIO(b'{"error":"input (1390 tokens) is too large to process. increase the physical batch size (current batch size: 512)"}'))+ with patch('vectordash_core.urllib.request.urlopen', side_effect=error):+ with self.assertRaises(InputTooLarge):+ embedding_request('sample')++ def test_vectors(self):+ self.assertAlmostEqual(cosine([1, 0], [1, 0]), 1)+ self.assertEqual(cosine([1], [1, 0]), 0)+ self.assertEqual(cosine([0], [1]), 0)++ def test_text_and_size_limit(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory)/'notes.txt'+ path.write_text('Windows search example', encoding='utf-8')+ self.assertEqual(read_text(path), 'Windows search example')+ with path.open('wb') as stream:+ stream.truncate(9 * 1024 * 1024)+ self.assertEqual(read_text(path), '')++if __name__ == '__main__':+ unittest.main()diff --git a/windows/vectordash_core.py b/windows/vectordash_core.pynew file mode 100644index 0000000..f33e7b4--- /dev/null+++ b/windows/vectordash_core.py@@ -0,0 +1,116 @@+"""VectorDash: local multimodal file search with llama.cpp embeddings."""+import os+import base64+import json+import math+import urllib.request+import urllib.error+import zipfile+import xml.etree.ElementTree as ET++SKIP = {'.git', '.ssh', '.aws', 'node_modules', 'windows', '$recycle.bin', 'system volume information', 'appdata', '__pycache__'}+SECRET = {'.pem', '.key', '.pfx', '.p12', '.kdbx'}+TEXT = {'.txt', '.md', '.csv', '.log', '.html', '.rtf'}++def safe(path):+ return not any(p.lower().startswith('.') or p.lower() in SKIP for p in path.parts) and path.suffix.lower() not in SECRET and not any(s in path.name.lower() for s in ('password', 'credential', 'secret'))++def read_text(path):+ if path.stat().st_size > 8 * 1024 * 1024:+ return ''+ if path.suffix.lower() in TEXT:+ return path.read_text(encoding='utf-8', errors='replace')+ if path.suffix.lower() == '.docx':+ with zipfile.ZipFile(path) as z:+ if z.getinfo('word/document.xml').file_size > 8 * 1024 * 1024:+ return ''+ root = ET.fromstring(z.read('word/document.xml'))+ return ' '.join(root.itertext())+ return ''++def cosine(a, b):+ if len(a) != len(b):+ return 0+ norm = math.sqrt(sum(x*x for x in a) * sum(x*x for x in b))+ return sum(x*y for x,y in zip(a,b)) / norm if norm else 0++def command(settings):+ args = [settings['server'], '-m', settings['model'], '--embedding', '--host', '127.0.0.1', '--port', '8787', '-c', '2048', '--batch-size', '2048', '--ubatch-size', '2048', '--parallel', '1']+ args += ['--pooling', 'mean']+ if settings.get('projector') and any(settings.get(key,True) for key in ('index_images','index_audio','index_video')):+ args += ['--mmproj', settings['projector'], '--image-min-tokens', '70', '--image-max-tokens', '280']+ if settings['mode'] == 'CPU / system RAM':+ args += ['--no-mmproj-offload']+ if settings['mode'] == 'CPU / system RAM':+ args += ['--device', 'none', '--gpu-layers', '0']+ else:+ if not settings.get('device'):+ raise ValueError('Select a device identifier from List devices before starting GPU inference.')+ args += ['--device', settings['device'], '--gpu-layers', 'all']+ return args++def server_url(settings=None):+ return (settings.get('remote_url','') if settings and settings.get('server_mode')=='Remote' else os.environ.get('VECTORDASH_SERVER_URL','http://127.0.0.1:8787')).rstrip('/')++def embedding_request(text, settings=None):+ if isinstance(text, bytes):+ with urllib.request.urlopen(urllib.request.Request(server_url(settings)+'/props',headers={'Authorization':'Bearer '+settings['remote_key']} if settings and settings.get('remote_key') else {}), timeout=5) as response:+ props=json.load(response)+ marker=props.get('media_marker')+ if not marker:+ raise RuntimeError('This llama-server does not expose multimodal embeddings. Install a current runtime and its matching encoder.')+ text={'prompt_string': marker, 'multimodal_data': [base64.b64encode(text).decode('ascii')]}+ request = urllib.request.Request(server_url(settings)+'/v1/embeddings', data=json.dumps({'input': text}).encode(), headers={'Content-Type': 'application/json', **({'Authorization': 'Bearer '+settings['remote_key']} if settings and settings.get('remote_key') else {})})+ try:+ with urllib.request.urlopen(request, timeout=60) as response:+ vector = json.load(response)['data'][0]['embedding']+ if not vector or not all(isinstance(x, (int, float)) and math.isfinite(x) for x in vector):+ raise RuntimeError('Model returned an invalid embedding')+ return vector+ except urllib.error.HTTPError as error:+ detail = error.read().decode('utf-8', errors='replace')[:2000]+ # Only input-size failures can be recovered by splitting. Other server+ # failures must remain visible and preserve the previous index.+ lower = detail.lower()+ if error.code in (400, 500) and any(term in lower for term in+ ('too large', 'too long', 'batch size', 'context size', 'context length', 'exceeds')):+ raise InputTooLarge(detail) from error+ raise RuntimeError(f'Model HTTP {error.code}: {detail or error.reason}') from error+++class InputTooLarge(RuntimeError):+ pass+++def embed(text, checkpoint=lambda: None, request=None):+ """Embed all bounded extracted text, splitting oversized model requests.++ Character counts cannot predict token counts, especially for code and+ multilingual text. Let the runtime reject an oversized chunk, then bisect+ it without discarding any content. Pool the successful chunk vectors.+ """+ request = request or embedding_request+ pending = [text[i:i+6000] for i in range(0, len(text), 6000)] or ['']+ vectors = []+ while pending:+ checkpoint()+ chunk = pending.pop()+ try:+ vectors.append((request(chunk), max(1, len(chunk))))+ except InputTooLarge:+ if len(chunk) <= 1:+ raise RuntimeError('Model cannot embed a minimal input; check its context/batch configuration')+ midpoint = len(chunk) // 2+ pending.extend((chunk[:midpoint], chunk[midpoint:]))+ dimensions = len(vectors[0][0])+ if any(len(vector) != dimensions for vector, _ in vectors):+ raise RuntimeError('Model embedding dimensions changed during indexing')+ total = sum(weight for _, weight in vectors)+ pooled = [sum(vector[i] * weight for vector, weight in vectors) / total for i in range(dimensions)]+ norm = math.sqrt(sum(x*x for x in pooled))+ return [x / norm for x in pooled] if norm else pooled+++if __name__ == '__main__':+ from desktop import main+ raise SystemExit(main())diff --git a/windows/windows_integration.py b/windows/windows_integration.pynew file mode 100644index 0000000..a1c8044--- /dev/null+++ b/windows/windows_integration.py@@ -0,0 +1,144 @@+"""Windows integrations; no administrator access required."""+import ctypes+from ctypes import wintypes+import os+from pathlib import Path+import re+import subprocess+import process_lifecycle+import sys++HOTKEY_ID = 0xD160++def hotkey_parts(text):+ modifiers = {'ctrl': 2, 'alt': 1, 'shift': 4, 'win': 8}+ keys = {'space': 0x20, 'enter': 0x0D, 'tab': 0x09}+ parts = [part.strip().lower() for part in text.split('+')]+ if len(parts) < 2 or any(p not in modifiers for p in parts[:-1]):+ raise ValueError('Use a modifier and key, such as Ctrl+Shift+Space.')+ mask = 0x4000 # MOD_NOREPEAT+ for part in parts[:-1]:+ mask |= modifiers[part]+ key = parts[-1]+ if key in keys:+ code = keys[key]+ elif len(key) == 1 and key.isascii() and key.isalnum():+ code = ord(key.upper())+ elif re.fullmatch(r'f([1-9]|1[0-9]|2[0-4])', key):+ code = 0x70 + int(key[1:]) - 1+ else:+ raise ValueError('Supported keys: Space, Enter, Tab, letters, digits, F1–F24.')+ return mask, code++class GlobalHotkey:+ def __init__(self):+ self.current = ''+ def register(self, text):+ mask, key = hotkey_parts(text)+ if os.name != 'nt':+ raise OSError('Global shortcuts require Windows.')+ old = self.current+ self.unregister()+ if not ctypes.windll.user32.RegisterHotKey(None, HOTKEY_ID, mask, key):+ if old:+ previous = hotkey_parts(old)+ ctypes.windll.user32.RegisterHotKey(None, HOTKEY_ID, *previous)+ self.current = old+ raise OSError('This shortcut is already in use. Choose another combination.')+ self.current = text+ def unregister(self):+ if os.name == 'nt' and self.current:+ ctypes.windll.user32.UnregisterHotKey(None, HOTKEY_ID)+ self.current = ''+++def set_startup(enabled):+ if os.name != 'nt':+ return+ import winreg+ key_path = r'Software\Microsoft\Windows\CurrentVersion\Run'+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path) as key:+ if enabled:+ executable = Path(sys.executable)+ if executable.name.lower() == 'python.exe':+ executable = executable.with_name('pythonw.exe')+ command = subprocess.list2cmdline([str(executable), str(Path(__file__).with_name('desktop.py').resolve()), '--startup'])+ winreg.SetValueEx(key, 'VectorDash', 0, winreg.REG_SZ, command)+ try:+ winreg.DeleteValue(key,'DigUp')+ except FileNotFoundError:+ pass+ else:+ try:+ winreg.DeleteValue(key, 'VectorDash')+ except FileNotFoundError:+ pass+ try:+ winreg.DeleteValue(key,'DigUp')+ except FileNotFoundError:+ pass+++def idle_seconds():+ if os.name != 'nt':+ return None+ class LASTINPUTINFO(ctypes.Structure):+ _fields_ = [('cbSize', wintypes.UINT), ('dwTime', wintypes.DWORD)]+ info = LASTINPUTINFO()+ info.cbSize = ctypes.sizeof(info)+ if not ctypes.windll.user32.GetLastInputInfo(ctypes.byref(info)):+ return None+ return ((ctypes.windll.kernel32.GetTickCount() & 0xffffffff) - info.dwTime & 0xffffffff)/1000+++def parse_devices(output):+ devices = []+ for line in output.splitlines():+ match = re.match(r'^\s*((?:CUDA|Vulkan|SYCL|ROCm|HIP|OpenCL|CPU)\d*)\s*:\s*(.+)', line, re.I)+ if match:+ devices.append((match[1], match[2].strip()))+ return list(dict.fromkeys(devices))+++def gpu_utilization():+ """Conservative system-wide GPU engine utilization, not vendor-specific."""+ if os.name != 'nt':+ return None+ script = r"$ErrorActionPreference='Stop'; $v=(Get-Counter '\GPU Engine(*)\Utilization Percentage').CounterSamples | Where-Object CookedValue -ge 0 | Measure-Object CookedValue -Sum; if ($null -ne $v.Sum) { [Console]::WriteLine($v.Sum.ToString([Globalization.CultureInfo]::InvariantCulture)) }"+ try:+ result = process_lifecycle.run(['powershell.exe','-NoProfile','-NonInteractive','-Command',script],capture_output=True,text=True,timeout=8,creationflags=subprocess.CREATE_NO_WINDOW)+ return min(100.0,max(0.0,float(result.stdout.strip()))) if result.returncode == 0 else None+ except (OSError, ValueError, subprocess.TimeoutExpired):+ return None+++def reveal_in_explorer(path):+ """Select the exact item using Windows Shell PIDLs, with no command parsing."""+ if os.name!='nt':+ raise OSError('Explorer selection requires Windows.')+ item=Path(path).resolve()+ if not item.exists():+ raise FileNotFoundError('This file no longer exists: '+str(item))+ ole=ctypes.windll.ole32+ shell=ctypes.windll.shell32+ ole.CoInitialize.argtypes=[ctypes.c_void_p]+ ole.CoInitialize.restype=ctypes.c_long+ ole.CoTaskMemFree.argtypes=[ctypes.c_void_p]+ shell.SHParseDisplayName.argtypes=[ctypes.c_wchar_p,ctypes.c_void_p,ctypes.POINTER(ctypes.c_void_p),wintypes.DWORD,ctypes.POINTER(wintypes.DWORD)]+ shell.SHParseDisplayName.restype=ctypes.c_long+ shell.SHOpenFolderAndSelectItems.argtypes=[ctypes.c_void_p,wintypes.UINT,ctypes.c_void_p,wintypes.DWORD]+ shell.SHOpenFolderAndSelectItems.restype=ctypes.c_long+ initialized=ole.CoInitialize(None)+ pidl=ctypes.c_void_p()+ try:+ result=shell.SHParseDisplayName(str(item),None,ctypes.byref(pidl),0,None)+ if result<0:+ raise OSError('Windows could not locate the item in Explorer.')+ result=shell.SHOpenFolderAndSelectItems(pidl,0,None,0)+ if result<0:+ raise OSError('Windows could not select this item in Explorer.')+ finally:+ if pidl.value:+ ole.CoTaskMemFree(pidl)+ if initialized>=0:+ ole.CoUninitialize()