Skip to content

Local, full Windows search replacement, clipboard manager, and launcher: files, apps, settings and semantic media search with Google's EmbeddingGemma 2.

Release 0.3.46: targeted indexing, retrieval evidence and Windows compatibility (#24)

ampersandruf98815d75a95
diff --git a/.github/workflows/native-windows.yml b/.github/workflows/native-windows.yml
index 3d28484..5e6ca2f 100644
--- a/.github/workflows/native-windows.yml
+++ b/.github/workflows/native-windows.yml
@@ -40,7 +40,7 @@ jobs:
- name: Verify release manifest and packaging regressions
shell: pwsh
run: |
- python -m unittest discover -s native/scripts -p test_release_gate.py
+ python -m unittest discover -s native/scripts -p "test_*.py"
if ($LASTEXITCODE) { exit $LASTEXITCODE }
$version = (Select-String -Path native/Cargo.toml -Pattern '^version = "([^"]+)"').Matches[0].Groups[1].Value
python native/scripts/release_gate.py --verify-only --directory dist/installer --version $version
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1
index 1284c6e..f9eb29e 100644
--- a/Build-Rust.ps1
+++ b/Build-Rust.ps1
@@ -102,8 +102,8 @@ if (Test-Path $taskPortable) { throw 'Portable staging directory already exists.
New-Item -ItemType Directory -Force $taskPortable | Out-Null
Get-ChildItem -LiteralPath $taskBundle | Copy-Item -Destination $taskPortable -Recurse -Force
Set-Content -LiteralPath (Join-Path $taskPortable 'portable.flag') -Value '' -Encoding ascii
-Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.45-x64.zip' -Force
-$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.45-x64.exe'
-$taskZip='dist/installer/VectorDash-Rust-0.3.45-x64.zip'
+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.46-x64.zip' -Force
+$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.46-x64.exe'
+$taskZip='dist/installer/VectorDash-Rust-0.3.46-x64.zip'
@($taskInstaller,$taskZip) | ForEach-Object {((Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash.ToLowerInvariant()+' '+(Split-Path $_ -Leaf))} | Set-Content 'dist/installer/RUST-SHA256SUMS.txt' -Encoding ascii
Write-Output "Native installer and portable ZIP ready."
diff --git a/docs/NETWORK-INDEXING.md b/docs/NETWORK-INDEXING.md
new file mode 100644
index 0000000..752fa0e
--- /dev/null
+++ b/docs/NETWORK-INDEXING.md
@@ -0,0 +1,40 @@
+# Network indexing
+
+Network drives use Windows directory change notifications as their fast path. Ordinary file notifications queue exact paths; genuine directory creation/rename can require subtree discovery. No NAS helper or new runtime download is required.
+
+## Notification boundaries
+
+The Windows notification buffer is 64 KiB, within the documented SMB limit. A network root with at most 128 top-level entries and at most 32 allowed direct subdirectories can use a nonrecursive root watch plus recursive branch watches. Wider roots retain one recursive watcher, keeping thread/handle growth bounded. New branches are attached automatically; exceeding the branch cap falls back to a recursive root before branch watches are removed. Local NTFS journal behavior is unchanged.
+
+Overflow, watcher reconnection and provider-requested rescan retain the watched branch's identity. A failure in a branch does not automatically escalate to the configured share root.
+
+## Incremental safety and gap recovery
+
+The optional periodic safety pass defaults to five minutes **after the prior pass completes**. A pass enumerates directory metadata, not file content. Normal notifications remain the immediate update path. Startup/offline gaps and known missed-event recovery use required incremental passes even if periodic safety is disabled.
+
+A background worker checks at most 256 directory/missing-child entries per batch, at most 16 small directories, and yields at a nominal 100 ms budget between blocking operations. A single stalled SMB call can last longer; it does not block the UI or monitor scheduler. Only one worker batch is active. Automatic-indexing hold, resource/idle conditions and an active indexing job pause further batches.
+
+On Windows, directory-entry metadata avoids an additional stat call for every file. New/changed files and confirmed missing immediate children are durably queued for the normal indexing pipeline. Directory records can be refreshed without recursively queuing that directory. Complete directory enumeration is required before considering missing children; an unreadable or partial listing retains their index entries. Engine-side existence checks still protect deletion handling.
+
+Directory work, temporary seen-entry sets and file changes live in the existing index database (including its encryption policy). Progress is committed with changed paths. Periodic work can resume safely after an interrupted directory. A new offline/monitoring gap starts a fresh metadata pass for the affected source or branch, because earlier directories may have changed while notifications were unavailable. Temporary seen rows are removed after each directory completes. A parent index supports immediate-child comparisons without querying every indexed file for every directory.
+
+A completed explicit full scan retires older reconciliation requests before timers run; genuinely newer monitoring gaps survive. Disabling periodic checks cancels periodic work without dropping required recovery. Logs report batch and current-run metadata counts separately from normal indexing counts.
+
+## Limits
+
+A complete safety pass still performs O(N) metadata enumeration. The improvement is bounded/background work, fewer metadata round trips and only indexing differences—not a promise of constant-cost reconciliation. SMB notifications cannot replay arbitrary offline changes, and remote NTFS USN access is not available through an ordinary mapped share. Server-side change tracking would require a separate optional service and is not included.
+
+Broad explicit manual updates, genuinely new/moved-in directory trees and local NTFS journal gaps can still require larger scans. An inaccessible branch is retained in the index and reported; periodic passes or subsequent recovery/manual updates can retry it. The first reconciliation creates a database parent-lookup index, which can take additional time on a large existing database without enumerating the filesystem.
+
+## Windows API references
+
+- [ReadDirectoryChangesW network support, overflow behavior and 64 KiB limit](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw)
+- [SMB recursive change notifications](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-smb2/598f395a-e7a2-4cc8-afb3-ccb30dd2df7c)
+- [USN journal operations are not available over ordinary SMB shares](https://learn.microsoft.com/en-us/windows/win32/api/winioctl/ni-winioctl-fsctl_read_usn_journal)
+- [Rust directory-entry metadata on Windows](https://doc.rust-lang.org/std/fs/struct.DirEntry.html#method.metadata)
+
+### Follow-up batching and unavailable branches
+
+After a successful automatic update, changes received during that update get a fresh 10-second batching window (with the existing maximum-latency rule). Network directory creation/rename discovery uses bounded metadata reconciliation rather than a recursive indexing job. File notifications remain exact, and removed paths still receive deletion checks.
+
+Missing or inaccessible child watch locations are skipped when a live ancestor watch can detect their return. They are reattached on a new parent notification or when monitoring is reconfigured. Share roots without a covering watch retain reconnect retries. Indexed records are retained for inaccessible locations.
diff --git a/docs/RETRIEVAL-BENCHMARK.md b/docs/RETRIEVAL-BENCHMARK.md
new file mode 100644
index 0000000..ac91042
--- /dev/null
+++ b/docs/RETRIEVAL-BENCHMARK.md
@@ -0,0 +1,47 @@
+# Retrieval evidence regression benchmark
+
+Issue [#23](https://github.com/ampersandru/VectorDash/issues/23) exposed a distinction between finding a file and finding the evidence requested inside it. These tools keep those scores separate. They do not claim that synthetic performance predicts real-world quality.
+
+## Larger deterministic corpus
+
+Use Python with Pillow installed. Write to a **new** directory outside your ordinary indexed folders:
+
+```powershell
+python native/scripts/generate_retrieval_corpus.py windows/.smoke/retrieval-corpus --ffmpeg .build-tools/ffmpeg-rust/ffmpeg.exe
+```
+
+This creates 156 files and 288 queries: 120 near-duplicate maintenance documents (24 Unicode RTFs), 24 identifier/shape images, and 12 silent forward/reverse video controls. Without `--ffmpeg`, it creates 144 files and 264 queries. Never add real personal documents to a published result bundle. The generator refuses an existing output directory.
+
+Full-index `corpus` in an isolated test profile, enable English OCR, use a video sampling interval of at most five seconds, and record the actual settings, model revision/quantization, hardware, and app commit. Run each query through CLI or MCP and store JSONL records shaped as `{ "query": { "id": "Q001" }, "response": { "results": [...] } }`. Keep native result ordering. Report cold/warm latency separately using the same interface and cache conditions for comparisons.
+
+```powershell
+python native/scripts/retrieval_benchmark.py --truth windows/.smoke/retrieval-corpus/ground-truth.json --responses results.jsonl --output scores.json
+python -m unittest discover -s native/scripts -p test_retrieval_benchmark.py
+```
+
+Default scoring keeps cross-category distractors, as universal search would. `--category-scoped` reproduces issue #23's category-filtered protocol; label that choice in reports. Missing/duplicate query responses are errors, not silently dropped samples.
+
+## Scores and evidence
+
+- **Top1/Top5:** first acceptable file after file deduplication.
+- **Evidence Top1:** first-ranked file is correct and supporting evidence has the required modality, timestamp range, and (for exact identifiers) actual matching text. Annotated queries are counted separately.
+- **Components:** timestamp, modality, exact-text, page and order checks also have separate counts. Optional `page_ranges` annotations use `file`, `start_page`, and `end_page`; optional `exact_text` separates a literal identifier from natural-language query wording.
+- **Order:** all required visual moments must be present in increasing timestamp order. Reverse-order and same-frame controls must not pass.
+
+CLI/MCP hits now include an optional `evidence` array, with `source`, `text`, `seconds`, `page`, and `line`. Sources include `video_frame`, `video_ocr`, `audio`, `image`, `image_ocr`, and `text`. The primary hit's timestamp remains the preview target. Combined queries expose up to three supporting moments. Old responses without this field can still be scored using their primary hit; they cannot prove multiple moments.
+
+The expanded synthetic corpus covers identifiers, near-duplicate document conditions, RTF extraction and temporal controls. It has **no real speech**; add separately licensed noisy recordings, audiovisual conjunctions, long videos, multiple languages, and human-judged hard negatives before drawing broader conclusions. Do not compare products using different category filters, interfaces, corpus coverage, or weak-result thresholds without disclosing those differences.
+
+## Beta retrieval behavior and limits
+
+Video frame OCR follows the existing optional OCR switch, engine, languages, video interval and frame deduplication. OCR failures are reported as warnings while visual frames remain indexable. Update affected Full sources to refresh video/RTF extraction; changed fingerprints retain old completed content until its replacement finishes.
+
+Explicit video queries using `then`/`followed by` (or supported Chinese order markers) split into at most three visual clauses. `while` or supported Chinese audio clauses split visual/audio evidence. Each clause searches only its relevant modality, with at most four candidate moments per file; reranking favors the weakest-supported condition. Candidate moments must score at least 0.35 and remain within 0.12 of that file's strongest moment for the clause; these are conservative heuristic cutoffs, not probabilities. Ordered clauses require distinct increasing timestamps. Visual/audio evidence must be within 30 seconds. This is a bounded heuristic, not a general language parser or verified scene reasoning. It may increase latency by up to three additional query embeddings. Ordinary queries retain a single embedding request.
+
+Brief scenes, tiny/obscured text, unsupported phrasing, and frame deduplication can still limit recall. Similarity-based evidence is labelled as a candidate; it must not be presented as proof that all requested facts are true.
+
+An ignored Rust runner, `synthetic_retrieval_benchmark_records_real_backend_results`, can index and query an explicitly supplied isolated profile (`VECTORDASH_BENCHMARK_HOME`). It requires `synthetic-benchmark.flag`, `settings.json`, and `ground-truth.json` in that profile, and writes `results.jsonl`. It uses category-scoped searches; score those runs with `--category-scoped`. Never point it at your ordinary profile.
+
+## Local validation, 2026-11-10
+
+On the generated 156-file/288-query corpus, the beta returned all 288 expected files first, with all 168 annotated evidence checks passing (24 timestamp/modality cases, 156 exact-text cases, 12 order cases; these overlap). The corpus was used during development to catch FFmpeg frame alignment and surrounding-punctuation mismatches. It is **not a held-out benchmark**, and contains no real audio or page-annotated PDFs. These numbers establish regression coverage, not general accuracy or a comparison with other products.
diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md
index 378289c..25bdc2c 100644
--- a/docs/RETRIEVAL.md
+++ b/docs/RETRIEVAL.md
@@ -67,3 +67,7 @@ Illustrative Windows x64 release-build measurements: three runs per mode, five-s
| 1080p / 4 frames | FFmpeg | GPU | 1.185 s | 126.1 MiB | 0.750 s |
GPU startup can outweigh decode savings on short clips; use CPU when it is faster for your workload. The native GPU route uses a D3D11 device manager and multithread protection; supported Windows codecs/drivers determine hardware acceleration. The default native GPU above was verified as an NVIDIA GeForce RTX 5080 (D3D11 video decoding, not CUDA). FFmpeg Auto selected DXVA2. Explicit AMD Radeon(TM) Graphics adapter tests also passed: native decoding took 0.429 s / 74.3 MiB at 360p and 0.537 s / 154.3 MiB at 1080p; FFmpeg D3D11VA took 1.190 s / 90.5 MiB and 2.764 s / 180.8 MiB respectively. These are separate video-device choices, independent of the embedding GPU. Native output is resized to at most 1024 pixels per dimension before JPEG encoding where the installed decoder supports it. Media Foundation is loaded on demand; systems without it can use the FFmpeg fallback.
+
+## Evidence-aware retrieval beta
+
+Sampled video frames can use the existing optional OCR engine and selected languages. Video text retains its frame timestamp separately from audio. Full-source updates refresh the affected video/RTF extraction fingerprints. Explicit combined and ordered video queries can use bounded multi-part reranking; results are labelled as candidate evidence, not guaranteed scene understanding. See [benchmark protocol and limits](RETRIEVAL-BENCHMARK.md).
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 233bc45..86ba87b 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -5750,7 +5750,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vectordash"
-version = "0.3.45"
+version = "0.3.46"
dependencies = [
"anyhow",
"arboard",
@@ -5763,6 +5763,7 @@ dependencies = [
"egui_commonmark",
"egui_extras",
"embed-resource",
+ "encoding_rs",
"half",
"hound",
"image",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index 7d01783..b438aec 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -1,12 +1,13 @@
[package]
name = "vectordash"
-version = "0.3.45"
+version = "0.3.46"
edition = "2024"
license = "MIT"
[dependencies]
anyhow = "1"
semver = "1"
regex = "1"
+encoding_rs = "0.8"
half = "2"
base64 = "0.22"
chrono = { version = "0.4", features = ["serde"] }
diff --git a/native/docs/0.3.46-beta.1.md b/native/docs/0.3.46-beta.1.md
new file mode 100644
index 0000000..f85dff0
--- /dev/null
+++ b/native/docs/0.3.46-beta.1.md
@@ -0,0 +1,17 @@
+# VectorDash 0.3.46-beta.1
+
+- Sampled video frames now use the configured optional OCR engine and languages. Text matches retain the frame timestamp, separately from visual and audio embeddings.
+- Corrected FFmpeg sampling alignment so a sampled frame is not labelled with a timestamp before its scene begins.
+- Search explains whether evidence comes from video frames, frame text, or audio. CLI/MCP results include structured supporting evidence.
+- Explicit combined visual/audio and ordered video queries use bounded multi-part reranking (up to three parts). Results remain semantic candidates, not guaranteed scene understanding.
+- Content ranking normalizes surrounding punctuation consistently, so constraints such as “Site 000:” can match “Site 000”.
+- RTF documents index readable text rather than formatting markup, including Unicode and escaped characters.
+- Added a larger deterministic synthetic corpus generator and scoring for file hits, supporting modality, exact identifiers, and timestamp/order correctness.
+
+## Testing
+
+Enable OCR and its required language packs, then run Update on Full-indexed video and RTF folders. Changed extraction fingerprints refresh affected content without rebuilding unrelated files. OCR increases video indexing time; it follows the existing video sample interval and similar-frame setting, so short scenes or tiny text can still be missed.
+
+Try an on-screen identifier, a visual/audio query using “while”, and a video query using “then”. Compare the selected timestamp with the actual content. Existing index files remain local. See docs/RETRIEVAL-BENCHMARK.md for reproducible evaluation.
+
+Thanks to the author of issue #23 for the reproducible multimodal benchmark that motivated these changes. No new model accuracy or speed claims are made from the synthetic tests.
diff --git a/native/docs/0.3.46-beta.2.md b/native/docs/0.3.46-beta.2.md
new file mode 100644
index 0000000..5d5edbd
--- /dev/null
+++ b/native/docs/0.3.46-beta.2.md
@@ -0,0 +1,20 @@
+# VectorDash 0.3.46-beta.2
+
+Includes the video OCR, evidence-aware retrieval, RTF extraction and benchmark improvements from beta.1, plus these automatic-indexing fixes:
+
+- Ambiguous journal basename lookups no longer recursively scan matching live directories. Directory metadata is refreshed on its own; unchanged file candidates are skipped.
+- Adding exclusions preserves valid journal replay. Removing an exclusion requests catch-up only for overlapping sources rather than unrelated drives.
+- Monitoring is configured before restarted scans, preventing startup recovery work from being queued behind a scan already covering it. Interrupted change-monitor runs resume queued affected paths instead of restarting all sources.
+- Added **Periodic network-drive catch-up scans** and an editable interval in Scheduling. Enabled by default at **5 minutes**. Folder notifications remain active when disabled; startup and genuine missed-event recovery can still run.
+- Periodic network catch-up waits for active indexing and restarts its timer after successful coverage, reducing back-to-back catch-up runs.
+- Quiet journal progress is checkpointed after all ambiguous names have been checked and no durable indexing work remains, avoiding replaying already-checked noise after restart.
+- Automatic-run deadlines are published before enabling concurrent checks. Run history now shows the actual stop/failure reason.
+- Registered missing/new UI messages in localization catalogs.
+
+## What to test
+
+In Scheduling, choose whether periodic network catch-up is enabled and set the interval. Save once; changing only the catch-up interval should not trigger a source restart.
+
+Create one file, edit one existing file, and create a subfolder with a file on a local indexed NTFS drive. Normal journal updates should stay targeted. Create and rename a directory containing files to confirm genuine subtree changes are still discovered. Add a browser exclusion on C: and confirm unrelated drives are not rescanned. Test T: changes with periodic catch-up both enabled and disabled.
+
+A genuine journal gap, missed-event recovery, expanded source coverage or explicit manual update can still require a broader scan. Existing queued work from earlier versions may need to drain once. This beta keeps completed index data and does not rebuild embeddings merely because an unrelated exclusion changes.
diff --git a/native/docs/0.3.46-beta.3.md b/native/docs/0.3.46-beta.3.md
new file mode 100644
index 0000000..34c9d21
--- /dev/null
+++ b/native/docs/0.3.46-beta.3.md
@@ -0,0 +1,24 @@
+# VectorDash 0.3.46-beta.3
+
+Includes beta.1 and beta.2 features and fixes, with notification-first network indexing:
+
+- Periodic network safety checks now compare directory metadata in bounded background batches instead of queuing a recursive share-root indexing job. Only new/changed/missing file paths enter the normal index queue; unchanged file contents are not opened.
+- Startup and watcher-gap recovery on network sources use the same incremental reconciler. Disabling periodic checks preserves notifications and required gap recovery.
+- Increased Windows change-notification buffers from 16 KiB to the SMB-compatible 64 KiB limit. Suitable shares use a nonrecursive root watch plus up to 32 recursive branch watches, so an overflow or reconnect can recover only its branch. Very wide roots retain a recursive watcher.
+- New top-level branches are watched automatically. Watch counts, directory-discovery limits and fallback modes stay bounded.
+- Fixed completion ordering: a successful full scan acknowledges older recovery requests and resets network timers before periodic work can be queued. Newer genuine gaps remain pending.
+- Directory progress and exact changed paths are committed together. Interrupted/incomplete listings retain indexed data and never establish deletions. Periodic progress is retained; a new offline gap starts a fresh metadata pass so already-checked branches are not missed.
+- Network metadata comes from directory-listing entries on Windows, avoiding a separate file-stat request per entry. Work pauses for indexing, idle rules and an automatic-indexing hold.
+- Added batch and reconciliation-run counts to logs, plus regression coverage for budgets, changed-file-only queueing, interruptions, disconnected shares, branch scopes and timer handling.
+
+## Settings and testing
+
+The existing Scheduling toggle and interval remain available (default enabled, 5 minutes). The interval now controls the delay between completed incremental passes, not a whole-share scan every five minutes.
+
+Create one file and edit three existing files in a test folder on T:. Test nested directory creation/rename and reconnect after a brief disconnect. Inspect the log for `Network reconciliation` batch/run counts; ordinary notifications should still produce small targeted jobs. No embedding rebuild is required.
+
+Safety reconciliation still enumerates metadata across a share over a complete pass; it spreads that work out and only indexes differences. It is not a replayable remote USN journal. A single slow SMB operation can exceed the scheduling time slice, but it runs off the UI/scheduler thread. Explicit manual full-source updates remain full scans. See docs/NETWORK-INDEXING.md for architecture and limits.
+
+## Validation
+
+466 Rust tests and 10 Python tests passed. Live tests on T: verified one new file plus three edits queue exactly four paths, and verified nested/new-branch notification delivery with safety reconciliation disabled in the notification checks. Only test-owned temporary folders were created and removed. These checks validate behavior, not a general NAS performance claim.
diff --git a/native/docs/0.3.46-beta.4.md b/native/docs/0.3.46-beta.4.md
new file mode 100644
index 0000000..edb88c8
--- /dev/null
+++ b/native/docs/0.3.46-beta.4.md
@@ -0,0 +1,10 @@
+# VectorDash 0.3.46-beta.4
+
+- Automatic updates now allow a fresh 10-second batching window after completion, preventing queued changes from immediately launching another job using an expired timer. Continuous changes retain the maximum-latency rule.
+- Network directory creation/rename discovery uses bounded metadata reconciliation and queues individual differences instead of launching a recursive indexing job for that directory. Removed paths retain deletion checks.
+- Unavailable child watch locations (for example T:\hermes) are skipped when a healthy ancestor watch can detect their return. Parent notifications or monitoring reconfiguration can reattach them; disconnected share roots retain reconnect retries. Existing index entries are not deleted just because a path is inaccessible.
+- A failed branch now restarts only its closest watch, leaving a healthy parent watch running.
+
+Periodic network catch-up can remain disabled while testing normal SMB notifications. Metadata recovery still runs for genuine coverage gaps. Local directory creation/rename can still require discovering that subtree; this update does not eliminate all metadata enumeration.
+
+Validation: full suite 470 passed before the final closest-watch adjustment; all 33 monitoring tests passed after it, plus two controlled live T: tests (exactly four paths for one new file and three edits; nested/new branch notification delivery).
diff --git a/native/docs/0.3.46-beta.5.md b/native/docs/0.3.46-beta.5.md
new file mode 100644
index 0000000..ce6923f
--- /dev/null
+++ b/native/docs/0.3.46-beta.5.md
@@ -0,0 +1,9 @@
+# VectorDash 0.3.46-beta.5
+
+Adds an optional native Windows minimize compatibility mode for Windows 10/11, disabled by default for both new and existing installations.
+
+Enable **Use native Windows minimize (compatibility mode)** in Settings → Startup and window behavior, then Save. With Minimize behavior set to Taskbar, try the title-bar minimize button in restored and maximized windows. Restore from the taskbar and repeat. The option also applies when Close is configured to minimize to the taskbar; Tray behavior is unchanged.
+
+The alternative queues Windows' standard minimize system command instead of the UI framework viewport command. If the command cannot be queued, the existing method remains the fallback. Logs record native minimize requests to help diagnose issue #25. A queued request is not proof that Windows kept the window minimized; reporter testing is still needed.
+
+Validation: 472 Rust tests and 10 Python tests passed, including old-settings/default-off and enabled-setting persistence coverage. Reporter confirmation is needed for the affected Windows installation.
diff --git a/native/docs/0.3.46.md b/native/docs/0.3.46.md
new file mode 100644
index 0000000..c2c5ec5
--- /dev/null
+++ b/native/docs/0.3.46.md
@@ -0,0 +1,30 @@
+# VectorDash 0.3.46
+
+## Search and indexing
+
+- Video frames can use optional OCR with the configured languages. Results retain frame timestamps and distinguish visual, on-screen text and audio evidence. Corrected FFmpeg sampling timestamps.
+- Added bounded multi-part reranking for combined visual/audio and ordered video queries, punctuation-normalized identifiers, and readable RTF text extraction. Semantic matches remain candidates, not guaranteed scene understanding.
+- Improved NTFS journal targeting: ambiguous directory names no longer trigger recursive walks, unchanged candidates are skipped, and exclusion changes preserve valid journal coverage.
+- Interrupted monitoring work resumes affected paths. Full scans retire older covered recovery requests before catch-up scheduling. Quiet journal progress is checkpointed, and automatic-run history records stop/failure reasons.
+
+## Network drives and automatic updates
+
+- Added configurable periodic network catch-up (default enabled, five minutes between completed passes). SMB notifications remain active when periodic catch-up is off; startup, reconnect and genuine coverage-gap recovery can still run.
+- Network safety checks use bounded background metadata batches and durably queue only differences. Improved notification buffering and bounded branch watches reduce broad recovery work.
+- Follow-up updates receive a fresh batching window rather than immediately starting another job with an expired timer. Network directory creation/rename discovery uses incremental reconciliation.
+- Unavailable child watches are skipped when a healthy parent can detect their return. Branch failures restart only the closest affected watch. Share-level reconnect retries remain active, and inaccessible listings retain indexed records.
+
+Safety reconciliation still enumerates metadata over a complete pass; it spreads that work out rather than eliminating it. Explicit full updates and genuine local subtree changes can still require broader discovery.
+
+## Windows minimize compatibility
+
+- Added **Use native Windows minimize (compatibility mode)** in Settings → Startup and window behavior, **off by default**, for Windows 10/11 systems where the regular taskbar minimize method fails.
+- Applies to the minimize button and Close configured to minimize to taskbar. Tray behavior is unchanged. Native minimize requests are logged for troubleshooting; confirmation on the reporter's affected system is still pending.
+
+## Updating
+
+No whole-index rebuild is required. To refresh video OCR and RTF contents, enable the desired OCR engine/language packs and update the relevant Full-indexed folders. Video OCR adds processing time and follows existing sampling settings.
+
+Includes a reproducible synthetic retrieval benchmark and monitoring regression tests. The latest beta passed 472 Rust tests and 10 Python tests; controlled T: tests verified exact-file reconciliation and nested/new-branch notifications. These are correctness checks, not general NAS performance or model-accuracy claims.
+
+Thanks to the reporters of issues #23 and #25 for their examples and recordings.
diff --git a/native/locales/de.json b/native/locales/de.json
index a0dfaf5..7db9701 100644
--- a/native/locales/de.json
+++ b/native/locales/de.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Regelmäßige Abgleichscans für Netzlaufwerke",
+ "Network catch-up interval (minutes)": "Netzwerk-Abgleichintervall (Minuten)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/en.json b/native/locales/en.json
index 567b6cb..de26e13 100644
--- a/native/locales/en.json
+++ b/native/locales/en.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Periodic network-drive catch-up scans",
+ "Network catch-up interval (minutes)": "Network catch-up interval (minutes)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/es.json b/native/locales/es.json
index c746c47..6de75d0 100644
--- a/native/locales/es.json
+++ b/native/locales/es.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Escaneos periódicos de recuperación de unidades de red",
+ "Network catch-up interval (minutes)": "Intervalo de recuperación de red (minutos)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/fr.json b/native/locales/fr.json
index 98fd76b..c79a5e2 100644
--- a/native/locales/fr.json
+++ b/native/locales/fr.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Analyses périodiques de rattrapage des lecteurs réseau",
+ "Network catch-up interval (minutes)": "Intervalle de rattrapage réseau (minutes)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/hi.json b/native/locales/hi.json
index 8669a46..3027f25 100644
--- a/native/locales/hi.json
+++ b/native/locales/hi.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "नेटवर्क ड्राइव के समय-समय पर कैच-अप स्कैन",
+ "Network catch-up interval (minutes)": "नेटवर्क कैच-अप अंतराल (मिनट)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/it.json b/native/locales/it.json
index 02bc436..aec653c 100644
--- a/native/locales/it.json
+++ b/native/locales/it.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Scansioni periodiche di recupero delle unità di rete",
+ "Network catch-up interval (minutes)": "Intervallo di recupero della rete (minuti)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/ja.json b/native/locales/ja.json
index 36ce02d..bbacd40 100644
--- a/native/locales/ja.json
+++ b/native/locales/ja.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "ネットワークドライブの定期補完スキャン",
+ "Network catch-up interval (minutes)": "ネットワーク補完スキャンの間隔(分)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/ko.json b/native/locales/ko.json
index 2031e59..673a5ee 100644
--- a/native/locales/ko.json
+++ b/native/locales/ko.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "네트워크 드라이브 정기 보완 검색",
+ "Network catch-up interval (minutes)": "네트워크 보완 검색 간격(분)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/pt-BR.json b/native/locales/pt-BR.json
index fbbe41c..779d5c3 100644
--- a/native/locales/pt-BR.json
+++ b/native/locales/pt-BR.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Verificações periódicas de atualização de unidades de rede",
+ "Network catch-up interval (minutes)": "Intervalo de atualização da rede (minutos)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/ru.json b/native/locales/ru.json
index d7f4161..193a626 100644
--- a/native/locales/ru.json
+++ b/native/locales/ru.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Периодическая сверка сетевых дисков",
+ "Network catch-up interval (minutes)": "Интервал сверки сети (минуты)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/vi.json b/native/locales/vi.json
index ff32d6d..442ab83 100644
--- a/native/locales/vi.json
+++ b/native/locales/vi.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "Quét bù định kỳ cho ổ đĩa mạng",
+ "Network catch-up interval (minutes)": "Khoảng thời gian quét bù mạng (phút)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/zh-CN.json b/native/locales/zh-CN.json
index c402441..b74dac7 100644
--- a/native/locales/zh-CN.json
+++ b/native/locales/zh-CN.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "定期补扫网络驱动器",
+ "Network catch-up interval (minutes)": "网络补扫间隔(分钟)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/locales/zh-TW.json b/native/locales/zh-TW.json
index 6e71771..6fb1130 100644
--- a/native/locales/zh-TW.json
+++ b/native/locales/zh-TW.json
@@ -944,5 +944,12 @@
"GPU for idle threshold": "GPU for idle threshold",
"Use model GPU": "Use model GPU",
"Selected GPU unavailable": "Selected GPU unavailable",
- "GPU monitored: {name}": "GPU monitored: {name}"
+ "GPU monitored: {name}": "GPU monitored: {name}",
+ "Periodic network-drive catch-up scans": "定期補掃網路磁碟機",
+ "Network catch-up interval (minutes)": "網路補掃間隔(分鐘)",
+ "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.": "Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up.",
+ "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.": "Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval.",
+ "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.": "Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off.",
+ "Use native Windows minimize (compatibility mode)": "Use native Windows minimize (compatibility mode)",
+ "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged.": "Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."
}
diff --git a/native/scripts/generate_retrieval_corpus.py b/native/scripts/generate_retrieval_corpus.py
new file mode 100644
index 0000000..7005de2
--- /dev/null
+++ b/native/scripts/generate_retrieval_corpus.py
@@ -0,0 +1,86 @@
+"""Generate a deterministic larger synthetic retrieval regression corpus.
+Requires Pillow for images; --ffmpeg optionally adds paired forward/reverse silent videos.
+Writes only to a new directory; never modifies an existing corpus.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+
+
+def generate(output, ffmpeg=None):
+ from PIL import Image, ImageDraw, ImageFont
+ output.mkdir(parents=True, exist_ok=False)
+ corpus = output / "corpus"
+ corpus.mkdir()
+ files, queries = [], []
+ def register(path, category):
+ files.append({"file": path.name, "category": category, "sha256": hashlib.sha256(path.read_bytes()).hexdigest()})
+ def query(text, name, category, group, **extra):
+ queries.append({"id": f"Q{len(queries)+1:03}", "query": text, "expected_files": [name], "category": category, "group": group, **extra})
+ jobs = [("bicycle", "replace the frayed rear brake cable; keep the front tire"),
+ ("garden", "repair the irrigation valve; leave the outdoor lights alone"),
+ ("meeting", "move the choir rehearsal to Thursday; leave the concert on Sunday"),
+ ("server", "rotate the access logs; preserve the database backup"),
+ ("kitchen", "replace the refrigerator seal; keep the compressor")]
+ # Twenty-four near-duplicate families, five conflicting tasks each. RTF includes Unicode escapes.
+ for family in range(24):
+ for task, (topic, instruction) in enumerate(jobs):
+ ident = f"CASE-{family:03}-{task}"
+ text = f"Maintenance record {ident}\nSite {family:03}\nTopic: {topic}\nAction: {instruction}\n维修记录:更换后刹车内线,不更换前胎。" if task == 0 else f"Maintenance record {ident}\nSite {family:03}\nTopic: {topic}\nAction: {instruction}"
+ path = corpus / f"record-{family:03}-{task}.{'rtf' if task == 0 else 'txt'}"
+ if task == 0:
+ encoded = "".join(f"\\u{int.from_bytes(text.encode('utf-16-le')[i:i+2], 'little', signed=True)}?" for i in range(0, len(text.encode('utf-16-le')), 2))
+ path.write_text("{\\rtf1\\ansi\\uc1 " + encoded + "}", encoding="ascii")
+ else:
+ path.write_text(text, encoding="utf-8")
+ register(path, "document")
+ query(ident, path.name, "document", "document-identifiers", exact_match=True)
+ query(f"Site {family:03}: {instruction}", path.name, "document", "document-conditions")
+ try:
+ font = ImageFont.truetype("arial.ttf", 64)
+ except OSError:
+ font = ImageFont.load_default(size=64)
+ images = []
+ for i in range(24):
+ ident = f"VN-{5100+i}"
+ image = Image.new("RGB", (960, 540), "white")
+ draw = ImageDraw.Draw(image)
+ if i % 2:
+ draw.ellipse((250,150,650,500),fill="blue")
+ else:
+ draw.rectangle((250,150,650,500),fill="red")
+ draw.text((35,35),ident,fill="black",font=font)
+ path = corpus / f"frame-{i:02}.png"
+ image.save(path)
+ register(path,"image"); images.append(path)
+ query(ident,path.name,"image","image-identifiers",exact_match=True)
+ seen_video_identifiers = set()
+ if ffmpeg:
+ for pair in range(6):
+ for reverse in (False,True):
+ indices=[pair*2,pair*2+1]
+ if reverse:indices.reverse()
+ path=corpus/f"sequence-{pair}-{int(reverse)}.mp4"
+ subprocess.run([ffmpeg,"-nostdin","-v","error","-loop","1","-t","6","-i",str(images[indices[0]]),"-loop","1","-t","6","-i",str(images[indices[1]]),"-filter_complex","[0:v][1:v]concat=n=2:v=1:a=0,format=yuv420p[v]","-map","[v]","-r","10",str(path)],check=True,timeout=90)
+ register(path,"video")
+ for j, index in enumerate(indices):
+ ident=f"VN-{5100+index}"
+ if ident not in seen_video_identifiers:
+ seen_video_identifiers.add(ident)
+ query(ident,path.name,"video","video-identifiers",exact_match=True,time_ranges=[{"file":path.name,"start_seconds":j*6,"end_seconds":j*6+5.99,"modality":"visual"}])
+ queries[-1]["expected_files"] = [f"sequence-{pair}-0.mp4", f"sequence-{pair}-1.mp4"]
+ queries[-1]["time_ranges"] = [{"file": f"sequence-{pair}-{r}.mp4", "start_seconds": (j if not r else 1-j)*6, "end_seconds": (j if not r else 1-j)*6+5.99, "modality": "visual"} for r in (0,1)]
+ shapes=["blue circle" if index%2 else "red square" for index in indices]
+ query(f"video labelled VN-{5100+indices[0]} showing a {shapes[0]} then VN-{5100+indices[1]} showing a {shapes[1]}",path.name,"video","video-order",ordered=True,time_ranges=[{"file":path.name,"start_seconds":0,"end_seconds":5.99,"modality":"visual"},{"file":path.name,"start_seconds":6,"end_seconds":11.99,"modality":"visual"}])
+ truth={"schema":1,"description":"Synthetic pipeline regression, not a representative quality ranking","files":files,"queries":queries}
+ (output/"ground-truth.json").write_text(json.dumps(truth,ensure_ascii=False,indent=2),encoding="utf-8")
+ return {"files":len(files),"queries":len(queries)}
+
+if __name__ == "__main__":
+ parser=argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("output",type=Path)
+ parser.add_argument("--ffmpeg")
+ args=parser.parse_args()
+ print(json.dumps(generate(args.output,args.ffmpeg)))
diff --git a/native/scripts/retrieval_benchmark.py b/native/scripts/retrieval_benchmark.py
new file mode 100644
index 0000000..393794f
--- /dev/null
+++ b/native/scripts/retrieval_benchmark.py
@@ -0,0 +1,134 @@
+"""Score file retrieval separately from modality, exact text and temporal evidence.
+Consumes JSON ground truth and JSONL {query:{id:...},response:{results:[...]}}.
+No product code or model is imported; raw responses are treated as data.
+"""
+import argparse
+import json
+from collections import defaultdict
+from pathlib import Path
+
+
+def basename(value):
+ return value.replace("\\", "/").rsplit("/", 1)[-1]
+
+
+def evidence(hit):
+ if hit.get("evidence"):
+ return hit["evidence"]
+ kind = hit.get("kind", "")
+ return [{"source": "audio" if kind == "video_audio" else "video_ocr" if kind == "video" and hit.get("text") else "video_frame" if kind == "video" else "text",
+ "seconds": hit.get("seconds", -1), "page": hit.get("page", 0), "text": hit.get("text", "")}]
+
+
+def evidence_checks(query, hit):
+ """Keep component scores as well as joint support; all checks require a correct file."""
+ timed = bool(query.get("time_ranges"))
+ paged = bool(query.get("page_ranges"))
+ exact = bool(query.get("exact_match"))
+ ordered = bool(query.get("ordered"))
+ checks = {"timestamp": None, "modality": None, "exact_text": None, "page": None, "order": None}
+ applicable = {"timestamp": timed, "modality": timed, "exact_text": exact, "page": paged, "order": ordered}
+ if not any(applicable.values()):
+ return checks, None
+ correct = hit is not None and basename(hit.get("path", "")) in query["expected_files"]
+ if not correct:
+ return {k: False if applicable[k] else None for k in checks}, False
+ name = basename(hit["path"])
+ points = evidence(hit)
+ token = query.get("exact_text", query["query"]).casefold()
+ if exact:
+ checks["exact_text"] = any(token in e.get("text", "").casefold() for e in points)
+ def modality(e, r):
+ source = e.get("source", "")
+ if r.get("modality") == "visual":
+ return source in ("video_frame", "video_ocr", "image", "image_ocr")
+ if r.get("modality") == "audio":
+ return source == "audio"
+ return True
+ joint = []
+ if timed:
+ ranges = [r for r in query["time_ranges"] if r["file"] == name]
+ checks["modality"] = bool(ranges) and all(any(modality(e, r) for e in points) for r in ranges)
+ checks["timestamp"] = bool(ranges) and all(any(r["start_seconds"] <= e.get("seconds", -1) <= r["end_seconds"] for e in points) for r in ranges)
+ for r in ranges:
+ joint.append([e.get("seconds", -1) for e in points if modality(e, r)
+ and r["start_seconds"] <= e.get("seconds", -1) <= r["end_seconds"]
+ and (not exact or token in e.get("text", "").casefold())])
+ if paged:
+ ranges = [r for r in query["page_ranges"] if r["file"] == name]
+ checks["page"] = bool(ranges) and all(any(r["start_page"] <= e.get("page", 0) <= r["end_page"] for e in points) for r in ranges)
+ if ordered:
+ last = -1
+ checks["order"] = bool(joint)
+ for candidates in joint:
+ later = [t for t in candidates if t > last]
+ if not later:
+ checks["order"] = False
+ break
+ last = min(later)
+ supported = all(v for v in checks.values() if v is not None)
+ if timed:
+ supported = supported and bool(joint) and all(joint)
+ return checks, bool(supported)
+
+
+def score(truth, responses, category_scoped=False):
+ queries = {q["id"]: q for q in truth["queries"]}
+ files = {f["file"]: f for f in truth["files"]}
+ rows = []
+ seen = set()
+ for raw in responses:
+ qid = raw["query"]["id"]
+ if qid in seen or qid not in queries:
+ raise ValueError("Unknown or duplicate query ID: " + qid)
+ seen.add(qid)
+ q = queries[qid]
+ response = raw["response"]
+ if response.get("ok") is False or raw.get("error"):
+ hits = []
+ else:
+ hits = response.get("results", response.get("hits", []))
+ unique = []
+ paths = set()
+ for hit in hits:
+ name = basename(hit.get("path", hit.get("file_path", "")))
+ if category_scoped and (name not in files or files[name]["category"] != q["category"]):
+ continue
+ if name not in paths:
+ paths.add(name)
+ unique.append((name, hit))
+ rank = next((i + 1 for i, (name, _) in enumerate(unique) if name in q["expected_files"]), None)
+ top = unique[0] if unique else None
+ checks, supported = evidence_checks(q, top[1] if top else None)
+ rows.append({"id": qid, "group": q.get("group", q.get("category", "other")), "rank": rank,
+ "top1": rank == 1, "top5": rank is not None and rank <= 5, "evidence_top1": supported, "checks": checks})
+ missing = set(queries) - seen
+ if missing:
+ raise ValueError("Missing query responses: " + ", ".join(sorted(missing)))
+ def aggregate(items):
+ annotated = [r for r in items if r["evidence_top1"] is not None]
+ components = {key: {"queries": sum(r["checks"][key] is not None for r in items), "top1": sum(r["checks"][key] is True for r in items)} for key in ("timestamp", "modality", "exact_text", "page", "order")}
+ return {"components": components, "queries": len(items), "top1": sum(r["top1"] for r in items), "top5": sum(r["top5"] for r in items),
+ "evidence_queries": len(annotated), "evidence_top1": sum(r["evidence_top1"] for r in annotated)}
+ groups = defaultdict(list)
+ for row in rows:
+ groups[row["group"]].append(row)
+ return {"category_scoped": category_scoped, "overall": aggregate(rows), "groups": {k: aggregate(v) for k, v in groups.items()}, "rows": rows}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--truth", type=Path, required=True)
+ parser.add_argument("--responses", type=Path, required=True)
+ parser.add_argument("--output", type=Path)
+ parser.add_argument("--category-scoped", action="store_true", help="Reproduce category-filtered reports; default keeps all distractors")
+ args = parser.parse_args()
+ result = score(json.loads(args.truth.read_text(encoding="utf-8-sig")),
+ [json.loads(line) for line in args.responses.read_text(encoding="utf-8-sig").splitlines() if line.strip()], args.category_scoped)
+ text = json.dumps(result, ensure_ascii=False, indent=2)
+ if args.output:
+ args.output.write_text(text, encoding="utf-8")
+ print(json.dumps(result["overall"]))
+
+if __name__ == "__main__":
+ main()
diff --git a/native/scripts/test_retrieval_benchmark.py b/native/scripts/test_retrieval_benchmark.py
new file mode 100644
index 0000000..9d47aca
--- /dev/null
+++ b/native/scripts/test_retrieval_benchmark.py
@@ -0,0 +1,36 @@
+import unittest
+from retrieval_benchmark import score
+class EvidenceScoringTests(unittest.TestCase):
+ def run_case(self, hit, ordered=False):
+ q={"id":"Q1","query":"VN-5103","category":"video","expected_files":["a.mp4"],"exact_match":not ordered,"ordered":ordered,"time_ranges":[{"file":"a.mp4","start_seconds":8,"end_seconds":16,"modality":"visual"}]}
+ if ordered: q["time_ranges"].append({"file":"a.mp4","start_seconds":17,"end_seconds":25,"modality":"visual"})
+ return score({"files":[],"queries":[q]},[{"query":{"id":"Q1"},"response":{"results":[hit]}}])["overall"]
+ def test_correct_file_wrong_audio_is_not_evidence_success(self):
+ r=self.run_case({"path":"a.mp4","kind":"video_audio","seconds":0})
+ self.assertEqual(r["top1"],1);self.assertEqual(r["evidence_top1"],0)
+ def test_visual_identifier_requires_actual_text_at_the_correct_time(self):
+ for text, expected in [("VN-5103",1),("unrelated",0)]:
+ r=self.run_case({"path":"a.mp4","kind":"video","text":text,"seconds":10})
+ self.assertEqual(r["evidence_top1"],expected)
+ def test_sequence_requires_both_moments(self):
+ h={"path":"a.mp4","evidence":[{"source":"video_frame","seconds":10},{"source":"video_frame","seconds":20}]}
+ self.assertEqual(self.run_case(h,True)["evidence_top1"],1)
+ h["evidence"].pop()
+ self.assertEqual(self.run_case(h,True)["evidence_top1"],0)
+ def test_universal_scoring_does_not_remove_wrong_category_distractors(self):
+ q={"id":"Q1","category":"video","expected_files":["a.mp4"]}
+ truth={"files":[{"file":"a.mp4","category":"video"},{"file":"b.txt","category":"text"}],"queries":[q]}
+ raw=[{"query":{"id":"Q1"},"response":{"results":[{"path":"b.txt"},{"path":"a.mp4"}]}}]
+ self.assertEqual(score(truth,raw)["overall"]["top1"],0)
+ self.assertEqual(score(truth,raw,True)["overall"]["top1"],1)
+ def test_page_and_exact_text_are_scored_separately(self):
+ q={"id":"Q1","query":"INV-123","expected_files":["a.pdf"],"exact_match":True,"page_ranges":[{"file":"a.pdf","start_page":3,"end_page":3}]}
+ truth={"files":[],"queries":[q]}
+ raw=[{"query":{"id":"Q1"},"response":{"results":[{"path":"a.pdf","page":1,"text":"INV-123"}]}}]
+ r=score(truth,raw)["overall"]
+ self.assertEqual(r["components"]["exact_text"]["top1"],1)
+ self.assertEqual(r["components"]["page"]["top1"],0)
+ self.assertEqual(r["evidence_top1"],0)
+ def test_missing_or_duplicate_queries_are_errors(self):
+ with self.assertRaises(ValueError):score({"files":[],"queries":[{"id":"Q1"}]},[])
+if __name__ == "__main__":unittest.main()
diff --git a/native/src/app.rs b/native/src/app.rs
index e97f973..dd86255 100644
--- a/native/src/app.rs
+++ b/native/src/app.rs
@@ -731,6 +731,7 @@ impl App {
}
if let Some(path) = get("--smoke-preview") {
app.hits = vec![Hit {
+ evidence: Vec::new(),
path,
kind: "image".into(),
score: 1.0,
@@ -775,6 +776,7 @@ impl App {
"clipboard-clear" => app.clipboard_clear_confirm = true,
"delete" => {
app.delete_confirm = Some(Hit {
+ evidence: Vec::new(),
path: "C:\\fixture\\selected-file.txt".into(),
kind: "file".into(),
text: String::new(),
@@ -2288,10 +2290,27 @@ impl App {
self.exiting = true;
ctx.send_viewport_cmd(egui::ViewportCommand::Close)
}
- "Minimize to taskbar" => ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true)),
+ "Minimize to taskbar" => self.minimize_to_taskbar(ctx),
_ => ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)),
}
}
+ fn minimize_to_taskbar(&self, ctx: &egui::Context) {
+ if self.s.native_minimize {
+ let queued = crate::platform::minimize_main_window_native();
+ self.engine.log(
+ "Info",
+ if queued {
+ "Native Windows minimize requested"
+ } else {
+ "Native Windows minimize unavailable; using standard minimize"
+ },
+ );
+ if queued {
+ return;
+ }
+ }
+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
+ }
fn titlebar(&mut self, ctx: &egui::Context) {
use crate::icons::{self, Icon};
egui::TopBottomPanel::top("title")
@@ -2412,11 +2431,11 @@ impl App {
.clicked()
{
self.stop_read_aloud();
- ctx.send_viewport_cmd(if self.s.minimize_behavior == "Tray" {
- egui::ViewportCommand::Visible(false)
+ if self.s.minimize_behavior == "Tray" {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
} else {
- egui::ViewportCommand::Minimized(true)
- });
+ self.minimize_to_taskbar(ctx);
+ }
}
if self.quick && ui.button(t("Open full app")).clicked() {
self.quick = false;
@@ -5012,6 +5031,7 @@ impl App {
&mut self.s.ocr_enabled,
t("Enable OCR text extraction for images and scanned PDF pages"),
);
+ ui.weak(t("Also recognizes text in sampled video frames; uses the selected OCR languages and video sample interval."));
path_field(ui, t("Tesseract OCR"), &mut self.s.ocr);
if self.s.ocr_enabled {
field(ui, t("OCR languages"), &mut self.s.ocr_languages);
@@ -5315,6 +5335,11 @@ impl App {
&mut self.s.minimize_behavior,
&["Taskbar", "Tray"],
);
+ ui.checkbox(
+ &mut self.s.native_minimize,
+ t("Use native Windows minimize (compatibility mode)"),
+ );
+ ui.weak(t("Off by default. Try this on Windows 10/11 if minimizing to the taskbar does not work. Applies to the minimize button and Close when set to minimize; hiding to tray is unchanged."));
ui.label(t("Closing to tray keeps the global shortcut and scheduled indexing running. Exit stops the application and owned model server."));
ui.checkbox(&mut self.s.start_with_windows, t("Start with Windows"));
ui.checkbox(&mut self.s.start_hidden, t("Start hidden at startup"));
@@ -6741,6 +6766,18 @@ impl App {
}
ui.label(t("Automatic file changes obey the idle conditions below, including when the periodic scan schedule is Manual. Manual only disables periodic scans."));
+ ui.checkbox(
+ &mut self.s.network_catchup_enabled,
+ t("Periodic network-drive catch-up scans"),
+ );
+ ui.add_enabled_ui(self.s.network_catchup_enabled, |ui| {
+ ui.horizontal(|ui| {
+ ui.label(t("Network catch-up interval (minutes)"));
+ ui.add(egui::DragValue::new(&mut self.s.network_catchup_minutes).range(1..=1440));
+ });
+ });
+ ui.weak(t("Default: 5 minutes. Folder notifications remain active when periodic catch-up is off. Startup or missed-event recovery can still run. The interval restarts after a successful catch-up."));
+ ui.weak(t("Network checks use bounded background metadata batches and queue only differences. The interval is a delay between completed passes; required recovery remains active when periodic checks are off."));
ui.checkbox(
&mut self.s.ntfs_journal,
t("Use NTFS change journal when available"),
diff --git a/native/src/app/settings_catalog.rs b/native/src/app/settings_catalog.rs
index 3feabd5..0d51a1a 100644
--- a/native/src/app/settings_catalog.rs
+++ b/native/src/app/settings_catalog.rs
@@ -1,5 +1,7 @@
// Generated by native/scripts/generate_settings_catalog.py.
pub(super) const ENTRIES: &[Entry] = &[
+ Entry { page: 3, section: "Scheduling", title: "Periodic network-drive catch-up scans", aliases: "network NAS SMB mapped drives notifications incremental reconciliation metadata budget interval minutes" },
+ Entry { page: 3, section: "Scheduling", title: "Network catch-up interval (minutes)", aliases: "network NAS catchup five minutes" },
Entry { page: 1, section: "Your sources", title: "Your sources", aliases: "" },
Entry { page: 1, section: "Index status", title: "Index status", aliases: "" },
Entry { page: 1, section: "Index status", title: "Update index", aliases: "" },
@@ -75,7 +77,7 @@ pub(super) const ENTRIES: &[Entry] = &[
Entry { page: 2, section: "Inference hardware", title: "GitHub download token", aliases: "" },
Entry { page: 2, section: "Inference hardware", title: "Hugging Face token", aliases: "" },
Entry { page: 2, section: "OCR and media tools", title: "OCR and media tools", aliases: "" },
- Entry { page: 2, section: "OCR and media tools", title: "Enable OCR text extraction for images and scanned PDF pages", aliases: "" },
+ Entry { page: 2, section: "OCR and media tools", title: "Enable OCR text extraction for images and scanned PDF pages", aliases: "video frames visible text identifiers timestamps" },
Entry { page: 2, section: "OCR and media tools", title: "Tesseract OCR", aliases: "" },
Entry { page: 2, section: "OCR and media tools", title: "OCR languages", aliases: "" },
Entry { page: 2, section: "OCR and media tools", title: "FFmpeg (bundled by default)", aliases: "" },
@@ -111,6 +113,7 @@ pub(super) const ENTRIES: &[Entry] = &[
Entry { page: 4, section: "Startup and window behavior", title: "Double Ctrl in File Explorer opens quick search", aliases: "" },
Entry { page: 4, section: "Startup and window behavior", title: "Explorer double Ctrl: search current folder/drive and subfolders", aliases: "" },
Entry { page: 4, section: "Startup and window behavior", title: "Double Ctrl in Open/Save dialogs; send selected paths to the dialog", aliases: "" },
+ Entry { page: 4, section: "Startup and window behavior", title: "Use native Windows minimize (compatibility mode)", aliases: "minimize taskbar compatibility Windows 10 Windows 11 native system command" },
Entry { page: 4, section: "Startup and window behavior", title: "Start with Windows", aliases: "" },
Entry { page: 4, section: "Startup and window behavior", title: "Start hidden at startup", aliases: "" },
Entry { page: 4, section: "Startup and window behavior", title: "Semantic cache precision", aliases: "" },
diff --git a/native/src/changes.rs b/native/src/changes.rs
index 35c594f..ad7adf5 100644
--- a/native/src/changes.rs
+++ b/native/src/changes.rs
@@ -124,6 +124,23 @@ fn source_watcher(
home: &Path,
sender: std::sync::mpsc::SyncSender<notify::Result<notify::Event>>,
spill: std::sync::Arc<std::sync::Mutex<NotificationSpill>>,
+) -> notify::Result<notify::RecommendedWatcher> {
+ source_watcher_mode(
+ target,
+ settings,
+ home,
+ sender,
+ spill,
+ RecursiveMode::Recursive,
+ )
+}
+fn source_watcher_mode(
+ target: &Path,
+ settings: &Settings,
+ home: &Path,
+ sender: std::sync::mpsc::SyncSender<notify::Result<notify::Event>>,
+ spill: std::sync::Arc<std::sync::Mutex<NotificationSpill>>,
+ mode: RecursiveMode,
) -> notify::Result<notify::RecommendedWatcher> {
let origin = target.to_path_buf();
let actual = crate::platform::preview_path(&target.to_string_lossy());
@@ -150,12 +167,37 @@ fn source_watcher(
});
deliver_notification(event, &origin, &filter, &data_home, &sender, &spill);
})?;
- watcher.watch(&actual, RecursiveMode::Recursive)?;
+ watcher.watch(&actual, mode)?;
Ok(watcher)
}
+const MAX_NETWORK_BRANCHES: usize = 32;
+/// Only inspect a bounded top-level listing, never recursively discover watches.
+fn network_branches(target: &Path, s: &Settings) -> Option<Vec<PathBuf>> {
+ let mut entries =
+ std::fs::read_dir(crate::platform::preview_path(&target.to_string_lossy())).ok()?;
+ let mut branches = Vec::new();
+ for _ in 0..128 {
+ let Some(entry) = entries.next() else {
+ return Some(branches);
+ };
+ let entry = entry.ok()?;
+ let kind = entry.file_type().ok()?;
+ if kind.is_dir() && !kind.is_symlink() {
+ let logical = target.join(entry.file_name());
+ if s.searched(&logical) {
+ branches.push(logical);
+ if branches.len() > MAX_NETWORK_BRANCHES {
+ return None;
+ }
+ }
+ }
+ }
+ None // Very wide roots retain a single recursive watch rather than unbounded handles.
+}
#[derive(Default)]
pub struct Monitor {
watchers: BTreeMap<PathBuf, notify::RecommendedWatcher>,
+ network_shards: HashSet<PathBuf>,
sender: Option<std::sync::mpsc::SyncSender<notify::Result<notify::Event>>>,
rx: Option<std::sync::mpsc::Receiver<notify::Result<notify::Event>>>,
signature: String,
@@ -164,6 +206,11 @@ pub struct Monitor {
spill: Option<std::sync::Arc<std::sync::Mutex<NotificationSpill>>>,
recovery_reason: String,
network_catchup: BTreeMap<PathBuf, Instant>,
+ reconcile: crate::network_reconcile::Reconciler,
+ pub reconciliation_paused: bool,
+ pub reconciliation_folders_changed: bool,
+ pub indexing: bool,
+ quiet_checkpoint: Option<Instant>,
journal_notification_log: BTreeMap<PathBuf, Instant>,
pending: HashSet<PathBuf>,
recovery: bool,
@@ -171,6 +218,7 @@ pub struct Monitor {
startup_recovery: bool,
retry_after: Option<Instant>,
failures: u32,
+ completed_at: Option<Instant>,
last: Option<Instant>,
first: Option<Instant>,
watched: usize,
@@ -207,7 +255,9 @@ impl Monitor {
self.recovery_reason.clear();
self.journal_notification_log.clear();
self.watchers.clear();
+ self.network_shards.clear();
self.network_catchup.clear();
+ self.reconcile.reset();
self.sender = None;
self.rx = None;
self.pending.clear();
@@ -278,12 +328,40 @@ impl Monitor {
if network_root(&target) {
self.network_catchup.insert(target.clone(), Instant::now());
}
- match source_watcher(&target, s, home, sender.clone(), spill.clone()) {
+ let branches = if network_root(&target) {
+ network_branches(&target, s)
+ } else {
+ None
+ };
+ let mode = if branches.is_some() {
+ self.network_shards.insert(target.clone());
+ RecursiveMode::NonRecursive
+ } else {
+ RecursiveMode::Recursive
+ };
+ match source_watcher_mode(&target, s, home, sender.clone(), spill.clone(), mode) {
Ok(watcher) => {
self.watchers.insert(target.clone(), watcher);
+ if let Some(branches) = branches {
+ for branch in branches {
+ match source_watcher(&branch, s, home, sender.clone(), spill.clone()) {
+ Ok(watcher) => {
+ self.watchers.insert(branch.clone(), watcher);
+ self.watched_roots.insert(branch);
+ }
+ Err(_) => {
+ self.watcher_retries.insert(
+ branch,
+ (1, Instant::now() + Duration::from_secs(5)),
+ );
+ }
+ }
+ }
+ }
watched.push(target);
}
Err(e) => {
+ self.network_shards.remove(&target);
self.watcher_retries
.insert(target.clone(), (1, Instant::now() + Duration::from_secs(5)));
self.watcher_failures.insert(target.clone(), 1);
@@ -295,7 +373,8 @@ impl Monitor {
}
}
self.watched = watched.len();
- self.watched_roots = watched.iter().cloned().collect();
+ self.watched_roots.extend(watched.iter().cloned());
+ self.watched = self.watchers.len();
let uncovered = self.journal.configure(s, home, tx);
if self.watched > 0 && !uncovered.is_empty() {
self.request_scoped_recovery(uncovered, "startup catch-up without continuous coverage");
@@ -306,8 +385,8 @@ impl Monitor {
let _ = tx.send(Event::Log(
"Info".into(),
format!(
- "Monitoring {} recursive source(s); changes wait for idle",
- watched.len()
+ "Monitoring {} native watch locations; changes wait for idle",
+ self.watchers.len()
),
));
}
@@ -317,7 +396,7 @@ impl Monitor {
.watched_roots
.iter()
.filter(|r| under(&path.to_string_lossy(), &r.to_string_lossy()))
- .min_by_key(|r| r.components().count())
+ .max_by_key(|r| r.components().count())
.cloned()
.unwrap_or_else(|| path.clone());
self.watched_roots.remove(&target);
@@ -352,8 +431,38 @@ impl Monitor {
else {
return;
};
+ // A live ancestor can report this branch becoming available again.
+ // Do not repeatedly reopen missing/inaccessible children of that watch.
+ if self
+ .watched_roots
+ .iter()
+ .any(|root| root != &path && path.starts_with(root))
+ && unavailable_watch_path(&path)
+ {
+ self.watchers.remove(&path);
+ self.watched_roots.remove(&path);
+ self.watcher_retries.remove(&path);
+ self.watched = self.watched_roots.len();
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log("Info".into(), format!(
+ "Folder monitor {} skipped: unavailable; parent notifications will detect its return", path.display())));
+ }
+ continue;
+ }
self.watchers.remove(&path);
- match source_watcher(&path, settings, &store.home, sender.clone(), spill.clone()) {
+ let mode = if self.network_shards.contains(&path) {
+ RecursiveMode::NonRecursive
+ } else {
+ RecursiveMode::Recursive
+ };
+ match source_watcher_mode(
+ &path,
+ settings,
+ &store.home,
+ sender.clone(),
+ spill.clone(),
+ mode,
+ ) {
Ok(watcher) => {
self.watchers.insert(path.clone(), watcher);
self.watcher_retries.remove(&path);
@@ -389,6 +498,77 @@ impl Monitor {
}
}
}
+ fn update_network_branch(&mut self, path: &Path) {
+ let Some(parent) = path.parent() else {
+ return;
+ };
+ let Some(root) = self
+ .network_shards
+ .iter()
+ .find(|r| crate::config::fold(r) == crate::config::fold(parent))
+ .cloned()
+ else {
+ return;
+ };
+ let physical = crate::platform::preview_path(&path.to_string_lossy());
+ match std::fs::symlink_metadata(&physical) {
+ Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {
+ if self.watchers.contains_key(path) {
+ return;
+ }
+ let (Some(s), Some(store), Some(sender), Some(spill)) =
+ (&self.settings, &self.store, &self.sender, &self.spill)
+ else {
+ return;
+ };
+ if !s.searched(path) {
+ return;
+ }
+ let count = self
+ .watchers
+ .keys()
+ .filter(|p| p.parent() == Some(root.as_path()))
+ .count();
+ if count >= MAX_NETWORK_BRANCHES {
+ // Expand back to one recursive root before dropping branch watches.
+ if let Ok(watcher) =
+ source_watcher(&root, s, &store.home, sender.clone(), spill.clone())
+ {
+ self.watchers.insert(root.clone(), watcher);
+ self.network_shards.remove(&root);
+ let children = self
+ .watchers
+ .keys()
+ .filter(|p| p.parent() == Some(root.as_path()))
+ .cloned()
+ .collect::<Vec<_>>();
+ for child in children {
+ self.watchers.remove(&child);
+ self.watched_roots.remove(&child);
+ self.watcher_retries.remove(&child);
+ }
+ }
+ } else {
+ match source_watcher(path, s, &store.home, sender.clone(), spill.clone()) {
+ Ok(w) => {
+ self.watchers.insert(path.into(), w);
+ self.watched_roots.insert(path.into());
+ }
+ Err(_) => {
+ self.watcher_retries
+ .insert(path.into(), (1, Instant::now() + Duration::from_secs(5)));
+ }
+ }
+ }
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ self.watchers.remove(path);
+ self.watched_roots.remove(path);
+ self.watcher_retries.remove(path);
+ }
+ _ => {}
+ }
+ }
fn request_scoped_recovery(&mut self, paths: Vec<PathBuf>, reason: &str) {
let mut roots = Vec::new();
if let Some(settings) = &self.settings {
@@ -408,12 +588,22 @@ impl Monitor {
.filter(|r| under(&path.to_string_lossy(), &r.path))
.max_by_key(|r| r.path.len())
{
- roots.push(PathBuf::from(&root.path));
+ let _ = root;
+ roots.push(path.clone());
}
}
}
- roots.sort();
- roots.dedup();
+ roots.sort_by_key(|p| p.components().count());
+ let mut selected: Vec<PathBuf> = Vec::new();
+ for root in roots {
+ if !selected
+ .iter()
+ .any(|p| under(&root.to_string_lossy(), &p.to_string_lossy()))
+ {
+ selected.push(root);
+ }
+ }
+ let roots = selected;
if let Some(tx) = &self.logger {
let _ = tx.send(Event::Log(
"Info".into(),
@@ -428,7 +618,16 @@ impl Monitor {
));
}
for root in roots {
- self.queue_path(root);
+ if network_root(&root)
+ || self
+ .network_catchup
+ .keys()
+ .any(|p| under(&root.to_string_lossy(), &p.to_string_lossy()))
+ {
+ self.reconcile.request_recovery(root);
+ } else {
+ self.queue_path(root);
+ }
}
}
fn watcher_recovery(&mut self, paths: Vec<PathBuf>, reason: &str) {
@@ -493,7 +692,14 @@ impl Monitor {
.network_catchup
.iter_mut()
.filter_map(|(root, last)| {
- if now.saturating_duration_since(*last) >= Duration::from_secs(300) {
+ if s.network_catchup_enabled
+ && !self.reconcile.has_root(root)
+ && !self.indexing
+ && now.saturating_duration_since(*last)
+ >= Duration::from_secs(
+ u64::from(s.network_catchup_minutes.clamp(1, 1440)) * 60,
+ )
+ {
*last = now;
Some(root.clone())
} else {
@@ -501,11 +707,52 @@ impl Monitor {
}
})
.collect::<Vec<_>>();
- if !due.is_empty() {
- self.request_scoped_recovery(
- due,
- "periodic network catch-up (notifications may be incomplete)",
- );
+ for root in due {
+ self.reconcile.request(root);
+ }
+ if !s.network_catchup_enabled {
+ self.reconcile.disable_periodic();
+ }
+ if let Some(db) = self.store.clone() {
+ if let Some(result) =
+ self.reconcile
+ .poll(&db, s, !self.indexing && !self.reconciliation_paused)
+ {
+ match result {
+ Ok(report) => {
+ self.reconciliation_folders_changed |= report.folders_changed;
+ if let (Some(tx), Some(warning)) = (&self.logger, &report.warning) {
+ let _ = tx.send(Event::Log(
+ "Warning".into(),
+ format!("Network reconciliation: {warning}"),
+ ));
+ }
+ if report.changed > 0 {
+ self.restore(s);
+ }
+ if report.done {
+ if let Some(last) = self.network_catchup.get_mut(&report.root) {
+ *last = Instant::now();
+ }
+ }
+ if report.done || report.changed > 0 {
+ if let Some(tx) = &self.logger {
+ let _=tx.send(Event::Log("Info".into(),format!("Network reconciliation {}: {} entries checked in bounded batch; {} exact paths queued; run totals {} checked / {} queued{}",report.root.display(),report.checked,report.changed,report.run_checked,report.run_changed,if report.done {"; pass complete"} else {"; continuing incrementally"})));
+ }
+ }
+ }
+ Err(error) => {
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Warning".into(),
+ format!(
+ "Network reconciliation deferred; index retained: {error:#}"
+ ),
+ ));
+ }
+ }
+ }
+ }
}
self.retry_watches();
let (paths, recovery) = self.journal.poll();
@@ -586,6 +833,7 @@ impl Monitor {
continue;
}
for path in event.paths {
+ self.update_network_branch(&path);
if directory_metadata_only(&event.kind, &path) {
continue;
}
@@ -600,7 +848,18 @@ impl Monitor {
.all(|p| s.allowed(p))
})
{
- self.queue_path(path);
+ if self
+ .network_catchup
+ .keys()
+ .any(|root| path.starts_with(root))
+ && path.is_dir()
+ {
+ // Discover new/renamed network subtrees in bounded metadata
+ // batches, rather than feeding a recursive directory job to indexing.
+ self.reconcile.request_recovery(path);
+ } else {
+ self.queue_path(path);
+ }
}
}
}
@@ -624,7 +883,32 @@ impl Monitor {
if (self.recovery || !self.pending.is_empty()) && self.first.is_none() {
self.first = Some(Instant::now());
}
- let _ = self.persist();
+ let persisted = self.persist().is_ok();
+ if persisted
+ && !self.indexing
+ && !self.journal_inflight
+ && !self.recovery
+ && self.pending.is_empty()
+ && self.dirty.is_empty()
+ && self
+ .quiet_checkpoint
+ .is_none_or(|last| last.elapsed() >= Duration::from_secs(30))
+ {
+ self.quiet_checkpoint = Some(Instant::now());
+ let quiet = self
+ .store
+ .as_ref()
+ .and_then(|db| db.connect(true).ok())
+ .is_some_and(|c| {
+ c.query_row("SELECT NOT EXISTS(SELECT 1 FROM native_changes)", [], |r| {
+ r.get::<_, bool>(0)
+ })
+ .unwrap_or(false)
+ });
+ if quiet {
+ self.journal.checkpoint_quiet(home);
+ }
+ }
}
/// A completed whole-source scan covers only notifications queued before
/// it started. Later generations (including repeated writes to one path)
@@ -637,7 +921,20 @@ impl Monitor {
let checkpoint_home = db.home.clone();
let c = db.connect(false)?;
c.execute("DELETE FROM native_changes WHERE queued<?1", [started])?;
+ for root in self.reconcile.covered_before(started) {
+ let _ = c.execute(
+ "DELETE FROM native_network_dirs WHERE root=?1",
+ [root.to_string_lossy().as_ref()],
+ );
+ let _ = c.execute(
+ "DELETE FROM native_network_seen WHERE root=?1",
+ [root.to_string_lossy().as_ref()],
+ );
+ }
drop(c);
+ for last in self.network_catchup.values_mut() {
+ *last = Instant::now();
+ }
self.pending.clear();
self.recovery = false;
self.recovery_saved = false;
@@ -663,7 +960,11 @@ impl Monitor {
};
let mut c = db.connect(false)?;
let tx = c.transaction()?;
- self.generation += 1;
+ self.generation = self.generation.max(tx.query_row(
+ "SELECT coalesce(max(generation),0) FROM native_changes",
+ [],
+ |r| r.get::<_, i64>(0),
+ )?) + 1;
{
let queued = chrono::Utc::now().timestamp_millis();
let mut statement=tx.prepare_cached("INSERT INTO native_changes VALUES(?1,?2,?3) ON CONFLICT(path) DO UPDATE SET generation=excluded.generation,queued=excluded.queued")?;
@@ -752,6 +1053,8 @@ impl Monitor {
"waiting to retry a failed update"
} else if busy {
"indexing is running"
+ } else if self.reconcile.pending() {
+ "incremental network reconciliation pending/running"
} else if self.ready() {
crate::scheduling::idle_allowed(s, crate::scheduling::metrics())
.err()
@@ -762,18 +1065,21 @@ impl Monitor {
"waiting for file changes"
};
format!(
- "Watching {} sources · {} NTFS journals ({} retrying) · {pending} · {waiting}",
+ "Watching {} locations · {} NTFS journals ({} retrying) · {pending} · {waiting}",
self.watched,
self.journal.active(),
self.journal.retrying()
)
}
pub fn pending_work(&self) -> bool {
- self.recovery || !self.pending.is_empty()
+ self.recovery || !self.pending.is_empty() || self.reconcile.pending()
}
pub fn ready(&self) -> bool {
- self.retry_after
- .is_none_or(|deadline| Instant::now() >= deadline)
+ self.completed_at
+ .is_none_or(|at| at.elapsed() >= Duration::from_secs(10))
+ && self
+ .retry_after
+ .is_none_or(|deadline| Instant::now() >= deadline)
&& (self.recovery || !self.pending.is_empty())
&& (self
.last
@@ -787,6 +1093,11 @@ impl Monitor {
return;
}
if success {
+ self.completed_at = Some(Instant::now());
+ // Events arriving during indexing form a new batch. Their old
+ // deadline must not cause an immediate second indexing run.
+ self.first = Some(Instant::now());
+ self.last = self.first;
self.failures = 0;
self.retry_after = None;
} else {
@@ -802,6 +1113,17 @@ impl Monitor {
self.journal_inflight = false;
if let Some(inflight) = self.inflight.take() {
if success {
+ for (root, last) in &mut self.network_catchup {
+ if inflight.iter().any(|(path, _)| {
+ path.as_os_str().is_empty()
+ || crate::config::under(
+ &root.to_string_lossy(),
+ &path.to_string_lossy(),
+ )
+ }) {
+ *last = Instant::now();
+ }
+ }
if let Some(db) = &self.store {
if let Ok(mut c) = db.connect(false) {
if let Ok(tx) = c.transaction() {
@@ -951,6 +1273,7 @@ mod notification_tests {
let (tx, _rx) = crossbeam_channel::bounded(64);
let mut monitor = Monitor::default();
monitor.configure(&s, home.path(), &tx.into());
+ monitor.reconcile.reset();
monitor.take();
std::thread::sleep(Duration::from_millis(150));
let note = child.join("new.txt");
@@ -988,6 +1311,105 @@ mod notification_tests {
mod debounce_tests {
use super::*;
#[test]
+ fn completed_run_does_not_immediately_dispatch_old_deadline() {
+ let mut monitor = Monitor::default();
+ monitor.pending.insert(PathBuf::from("later.txt"));
+ monitor.first = Some(Instant::now() - Duration::from_secs(120));
+ monitor.last = Some(Instant::now() - Duration::from_secs(20));
+ monitor.completed_at = Some(Instant::now());
+ assert!(!monitor.ready());
+ monitor.completed_at = Some(Instant::now() - Duration::from_secs(11));
+ assert!(monitor.ready());
+ }
+ #[test]
+ fn missing_branch_stops_retrying_and_parent_can_reattach_it() {
+ let parent = tempfile::Builder::new()
+ .prefix("VectorDash-watch-parent-")
+ .tempdir()
+ .unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let mut settings = Settings::default();
+ settings.encrypt_index = false;
+ settings.watch_changes = true;
+ settings.ntfs_journal = false;
+ settings.roots = vec![crate::config::Source {
+ path: parent.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let (tx, _) = crossbeam_channel::unbounded();
+ let mut monitor = Monitor::default();
+ monitor.configure(&settings, home.path(), &tx.into());
+ let branch = parent.path().join("unavailable");
+ monitor
+ .watcher_retries
+ .insert(branch.clone(), (1, Instant::now()));
+ monitor.retry_watches();
+ assert!(!monitor.watcher_retries.contains_key(&branch));
+ assert!(monitor.watchers.contains_key(parent.path()));
+ // The nonrecursive network parent is sufficient to observe branch return.
+ monitor.network_shards.insert(parent.path().to_path_buf());
+ std::fs::create_dir(&branch).unwrap();
+ monitor.update_network_branch(&branch);
+ assert!(monitor.watchers.contains_key(&branch));
+ }
+ #[test]
+ fn network_directory_creation_uses_reconciliation_not_recursive_index_job() {
+ let root = tempfile::Builder::new()
+ .prefix("VectorDash-network-event-")
+ .tempdir()
+ .unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let mut settings = Settings::default();
+ settings.encrypt_index = false;
+ settings.watch_changes = true;
+ settings.ntfs_journal = false;
+ settings.network_catchup_enabled = false;
+ settings.roots = vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let (tx, _) = crossbeam_channel::unbounded();
+ let mut monitor = Monitor::default();
+ monitor.configure(&settings, home.path(), &tx.into());
+ monitor.reconcile.reset();
+ monitor
+ .network_catchup
+ .insert(root.path().to_path_buf(), Instant::now());
+ let child = root.path().join("new-branch");
+ std::fs::create_dir(&child).unwrap();
+ monitor
+ .sender
+ .as_ref()
+ .unwrap()
+ .send(Ok(notify::Event::new(notify::EventKind::Create(
+ notify::event::CreateKind::Folder,
+ ))
+ .add_path(child.clone())))
+ .unwrap();
+ monitor.collect(&settings, home.path());
+ assert!(monitor.reconcile.has_root(&child));
+ assert!(!monitor.pending.contains(&child));
+ assert!(!monitor.dirty.contains(&child));
+ }
+ #[test]
+ fn failed_branch_does_not_restart_healthy_parent_watch() {
+ let mut monitor = Monitor::default();
+ let root = PathBuf::from(r"T:\");
+ let child = root.join("hermes");
+ monitor.watched_roots.insert(root.clone());
+ monitor.watched_roots.insert(child.clone());
+ monitor.schedule_watch_retry(&[child.clone()]);
+ assert!(monitor.watched_roots.contains(&root));
+ assert!(!monitor.watcher_retries.contains_key(&root));
+ assert!(monitor.watcher_retries.contains_key(&child));
+ }
+ #[test]
+ fn unavailable_child_is_skipped_but_existing_directory_is_not() {
+ let root = tempfile::tempdir().unwrap();
+ assert!(!unavailable_watch_path(root.path()));
+ assert!(unavailable_watch_path(&root.path().join("missing")));
+ }
+ #[test]
fn continual_changes_cannot_starve_ready_queue() {
let mut monitor = Monitor::default();
monitor.pending.insert(PathBuf::from("note.txt"));
@@ -997,6 +1419,19 @@ mod debounce_tests {
}
}
+fn unavailable_watch_path(path: &Path) -> bool {
+ let physical = crate::platform::preview_path(&path.to_string_lossy());
+ match std::fs::metadata(physical) {
+ Ok(meta) => !meta.is_dir(),
+ Err(error) => {
+ matches!(
+ error.kind(),
+ std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied
+ ) || matches!(error.raw_os_error(), Some(3 | 5 | 53 | 59 | 67))
+ }
+ }
+}
+
// Updating a child changes its parent's mtime too. Windows sends the child's own
// notification; rescanning that parent for metadata-only events defeats targeting.
fn directory_metadata_only(kind: &notify::EventKind, path: &Path) -> bool {
@@ -1265,22 +1700,31 @@ mod scoped_recovery_tests {
#[test]
fn scoped_recovery_is_coalesced_and_never_schedules_second_global_scan() {
let mut m = Monitor::default();
- let mut s = Settings::default();
- s.roots = ["C:\\", "T:\\"]
- .iter()
- .map(|p| crate::config::Source {
- path: (*p).into(),
- mode: "quick".into(),
- })
- .collect();
+ let s = Settings {
+ roots: vec![
+ crate::config::Source {
+ path: r"C:\".into(),
+ mode: "quick".into(),
+ },
+ crate::config::Source {
+ path: r"\\nas\share".into(),
+ mode: "quick".into(),
+ },
+ ],
+ ..Default::default()
+ };
m.settings = Some(s);
- m.request_scoped_recovery(vec![PathBuf::from("T:\\folder")], "connection lost");
- m.queue_path(PathBuf::from("T:\\folder\\file.txt"));
- m.queue_path(PathBuf::from("C:\\Users\\changed.txt"));
+ let branch = PathBuf::from(r"\\nas\share\folder");
+ let file = branch.join("file.txt");
+ m.request_scoped_recovery(vec![branch.clone()], "connection lost");
+ m.queue_path(file.clone());
+ m.queue_path(PathBuf::from(r"C:\Users\changed.txt"));
let paths = m.take().unwrap();
assert_eq!(paths.len(), 2);
- assert!(paths.contains(&PathBuf::from("T:\\")));
- assert!(!paths.contains(&PathBuf::from("C:\\")));
+ assert!(paths.contains(&file));
+ assert!(m.reconcile.has_root(&branch));
+ assert!(!m.reconcile.has_root(Path::new(r"\\nas\share")));
+ assert!(!paths.contains(&PathBuf::from(r"C:\")));
m.complete(true, Path::new("unused"));
assert!(!m.recovery && m.pending.is_empty());
}
@@ -1575,7 +2019,11 @@ mod network_catchup_tests {
Instant::now() - Duration::from_secs(301),
);
monitor.collect(&s, home.path());
- assert!(monitor.pending.contains(&PathBuf::from(r"T:\")));
+ assert!(monitor.reconcile.pending());
+ assert!(
+ monitor.pending.is_empty(),
+ "periodic work must not queue the share root"
+ );
assert!(!monitor.pending.contains(&PathBuf::from(r"C:\")));
assert!(!monitor.recovery);
monitor.pending.clear();
@@ -1583,3 +2031,185 @@ mod network_catchup_tests {
assert!(monitor.pending.is_empty(), "catch-up must be rate limited");
}
}
+
+#[cfg(test)]
+mod configurable_network_tests {
+ use super::*;
+ #[test]
+ fn catchup_can_be_disabled_delayed_and_deferred_while_indexing() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ let mut m = Monitor::default();
+ let root = PathBuf::from(r"\\nas\share");
+ s.watch_changes = true;
+ s.roots = vec![crate::config::Source {
+ path: root.to_string_lossy().into_owned(),
+ mode: "quick".into(),
+ }];
+ m.settings = Some(s.clone());
+ m.network_catchup
+ .insert(root.clone(), Instant::now() - Duration::from_secs(601));
+ s.network_catchup_enabled = false;
+ m.collect(&s, home.path());
+ assert!(m.pending.is_empty());
+ s.network_catchup_enabled = true;
+ s.network_catchup_minutes = 15;
+ m.collect(&s, home.path());
+ assert!(m.pending.is_empty());
+ s.network_catchup_minutes = 5;
+ m.indexing = true;
+ m.collect(&s, home.path());
+ assert!(m.pending.is_empty());
+ m.indexing = false;
+ m.collect(&s, home.path());
+ assert!(m.reconcile.pending());
+ assert!(m.pending.is_empty());
+ }
+ #[test]
+ fn successful_catchup_restarts_interval_at_completion() {
+ let mut m = Monitor::default();
+ let root = PathBuf::from(r"\\nas\share");
+ m.network_catchup
+ .insert(root.clone(), Instant::now() - Duration::from_secs(601));
+ m.journal_inflight = true;
+ m.inflight = Some(vec![(root.clone(), 0)]);
+ let home = tempfile::tempdir().unwrap();
+ m.complete(true, home.path());
+ assert!(m.network_catchup[&root].elapsed() < Duration::from_secs(1));
+ }
+}
+
+#[cfg(test)]
+mod network_policy_tests {
+ use super::*;
+ #[test]
+ fn completed_full_scan_resets_timer_before_periodic_collection() {
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ encrypt_index: false,
+ ..Default::default()
+ };
+ let db = crate::db::Database::new(home.path(), &s).unwrap();
+ db.connect(false).unwrap().execute_batch("CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL)").unwrap();
+ let mut m = Monitor::default();
+ m.store = Some(db);
+ m.settings = Some(s.clone());
+ m.reconciliation_paused = true;
+ m.network_catchup.insert(
+ PathBuf::from(r"\\nas\share"),
+ Instant::now() - Duration::from_secs(601),
+ );
+ m.acknowledge_full_scan(chrono::Utc::now().timestamp_millis(), &s)
+ .unwrap();
+ m.collect(&s, home.path());
+ assert!(!m.reconcile.pending());
+ }
+ #[test]
+ fn watcher_gap_keeps_branch_scope_and_disabling_periodic_does_not_drop_it() {
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ network_catchup_enabled: false,
+ roots: vec![crate::config::Source {
+ path: r"\\nas\share".into(),
+ mode: "quick".into(),
+ }],
+ ..Default::default()
+ };
+ let mut m = Monitor::default();
+ m.settings = Some(s.clone());
+ m.request_scoped_recovery(vec![PathBuf::from(r"\\nas\share\photos")], "fixture gap");
+ assert!(m.reconcile.has_root(Path::new(r"\\nas\share\photos")));
+ assert!(!m.reconcile.has_root(Path::new(r"\\nas\share")));
+ m.collect(&s, home.path());
+ assert!(m.reconcile.pending());
+ assert!(m.pending.is_empty());
+ }
+ #[test]
+ fn branch_discovery_is_bounded_and_does_not_recurse() {
+ let root = tempfile::Builder::new()
+ .prefix("VectorDash-branches-")
+ .tempdir()
+ .unwrap();
+ let s = Settings {
+ include_hidden: true,
+ skip_windows_churn: false,
+ roots: vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }],
+ ..Default::default()
+ };
+ std::fs::create_dir(root.path().join("one")).unwrap();
+ std::fs::create_dir(root.path().join("one/nested")).unwrap();
+ assert_eq!(
+ network_branches(root.path(), &s).unwrap(),
+ vec![root.path().join("one")]
+ );
+ for n in 0..MAX_NETWORK_BRANCHES {
+ std::fs::create_dir(root.path().join(format!("branch-{n}"))).unwrap();
+ }
+ assert!(network_branches(root.path(), &s).is_none());
+ }
+}
+
+#[cfg(test)]
+mod live_shard_tests {
+ use super::*;
+ #[test]
+ #[ignore = "Requires an explicit writable network test root; only its own temporary folder is changed"]
+ fn live_network_shards_deliver_nested_and_new_branch_notifications() {
+ let share = std::env::var("VECTORDASH_TEST_NETWORK_ROOT").unwrap();
+ let root = tempfile::Builder::new()
+ .prefix("VectorDash-sharewatch-QA-")
+ .tempdir_in(share)
+ .unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let branch = root.path().join("existing");
+ std::fs::create_dir(&branch).unwrap();
+ let s = Settings {
+ watch_changes: true,
+ include_hidden: true,
+ skip_windows_churn: false,
+ roots: vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }],
+ ..Default::default()
+ };
+ let (tx, _rx) = crossbeam_channel::unbounded();
+ let mut m = Monitor::default();
+ m.configure(&s, home.path(), &tx.into());
+ m.reconcile.reset();
+ m.take();
+ assert!(m.network_shards.contains(root.path()));
+ assert!(m.watchers.contains_key(&branch));
+ std::thread::sleep(Duration::from_millis(150));
+ let first = branch.join("first.txt");
+ std::fs::write(&first, "first").unwrap();
+ let until = Instant::now() + Duration::from_secs(8);
+ while !m.pending.contains(&first) {
+ m.collect(&s, home.path());
+ assert!(Instant::now() < until);
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ let added = root.path().join("added");
+ std::fs::create_dir(&added).unwrap();
+ let until = Instant::now() + Duration::from_secs(8);
+ while !m.watchers.contains_key(&added) {
+ m.collect(&s, home.path());
+ assert!(Instant::now() < until);
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ m.take();
+ m.complete(true, home.path());
+ let second = added.join("second.txt");
+ std::fs::write(&second, "second").unwrap();
+ let until = Instant::now() + Duration::from_secs(8);
+ while !m.pending.contains(&second) {
+ m.collect(&s, home.path());
+ assert!(Instant::now() < until);
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(!m.pending.contains(root.path()));
+ }
+}
diff --git a/native/src/config.rs b/native/src/config.rs
index bdd13f7..e516477 100644
--- a/native/src/config.rs
+++ b/native/src/config.rs
@@ -38,6 +38,8 @@ pub struct Settings {
pub image_search_auto: bool,
pub watch_changes: bool,
pub ntfs_journal: bool,
+ pub network_catchup_enabled: bool,
+ pub network_catchup_minutes: u32,
pub saved_searches: Vec<SavedSearch>,
pub auto_check_updates: bool,
pub auto_update: bool,
@@ -78,6 +80,7 @@ pub struct Settings {
pub sidebar_collapsed: bool,
pub close_behavior: String,
pub minimize_behavior: String,
+ pub native_minimize: bool,
pub runtime_backend: String,
pub ocr_enabled: bool,
pub setup_runtime: bool,
@@ -228,6 +231,8 @@ impl Default for Settings {
picture_grid: true,
watch_changes: false,
ntfs_journal: false,
+ network_catchup_enabled: true,
+ network_catchup_minutes: 5,
saved_searches: vec![],
auto_check_updates: true,
auto_update: false,
@@ -268,6 +273,7 @@ impl Default for Settings {
sidebar_collapsed: false,
close_behavior: "Hide to tray".into(),
minimize_behavior: "Taskbar".into(),
+ native_minimize: false,
runtime_backend: "Auto".into(),
ocr_enabled: true,
setup_runtime: true,
@@ -1662,3 +1668,42 @@ mod trail_color_tests {
assert_eq!(restored.activity_colors("AI"), ai);
}
}
+
+#[cfg(test)]
+mod network_catchup_settings_tests {
+ use super::*;
+ #[test]
+ fn defaults_preserve_five_minute_behavior_and_choices_round_trip() {
+ let home = tempfile::tempdir().unwrap();
+ std::fs::write(home.path().join("settings.json"), "{}").unwrap();
+ let mut s = Settings::load(home.path()).unwrap();
+ assert!(s.network_catchup_enabled);
+ assert_eq!(s.network_catchup_minutes, 5);
+ s.network_catchup_enabled = false;
+ s.network_catchup_minutes = 45;
+ s.save(home.path()).unwrap();
+ let read = Settings::load(home.path()).unwrap();
+ assert!(!read.network_catchup_enabled);
+ assert_eq!(read.network_catchup_minutes, 45);
+ }
+}
+
+#[cfg(test)]
+mod native_minimize_tests {
+ use super::*;
+ #[test]
+ fn alternative_minimize_is_opt_in_and_persists() {
+ assert!(!Settings::default().native_minimize);
+ let old: Settings = serde_json::from_str(r#"{"minimize_behavior":"Taskbar"}"#).unwrap();
+ assert!(!old.native_minimize);
+ let home = tempfile::tempdir().unwrap();
+ let mut settings = old;
+ settings.native_minimize = true;
+ settings.save(home.path()).unwrap();
+ let saved: Settings =
+ serde_json::from_slice(&std::fs::read(home.path().join("settings.json")).unwrap())
+ .unwrap();
+ assert!(saved.native_minimize);
+ assert_eq!(saved.minimize_behavior, "Taskbar");
+ }
+}
diff --git a/native/src/content.rs b/native/src/content.rs
index 237b1a9..70e1788 100644
--- a/native/src/content.rs
+++ b/native/src/content.rs
@@ -346,11 +346,15 @@ pub fn extract(
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
String::from_utf16_lossy(&u)
+ } else if ext == "rtf" && std::str::from_utf8(&bytes).is_err() {
+ encoding_rs::WINDOWS_1252.decode(&bytes).0.into_owned()
} else {
String::from_utf8_lossy(&bytes).into_owned()
};
let text = if ["html", "htm"].contains(&ext.as_str()) {
visible_html(&text)
+ } else if ext == "rtf" {
+ crate::rtf::visible_text(&text)
} else {
text
};
@@ -583,6 +587,65 @@ fn stream_pdf(
Err(error) => Err(error),
}
}
+/// Keep visual and OCR evidence separate so exact text retains its frame timestamp.
+fn emit_video_frame(
+ seconds: f32,
+ media: Vec<u8>,
+ s: &Settings,
+ checkpoint: &dyn Fn() -> Result<()>,
+ emit: &mut dyn FnMut(Segment) -> Result<()>,
+) -> Result<()> {
+ let text = if s.ocr_enabled && !s.ocr.is_empty() {
+ checkpoint()?;
+ match ocr_bytes(&media, s) {
+ Ok(text) => Some(text),
+ Err(error) => {
+ emit(Segment::text(
+ "warning",
+ format!("Video frame OCR unavailable at {seconds:.1}s: {error}"),
+ 0,
+ 0,
+ ))?;
+ None
+ }
+ }
+ } else {
+ None
+ };
+ checkpoint()?;
+ emit(Segment {
+ kind: "video".into(),
+ text: String::new(),
+ page: 0,
+ seconds,
+ line: 0,
+ media,
+ })?;
+ if let Some(text) = text {
+ emit_video_text(seconds, &text, emit)?;
+ }
+ Ok(())
+}
+fn emit_video_text(
+ seconds: f32,
+ text: &str,
+ emit: &mut dyn FnMut(Segment) -> Result<()>,
+) -> Result<()> {
+ if !text.trim().is_empty() {
+ for (text, line) in chunks(text, 1800) {
+ emit(Segment {
+ kind: "video".into(),
+ text,
+ page: 0,
+ seconds,
+ line,
+ media: vec![],
+ })?;
+ }
+ }
+ Ok(())
+}
+
pub fn stream(
path: &Path,
s: &Settings,
@@ -636,14 +699,7 @@ pub fn stream_from(
if s.skip_similar_frames && !dedupe.keep(&media)? {
continue;
}
- emit(Segment {
- kind: "video".into(),
- text: String::new(),
- page: 0,
- seconds,
- line: 0,
- media,
- })?;
+ emit_video_frame(seconds, media, s, checkpoint, emit)?;
emitted += 1;
}
Ok(())
@@ -675,7 +731,7 @@ pub fn stream_from(
"-an",
"-vf",
&format!(
- "fps=1/{},scale='min(1024,iw)':-2",
+ "fps=1/{}:start_time=0:round=up,scale='min(1024,iw)':-2",
s.video_interval.clamp(1.0, 60.0)
),
"-f",
@@ -711,14 +767,7 @@ pub fn stream_from(
if s.skip_similar_frames && !dedupe.keep(&media)? {
continue;
}
- emit(Segment {
- kind: "video".into(),
- text: String::new(),
- page: 0,
- seconds,
- line: 0,
- media,
- })?;
+ emit_video_frame(seconds, media, s, checkpoint, emit)?;
}
}
let status = child.wait()?;
@@ -897,3 +946,121 @@ mod frame_dedupe_tests {
assert!(!filter.keep(&encode([10, 10, 180])).unwrap());
}
}
+
+#[cfg(test)]
+mod video_evidence_tests {
+ use super::*;
+ #[test]
+ fn ocr_chunks_keep_visual_time_and_do_not_create_audio_evidence() {
+ let mut out = vec![];
+ emit_video_text(10.0, "VN-5103\nBeach", &mut |s| {
+ out.push(s);
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].seconds, 10.0);
+ assert_eq!(out[0].kind, "video");
+ assert!(out[0].media.is_empty());
+ assert!(out[0].text.contains("VN-5103"));
+ emit_video_text(20.0, " ", &mut |s| {
+ out.push(s);
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(out.len(), 1);
+ }
+ #[test]
+ fn disabled_ocr_preserves_frame_and_cancellation() {
+ let mut settings = Settings::default();
+ settings.ocr_enabled = false;
+ let mut out = vec![];
+ emit_video_frame(5.0, vec![1, 2], &settings, &|| Ok(()), &mut |s| {
+ out.push(s);
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].media, vec![1, 2]);
+ assert!(
+ emit_video_frame(
+ 5.0,
+ vec![],
+ &settings,
+ &|| anyhow::bail!("cancelled"),
+ &mut |_| Ok(())
+ )
+ .is_err()
+ );
+ }
+}
+
+#[cfg(test)]
+mod live_video_ocr_tests {
+ use super::*;
+ #[test]
+ #[ignore = "Requires explicitly configured OCR executable and a synthetic VN-5100 PNG fixture"]
+ fn video_frame_ocr_live_retains_identifier_and_timestamp() {
+ let settings = Settings {
+ ocr_enabled: true,
+ ocr: std::env::var("VECTORDASH_TEST_OCR").unwrap(),
+ ocr_languages: "eng".into(),
+ ..Default::default()
+ };
+ let bytes = fs::read(std::env::var("VECTORDASH_TEST_OCR_IMAGE").unwrap()).unwrap();
+ let mut out = vec![];
+ emit_video_frame(10., bytes, &settings, &|| Ok(()), &mut |s| {
+ out.push(s);
+ Ok(())
+ })
+ .unwrap();
+ assert!(out.iter().any(|s| s.media.is_empty()
+ && s.text.contains("VN-5100")
+ && s.seconds == 10.
+ && s.kind == "video"));
+ assert_eq!(out.iter().filter(|s| !s.media.is_empty()).count(), 1);
+ }
+}
+
+#[cfg(test)]
+mod live_ffmpeg_evidence_tests {
+ use super::*;
+ #[test]
+ #[ignore = "Requires explicitly configured FFmpeg, OCR and a synthetic two-scene video"]
+ fn ffmpeg_frame_text_does_not_precede_the_scene_it_came_from() {
+ let settings = Settings {
+ ocr_enabled: true,
+ ocr: std::env::var("VECTORDASH_TEST_OCR").unwrap(),
+ ocr_languages: "eng".into(),
+ ffmpeg: std::env::var("VECTORDASH_TEST_FFMPEG").unwrap(),
+ video_decoder: "FFmpeg".into(),
+ video_interval: 5.,
+ index_audio: false,
+ skip_similar_frames: false,
+ ..Default::default()
+ };
+ let mut out = vec![];
+ stream(
+ Path::new(&std::env::var("VECTORDASH_TEST_VIDEO").unwrap()),
+ &settings,
+ &|| Ok(()),
+ &mut |s| {
+ out.push(s);
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(
+ out.iter()
+ .any(|s| s.text.contains("VN-5101") && s.seconds >= 6.)
+ );
+ assert!(
+ !out.iter()
+ .any(|s| s.text.contains("VN-5101") && s.seconds < 6.)
+ );
+ assert!(
+ out.iter()
+ .any(|s| s.text.contains("VN-5100") && s.seconds < 6.)
+ );
+ }
+}
diff --git a/native/src/db.rs b/native/src/db.rs
index 1ca162b..a1ec4ca 100644
--- a/native/src/db.rs
+++ b/native/src/db.rs
@@ -20,6 +20,8 @@ pub struct Database {
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Hit {
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub evidence: Vec<Evidence>,
pub path: String,
pub kind: String,
pub text: String,
@@ -29,6 +31,14 @@ pub struct Hit {
pub seconds: f32,
pub line: u32,
}
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct Evidence {
+ pub source: String,
+ pub text: String,
+ pub seconds: f32,
+ pub page: u32,
+ pub line: u32,
+}
#[derive(Clone, Debug, Default, Serialize)]
pub struct Stats {
pub files: u64,
@@ -1018,6 +1028,7 @@ fn add_name(
0
};
out.push(Hit {
+ evidence: Vec::new(),
path,
kind,
score: if low == q {
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 4555519..444fdcf 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -359,7 +359,7 @@ impl Control {
}
pub fn check_with(&self, stopped: &dyn Fn() -> bool) -> Result<()> {
anyhow::ensure!(!stopped(), "Preparation stopped");
- if self.automatic.load(Ordering::Relaxed) {
+ if self.automatic.load(Ordering::Acquire) {
let settings = self.schedule.lock().unwrap();
if self.watching.load(Ordering::Relaxed) && !settings.watch_changes {
self.cancel.store(true, Ordering::Relaxed);
@@ -542,6 +542,35 @@ impl Engine {
&engine.db.home,
);
}
+ changes.configure(&settings, &engine.db.home, &engine.tx);
+ if let Some(held) = changes.restored_hold.take() {
+ if held {
+ engine.control.automatic_hold.store(true, Ordering::Release);
+ }
+ }
+ changes.persist_hold(engine.control.automatic_hold.load(Ordering::Acquire));
+ changes.indexing = engine.control.running.load(Ordering::Acquire);
+ let full_scan = engine
+ .control
+ .successful_full_scan_started
+ .load(Ordering::Acquire);
+ if full_scan > acknowledged_full_scan
+ && changes.acknowledge_full_scan(full_scan, &settings).is_ok()
+ {
+ acknowledged_full_scan = full_scan;
+ engine.log("Info","Completed full scan satisfied older queued monitoring work; later notifications remain targeted");
+ }
+ // Acknowledge successful full coverage before any periodic work is considered.
+ // Otherwise a just-due timer queues a duplicate share scan at completion.
+ changes.reconciliation_paused =
+ engine.control.automatic_hold.load(Ordering::Acquire)
+ || crate::scheduling::idle_allowed(&settings, crate::scheduling::metrics())
+ .is_err();
+ changes.collect(&settings, &engine.db.home);
+ if changes.reconciliation_folders_changed {
+ changes.reconciliation_folders_changed = false;
+ engine.refresh_stats(&settings);
+ }
if !engine.control.index_maintenance.load(Ordering::Acquire)
&& engine.control.restart_requested.load(Ordering::Acquire)
&& !engine.control.running.load(Ordering::Acquire)
@@ -563,15 +592,15 @@ impl Engine {
.restart_requested
.store(false, Ordering::SeqCst);
engine.control.automatic_hold.store(false, Ordering::SeqCst);
- engine.control.automatic.store(automatic, Ordering::Relaxed);
- engine.control.watching.store(
- engine.control.restart_watching.load(Ordering::Relaxed),
- Ordering::Relaxed,
- );
engine
.control
.automatic_started
.store(chrono::Local::now().timestamp(), Ordering::Relaxed);
+ engine.control.watching.store(
+ engine.control.restart_watching.load(Ordering::Relaxed),
+ Ordering::Relaxed,
+ );
+ engine.control.automatic.store(automatic, Ordering::Release);
engine.log(
"Info",
"Sources changed; restarting with current saved sources",
@@ -579,28 +608,26 @@ impl Engine {
if automatic {
let _ = engine.tx.send(Event::AutomaticStarted);
}
- engine.launch_index(settings.clone(), false);
+ if engine.control.restart_watching.load(Ordering::Relaxed) {
+ match changes.try_take() {
+ Ok(paths) => {
+ engine.launch_paths(settings.clone(), false, paths)
+ }
+ Err(error) => {
+ engine.control.running.store(false, Ordering::Release);
+ engine
+ .control
+ .restart_requested
+ .store(true, Ordering::Release);
+ engine.log("Warning", format!("Restart retained queued changes; durable queue unavailable: {error:#}"));
+ }
+ }
+ } else {
+ engine.launch_index(settings.clone(), false);
+ }
}
}
}
- changes.configure(&settings, &engine.db.home, &engine.tx);
- if let Some(held) = changes.restored_hold.take() {
- if held {
- engine.control.automatic_hold.store(true, Ordering::Release);
- }
- }
- changes.persist_hold(engine.control.automatic_hold.load(Ordering::Acquire));
- changes.collect(&settings, &engine.db.home);
- let full_scan = engine
- .control
- .successful_full_scan_started
- .load(Ordering::Acquire);
- if full_scan > acknowledged_full_scan
- && changes.acknowledge_full_scan(full_scan, &settings).is_ok()
- {
- acknowledged_full_scan = full_scan;
- engine.log("Info","Completed full scan satisfied older queued monitoring work; later notifications remain targeted");
- }
let watch_status = if engine.control.automatic_hold.load(Ordering::Acquire) {
if engine.control.sources_pending.load(Ordering::Acquire) {
"Sources changed; save to restart indexing with the updated sources".into()
@@ -664,11 +691,11 @@ impl Engine {
}
};
engine.control.watching.store(true, Ordering::Relaxed);
- engine.control.automatic.store(true, Ordering::Relaxed);
engine
.control
.automatic_started
.store(chrono::Local::now().timestamp(), Ordering::Relaxed);
+ engine.control.automatic.store(true, Ordering::Release);
let _ = engine.tx.send(Event::AutomaticStarted);
engine.log(
"Info",
@@ -705,11 +732,11 @@ impl Engine {
settings.last_schedule_slot = slot;
*engine.control.schedule.lock().unwrap() = settings.clone();
let _ = settings.save(&engine.db.home);
- engine.control.automatic.store(true, Ordering::Relaxed);
engine
.control
.automatic_started
.store(chrono::Local::now().timestamp(), Ordering::Relaxed);
+ engine.control.automatic.store(true, Ordering::Release);
let _ = engine.tx.send(Event::AutomaticStarted);
engine.launch_index(settings, false);
}
@@ -849,7 +876,7 @@ impl Engine {
result
.as_ref()
.map(String::as_str)
- .unwrap_or("Stopped / failed")
+ .unwrap_or_else(|error| error.as_str())
),
);
settings.schedule_history.truncate(20);
@@ -1302,7 +1329,10 @@ impl Engine {
if indexing_mode == "full" {
let extension = content::extension(path);
let mut detail = String::new();
- if content::is_image(&extension) || extension == "pdf" {
+ if content::is_image(&extension)
+ || extension == "pdf"
+ || content::is_video(&extension)
+ {
if s.ocr_enabled && !s.ocr.is_empty() {
detail.push_str("|ocr:png-v1");
}
@@ -1313,6 +1343,15 @@ impl Engine {
detail.push_str(&format!("|ocr-lang:{}", s.ocr_languages));
}
}
+ if content::is_video(&extension) && s.index_video {
+ detail.push_str("|video:sampling-v2");
+ }
+ if content::is_video(&extension) && s.ocr_enabled && !s.ocr.is_empty() {
+ detail.push_str("|video:ocr-v1");
+ }
+ if extension == "rtf" {
+ detail.push_str("|rtf:visible-v1");
+ }
if content::is_image(&extension) && s.visual_detail == "Detailed" {
detail.push_str("|visual:detailed");
}
@@ -2197,7 +2236,7 @@ impl Engine {
anyhow::ensure!(!cancel.load(Ordering::Acquire), "Search cancelled");
Ok(
serde_json::json!({"results": hits.into_iter().filter(|h| h.kind != "calculator" && !h.path.starts_with("settings:")).take(5).map(|h| serde_json::json!({
- "path": h.path, "kind": h.kind, "snippet": h.text.chars().take(700).collect::<String>(), "page": h.page, "seconds": h.seconds, "score": h.score
+ "path": h.path, "kind": h.kind, "snippet": h.text.chars().take(700).collect::<String>(), "page": h.page, "seconds": h.seconds, "score": h.score, "evidence": h.evidence
})).collect::<Vec<_>>(), "semantic_error":semantic_error, "note":"Indexed data only; files may have changed since indexing."}),
)
}
@@ -2242,6 +2281,7 @@ impl Engine {
if let Ok(value) = meval::eval_str(&expression) {
if q.chars().any(|c| "+-*/^()%".contains(c)) {
return Ok(vec![Hit {
+ evidence: Vec::new(),
path: format!("{value}"),
kind: "calculator".into(),
text: q.into(),
@@ -2424,11 +2464,29 @@ impl Engine {
/ tokens.len().max(1) as f32;
let v: serde_json::Value = serde_json::from_str(&loc)?;
hits.push(Hit {
+ evidence: vec![crate::db::Evidence {
+ source: match kind.as_str() {
+ "video" => "video_ocr",
+ "video_audio" => "audio",
+ "image" => "image_ocr",
+ _ => "text",
+ }
+ .into(),
+ text: text.chars().take(1000).collect(),
+ page: v["page"].as_u64().unwrap_or(0) as u32,
+ seconds: v["seconds"].as_f64().unwrap_or(-1.0) as f32,
+ line: v["line"].as_u64().unwrap_or(0) as u32,
+ }],
path,
- kind,
+ kind: kind.clone(),
text: text.chars().take(8000).collect(),
score: exact * 0.9,
- reason: "Matches words in the content".into(),
+ reason: if kind == "video" || kind == "video_audio" {
+ crate::retrieval::evidence_reason(&kind, false, true)
+ } else {
+ "Matches words in the content"
+ }
+ .into(),
page: v["page"].as_u64().unwrap_or(0) as u32,
seconds: v["seconds"].as_f64().unwrap_or(-1.0) as f32,
line: v["line"].as_u64().unwrap_or(0) as u32,
@@ -2445,6 +2503,38 @@ impl Engine {
excluded: &str,
filters: Option<&crate::search_filters::Filters>,
ticket: Option<u64>,
+ ) -> Result<Vec<Hit>> {
+ let base = self.semantic_evidence(
+ q,
+ s,
+ category,
+ scope,
+ excluded,
+ filters,
+ ticket,
+ crate::retrieval::Channel::Any,
+ )?;
+ let Some(plan) = crate::retrieval::plan(q, category) else {
+ return Ok(crate::retrieval::best_per_file(base));
+ };
+ let mut parts = Vec::new();
+ for (query, channel) in plan.parts {
+ parts.push(self.semantic_evidence(
+ &query, s, category, scope, excluded, filters, ticket, channel,
+ )?);
+ }
+ Ok(crate::retrieval::combine(base, parts, plan.ordered))
+ }
+ fn semantic_evidence(
+ &self,
+ q: &str,
+ s: &Settings,
+ category: &str,
+ scope: &str,
+ excluded: &str,
+ filters: Option<&crate::search_filters::Filters>,
+ ticket: Option<u64>,
+ evidence_channel: crate::retrieval::Channel,
) -> Result<Vec<Hit>> {
let normalized = normalized_media_query(q);
let vector = self.models.query_checked(s, &normalized, &|| {
@@ -2491,6 +2581,7 @@ impl Engine {
.enumerate()
.map(|(i, g)| {
(s.code_search || g.namespace != "code")
+ && evidence_channel.allows(&g.kind)
&& !(cat == "Images" && g.channel == "text" && !text_intent)
&& policy.allowed(&g.path, &g.kind)
&& metadata_allowed[i]
@@ -2529,6 +2620,9 @@ impl Engine {
let kind: String = row.get(2)?;
let namespace: String = row.get(4)?;
let channel: String = row.get(5)?;
+ if !evidence_channel.allows(&kind) {
+ continue;
+ }
if cat == "Images" && channel == "text" && !text_intent {
continue;
}
@@ -2564,20 +2658,10 @@ impl Engine {
total.0 += score;
total.1 += 1;
}
- let mut hits = HashMap::<String, Hit>::new();
+ let mut hits = Vec::new();
pool.sort_by(|a, b| b.0.total_cmp(&a.0));
pool.truncate(400);
- let tokens = q
- .split_whitespace()
- .map(str::to_lowercase)
- .filter(|t| {
- ![
- "a", "the", "of", "image", "images", "photo", "photos", "picture", "pictures",
- "in", "on",
- ]
- .contains(&t.as_str())
- })
- .collect::<Vec<_>>();
+ let tokens = search_tokens(q);
let scores: HashMap<i64, f32> = pool.iter().map(|(score, id)| (*id, *score)).collect();
let ids = serde_json::to_string(&pool.iter().map(|(_, id)| *id).collect::<Vec<_>>())?;
let mut details=conn.prepare_cached("SELECT rowid,path,kind,text,location FROM segments WHERE rowid IN (SELECT value FROM json_each(?1))")?;
@@ -2616,34 +2700,44 @@ impl Engine {
};
let media = location["embedding_source"] == "media";
let h = Hit {
+ evidence: Vec::new(),
path: path.clone(),
kind: kind.clone(),
text: text.chars().take(8000).collect(),
score: ranking,
- reason: if exact > 0.5 {
- "Matches exact words and meaning"
- } else if media && kind == "image" {
- "Matches the picture"
- } else if media {
- "Matches this media moment"
- } else {
- "Matches the meaning of this passage"
- }
- .into(),
+ reason: crate::retrieval::evidence_reason(&kind, media, exact > 0.5).into(),
page: location["page"].as_u64().unwrap_or(0) as u32,
seconds: location["seconds"].as_f64().unwrap_or(-1.0) as f32,
line: location["line"].as_u64().unwrap_or(0) as u32,
};
- if hits.get(&path).is_none_or(|p| p.score < h.score) {
- hits.insert(path, h);
- }
+ let mut h = h;
+ h.evidence.push(crate::db::Evidence {
+ source: match (kind.as_str(), media) {
+ ("video", true) => "video_frame",
+ ("video", false) => "video_ocr",
+ ("video_audio", _) => "audio",
+ ("image", true) => "image",
+ ("image", false) => "image_ocr",
+ _ => "text",
+ }
+ .into(),
+ text: h.text.chars().take(1000).collect(),
+ seconds: h.seconds,
+ page: h.page,
+ line: h.line,
+ });
+ hits.push(h);
}
- Ok(hits.into_values().collect())
+ Ok(hits)
}
}
fn search_tokens(q: &str) -> Vec<String> {
q.split_whitespace()
- .map(str::to_lowercase)
+ .map(|t| {
+ t.trim_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '-')
+ .to_lowercase()
+ })
+ .filter(|t| !t.is_empty())
.filter(|t| {
![
"a", "the", "of", "image", "images", "photo", "photos", "picture", "pictures",
@@ -2728,6 +2822,7 @@ pub(crate) fn content_equivalent(old: &str, new: &str, ext: &str) -> bool {
|| v.starts_with("dedupe:")
|| v.starts_with("video:")
|| v.starts_with("raw:")
+ || v.starts_with("rtf:")
|| **v == "html-visible-v1"
})
.map(|v| (*v).to_owned())
@@ -3221,6 +3316,7 @@ mod media_ranking_tests {
use super::*;
fn hit(path: &str, score: f32) -> Hit {
Hit {
+ evidence: Vec::new(),
path: path.into(),
kind: "file".into(),
text: String::new(),
@@ -4190,3 +4286,36 @@ mod network_scan_identity_tests {
);
}
}
+
+#[cfg(test)]
+mod evidence_stamp_tests {
+ use super::*;
+ #[test]
+ fn changed_extractors_refresh_only_relevant_content() {
+ let old = "v3|1|42|model|true|true|true";
+ assert!(!content_equivalent(
+ old,
+ &format!("{old}|rtf:visible-v1"),
+ "rtf"
+ ));
+ assert!(!content_equivalent(
+ old,
+ &format!("{old}|video:ocr-v1|ocr:png-v1"),
+ "mp4"
+ ));
+ assert!(content_equivalent(old, old, "txt"));
+ }
+}
+
+#[cfg(test)]
+mod query_token_tests {
+ use super::*;
+ #[test]
+ fn punctuation_does_not_remove_identifier_and_document_constraints() {
+ assert_eq!(
+ search_tokens("Site 000: replace cable; (VN-5103)."),
+ vec!["site", "000", "replace", "cable", "vn-5103"]
+ );
+ assert!(search_tokens("?! ...").is_empty());
+ }
+}
diff --git a/native/src/image_search.rs b/native/src/image_search.rs
index 0f35b8b..3a89106 100644
--- a/native/src/image_search.rs
+++ b/native/src/image_search.rs
@@ -232,6 +232,7 @@ impl Engine {
}
let loc: serde_json::Value = serde_json::from_str(&row.get::<_, String>(4)?)?;
hits.push(Hit {
+ evidence: Vec::new(),
path,
kind: row.get(2)?,
text,
diff --git a/native/src/journal.rs b/native/src/journal.rs
index 19f2f08..d7db8d4 100644
--- a/native/src/journal.rs
+++ b/native/src/journal.rs
@@ -36,6 +36,39 @@ fn malformed(error: &anyhow::Error) -> bool {
true
}
}
+fn relevant_exclusions(exclusions: &[String], root: &str) -> Vec<String> {
+ let mut relevant = exclusions
+ .iter()
+ .filter(|p| {
+ p.contains(['*', '?']) || crate::config::under(p, root) || crate::config::under(root, p)
+ })
+ .map(|p| crate::config::fold(p))
+ .collect::<Vec<_>>();
+ relevant.sort();
+ relevant.dedup();
+ relevant
+}
+/// New exclusions only narrow visibility; replay remains valid. Removing an exclusion
+/// expands coverage and requires catch-up, but only for the overlapping source.
+fn coverage_compatible(old: &str, new: &str, root: &str) -> bool {
+ if old == new {
+ return true;
+ }
+ let a = old.split('|').collect::<Vec<_>>();
+ let b = new.split('|').collect::<Vec<_>>();
+ if a.len() != 5 || b.len() != 5 || a[0] != b[0] || a[2..] != b[2..] {
+ return false;
+ }
+ let (Ok(old), Ok(new)) = (
+ serde_json::from_str::<Vec<String>>(a[1]),
+ serde_json::from_str::<Vec<String>>(b[1]),
+ ) else {
+ return false;
+ };
+ let old = relevant_exclusions(&old, root);
+ let new = relevant_exclusions(&new, root);
+ old.iter().all(|p| new.contains(p))
+}
fn retry_delay(attempts: u32) -> Duration {
Duration::from_secs((5u64 << attempts.saturating_sub(1).min(6)).min(300))
}
@@ -103,7 +136,7 @@ impl Tracker {
format!(
"{}|{:?}|{}|{}|{}",
root.mode,
- s.exclusions,
+ relevant_exclusions(&s.exclusions, &root.path),
s.excluded_types,
s.skip_windows_churn,
s.include_hidden
@@ -138,7 +171,9 @@ impl Tracker {
if crate::config::under(&root.path, &format!("{volume}\\"))
&& (old.is_none()
|| !saved.coverage.get(&key).map_or(signature_matches, |value| {
- Some(value) == self.coverage.get(&key)
+ self.coverage.get(&key).is_some_and(|current| {
+ coverage_compatible(value, current, &root.path)
+ })
}))
{
uncovered.push(PathBuf::from(&root.path));
@@ -169,7 +204,9 @@ impl Tracker {
if crate::config::under(&root.path, &format!("{volume}\\"))
&& (saved.marks.get(&volume).is_none()
|| !saved.coverage.get(&key).map_or(signature_matches, |value| {
- Some(value) == self.coverage.get(&key)
+ self.coverage.get(&key).is_some_and(|current| {
+ coverage_compatible(value, current, &root.path)
+ })
}))
{
uncovered.push(PathBuf::from(&root.path));
@@ -221,11 +258,11 @@ impl Tracker {
if self.missing_names.is_empty() {
return Ok(vec![]);
}
- let c = db.connect(true)?;
+ let c = db.connect(false)?;
// Bound each scheduler tick to four indexed-name seeks / 1024 paths.
// Continuations retain duplicate basenames without allocating huge lists.
let mut statement = c.prepare_cached(
- "SELECT rowid,path FROM names WHERE base=?1 AND rowid>?2 ORDER BY rowid LIMIT 256",
+ "SELECT rowid,path,coalesce(mtime,-1),coalesce(size,-1),coalesce(kind,'') FROM names WHERE base=?1 AND rowid>?2 ORDER BY rowid LIMIT 256",
)?;
let mut paths = std::collections::BTreeSet::new();
let keys = self
@@ -238,17 +275,53 @@ impl Tracker {
for key in &keys {
let (volume, name) = key;
let cursor = &self.missing_names[key];
- let rows = statement
- .query_map(rusqlite::params![name.to_lowercase(), cursor], |r| {
- Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
+ let rows =
+ statement.query_map(rusqlite::params![name.to_lowercase(), cursor], |r| {
+ Ok((
+ r.get::<_, i64>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, i64>(2)?,
+ r.get::<_, i64>(3)?,
+ r.get::<_, String>(4)?,
+ ))
})?;
let mut count = 0;
let mut last = i64::MIN;
for row in rows {
- let (id, path) = row?;
+ let (id, path, old_mtime, old_size, old_kind) = row?;
last = id;
count += 1;
if crate::config::under(&path, &format!("{volume}\\")) {
+ if let Ok(meta) = std::fs::metadata(crate::platform::preview_path(&path)) {
+ let mtime = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_nanos().min(i64::MAX as u128) as i64)
+ .unwrap_or(-1);
+ if meta.is_dir() {
+ if old_kind == "file" {
+ // A former file was replaced by a directory: its new
+ // children really do need discovery, unlike metadata noise.
+ paths.insert(PathBuf::from(path));
+ continue;
+ }
+ // This is an ambiguous same-name fallback, not evidence of a
+ // create/rename. Refresh this row only, never walk its descendants.
+ if mtime != old_mtime
+ || i64::try_from(meta.len()).ok() != Some(old_size)
+ {
+ c.execute(
+ "UPDATE names SET mtime=?2,size=?3,kind='folder' WHERE path=?1",
+ rusqlite::params![path, mtime, meta.len()],
+ )?;
+ }
+ continue;
+ }
+ if mtime == old_mtime && i64::try_from(meta.len()).ok() == Some(old_size) {
+ continue;
+ }
+ }
paths.insert(PathBuf::from(path));
}
}
@@ -361,6 +434,23 @@ impl Tracker {
paths.dedup();
(paths, false) // scoped recovery paths use the existing durable targeted queue
}
+ /// Safe to advance a quiet reader only after all ambiguous names were checked
+ /// and the monitor confirmed that there is no outstanding durable indexing work.
+ pub fn checkpoint_quiet(&mut self, home: &Path) -> bool {
+ if self.flight.is_some()
+ || !self.missing_names.is_empty()
+ || !self.read.iter().any(|(volume, mark)| {
+ self.committed
+ .get(volume)
+ .is_none_or(|old| old.id != mark.id || old.usn != mark.usn)
+ })
+ {
+ return false;
+ }
+ self.begin();
+ self.finish(true, home);
+ true
+ }
pub fn begin(&mut self) {
self.flight_cache = Some(self.directory_cache.clone());
self.flight = if self.read.is_empty() {
@@ -1287,3 +1377,162 @@ mod source_coverage_tests {
assert_eq!(uncovered, vec![PathBuf::from("C:\\")]);
}
}
+
+#[cfg(test)]
+mod coverage_and_lookup_tests {
+ use super::*;
+ fn key(exclusions: Vec<String>) -> String {
+ format!("quick|{exclusions:?}||true|false")
+ }
+ #[test]
+ fn exclusion_changes_preserve_unrelated_drive_coverage_and_narrowing() {
+ let old = key(vec![r"C:\Windows".into()]);
+ let narrowed = key(vec![r"C:\Windows".into(), r"C:\Users\test\browser".into()]);
+ assert!(coverage_compatible(&old, &narrowed, r"D:\"));
+ assert!(coverage_compatible(&old, &narrowed, r"C:\"));
+ assert!(!coverage_compatible(&narrowed, &old, r"C:\"));
+ assert!(coverage_compatible(&narrowed, &old, r"D:\"));
+ assert!(!coverage_compatible(
+ &old,
+ &old.replace("quick|", "full|"),
+ r"C:\"
+ ));
+ }
+ #[test]
+ #[cfg(windows)]
+ fn ambiguous_directory_names_do_not_walk_or_queue_unchanged_files() {
+ use crate::db::Database;
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let folder = root.path().join("build");
+ std::fs::create_dir(&folder).unwrap();
+ let file = root.path().join("same.txt");
+ std::fs::write(&file, "unchanged").unwrap();
+ let s = crate::config::Settings {
+ encrypt_index: false,
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ let volume = root.path().to_string_lossy()[..2].to_string();
+ for (path, kind) in [(&folder, "folder"), (&file, "file")] {
+ let meta = std::fs::metadata(path).unwrap();
+ let mt = meta
+ .modified()
+ .unwrap()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ .min(i64::MAX as u128) as i64;
+ Database::touch_name(
+ &c,
+ path,
+ kind,
+ if kind == "folder" { 0 } else { mt },
+ meta.len(),
+ "quick",
+ &root.path().to_string_lossy(),
+ 1,
+ )
+ .unwrap();
+ }
+ drop(c);
+ let mut tracker = Tracker::default();
+ tracker
+ .missing_names
+ .insert((volume.clone(), "build".into()), i64::MIN);
+ tracker
+ .missing_names
+ .insert((volume.clone(), "same.txt".into()), i64::MIN);
+ assert!(tracker.resolve_missing(&db).unwrap().is_empty());
+ let c = db.connect(true).unwrap();
+ let mt: i64 = c
+ .query_row(
+ "SELECT mtime FROM names WHERE path=?1",
+ [folder.to_string_lossy().as_ref()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert!(mt > 0);
+ drop(c);
+ std::fs::write(&file, "changed and longer").unwrap();
+ tracker
+ .missing_names
+ .insert((volume, "same.txt".into()), i64::MIN);
+ assert_eq!(tracker.resolve_missing(&db).unwrap(), vec![file]);
+ }
+}
+
+#[cfg(test)]
+mod scoped_coverage_replay_tests {
+ use super::*;
+ #[test]
+ fn adding_browser_exclusion_replays_existing_cursors_without_drive_catchup() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = crate::config::Settings::default();
+ s.ntfs_journal = true;
+ s.roots = vec![
+ crate::config::Source {
+ path: r"C:\".into(),
+ mode: "quick".into(),
+ },
+ crate::config::Source {
+ path: r"D:\".into(),
+ mode: "quick".into(),
+ },
+ ];
+ let mut coverage = BTreeMap::new();
+ for root in &s.roots {
+ coverage.insert(
+ crate::config::fold(&root.path),
+ format!(
+ "quick|[]|{}|{}|{}",
+ s.excluded_types, s.skip_windows_churn, s.include_hidden
+ ),
+ );
+ }
+ let saved = Saved {
+ signature: String::new(),
+ marks: BTreeMap::from([
+ ("C:".into(), Mark { id: 1, usn: 50 }),
+ ("D:".into(), Mark { id: 1, usn: 50 }),
+ ]),
+ coverage,
+ };
+ std::fs::write(
+ home.path().join("ntfs-journal.json"),
+ serde_json::to_vec(&saved).unwrap(),
+ )
+ .unwrap();
+ s.exclusions.push(r"C:\Users\test\browser".into());
+ let (tx, _) = crossbeam_channel::unbounded();
+ let mut tracker = Tracker::default();
+ let uncovered =
+ tracker.configure_with(&s, home.path(), &tx.into(), |_| Ok((1, 0, 100)), |_| true);
+ assert!(uncovered.is_empty());
+ assert_eq!(tracker.read["C:"].usn, 50);
+ assert_eq!(tracker.read["D:"].usn, 50);
+ }
+}
+
+#[cfg(test)]
+mod quiet_checkpoint_tests {
+ use super::*;
+ #[test]
+ fn quiet_checkpoint_advances_checked_cursor_but_never_unresolved_names() {
+ let home = tempfile::tempdir().unwrap();
+ let mut t = Tracker::default();
+ t.read.insert("C:".into(), Mark { id: 1, usn: 110 });
+ t.committed.insert("C:".into(), Mark { id: 1, usn: 100 });
+ t.missing_names.insert(("C:".into(), "unknown".into()), 0);
+ assert!(!t.checkpoint_quiet(home.path()));
+ assert_eq!(t.committed["C:"].usn, 100);
+ t.missing_names.clear();
+ assert!(t.checkpoint_quiet(home.path()));
+ let saved: Saved =
+ serde_json::from_slice(&std::fs::read(home.path().join("ntfs-journal.json")).unwrap())
+ .unwrap();
+ assert_eq!(saved.marks["C:"].usn, 110);
+ assert!(!t.checkpoint_quiet(home.path()));
+ }
+}
diff --git a/native/src/journal/directory.rs b/native/src/journal/directory.rs
index f3236bd..3fd68b6 100644
--- a/native/src/journal/directory.rs
+++ b/native/src/journal/directory.rs
@@ -276,6 +276,33 @@ mod tests {
attributes: if directory { 16 } else { 0 },
}
}
+
+ #[test]
+ fn one_new_and_three_updated_files_stay_four_paths_not_the_parent_tree() {
+ let mark = Mark { id: 1, usn: 10 };
+ let mut cache = DirectoryCache::default();
+ cache.align("C:", mark);
+ cache.insert("C:", 100, PathBuf::from(r"C:\indexed"));
+ let records = vec![
+ rec(201, 100, "new.txt", 0x100, false),
+ rec(202, 100, "one.txt", 0x1, false),
+ rec(203, 100, "two.txt", 0x1, false),
+ rec(204, 100, "three.txt", 0x1, false),
+ rec(100, 5, "indexed", 0x8000, true),
+ ];
+ let batch = resolve_records("C:", mark, 20, records, &mut cache, |_| {
+ anyhow::bail!("unexpected parent lookup")
+ })
+ .unwrap();
+ assert_eq!(batch.paths.len(), 4);
+ assert!(
+ batch
+ .paths
+ .iter()
+ .all(|p| p.extension().is_some_and(|e| e == "txt"))
+ );
+ assert!(!batch.paths.contains(&PathBuf::from(r"C:\indexed")));
+ }
#[test]
fn deleted_parent_is_resolved_from_bounded_tombstone_cache() {
let mark = Mark { id: 1, usn: 10 };
diff --git a/native/src/main.rs b/native/src/main.rs
index adabb55..f1206d9 100644
--- a/native/src/main.rs
+++ b/native/src/main.rs
@@ -27,12 +27,15 @@ mod local_tts;
mod mcp;
mod models;
mod native_video;
+mod network_reconcile;
mod pdf;
mod platform;
mod previews;
mod raw;
mod remote;
mod resources;
+mod retrieval;
+mod rtf;
mod scheduling;
mod search_filters;
mod setup;
diff --git a/native/src/network_reconcile.rs b/native/src/network_reconcile.rs
new file mode 100644
index 0000000..5e76201
--- /dev/null
+++ b/native/src/network_reconcile.rs
@@ -0,0 +1,934 @@
+//! Incremental SMB safety reconciliation. No recursive filesystem walk is queued.
+//! Directory progress and exact changed paths are committed together; incomplete
+//! listings never establish deletion. Blocking SMB calls stay off the scheduler/UI.
+use crate::{config::Settings, db::Database};
+use anyhow::{Context, Result};
+use rusqlite::{OptionalExtension, params};
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ fs,
+ path::{Path, PathBuf},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ mpsc,
+ },
+ time::{Duration, Instant},
+};
+const ENTRIES: usize = 256;
+struct Cursor {
+ root: PathBuf,
+ path: PathBuf,
+ reader: Option<fs::ReadDir>,
+}
+pub struct Report {
+ pub root: PathBuf,
+ pub checked: usize,
+ pub changed: usize,
+ pub folders_changed: bool,
+ pub done: bool,
+ pub warning: Option<String>,
+ pub run_checked: usize,
+ pub run_changed: usize,
+}
+struct Output {
+ cursor: Option<Cursor>,
+ report: Report,
+}
+#[derive(Default)]
+pub struct Reconciler {
+ root: Option<PathBuf>,
+ cursor: Option<Cursor>,
+ queued: VecDeque<PathBuf>,
+ reply: Option<mpsc::Receiver<(u64, Result<Output>)>>,
+ generation: u64,
+ cancel: Arc<AtomicBool>,
+ requests: HashMap<PathBuf, (bool, i64)>,
+ totals: HashMap<PathBuf, (usize, usize)>,
+ fresh: HashSet<PathBuf>,
+}
+impl Drop for Reconciler {
+ fn drop(&mut self) {
+ self.cancel.store(true, Ordering::Release);
+ }
+}
+impl Reconciler {
+ pub fn reset(&mut self) {
+ self.cancel.store(true, Ordering::Release);
+ self.cancel = Arc::new(AtomicBool::new(false));
+ self.generation = self.generation.wrapping_add(1);
+ self.root = None;
+ self.cursor = None;
+ self.queued.clear();
+ self.requests.clear();
+ self.totals.clear();
+ self.fresh.clear();
+ }
+ pub fn request(&mut self, root: PathBuf) {
+ self.requests
+ .entry(root.clone())
+ .or_insert((false, chrono::Utc::now().timestamp_millis()));
+ if self.root.as_ref() != Some(&root) && !self.queued.contains(&root) {
+ self.queued.push_back(root);
+ }
+ }
+ pub fn request_recovery(&mut self, root: PathBuf) {
+ self.fresh.insert(root.clone());
+ self.requests
+ .entry(root.clone())
+ .and_modify(|r| {
+ *r = (true, chrono::Utc::now().timestamp_millis());
+ })
+ .or_insert((true, chrono::Utc::now().timestamp_millis()));
+ self.request(root);
+ }
+ fn retire(&mut self, roots: &[PathBuf]) {
+ for root in roots {
+ self.requests.remove(root);
+ self.totals.remove(root);
+ self.fresh.remove(root);
+ }
+ self.queued.retain(|p| !roots.contains(p));
+ if self.root.as_ref().is_some_and(|p| roots.contains(p)) {
+ self.cancel.store(true, Ordering::Release);
+ self.cancel = Arc::new(AtomicBool::new(false));
+ self.generation = self.generation.wrapping_add(1);
+ self.root = None;
+ self.cursor = None;
+ }
+ }
+ pub fn disable_periodic(&mut self) {
+ let roots = self
+ .requests
+ .iter()
+ .filter(|(_, r)| !r.0)
+ .map(|(p, _)| p.clone())
+ .collect::<Vec<_>>();
+ self.retire(&roots);
+ }
+ pub fn covered_before(&mut self, started: i64) -> Vec<PathBuf> {
+ let roots = self
+ .requests
+ .iter()
+ .filter(|(_, r)| !r.0 || r.1 < started)
+ .map(|(p, _)| p.clone())
+ .collect::<Vec<_>>();
+ self.retire(&roots);
+ roots
+ }
+ pub fn has_root(&self, root: &Path) -> bool {
+ self.requests.contains_key(root)
+ }
+ pub fn pending(&self) -> bool {
+ self.root.is_some() || !self.queued.is_empty() || self.reply.is_some()
+ }
+ pub fn poll(&mut self, db: &Database, s: &Settings, allow: bool) -> Option<Result<Report>> {
+ let mut report = None;
+ if let Some(rx) = &self.reply {
+ match rx.try_recv() {
+ Ok((generation, result)) => {
+ self.reply = None;
+ if generation == self.generation {
+ match result {
+ Ok(mut out) => {
+ let total = self.totals.entry(out.report.root.clone()).or_default();
+ total.0 += out.report.checked;
+ total.1 += out.report.changed;
+ out.report.run_checked = total.0;
+ out.report.run_changed = total.1;
+ if self.fresh.contains(&out.report.root) {
+ self.cursor = None;
+ out.report.done = false;
+ } else {
+ self.cursor = out.cursor;
+ }
+ if out.report.done {
+ self.requests.remove(&out.report.root);
+ self.totals.remove(&out.report.root);
+ self.root = None;
+ }
+ report = Some(Ok(out.report));
+ }
+ Err(e)
+ if self
+ .root
+ .as_ref()
+ .is_some_and(|root| self.fresh.contains(root)) =>
+ {
+ self.cursor = None;
+ report = Some(Err(e));
+ }
+ Err(e) => {
+ if let Some(root) = &self.root {
+ self.requests.remove(root);
+ self.totals.remove(root);
+ }
+ self.cursor = None;
+ self.root = None;
+ report = Some(Err(e));
+ }
+ }
+ }
+ }
+ Err(mpsc::TryRecvError::Disconnected) => {
+ self.reply = None;
+ if let Some(root) = &self.root {
+ self.requests.remove(root);
+ self.totals.remove(root);
+ }
+ self.cursor = None;
+ self.root = None;
+ report = Some(Err(anyhow::anyhow!(
+ "Network reconciliation worker stopped"
+ )));
+ }
+ Err(mpsc::TryRecvError::Empty) => {}
+ }
+ }
+ if allow && self.reply.is_none() {
+ if self.root.is_none() {
+ self.root = self.queued.pop_front();
+ }
+ if let Some(root) = self.root.clone() {
+ let cursor = self.cursor.take();
+ let db = db.clone();
+ let s = s.clone();
+ let cancel = self.cancel.clone();
+ let generation = self.generation;
+ let fresh = self.fresh.remove(&root);
+ let (tx, rx) = mpsc::channel();
+ self.reply = Some(rx);
+ std::thread::spawn(move || {
+ let result = (|| {
+ if fresh {
+ reset_progress(&db, &root, &cancel)?;
+ }
+ run_budget(&db, &s, root, if fresh { None } else { cursor }, &cancel)
+ })();
+ let _ = tx.send((generation, result));
+ });
+ }
+ }
+ report
+ }
+}
+fn reset_progress(db: &Database, root: &Path, cancel: &AtomicBool) -> Result<()> {
+ let mut c = db.connect(false)?;
+ schema(&c)?;
+ let tx = c.transaction()?;
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ tx.execute(
+ "DELETE FROM native_network_dirs WHERE root=?1",
+ [root.to_string_lossy().as_ref()],
+ )?;
+ tx.execute(
+ "DELETE FROM native_network_seen WHERE root=?1",
+ [root.to_string_lossy().as_ref()],
+ )?;
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ tx.commit()?;
+ Ok(())
+}
+fn run_budget(
+ db: &Database,
+ s: &Settings,
+ root: PathBuf,
+ cursor: Option<Cursor>,
+ cancel: &AtomicBool,
+) -> Result<Output> {
+ let began = Instant::now();
+ let mut out = step(db, s, root.clone(), cursor, cancel)?;
+ for _ in 1..16 {
+ if out.report.done
+ || out.cursor.is_some()
+ || out.report.warning.is_some()
+ || out.report.checked >= ENTRIES
+ || began.elapsed() >= Duration::from_millis(100)
+ {
+ break;
+ }
+ let mut next = step_limited(
+ db,
+ s,
+ root.clone(),
+ None,
+ cancel,
+ ENTRIES - out.report.checked,
+ )?;
+ next.report.checked += out.report.checked;
+ next.report.changed += out.report.changed;
+ next.report.folders_changed |= out.report.folders_changed;
+ out = next;
+ }
+ Ok(out)
+}
+fn schema(c: &rusqlite::Connection) -> Result<()> {
+ c.execute_batch("CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS native_network_dirs(root TEXT NOT NULL,path TEXT NOT NULL,PRIMARY KEY(root,path));
+ CREATE TABLE IF NOT EXISTS native_network_seen(root TEXT NOT NULL,directory TEXT NOT NULL,path TEXT NOT NULL COLLATE NOCASE,PRIMARY KEY(root,directory,path));
+ CREATE INDEX IF NOT EXISTS names_parent_network ON names(parent COLLATE NOCASE);")?;
+ Ok(())
+}
+fn enqueue(c: &rusqlite::Connection, path: &Path, generation: i64) -> Result<()> {
+ c.prepare_cached("INSERT INTO native_changes VALUES(?1,?2,?3) ON CONFLICT(path) DO UPDATE SET generation=excluded.generation,queued=excluded.queued")?.execute(params![path.to_string_lossy(),generation,chrono::Utc::now().timestamp_millis()])?;
+ Ok(())
+}
+fn mark(c: &rusqlite::Connection, root: &Path, dir: &Path, path: &Path) -> Result<()> {
+ c.prepare_cached("INSERT OR IGNORE INTO native_network_seen VALUES(?1,?2,?3)")?
+ .execute(params![
+ root.to_string_lossy(),
+ dir.to_string_lossy(),
+ path.to_string_lossy()
+ ])?;
+ Ok(())
+}
+fn step(
+ db: &Database,
+ s: &Settings,
+ root: PathBuf,
+ cursor: Option<Cursor>,
+ cancel: &AtomicBool,
+) -> Result<Output> {
+ step_limited(db, s, root, cursor, cancel, ENTRIES)
+}
+fn step_limited(
+ db: &Database,
+ s: &Settings,
+ root: PathBuf,
+ cursor: Option<Cursor>,
+ cancel: &AtomicBool,
+ limit: usize,
+) -> Result<Output> {
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ let mut c = db.connect(false)?;
+ schema(&c)?;
+ let mut cursor = if let Some(cursor) = cursor {
+ cursor
+ } else {
+ let outstanding: bool = c.query_row(
+ "SELECT EXISTS(SELECT 1 FROM native_network_dirs WHERE root=?1)",
+ [root.to_string_lossy().as_ref()],
+ |r| r.get(0),
+ )?;
+ if !outstanding {
+ c.execute(
+ "INSERT OR IGNORE INTO native_network_dirs VALUES(?1,?1)",
+ [root.to_string_lossy().as_ref()],
+ )?;
+ }
+ let path: String = c.query_row(
+ "SELECT path FROM native_network_dirs WHERE root=?1 ORDER BY length(path),path LIMIT 1",
+ [root.to_string_lossy().as_ref()],
+ |r| r.get(0),
+ )?;
+ let path = PathBuf::from(path);
+ if !s.searched(&path) {
+ c.execute(
+ "DELETE FROM native_network_dirs WHERE root=?1 AND path=?2",
+ params![root.to_string_lossy(), path.to_string_lossy()],
+ )?;
+ return finish_directory(c, &root, &path, false, 0, 0, false);
+ }
+ let physical = crate::platform::preview_path(&path.to_string_lossy());
+ // A disconnected/unreadable root never proves that files were deleted.
+ let reader = match fs::read_dir(&physical) {
+ Ok(reader) => reader,
+ Err(error) if path != root => {
+ return skip_directory(c, &root, &path, &error.to_string(), cancel);
+ }
+ Err(error) => {
+ return Err(error)
+ .with_context(|| format!("Cannot list network root {}", root.display()));
+ }
+ };
+ c.execute(
+ "DELETE FROM native_network_seen WHERE root=?1 AND directory=?2",
+ params![root.to_string_lossy(), path.to_string_lossy()],
+ )?;
+ Cursor {
+ root: root.clone(),
+ path,
+ reader: Some(reader),
+ }
+ };
+ let began = Instant::now();
+ let mut entries = vec![];
+ let mut finished = false;
+ if let Some(reader) = &mut cursor.reader {
+ for _ in 0..limit {
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ match reader.next() {
+ Some(entry) => {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(error) => {
+ return skip_directory(
+ c,
+ &root,
+ &cursor.path,
+ &error.to_string(),
+ cancel,
+ );
+ }
+ };
+ let logical = cursor.path.join(entry.file_name());
+ let meta = match entry.metadata() {
+ Ok(meta) => meta,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(error) => {
+ return skip_directory(
+ c,
+ &root,
+ &cursor.path,
+ &error.to_string(),
+ cancel,
+ );
+ }
+ };
+ entries.push((logical, meta));
+ }
+ None => {
+ finished = true;
+ break;
+ }
+ }
+ if began.elapsed() >= Duration::from_millis(100) {
+ break;
+ }
+ }
+ if finished {
+ cursor.reader = None;
+ }
+ }
+ let mut checked = entries.len();
+ let mut changed = 0;
+ let mut folders_changed = false;
+ let tx = c.transaction()?;
+ let generation: i64 = tx.query_row(
+ "SELECT coalesce(max(generation),0)+1 FROM native_changes",
+ [],
+ |r| r.get(0),
+ )?;
+ for (path, meta) in entries {
+ mark(&tx, &root, &cursor.path, &path)?;
+ if meta.file_type().is_symlink() || !s.searched(&path) {
+ continue;
+ }
+ let mtime = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_nanos().min(i64::MAX as u128) as i64)
+ .unwrap_or(-1);
+ let old:Option<(i64,i64,String,String)>=tx.query_row("SELECT coalesce(mtime,-1),coalesce(size,-1),coalesce(index_mode,''),coalesce(kind,'') FROM names WHERE path=?1",[path.to_string_lossy().as_ref()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
+ let mode = crate::config::mode(&path.to_string_lossy(), s);
+ if meta.is_dir() {
+ if old.as_ref().is_none_or(|(mt, size, old_mode, kind)| {
+ *mt != mtime
+ || i64::try_from(meta.len()).ok() != Some(*size)
+ || old_mode != mode
+ || kind != "folder"
+ }) {
+ Database::touch_name(
+ &tx,
+ &path,
+ "folder",
+ mtime,
+ meta.len(),
+ mode,
+ &root.to_string_lossy(),
+ 0,
+ )?;
+ folders_changed = true;
+ }
+ tx.execute(
+ "INSERT OR IGNORE INTO native_network_dirs VALUES(?1,?2)",
+ params![root.to_string_lossy(), path.to_string_lossy()],
+ )?;
+ } else if meta.is_file()
+ && old.is_none_or(|(mt, size, old_mode, kind)| {
+ mt != mtime
+ || i64::try_from(meta.len()).ok() != Some(size)
+ || old_mode != mode
+ || kind != "file"
+ })
+ {
+ enqueue(&tx, &path, generation)?;
+ changed += 1;
+ }
+ }
+ // Only a complete, error-free listing can establish a missing immediate child.
+ if cursor.reader.is_none() && checked < limit {
+ let remaining = limit - checked;
+ let missing = {
+ let mut stmt=tx.prepare("SELECT path FROM names WHERE parent=?1 COLLATE NOCASE AND NOT EXISTS(SELECT 1 FROM native_network_seen s WHERE s.root=?2 AND s.directory=?1 AND s.path=names.path COLLATE NOCASE) LIMIT ?3")?;
+ stmt.query_map(
+ params![
+ cursor.path.to_string_lossy(),
+ root.to_string_lossy(),
+ remaining
+ ],
+ |r| r.get::<_, String>(0),
+ )?
+ .collect::<rusqlite::Result<Vec<_>>>()?
+ };
+ checked += missing.len();
+ for path in &missing {
+ let path = Path::new(path);
+ mark(&tx, &root, &cursor.path, path)?;
+ if s.searched(path) {
+ enqueue(&tx, path, generation)?;
+ changed += 1;
+ }
+ }
+ if missing.len() < remaining {
+ tx.execute(
+ "DELETE FROM native_network_dirs WHERE root=?1 AND path=?2",
+ params![root.to_string_lossy(), cursor.path.to_string_lossy()],
+ )?;
+ tx.execute(
+ "DELETE FROM native_network_seen WHERE root=?1 AND directory=?2",
+ params![root.to_string_lossy(), cursor.path.to_string_lossy()],
+ )?;
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ tx.commit()?;
+ return finish_directory(
+ c,
+ &root,
+ &cursor.path,
+ true,
+ checked,
+ changed,
+ folders_changed,
+ );
+ }
+ }
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ tx.commit()?;
+ Ok(Output {
+ cursor: Some(cursor),
+ report: Report {
+ root,
+ checked,
+ changed,
+ folders_changed,
+ done: false,
+ warning: None,
+ run_checked: 0,
+ run_changed: 0,
+ },
+ })
+}
+fn skip_directory(
+ c: rusqlite::Connection,
+ root: &Path,
+ path: &Path,
+ error: &str,
+ cancel: &AtomicBool,
+) -> Result<Output> {
+ anyhow::ensure!(
+ !cancel.load(Ordering::Acquire),
+ "Network reconciliation cancelled"
+ );
+ // Keep all indexed children. The next pass can retry the branch; no partial
+ // enumeration is allowed to manufacture deletion or block every other branch.
+ c.execute(
+ "DELETE FROM native_network_dirs WHERE root=?1 AND path=?2",
+ params![root.to_string_lossy(), path.to_string_lossy()],
+ )?;
+ c.execute(
+ "DELETE FROM native_network_seen WHERE root=?1 AND directory=?2",
+ params![root.to_string_lossy(), path.to_string_lossy()],
+ )?;
+ let mut out = finish_directory(c, root, path, false, 0, 0, false)?;
+ out.report.warning = Some(format!(
+ "{}: {error}; incomplete listing retained indexed files",
+ path.display()
+ ));
+ Ok(out)
+}
+fn finish_directory(
+ c: rusqlite::Connection,
+ root: &Path,
+ _path: &Path,
+ _complete: bool,
+ checked: usize,
+ changed: usize,
+ folders_changed: bool,
+) -> Result<Output> {
+ let remaining: bool = c.query_row(
+ "SELECT EXISTS(SELECT 1 FROM native_network_dirs WHERE root=?1)",
+ [root.to_string_lossy().as_ref()],
+ |r| r.get(0),
+ )?;
+ Ok(Output {
+ cursor: None,
+ report: Report {
+ root: root.into(),
+ checked,
+ changed,
+ folders_changed,
+ done: !remaining,
+ warning: None,
+ run_checked: 0,
+ run_changed: 0,
+ },
+ })
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn fixture() -> (tempfile::TempDir, tempfile::TempDir, Settings, Database) {
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::Builder::new()
+ .prefix("VectorDash-network-")
+ .tempdir()
+ .unwrap();
+ let s = Settings {
+ encrypt_index: false,
+ include_hidden: true,
+ skip_windows_churn: false,
+ roots: vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }],
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ (home, root, s, db)
+ }
+ fn indexed(db: &Database, s: &Settings, path: &Path) {
+ let m = fs::metadata(path).unwrap();
+ let mt = m
+ .modified()
+ .unwrap()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ .min(i64::MAX as u128) as i64;
+ Database::touch_name(
+ &db.connect(false).unwrap(),
+ path,
+ "file",
+ mt,
+ m.len(),
+ "quick",
+ &s.roots[0].path,
+ 1,
+ )
+ .unwrap();
+ }
+ #[test]
+ fn large_directory_is_incremental_and_only_changed_files_are_queued() {
+ let (_h, r, s, db) = fixture();
+ for i in 0..600 {
+ let p = r.path().join(format!("file-{i}.txt"));
+ fs::write(&p, "same").unwrap();
+ indexed(&db, &s, &p);
+ }
+ fs::write(r.path().join("file-1.txt"), "changed longer").unwrap();
+ fs::remove_file(r.path().join("file-2.txt")).unwrap();
+ fs::write(r.path().join("new.txt"), "new").unwrap();
+ let cancel = AtomicBool::new(false);
+ let mut cursor = None;
+ let mut steps = 0;
+ loop {
+ let out = step(&db, &s, r.path().into(), cursor, &cancel).unwrap();
+ assert!(out.report.checked <= ENTRIES);
+ steps += 1;
+ if out.report.done {
+ break;
+ }
+ cursor = out.cursor;
+ assert!(steps < 20);
+ }
+ assert!(steps >= 3);
+ let c = db.connect(true).unwrap();
+ let mut stmt = c.prepare("SELECT path FROM native_changes").unwrap();
+ let paths = stmt
+ .query_map([], |r| r.get::<_, String>(0))
+ .unwrap()
+ .collect::<rusqlite::Result<Vec<_>>>()
+ .unwrap();
+ assert_eq!(paths.len(), 3);
+ assert!(paths.iter().all(|p| Path::new(p).extension().is_some()));
+ }
+
+ #[test]
+ fn small_directory_batches_are_budgeted_and_only_files_enter_index_queue() {
+ let (_h, r, s, db) = fixture();
+ for n in 0..20 {
+ let dir = r.path().join(format!("branch-{n}"));
+ fs::create_dir(&dir).unwrap();
+ for i in 0..20 {
+ fs::write(dir.join(format!("new-{i}.txt")), "new").unwrap();
+ }
+ }
+ let cancel = AtomicBool::new(false);
+ let mut cursor = None;
+ for _ in 0..30 {
+ let out = run_budget(&db, &s, r.path().into(), cursor, &cancel).unwrap();
+ assert!(out.report.checked <= ENTRIES);
+ if out.report.done {
+ break;
+ }
+ cursor = out.cursor;
+ }
+ let c = db.connect(true).unwrap();
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM native_changes", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 400
+ );
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM native_network_dirs", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM names WHERE kind='folder'", [], |r| {
+ r.get::<_, i64>(0)
+ })
+ .unwrap(),
+ 20
+ );
+ }
+ #[test]
+ fn failed_branch_retains_index_and_does_not_starve_other_branches() {
+ let (_h, r, s, db) = fixture();
+ let inaccessible = r.path().join("not-a-directory.txt");
+ fs::write(&inaccessible, "file").unwrap();
+ indexed(&db, &s, &inaccessible);
+ let c = db.connect(false).unwrap();
+ schema(&c).unwrap();
+ c.execute(
+ "INSERT INTO native_network_dirs VALUES(?1,?2)",
+ params![r.path().to_string_lossy(), inaccessible.to_string_lossy()],
+ )
+ .unwrap();
+ drop(c);
+ let out = step(&db, &s, r.path().into(), None, &AtomicBool::new(false)).unwrap();
+ assert!(out.report.warning.is_some());
+ assert!(out.report.done);
+ assert_eq!(db.stats().unwrap().files, 1);
+ assert_eq!(
+ db.connect(true)
+ .unwrap()
+ .query_row("SELECT count(*) FROM native_changes", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ }
+
+ #[test]
+ fn required_gap_rechecks_branches_completed_before_the_gap() {
+ let (_h, r, s, db) = fixture();
+ for branch in ["a", "b"] {
+ let dir = r.path().join(branch);
+ fs::create_dir(&dir).unwrap();
+ let file = dir.join("one.txt");
+ fs::write(&file, "before").unwrap();
+ indexed(&db, &s, &file);
+ }
+ let cancel = AtomicBool::new(false);
+ let out = step(&db, &s, r.path().into(), None, &cancel).unwrap();
+ assert!(!out.report.done);
+ let out = step(&db, &s, r.path().into(), None, &cancel).unwrap();
+ assert!(!out.report.done);
+ let changed = r.path().join("a").join("one.txt");
+ fs::write(&changed, "changed after branch a was checked").unwrap();
+ let mut reconciler = Reconciler::default();
+ reconciler.request_recovery(r.path().into());
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ if let Some(report) = reconciler.poll(&db, &s, true) {
+ if report.unwrap().done {
+ break;
+ }
+ }
+ assert!(Instant::now() < deadline);
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(
+ db.connect(true)
+ .unwrap()
+ .query_row(
+ "SELECT count(*) FROM native_changes WHERE path=?1",
+ [changed.to_string_lossy().as_ref()],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 1
+ );
+ }
+ #[test]
+ fn interrupted_listing_restarts_safely_and_missing_share_does_not_delete_index() {
+ let (_h, r, s, db) = fixture();
+ for i in 0..300 {
+ let p = r.path().join(format!("file-{i}.txt"));
+ fs::write(&p, "same").unwrap();
+ indexed(&db, &s, &p);
+ }
+ let cancel = AtomicBool::new(false);
+ let out = step(&db, &s, r.path().into(), None, &cancel).unwrap();
+ assert!(!out.report.done);
+ drop(out);
+ let mut cursor = None;
+ for _ in 0..10 {
+ let out = step(&db, &s, r.path().into(), cursor, &cancel).unwrap();
+ if out.report.done {
+ break;
+ }
+ cursor = out.cursor;
+ }
+ assert_eq!(
+ db.connect(true)
+ .unwrap()
+ .query_row("SELECT count(*) FROM native_changes", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ assert!(step(&db, &s, r.path().join("unavailable"), None, &cancel).is_err());
+ assert_eq!(db.stats().unwrap().files, 300);
+ }
+}
+
+#[cfg(test)]
+mod request_tests {
+ use super::*;
+ #[test]
+ fn disable_periodic_preserves_required_recovery_and_full_coverage_preserves_new_gaps() {
+ let mut r = Reconciler::default();
+ let a = PathBuf::from("periodic");
+ let b = PathBuf::from("old-gap");
+ let c = PathBuf::from("new-gap");
+ r.request(a.clone());
+ r.request_recovery(b.clone());
+ r.disable_periodic();
+ assert!(!r.has_root(&a));
+ assert!(r.has_root(&b));
+ r.request_recovery(c.clone());
+ r.requests.get_mut(&b).unwrap().1 = 100;
+ r.requests.get_mut(&c).unwrap().1 = 300;
+ let retired = r.covered_before(200);
+ assert!(retired.contains(&b));
+ assert!(r.has_root(&c));
+ assert!(r.pending());
+ }
+}
+
+#[cfg(test)]
+mod live_share_tests {
+ use super::*;
+ #[test]
+ #[ignore = "Requires an explicitly supplied writable network test root; creates and removes only its own temporary folder"]
+ fn live_network_metadata_reconciliation_queues_one_new_and_three_updates() {
+ let share = std::env::var("VECTORDASH_TEST_NETWORK_ROOT").unwrap();
+ let root = tempfile::Builder::new()
+ .prefix("VectorDash-network-QA-")
+ .tempdir_in(share)
+ .unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ encrypt_index: false,
+ include_hidden: true,
+ skip_windows_churn: false,
+ roots: vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }],
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for n in 0..3 {
+ let path = root.path().join(format!("existing-{n}.txt"));
+ fs::write(&path, "before").unwrap();
+ let m = fs::metadata(&path).unwrap();
+ let mt = m
+ .modified()
+ .unwrap()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ .min(i64::MAX as u128) as i64;
+ Database::touch_name(&c, &path, "file", mt, m.len(), "quick", &s.roots[0].path, 1)
+ .unwrap();
+ fs::write(&path, "after with a different length").unwrap();
+ }
+ drop(c);
+ fs::write(root.path().join("new.txt"), "new").unwrap();
+ let mut cursor = None;
+ let cancel = AtomicBool::new(false);
+ for _ in 0..20 {
+ let out = step(&db, &s, root.path().into(), cursor, &cancel).unwrap();
+ if out.report.done {
+ break;
+ }
+ cursor = out.cursor;
+ }
+ let c = db.connect(true).unwrap();
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM native_changes", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 4
+ );
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM native_changes WHERE path=?1",
+ [root.path().to_string_lossy().as_ref()],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 0
+ );
+ }
+}
+
+#[cfg(test)]
+mod query_plan_tests {
+ use super::*;
+ #[test]
+ fn missing_child_lookup_uses_the_full_seen_key_instead_of_scanning_each_listing() {
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ encrypt_index: false,
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ schema(&c).unwrap();
+ let mut stmt=c.prepare("EXPLAIN QUERY PLAN SELECT path FROM names WHERE parent=?1 COLLATE NOCASE AND NOT EXISTS(SELECT 1 FROM native_network_seen s WHERE s.root=?2 AND s.directory=?1 AND s.path=names.path COLLATE NOCASE) LIMIT 256").unwrap();
+ let plan = stmt
+ .query_map(params!["parent", "root"], |r| r.get::<_, String>(3))
+ .unwrap()
+ .collect::<rusqlite::Result<Vec<_>>>()
+ .unwrap()
+ .join("\n");
+ assert!(plan.contains("names_parent_network"));
+ assert!(plan.contains("root=? AND directory=? AND path=?"), "{plan}");
+ }
+}
diff --git a/native/src/platform.rs b/native/src/platform.rs
index 5814acc..2b7fe36 100644
--- a/native/src/platform.rs
+++ b/native/src/platform.rs
@@ -396,6 +396,7 @@ pub fn actions(q: &str, s: &Settings) -> Vec<Hit> {
] {
if name.contains(query.trim_start_matches("settings: ")) {
out.push(Hit {
+ evidence: Vec::new(),
path: uri.into(),
kind: "settings".into(),
text: name.into(),
@@ -1451,6 +1452,7 @@ fn scan_programs() -> Vec<Hit> {
.to_string_lossy()
.into_owned();
out.push(Hit {
+ evidence: Vec::new(),
path: entry.path().to_string_lossy().into_owned(),
kind: "application".into(),
text: name,
@@ -1474,6 +1476,7 @@ fn scan_programs() -> Vec<Hit> {
.join(file);
if path.exists() {
out.push(Hit {
+ evidence: Vec::new(),
path: path.to_string_lossy().into_owned(),
kind: "application".into(),
text: name.into(),
@@ -1922,6 +1925,7 @@ fn store_apps() -> Result<Vec<Hit>> {
CoTaskMemFree(Some(parsing.0 as *const _));
let id = path.rsplit('\\').next().unwrap_or(&path);
out.push(Hit {
+ evidence: Vec::new(),
path: format!("shell:AppsFolder\\{id}"),
kind: "application".into(),
text: name,
@@ -3330,3 +3334,32 @@ mod search_path_regression_tests {
assert!(missing_local_file(file.to_str().unwrap()));
}
}
+
+/// Queue the standard Windows minimize system command, independently of the
+/// UI framework's viewport state. Never activates/restores the target window.
+pub fn minimize_main_window_native() -> bool {
+ #[cfg(windows)]
+ {
+ use windows::Win32::{
+ Foundation::{HWND, LPARAM, WPARAM},
+ UI::WindowsAndMessaging::{PostMessageW, SC_MINIMIZE, WM_SYSCOMMAND},
+ };
+ let value = MAIN_WINDOW.load(std::sync::atomic::Ordering::Acquire);
+ if value == 0 {
+ return false;
+ }
+ unsafe {
+ PostMessageW(
+ Some(HWND(value as *mut _)),
+ WM_SYSCOMMAND,
+ WPARAM(SC_MINIMIZE as usize),
+ LPARAM(0),
+ )
+ .is_ok()
+ }
+ }
+ #[cfg(not(windows))]
+ {
+ false
+ }
+}
diff --git a/native/src/retrieval.rs b/native/src/retrieval.rs
new file mode 100644
index 0000000..1ee2ef3
--- /dev/null
+++ b/native/src/retrieval.rs
@@ -0,0 +1,299 @@
+//! Bounded evidence selection. Similarity is candidate evidence, never a factual confidence.
+use crate::db::Hit;
+use std::collections::HashMap;
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Channel {
+ Any,
+ Visual,
+ Audio,
+}
+impl Channel {
+ pub fn allows(self, kind: &str) -> bool {
+ match self {
+ Self::Any => true,
+ Self::Visual => kind == "video",
+ Self::Audio => kind == "video_audio",
+ }
+ }
+}
+#[derive(Debug)]
+pub struct Plan {
+ pub parts: Vec<(String, Channel)>,
+ pub ordered: bool,
+}
+/// Only explicit video conjunction/order syntax triggers additional embeddings (at most three).
+pub fn plan(query: &str, category: &str) -> Option<Plan> {
+ let q = query.to_lowercase();
+ if category != "Videos" && !["video", "画面", "视频"].iter().any(|w| q.contains(w)) {
+ return None;
+ }
+ for marker in [
+ ", while ",
+ " while ",
+ ",声音",
+ ",英文音轨",
+ ",音轨",
+ ",声音却",
+ ",声音在",
+ ] {
+ if let Some((a, b)) = q.split_once(marker) {
+ if a.chars().count() >= 4 && b.chars().count() >= 4 {
+ return Some(Plan {
+ parts: vec![(a.into(), Channel::Visual), (b.into(), Channel::Audio)],
+ ordered: false,
+ });
+ }
+ }
+ }
+ let normalized = q
+ .replace(" followed by ", " then ")
+ .replace(", then ", " then ")
+ .replace("紧接着切换为", " then ")
+ .replace("紧接着", " then ")
+ .replace("最后切到", " then ")
+ .replace("然后", " then ");
+ let normalized = if normalized.contains("依次") {
+ normalized
+ .replace('、', " then ")
+ .replace(",最后", " then ")
+ } else {
+ normalized
+ };
+ let parts: Vec<_> = normalized
+ .split(" then ")
+ .map(str::trim)
+ .filter(|p| !p.is_empty())
+ .collect();
+ if !(2..=3).contains(&parts.len()) || parts.iter().any(|p| p.chars().count() < 4) {
+ return None;
+ }
+ Some(Plan {
+ parts: parts
+ .into_iter()
+ .map(|p| (p.into(), Channel::Visual))
+ .collect(),
+ ordered: true,
+ })
+}
+pub fn evidence_reason(kind: &str, media: bool, exact: bool) -> &'static str {
+ match (kind, media, exact) {
+ ("video", false, true) => "Matches text visible in this video frame",
+ ("video", false, false) => "Matches OCR text from this video frame",
+ ("video", true, _) => "Matches this video frame visually",
+ ("video_audio", _, _) => "Matches audio near this timestamp",
+ (_, _, true) => "Matches exact words and meaning",
+ ("image", true, _) => "Matches the picture",
+ (_, true, _) => "Matches this media moment",
+ _ => "Matches the meaning of this passage",
+ }
+}
+pub fn best_per_file(mut hits: Vec<Hit>) -> Vec<Hit> {
+ hits.sort_by(|a, b| {
+ b.score
+ .total_cmp(&a.score)
+ .then_with(|| a.seconds.total_cmp(&b.seconds))
+ .then_with(|| a.kind.cmp(&b.kind))
+ });
+ let mut seen = std::collections::HashSet::new();
+ hits.retain(|h| seen.insert(h.path.clone()));
+ hits
+}
+/// Up to four moments per clause/file and at most 4^3 combinations per candidate.
+/// Ordered queries require distinct increasing timestamps; AV clauses must be within 30s.
+pub fn combine(base: Vec<Hit>, parts: Vec<Vec<Hit>>, ordered: bool) -> Vec<Hit> {
+ let mut by_part: Vec<HashMap<String, Vec<Hit>>> = vec![];
+ for mut hits in parts {
+ hits.sort_by(|a, b| b.score.total_cmp(&a.score));
+ let mut map: HashMap<String, Vec<Hit>> = HashMap::new();
+ for h in hits {
+ let list = map.entry(h.path.clone()).or_default();
+ if list.len() < 4
+ && h.seconds >= 0.0
+ && h.score >= 0.35
+ && list.first().is_none_or(|best| h.score >= best.score - 0.12)
+ {
+ list.push(h);
+ }
+ }
+ by_part.push(map);
+ }
+ let mut output = HashMap::new();
+ for mut h in best_per_file(base) {
+ h.score -= 0.18;
+ h.reason = "Partial evidence; all requested conditions are not established".into();
+ output.insert(h.path.clone(), h);
+ }
+ if !(2..=3).contains(&by_part.len()) {
+ return output.into_values().collect();
+ }
+ for (path, first) in &by_part[0] {
+ if by_part.iter().any(|p| !p.contains_key(path)) {
+ continue;
+ }
+ let mut best: Option<(f32, Vec<&Hit>)> = None;
+ for a in first {
+ for b in &by_part[1][path] {
+ let third: Vec<Option<&Hit>> = if by_part.len() == 3 {
+ by_part[2][path].iter().map(Some).collect()
+ } else {
+ vec![None]
+ };
+ for c in third {
+ let mut selected = vec![a, b];
+ if let Some(c) = c {
+ selected.push(c);
+ }
+ let valid = if ordered {
+ selected
+ .windows(2)
+ .all(|p| p[1].seconds > p[0].seconds + 0.1)
+ } else {
+ let lo = selected
+ .iter()
+ .map(|h| h.seconds)
+ .fold(f32::INFINITY, f32::min);
+ let hi = selected.iter().map(|h| h.seconds).fold(0.0, f32::max);
+ hi - lo <= 30.0
+ };
+ if !valid {
+ continue;
+ }
+ let weakest = selected
+ .iter()
+ .map(|h| h.score)
+ .fold(f32::INFINITY, f32::min);
+ let mean =
+ selected.iter().map(|h| h.score).sum::<f32>() / selected.len() as f32;
+ let score = 0.7 * weakest + 0.3 * mean;
+ if best.as_ref().is_none_or(|(s, _)| score > *s) {
+ best = Some((score, selected));
+ }
+ }
+ }
+ }
+ if let Some((score, selected)) = best {
+ let mut h = selected[0].clone();
+ h.score = score;
+ h.evidence = selected
+ .iter()
+ .flat_map(|h| h.evidence.iter().cloned())
+ .take(3)
+ .collect();
+ h.reason = if ordered {
+ "Candidate visual evidence in the requested time order"
+ } else {
+ "Candidate visual and audio evidence within 30 seconds"
+ }
+ .into();
+ h.text = selected
+ .iter()
+ .enumerate()
+ .map(|(i, h)| {
+ format!(
+ "Evidence {} at {:.1}s — {}{}",
+ i + 1,
+ h.seconds,
+ h.reason,
+ if h.text.is_empty() {
+ String::new()
+ } else {
+ format!(": {}", h.text.chars().take(1000).collect::<String>())
+ }
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ output.insert(path.clone(), h);
+ }
+ }
+ output.into_values().collect()
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn hit(path: &str, t: f32, score: f32, kind: &str) -> Hit {
+ Hit {
+ evidence: Vec::new(),
+ path: path.into(),
+ kind: kind.into(),
+ text: String::new(),
+ score,
+ reason: "candidate".into(),
+ seconds: t,
+ page: 0,
+ line: 0,
+ }
+ }
+ #[test]
+ fn ordered_rerank_rejects_reverse_and_same_frame_controls() {
+ let parts = vec![
+ vec![
+ hit("right", 0., 0.8, "video"),
+ hit("reverse", 10., 0.9, "video"),
+ hit("same", 0., 0.9, "video"),
+ ],
+ vec![
+ hit("right", 10., 0.8, "video"),
+ hit("reverse", 0., 0.9, "video"),
+ hit("same", 0., 0.9, "video"),
+ ],
+ ];
+ let out = combine(vec![], parts, true);
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].path, "right");
+ assert_eq!(out[0].seconds, 0.);
+ assert!(out[0].text.contains("10.0s"));
+ }
+ #[test]
+ fn cross_modal_requires_both_and_proximity_and_weakest_link() {
+ let out = combine(
+ vec![],
+ vec![
+ vec![
+ hit("both", 5., 0.8, "video"),
+ hit("remote", 0., 0.9, "video"),
+ hit("visual_only", 0., 0.99, "video"),
+ ],
+ vec![
+ hit("both", 10., 0.7, "video_audio"),
+ hit("remote", 90., 0.9, "video_audio"),
+ ],
+ ],
+ false,
+ );
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].path, "both");
+ assert!(out[0].score < 0.75);
+ assert!(!Channel::Visual.allows("video_audio"));
+ assert!(Channel::Visual.allows("video"));
+ }
+ #[test]
+ fn query_plans_are_explicit_bounded_and_multilingual() {
+ assert!(plan("dogs and cats", "Images").is_none());
+ assert!(
+ plan("video forest then a golden dog then ocean", "Videos")
+ .unwrap()
+ .ordered
+ );
+ assert_eq!(
+ plan("画面有金色狗,声音在讲合唱排练", "Videos")
+ .unwrap()
+ .parts[1]
+ .1,
+ Channel::Audio
+ );
+ assert!(
+ plan(
+ "find video forest then dog then ocean then mountains",
+ "Videos"
+ )
+ .is_none()
+ );
+ assert!(plan("find notes then edit them", "Documents").is_none());
+ }
+ #[test]
+ fn evidence_labels_never_call_audio_a_visual_identifier() {
+ assert!(evidence_reason("video_audio", true, false).contains("audio"));
+ assert!(evidence_reason("video", false, true).contains("visible"));
+ }
+}
diff --git a/native/src/rtf.rs b/native/src/rtf.rs
new file mode 100644
index 0000000..18f5955
--- /dev/null
+++ b/native/src/rtf.rs
@@ -0,0 +1,171 @@
+//! Small bounded RTF text reader: no external programs, links or embedded objects are opened.
+#[derive(Clone, Copy)]
+struct State {
+ skip: bool,
+ uc: usize,
+}
+pub fn visible_text(source: &str) -> String {
+ if !source.trim_start().starts_with("{\\rtf") {
+ return source.into();
+ }
+ let b = source.as_bytes();
+ let mut i = 0;
+ let mut state = State { skip: false, uc: 1 };
+ let mut stack = Vec::new();
+ let mut out: Vec<u16> = Vec::new();
+ let mut fallback = 0usize;
+ let mut encoding = encoding_rs::WINDOWS_1252;
+ while i < b.len() {
+ match b[i] {
+ b'{' => {
+ if stack.len() >= 256 {
+ break;
+ }
+ stack.push(state);
+ i += 1;
+ }
+ b'}' => {
+ state = stack.pop().unwrap_or(State { skip: false, uc: 1 });
+ i += 1;
+ }
+ b'\r' | b'\n' => i += 1,
+ b'\\' => {
+ i += 1;
+ if i >= b.len() {
+ break;
+ }
+ if b[i] == b'*' {
+ state.skip = true;
+ i += 1;
+ continue;
+ }
+ if b[i] == b'\'' && i + 2 < b.len() {
+ let mut bytes = vec![];
+ while i + 2 < b.len() && b[i] == b'\'' {
+ if let Ok(v) = u8::from_str_radix(
+ std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""),
+ 16,
+ ) {
+ bytes.push(v);
+ }
+ i += 3;
+ if i + 1 < b.len() && b[i] == b'\\' && b[i + 1] == b'\'' {
+ i += 1;
+ } else {
+ break;
+ }
+ }
+ if fallback > 0 {
+ let n = fallback.min(bytes.len());
+ fallback -= n;
+ bytes.drain(..n);
+ }
+ if !state.skip {
+ out.extend(encoding.decode(&bytes).0.encode_utf16());
+ }
+ continue;
+ }
+ if !b[i].is_ascii_alphabetic() {
+ let c = match b[i] {
+ b'\\' => Some('\\'),
+ b'{' => Some('{'),
+ b'}' => Some('}'),
+ b'~' => Some(' '),
+ b'_' => Some('-'),
+ _ => None,
+ };
+ if fallback > 0 {
+ fallback -= 1;
+ } else if !state.skip {
+ if let Some(c) = c {
+ out.extend(c.encode_utf16(&mut [0; 2]).iter().copied());
+ }
+ }
+ i += 1;
+ continue;
+ }
+ let start = i;
+ while i < b.len() && b[i].is_ascii_alphabetic() {
+ i += 1;
+ }
+ let word = &source[start..i];
+ let start = i;
+ if i < b.len() && b[i] == b'-' {
+ i += 1;
+ }
+ while i < b.len() && b[i].is_ascii_digit() {
+ i += 1;
+ }
+ let n = source[start..i].parse::<i32>().ok();
+ if i < b.len() && b[i] == b' ' {
+ i += 1;
+ }
+ match word {
+ "fonttbl" | "colortbl" | "stylesheet" | "info" | "pict" | "object"
+ | "header" | "footer" | "filetbl" | "datastore" | "themedata" | "fldinst" => {
+ state.skip = true
+ }
+ "bin" => {
+ i = i
+ .saturating_add(n.unwrap_or(0).max(0) as usize)
+ .min(b.len())
+ }
+ "ansicpg" => {
+ let label = format!("windows-{}", n.unwrap_or(1252));
+ encoding = encoding_rs::Encoding::for_label(label.as_bytes())
+ .unwrap_or(encoding_rs::WINDOWS_1252);
+ }
+ "uc" => state.uc = n.unwrap_or(1).clamp(0, 16) as usize,
+ "u" => {
+ if !state.skip {
+ out.push(n.unwrap_or(0) as u16);
+ }
+ fallback = state.uc;
+ }
+ "par" | "line" if !state.skip => out.push(b'\n' as u16),
+ "tab" if !state.skip => out.push(b'\t' as u16),
+ "emdash" if !state.skip => out.push(0x2014),
+ "endash" if !state.skip => out.push(0x2013),
+ "bullet" if !state.skip => out.push(0x2022),
+ _ => {}
+ }
+ }
+ _ => {
+ let Some(rest) = source.get(i..) else {
+ break;
+ };
+ let c = rest.chars().next().unwrap();
+ i += c.len_utf8();
+ if fallback > 0 {
+ fallback -= 1;
+ } else if !state.skip {
+ out.extend(c.encode_utf16(&mut [0; 2]).iter().copied());
+ }
+ }
+ }
+ }
+ String::from_utf16_lossy(&out)
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn extracts_unicode_text_without_tables_or_hidden_payloads() {
+ let s = r"{\rtf1\ansi{\fonttbl{\f0 Arial;}}{\*\generator hidden;}\uc1\u21518?\u21049?\u36710? cable\par replace {\b inner wire}{\pict garbage}}";
+ assert_eq!(visible_text(s), "后刹车 cable\nreplace inner wire");
+ }
+ #[test]
+ fn decodes_escapes_fields_surrogates_and_binary() {
+ assert_eq!(
+ visible_text(
+ r"{\rtf1 caf\'e9 \{x\} {\field{\*\fldinst HYPERLINK secret}{\fldrslt label}}\u-10179?\u-8704?{\pict\bin3 abc}}"
+ ),
+ "café {x} label😀"
+ );
+ }
+ #[test]
+ fn plain_text_is_untouched_and_truncated_rtf_is_safe() {
+ assert_eq!(visible_text("plain {text}"), "plain {text}");
+ assert_eq!(visible_text(r"{\rtf1 hello\"), "hello");
+ }
+}
diff --git a/native/src/stability_tests.rs b/native/src/stability_tests.rs
index 9803736..4735106 100644
--- a/native/src/stability_tests.rs
+++ b/native/src/stability_tests.rs
@@ -1017,3 +1017,192 @@ fn async_search_omits_deleted_local_results_without_waiting_for_reindex() {
"A search must not mutate the index"
);
}
+
+#[test]
+fn video_identifier_selects_ocr_time_in_cached_and_low_memory_search() {
+ for performance in ["Low memory", "Balanced"] {
+ let (_home, root, mut settings, engine, _) = fixture();
+ settings.performance = performance.into();
+ let path = root.path().join("evidence.mp4");
+ add(&engine, &settings, &path, "placeholder");
+ let records = vec![
+ crate::content::Segment {
+ kind: "video_audio".into(),
+ text: String::new(),
+ page: 0,
+ seconds: 0.,
+ line: 0,
+ media: vec![1],
+ },
+ crate::content::Segment {
+ kind: "video".into(),
+ text: "VN-5103".into(),
+ page: 0,
+ seconds: 10.,
+ line: 0,
+ media: vec![],
+ },
+ ];
+ Database::save_segments(
+ &engine.db.connect(false).unwrap(),
+ &path.to_string_lossy(),
+ &records,
+ &[vec![1., 0.], vec![0.9, 0.43589]],
+ "fixture",
+ )
+ .unwrap();
+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
+ settings.remote_url = format!("http://{}", server.server_addr());
+ let reply = std::thread::spawn(move || {
+ let r = server
+ .recv_timeout(Duration::from_secs(10))
+ .unwrap()
+ .unwrap();
+ r.respond(tiny_http::Response::from_string(
+ r#"{"data":[{"index":0,"embedding":[1,0]}]}"#,
+ ))
+ .unwrap();
+ });
+ let hits = engine
+ .search_inner("VN-5103", &settings, "Semantic", "Videos", "", "")
+ .unwrap();
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].seconds, 10.);
+ assert_eq!(hits[0].kind, "video");
+ assert_eq!(hits[0].evidence[0].source, "video_ocr");
+ assert!(hits[0].reason.contains("visible"));
+ reply.join().unwrap();
+ }
+}
+#[test]
+fn ordered_video_search_reranks_reverse_control_and_returns_both_moments() {
+ use std::io::Read;
+ let (_home, root, mut settings, engine, _) = fixture();
+ settings.rank_calibration = false;
+ for (name, times) in [("forward.mp4", [0., 10.]), ("reverse.mp4", [10., 0.])] {
+ let path = root.path().join(name);
+ add(&engine, &settings, &path, "placeholder");
+ let records = times
+ .into_iter()
+ .map(|seconds| crate::content::Segment {
+ kind: "video".into(),
+ text: String::new(),
+ page: 0,
+ seconds,
+ line: 0,
+ media: vec![1],
+ })
+ .collect::<Vec<_>>();
+ Database::save_segments(
+ &engine.db.connect(false).unwrap(),
+ &path.to_string_lossy(),
+ &records,
+ &[vec![1., 0.], vec![0., 1.]],
+ "fixture",
+ )
+ .unwrap();
+ }
+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
+ settings.remote_url = format!("http://{}", server.server_addr());
+ let reply = std::thread::spawn(move || {
+ for _ in 0..3 {
+ let mut r = server
+ .recv_timeout(Duration::from_secs(10))
+ .unwrap()
+ .unwrap();
+ let mut body = String::new();
+ r.as_reader().read_to_string(&mut body).unwrap();
+ let vector = if body.contains("then") {
+ vec![0.707107, 0.707107]
+ } else if body.contains("forest") {
+ vec![1., 0.]
+ } else {
+ vec![0., 1.]
+ };
+ r.respond(tiny_http::Response::from_string(
+ serde_json::json!({"data":[{"index":0,"embedding":vector}]}).to_string(),
+ ))
+ .unwrap();
+ }
+ });
+ let hits = engine
+ .search_inner(
+ "video forest then golden dog",
+ &settings,
+ "Semantic",
+ "Videos",
+ "",
+ "",
+ )
+ .unwrap();
+ assert!(hits[0].path.ends_with("forward.mp4"));
+ assert_eq!(hits[0].evidence.len(), 2);
+ assert_eq!(hits[0].evidence[0].seconds, 0.);
+ assert_eq!(hits[0].evidence[1].seconds, 10.);
+ assert!(
+ hits.iter()
+ .find(|h| h.path.ends_with("reverse.mp4"))
+ .unwrap()
+ .reason
+ .contains("Partial")
+ );
+ reply.join().unwrap();
+}
+
+#[test]
+#[ignore = "Requires an explicit isolated synthetic benchmark profile and embedding backend"]
+fn synthetic_retrieval_benchmark_records_real_backend_results() {
+ use std::io::Write;
+ let home = std::path::PathBuf::from(std::env::var("VECTORDASH_BENCHMARK_HOME").unwrap());
+ assert!(
+ home.join("synthetic-benchmark.flag").is_file(),
+ "Refusing a non-test profile"
+ );
+ let s = Settings::load(&home).unwrap();
+ let truth: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(home.join("ground-truth.json")).unwrap()).unwrap();
+ let queries = truth["queries"].as_array().unwrap();
+ assert!(!queries.is_empty());
+ let db = Database::new(&home, &s).unwrap();
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let engine = Engine {
+ db,
+ models: Models::default(),
+ control: Control::default(),
+ tx: tx.into(),
+ searching: Arc::new(AtomicBool::new(false)),
+ vectors: crate::vector_cache::Cache::default(),
+ };
+ let began = Instant::now();
+ engine.index(s.clone(), false);
+ loop {
+ match rx.recv_timeout(Duration::from_secs(180)).unwrap() {
+ Event::IndexDone(result) => {
+ println!("index: {}", result.unwrap());
+ break;
+ }
+ Event::Log(level, text) => println!("{level}: {text}"),
+ _ => {}
+ }
+ }
+ let index_ms = began.elapsed().as_secs_f64() * 1000.;
+ let mut out = std::fs::File::create(home.join("results.jsonl")).unwrap();
+ for q in queries {
+ let category = match q["category"].as_str().unwrap() {
+ "image" => "Images",
+ "video" => "Videos",
+ _ => "Documents",
+ };
+ let began = Instant::now();
+ let hits = engine
+ .search_inner(q["query"].as_str().unwrap(), &s, "Both", category, "", "")
+ .unwrap();
+ let record = serde_json::json!({"query":q,"response":{"results":hits,"ok":true},"elapsed_ms":began.elapsed().as_secs_f64()*1000.});
+ writeln!(out, "{record}").unwrap();
+ }
+ engine.models.stop().unwrap();
+ println!(
+ "benchmark: {}",
+ serde_json::json!({"files":engine.db.stats().unwrap().files,"queries":queries.len(),"index_ms":index_ms,"version":env!("CARGO_PKG_VERSION"),"category_scoped":true})
+ );
+}
diff --git a/native/vendor/notify/VECTORDASH-PATCH.md b/native/vendor/notify/VECTORDASH-PATCH.md
index 2b43237..153e307 100644
--- a/native/vendor/notify/VECTORDASH-PATCH.md
+++ b/native/vendor/notify/VECTORDASH-PATCH.md
@@ -5,3 +5,5 @@ Source: crates.io notify 8.2.0, CC0-1.0 (LICENSE-CC0 retained).
Only src/windows.rs changes. ReadDirectoryChangesW startup/completion failures now reach the application callback with the originating watched root before the backend removes the watch. Successful zero-byte completions produce a root-scoped Rescan event after rearming, instead of parsing an empty buffer. VectorDash retries the failed watch independently with capped backoff and reconciles only its source on reconnection. Normal notifications and non-Windows implementations remain upstream code.
Remove this patch after equivalent upstream fixes are available. Validate real directory create/delete/rename delivery, root removal/recreation and notification overflow before upgrading.
+
+The request buffer is now 64 KiB (the documented maximum for network-directory notifications), replacing upstream's 16 KiB buffer. VectorDash may use nonrecursive share-root watches plus bounded recursive branch watches to limit the scope of network notification overflow. Do not raise the buffer beyond 64 KiB for SMB.
diff --git a/native/vendor/notify/src/windows.rs b/native/vendor/notify/src/windows.rs
index b7849e5..4919429 100644
--- a/native/vendor/notify/src/windows.rs
+++ b/native/vendor/notify/src/windows.rs
@@ -37,7 +37,8 @@ use windows_sys::Win32::System::Threading::{
};
use windows_sys::Win32::System::IO::{CancelIo, OVERLAPPED};
-const BUF_SIZE: u32 = 16384;
+// SMB supports buffers up to 64 KiB; larger requests fail on network shares.
+const BUF_SIZE: u32 = 64 * 1024;
#[derive(Clone)]
struct ReadData {
diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.iss
index 42615ba..f4a5366 100644
--- a/packaging/VectorDash-Rust.iss
+++ b/packaging/VectorDash-Rust.iss
@@ -3,8 +3,8 @@ AppId={{C6AC1B4D-A119-4D73-B2C8-6C507DEFE923}
AppName=VectorDash
AppVerName=VectorDash
UninstallDisplayName=VectorDash
-AppVersion=0.3.45
-VersionInfoVersion=0.3.45.0
+AppVersion=0.3.46
+VersionInfoVersion=0.3.46.0
AppPublisher=VectorDash contributors
AppPublisherURL=https://github.com/ampersandru/VectorDash
DefaultDirName={localappdata}\Programs\VectorDash
@@ -14,7 +14,7 @@ ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
MinVersion=10.0.19041
OutputDir=..\dist\installer
-OutputBaseFilename=VectorDash-Rust-Setup-0.3.45-x64
+OutputBaseFilename=VectorDash-Rust-Setup-0.3.46-x64
SetupIconFile=VectorDash.ico
UninstallDisplayIcon={app}\VectorDash.exe
LicenseFile=..\LICENSE