Skip to content

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

Improve search responsiveness, targeted indexing recovery, and tray reliability (#18)

ampersandru05e07a99d94b
diff --git a/Build-Raw.ps1 b/Build-Raw.ps1
index 6d9a4c0..1df3419 100644
--- a/Build-Raw.ps1
+++ b/Build-Raw.ps1
@@ -11,6 +11,15 @@ Expand-Archive -LiteralPath $taskRawZip -DestinationPath $taskRawRoot -Force
$taskRawSource=Join-Path $taskRawRoot 'LibRaw-0.22.2'
$taskVswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe'
$taskVs=& $taskVswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+$taskUseDevShell=$false
+if (!$taskVs -and $env:VSINSTALLDIR -and $env:VSCMD_ARG_TGT_ARCH -eq 'x64') {
+ $taskCl=Get-Command cl.exe -ErrorAction SilentlyContinue
+ $taskCandidate=[IO.Path]::GetFullPath($env:VSINSTALLDIR)
+ if ($taskCl -and $taskCl.Source.StartsWith((Join-Path $taskCandidate 'VC'),[StringComparison]::OrdinalIgnoreCase)) {
+ $taskVs=$taskCandidate
+ $taskUseDevShell=$true
+ }
+}
if (!$taskVs) {throw 'MSVC C++ build tools required to build the isolated LibRaw adapter'}
$taskVcvars=Join-Path $taskVs 'VC/Auxiliary/Build/vcvars64.bat'
$taskRawOut=Join-Path $PSScriptRoot 'native/target/raw-decoder'
@@ -19,7 +28,10 @@ $taskCpp=Join-Path $PSScriptRoot 'native/raw/decode.cpp'
# Compilation only: no destructive filesystem operations are delegated to cmd.
$taskCompile='cl /nologo /std:c++17 /EHsc /O2 /MD /I"'+$taskRawSource+'" "'+$taskCpp+'" /Fo"'+$taskRawOut+'/decode.obj" /Fe"'+$taskRawOut+'/vectordash-raw.exe" /link "'+$taskRawSource+'/lib/libraw.lib"'
$taskBat=Join-Path $taskRawOut 'compile.cmd'
-@('@echo off',('call "'+$taskVcvars+'" >nul'),'if errorlevel 1 exit /b 1',$taskCompile,'exit /b %errorlevel%') | Set-Content -LiteralPath $taskBat -Encoding ascii
+$taskCommands=@('@echo off')
+if (!$taskUseDevShell) {$taskCommands+=('call "'+$taskVcvars+'" >nul');$taskCommands+='if errorlevel 1 exit /b 1'}
+$taskCommands+=@($taskCompile,'exit /b %errorlevel%')
+$taskCommands | Set-Content -LiteralPath $taskBat -Encoding ascii
& $env:ComSpec /d /c $taskBat
if ($LASTEXITCODE) {throw 'RAW adapter build failed'}
Copy-Item -LiteralPath (Join-Path $taskRawSource 'bin/libraw.dll') -Destination $taskRawOut -Force
diff --git a/Build-Rust.ps1 b/Build-Rust.ps1
index d1e132f..4c34917 100644
--- a/Build-Rust.ps1
+++ b/Build-Rust.ps1
@@ -49,6 +49,7 @@ Get-ChildItem -LiteralPath 'native/target/raw-decoder' -File | Where-Object {$_.
Copy-Item -LiteralPath LICENSE -Destination $taskBundle
$taskNotices=Join-Path $taskBundle 'licenses'
New-Item -ItemType Directory -Force $taskNotices | Out-Null
+Copy-Item -LiteralPath 'native/vendor/notify/VECTORDASH-PATCH.md' -Destination (Join-Path $taskNotices 'VectorDash-notify-PATCH.md')
$taskRawNotices=Join-Path $taskNotices 'LibRaw-0.22.2'
New-Item -ItemType Directory -Force $taskRawNotices | Out-Null
Copy-Item -LiteralPath '.build-tools/raw/LibRaw-0.22.2/LICENSE.CDDL','.build-tools/raw/LibRaw-0.22.2/COPYRIGHT','native/raw/NOTICE.txt' -Destination $taskRawNotices
@@ -92,8 +93,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.25-x64.zip' -Force
-$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.25-x64.exe'
-$taskZip='dist/installer/VectorDash-Rust-0.3.25-x64.zip'
+Compress-Archive -Path (Join-Path $taskPortable '*') -DestinationPath 'dist/installer/VectorDash-Rust-0.3.40-x64.zip' -Force
+$taskInstaller='dist/installer/VectorDash-Rust-Setup-0.3.40-x64.exe'
+$taskZip='dist/installer/VectorDash-Rust-0.3.40-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/README.md b/README.md
index a61ea6b..b149b7f 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@ Includes a clipboard manager, which lets you store copied text and images for a
- **Make it yours:** light/dark themes, app accent colors, popup tint/transparency/gradient, a collapsible icon sidebar. About includes updates and a changelog covering releases since your installed version.
- **Camera RAW (BETA):** optional ARW, CR2/CR3, DNG, RAF, NEF and other LibRaw-supported formats use embedded previews first, with optional development fallback; enable in Sources, save and update a Full source, and please test your camera files.
- **Interface localization (BETA):** 13 languages cover search, settings, help, dialogs and tray menus; native-speaker and complex-script testing is still needed.
-- **Indexing reliability:** file notifications stay targeted, interrupted chunks resume, inaccessible network subfolders do not stop accessible siblings, and completed manual scans satisfy older recovery work.
+- **Indexing reliability:** file notifications stay targeted, interrupted chunks resume, inaccessible network subfolders do not stop accessible siblings, and completed manual scans satisfy older recovery work. Notification overflows retain their source and use healthy NTFS journal replay; unreadable journal parents use targeted filename checks rather than drive-wide rescans. Deleted-file cleanup runs in small batches and reports its own removed-record count and elapsed time.
- **Search tuning (BETA):** optional FP16 semantic caching reduces vector RAM, while Rank Calibration adjusts cross-media ranking at search time without changing stored embeddings or requiring reindexing; test relevance on your own collection.
- **Resizable previews and picture grids:** Search and Clipboard dividers remember their widths, Images/Videos grids have a separate preview width, and video thumbnails load on demand into a bounded RAM cache.
- **Update channels:** choose Release or Beta in About, inspect changes since your installed version, and return to VectorDash automatically after a UI update.
@@ -74,9 +74,11 @@ Enable **Include Start menu programs** in Sources to search installed program sh
| **Quick** | File and folder names and paths; no file-content extraction or semantic embeddings. Faster indexing with lower resource use. | **No.** Quick indexing and filename searches work without an embedding model. | General files and folders, entire drives, and anything you mainly want to find by name or location. |
| **Full** | Names and paths, plus supported document contents and image, video and audio content according to your indexing settings. Takes more time and storage. | **Yes, by default.** Uses local EmbeddingGemma 2 or your configured remote embedding model to create semantic embeddings. | Images, videos, documents, audio and other supported files whose contents or meaning you want to search later. |
+**Search by folder path:** type `appdata\local` to find Local folders inside AppData, `\Local\RHI` to find RHI folders inside Local, or `\RHI\nvngx_dlssnr.dll` to find that file anywhere beneath an RHI folder. Matching ignores case, accepts `/` or `\`, and supports partial final names. Works with existing Quick and Full indexes without reindexing or an embedding model. Use `*nr*` for filename wildcards or `*\*nr*` for path wildcards. Quick sources can catalog names in AppData. **Exclude common Windows/cache folders** applies to both Quick and Full sources: saving it hides matching results and removes existing index records in the background. Other AppData names remain searchable in Quick sources. Explicit exclusions still apply. Run **Update index** after adding a source to make its files searchable.
+
**Recommended setup:** use Quick for broad drive coverage, then add specific media or document folders as Full sources. A more specific Full folder takes precedence over its parent Quick source. Exclusions and content-type settings still apply; unsupported files remain searchable by name.
-**At search time:** File/Folder Names search needs no model. Semantic search, and the semantic part of Hybrid search, need the configured embedding model running locally or remotely. Selecting Hybrid does not give Quick-indexed files content-based matches; use Full indexing for those. Local image/audio embedding also needs its matching encoder. You can select existing model files instead of downloading them. Changing the embedding model or encoder requires rebuilding the Full content index.
+**At search time:** File/Folder Names search needs no model. Semantic search, and the semantic part of Hybrid search, need the configured embedding model running locally or remotely. Selecting Hybrid does not give Quick-indexed files content-based matches; use Full indexing for those. Local image/audio embedding also needs its matching encoder. You can select existing model files instead of downloading them. Switching Local/Remote, server addresses or model file paths preserves the index. Use the same compatible model, dimensions, pooling and preprocessing on both backends; use **Rebuild full content** explicitly when changing to an incompatible model or encoder.
| Shortcut | Action |
| --- | --- |
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index 133d694..aa4aa2d 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -162,3 +162,26 @@ Live change notifications run targeted file/subtree updates without file countin
A dedicated hide-to-tray fixture reproduced 7.922 CPU-seconds over eight seconds (about one fully occupied core), despite rendering only nine frames before hiding. This traced to eframe 0.33.3 leaving ControlFlow::Poll set after a redraw deadline was drained. A hidden Windows window does not deliver the paint event that normally returns the loop to waiting. A local dependency patch explicitly returns to Wait when no repaint deadlines remain; its provenance is documented in native/vendor/eframe/VECTORDASH-PATCH.md. Hidden GUI work also stops constructing controls/painting, and preview textures are released.
After the event-loop patch, the same tray fixture used 0.0156 CPU-seconds over eight seconds (0.195% of one core), versus 7.9219 before (~99.8% reduction). Visible idle used 0.0625 CPU-seconds. A hide/reopen test restored query focus and returned a result. These are controlled development-PC GUI measurements; enabled watchers and background work add their own activity.
+
+
+### NTFS journal failures and recovery
+
+Journal readers retain their cursors after transient access, sharing or device errors. Each failed volume retries independently after 5, 10, 20, 40, 80, 160 and then at most 300 seconds; healthy volumes continue replaying. The monitor reports active readers and retrying volumes separately. Logs identify the drive, cursor, complete error chain, retry delay and successful resumption. Repeated unresolved-parent warnings are limited to once per minute per drive; recovery paths are still queued each time.
+
+Replay explicitly requests V2 records, matching the parser. An unresolved parent (for example, a directory deleted before replay) no longer aborts the whole batch or removes the reader: resolvable changes are retained, the cursor advances, and the affected drive's configured sources enter the durable targeted queue. A confirmed expired cursor or changed journal ID similarly queues only that drive's sources. Repeated malformed batches receive bounded retries before a scoped recovery and cursor reset; Windows access/I/O errors never reset a still-valid cursor. Recovery may still enumerate a large source on that drive when the original changed path cannot be recovered. Startup catch-up is now tracked per source: adding or reconnecting a network source does not invalidate healthy local journal coverage. Nested recovery requests are merged, and completed scopes acknowledge only the generations present when the scan began.
+
+Checkpoints preserve unavailable drives' previous durable cursors, and checkpoint failures are logged. Cursors advance durably only after successful indexing. Validation includes injected access-denied/offline/gap/malformed failures, backoff and checkpoint tests, plus live NTFS create/delete replay with a deleted parent. This does not establish that all six drives stay accessible on every system.
+
+References: [Microsoft READ_USN_JOURNAL_DATA_V1](https://learn.microsoft.com/en-us/windows/win32/api/winioctl/ns-winioctl-read_usn_journal_data_v1) documents version negotiation, expired cursors and journal-ID changes; [OpenFileById](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfilebyid) documents resolving a current file/directory identifier.
+
+
+The journal directory cache retains up to 4096 full file references with a 2 MiB estimated path/entry budget, plus a temporary checkpoint snapshot. It remembers deleted directories and updates cached descendant paths on directory moves. Discontinuous cursors invalidate the affected volume cache. Checkpoint snapshots are protected with Windows DPAPI when index encryption is enabled; cache failure only discards this optimization. NTFS volume-root metadata is filtered consistently in scanning, search and notification queues; existing stored metadata is purged through indexed path ranges without resetting an existing policy cleanup cursor.
+
+The local notify 8.2.0 Windows patch reports asynchronous failures with their watched root and emits a scoped Rescan on zero-byte overflow. Failed watches reattach independently with capped backoff and queue catch-up on reconnection. Folder-notification gaps with no known origin must conservatively reconcile monitored sources. An unknown parent absent from the bounded cache can still require recovery of that drive's configured sources; genuine gaps are never silently ignored.
+
+
+### Tray activation and status icons
+
+Tray open requests that encounter a full notification channel are retained in one shared atomic flag and consumed before normal UI notifications. Repeated requests coalesce without blocking the tray thread or creating retry threads. This fixes the reproduced case where the installed app accepted a double-click callback but stayed hidden while the hotkey still worked.
+
+The tray uses a transparent antialiased magnifier: the saved accent color while idle, yellow only when pending/running indexing is blocked by its applicable conditions or pause, and red while indexing is active. The background scheduler publishes this state even when the main window is hidden. Native icon updates occur only when the visual changes, with at most one failed refresh attempt per second, and replaced icon handles are destroyed. Shell version-4 callbacks, keyboard activation and Explorer restart notifications are supported; only the tray callback/restart messages are allowed through its window-specific message filter.
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 929b1ed..b40bdfe 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -3232,8 +3232,6 @@ dependencies = [
[[package]]
name = "notify"
version = "8.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
dependencies = [
"bitflags 2.13.2",
"fsevent-sys",
@@ -5716,7 +5714,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vectordash"
-version = "0.3.25"
+version = "0.3.40"
dependencies = [
"anyhow",
"arboard",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index 4c8b210..46d019c 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "vectordash"
-version = "0.3.25"
+version = "0.3.40"
edition = "2024"
license = "MIT"
[dependencies]
@@ -58,3 +58,4 @@ strip = true
[patch.crates-io]
eframe = { path = "vendor/eframe" }
+notify = { path = "vendor/notify" }
diff --git a/native/docs/0.3.40-beta.1.md b/native/docs/0.3.40-beta.1.md
new file mode 100644
index 0000000..be264ad
--- /dev/null
+++ b/native/docs/0.3.40-beta.1.md
@@ -0,0 +1,13 @@
+- Recovery scans: Notification overflows retain their affected source and use healthy NTFS journal replay instead of repeatedly scanning every configured drive.
+- Targeted journal recovery: Unreadable parent folders use live file IDs and bounded indexed-filename checks instead of triggering whole-drive rescans.
+- Startup recovery: Temporary journal-access failures retain saved cursors and wait for validation before requesting catch-up scans.
+- Recovery reliability: Unfinished targeted checks preserve their journal history across restarts, while confirmed missing history still triggers catch-up for the affected source.
+- NTFS tracking: Journal readers use bounded retries, retain valid cursors through temporary errors, and isolate failures to the affected drive.
+- Windows internal activity: Filter NTFS metadata activity and clean previously indexed internal records without broadening ordinary changes into drive scans.
+- Network drives: Network and unavailable drive mappings avoid inappropriate local-journal retry loops, with folder notifications providing change tracking.
+- Administrator access: Add journal-access information, a relaunch-as-administrator button, and an option to always start with administrator access.
+- Tray activation: Preserve open requests when the notification queue is full and improve double-click, keyboard, and Explorer restart handling.
+- Tray status: Restore the magnifying glass with the theme color for idle, yellow for waiting or paused indexing, and red for active indexing.
+- Diagnostics: Report the source and reason for recovery and explain when journal replay avoids a source rescan.
+- Validation: 250 automated tests passed, and live create/modify/delete tests with 4,500 injected overflow notifications queued no source-root rescans.
+- Beta status: Camera RAW support, localization, and Windows 10 support remain BETA and need additional testing.
diff --git a/native/docs/0.3.40.md b/native/docs/0.3.40.md
new file mode 100644
index 0000000..810ae2b
--- /dev/null
+++ b/native/docs/0.3.40.md
@@ -0,0 +1,24 @@
+- Search selection: Ctrl+F and new searches select the first result and scroll to the top instead of retaining a matching file from the previous search.
+- Path search: Find folders and files with fragments such as `\Local\RHI`, `appdata\local`, and `\RHI\nvngx_dlssnr.dll`, including partial names and filename/path wildcards.
+- Responsive Hybrid search: Filename and application results appear before semantic inference finishes, and a new query does not wait behind an obsolete embedding request.
+- Windows/cache exclusions: The checked setting now applies to Quick and Full sources, hides excluded results immediately after saving, and removes existing database records in background batches while preserving other Quick AppData names.
+- Hidden files: Sources now has an option to include hidden files and folders, enabled by default to preserve AppData searches.
+- Deleted-record cleanup: Indexed, atomic batches avoid repeated scans of unrelated content and vector tables when removing stale records.
+- Background disk activity: Metadata-only Quick updates no longer trigger a recount of the entire index after every notification batch.
+- Search memory: Hiding the search window releases its semantic cache, and replacing an obsolete cache releases the previous cached matrix first.
+- Embedding reuse: Switching between compatible local and remote deployments preserves completed embeddings unless files, extraction settings, or an explicit rebuild require processing.
+- Interrupted indexing: Obsolete queued jobs no longer override valid completed content, while genuinely incomplete files remain resumable.
+- Index status: Removed the duplicate indexing-phase label and refresh totals when exclusion cleanup finishes.
+- Recovery scans: Notification overflows retain their affected source and use healthy NTFS journal replay instead of repeatedly scanning every configured drive.
+- Targeted journal recovery: Unreadable parent folders use live file IDs and bounded indexed-filename checks instead of triggering whole-drive rescans.
+- Startup recovery: Temporary journal-access failures retain saved cursors and wait for validation before requesting catch-up scans.
+- Recovery reliability: Unfinished targeted checks preserve their journal history across restarts, while confirmed missing history still triggers catch-up for the affected source.
+- NTFS tracking: Journal readers use bounded retries, retain valid cursors through temporary errors, and isolate failures to the affected drive.
+- Windows internal activity: Filter NTFS metadata activity and clean previously indexed internal records without broadening ordinary changes into drive scans.
+- Network drives: Network and unavailable drive mappings avoid inappropriate local-journal retry loops, with folder notifications providing change tracking.
+- Administrator access: Add journal-access information, a relaunch-as-administrator button, and an option to always start with administrator access.
+- Tray activation: Preserve open requests when the notification queue is full and improve double-click, keyboard, and Explorer restart handling.
+- Tray status: Restore the magnifying glass with the theme color for idle, yellow for waiting or paused indexing, and red for active indexing.
+- Diagnostics: Report the source and reason for recovery and explain when journal replay avoids a source rescan.
+- Validation: 250 automated tests passed, and live create/modify/delete tests with 4,500 injected overflow notifications queued no source-root rescans.
+- Beta status: Camera RAW support, localization, and Windows 10 support remain BETA and need additional testing.
diff --git a/native/locales/de.json b/native/locales/de.json
index a3c6d91..433b938 100644
--- a/native/locales/de.json
+++ b/native/locales/de.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Englische Speech-to-Text",
"Warm embedding model when search opens": "Warmes Einbettungsmodell, wenn die Suche geöffnet wird",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Sendet eine kleine Einbettungsanfrage, wenn die Hybrid- oder semantische Suche geöffnet wird, bevor Sie etwas eingeben. Der Remote-Server benötigt möglicherweise einige Sekunden, um sein Modell zu laden.",
- "Warming embedding model…": "Wärmendes Einbettmodell…"
+ "Warming embedding model…": "Wärmendes Einbettmodell…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Der Wechsel zwischen Lokal und Remote behält vorhandene Embeddings bei. Verwenden Sie dasselbe Modell, dieselben Dimensionen sowie identisches Pooling und dieselbe Vorverarbeitung. Der Neuaufbau erfolgt manuell.",
+ "Include hidden files and folders": "Versteckte Dateien und Ordner einbeziehen",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Schließt Windows-, Temp- und Cache-Ordner aus Quick- und Full-Quellen aus. Quick-Quellen können andere AppData-Namen weiterhin durchsuchen. Speichern entfernt ausgeschlossene Einträge im Hintergrund aus dem Index.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Zum Lesen vorhandener Journale können Administratorrechte erforderlich sein. Die Anzahl zeigt aktive Leser.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Fehlende oder abgelaufene Journalpositionen und geänderte Quellen erfordern einen Nachholscan der betroffenen Quellen. Netzlaufwerke verwenden Ordnerbenachrichtigungen und quellenbezogene Nachholscans.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Speichern, um dies beim nächsten Start anzuwenden. Windows fragt nach Zustimmung. Zugeordnete Laufwerke sind mit erhöhten Rechten möglicherweise nicht verfügbar.",
+ "Always start as administrator": "Immer als Administrator starten",
+ "Running as administrator": "Wird als Administrator ausgeführt",
+ "Relaunch as administrator": "Als Administrator neu starten",
+ "Idle": "Leerlauf",
+ "Waiting for indexing conditions": "Warten auf Indexierungsbedingungen",
+ "Indexing": "Indizierung"
}
diff --git a/native/locales/en.json b/native/locales/en.json
index cdc4243..bbf2ba1 100644
--- a/native/locales/en.json
+++ b/native/locales/en.json
@@ -707,5 +707,17 @@
"English speech-to-text": "English speech-to-text",
"Warm embedding model when search opens": "Warm embedding model when search opens",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.",
- "Warming embedding model…": "Warming embedding model…"
+ "Warming embedding model…": "Warming embedding model…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.",
+ "Include hidden files and folders": "Include hidden files and folders",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Administrator access may be required to read existing journals. The count shows active readers.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.",
+ "Always start as administrator": "Always start as administrator",
+ "Running as administrator": "Running as administrator",
+ "Relaunch as administrator": "Relaunch as administrator",
+ "Idle": "Idle",
+ "Waiting for indexing conditions": "Waiting for indexing conditions",
+ "Indexing": "Indexing"
}
diff --git a/native/locales/es.json b/native/locales/es.json
index 6d19c7e..a06399b 100644
--- a/native/locales/es.json
+++ b/native/locales/es.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Inglés de voz a texto",
"Warm embedding model when search opens": "Modelo de incrustación cálida cuando se abre la búsqueda",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Envía una pequeña solicitud de incrustación cuando se abre la búsqueda híbrida o semántica, antes de escribir. Es posible que el servidor remoto necesite unos segundos para cargar su modelo.",
- "Warming embedding model…": "Modelo de incrustación de calentamiento…"
+ "Warming embedding model…": "Modelo de incrustación de calentamiento…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Cambiar entre Local y Remoto conserva los embeddings existentes. Usa el mismo modelo, dimensiones, agrupación y preprocesamiento. La reconstrucción es manual.",
+ "Include hidden files and folders": "Incluir archivos y carpetas ocultos",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Excluye las carpetas Windows, Temp y de caché de las fuentes Quick y Full. Las fuentes Quick aún pueden buscar otros nombres en AppData. Guarda para eliminar del índice los registros excluidos en segundo plano.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Puede requerirse acceso de administrador para leer diarios existentes. El recuento muestra lectores activos.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Las posiciones del diario ausentes o caducadas, o los cambios en las fuentes, requieren actualizar las fuentes afectadas. Las unidades de red usan notificaciones de carpetas y actualizaciones específicas de cada fuente.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Guarda para aplicar en el próximo inicio. Windows pedirá aprobación. Las unidades asignadas pueden no estar disponibles con privilegios elevados.",
+ "Always start as administrator": "Iniciar siempre como administrador",
+ "Running as administrator": "Ejecutándose como administrador",
+ "Relaunch as administrator": "Reiniciar como administrador",
+ "Idle": "Inactivo",
+ "Waiting for indexing conditions": "Esperando las condiciones de indexación",
+ "Indexing": "Indexando"
}
diff --git a/native/locales/fr.json b/native/locales/fr.json
index caf2ddc..5ed128d 100644
--- a/native/locales/fr.json
+++ b/native/locales/fr.json
@@ -707,5 +707,17 @@
"English speech-to-text": "synthèse vocale en anglais",
"Warm embedding model when search opens": "Modèle d'intégration chaleureux à l'ouverture de la recherche",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Envoie une petite demande d'intégration lorsque la recherche hybride ou sémantique s'ouvre, avant de taper. Le serveur distant peut avoir besoin de quelques secondes pour charger son modèle.",
- "Warming embedding model…": "Modèle d’intégration chauffant…"
+ "Warming embedding model…": "Modèle d’intégration chauffant…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Passer de Local à Distant conserve les embeddings existants. Utilisez le même modèle, les mêmes dimensions, pooling et prétraitement. La reconstruction est manuelle.",
+ "Include hidden files and folders": "Inclure les fichiers et dossiers cachés",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Exclut les dossiers Windows, Temp et de cache des sources Quick et Full. Les sources Quick peuvent toujours rechercher les autres noms dans AppData. Enregistrez pour supprimer les entrées exclues de l’index en arrière-plan.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Des droits administrateur peuvent être nécessaires pour lire les journaux existants. Le nombre indique les lecteurs actifs.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Les positions de journal manquantes ou expirées et les changements de sources nécessitent un rattrapage des sources concernées. Les lecteurs réseau utilisent les notifications de dossiers et un rattrapage par source.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Enregistrez pour appliquer au prochain lancement. Windows demandera une autorisation. Les lecteurs réseau mappés peuvent être indisponibles en mode administrateur.",
+ "Always start as administrator": "Toujours démarrer en tant qu’administrateur",
+ "Running as administrator": "Exécution en tant qu’administrateur",
+ "Relaunch as administrator": "Relancer en tant qu’administrateur",
+ "Idle": "Inactif",
+ "Waiting for indexing conditions": "En attente des conditions d’indexation",
+ "Indexing": "Indexation en cours"
}
diff --git a/native/locales/hi.json b/native/locales/hi.json
index 4852bfa..c8c55bd 100644
--- a/native/locales/hi.json
+++ b/native/locales/hi.json
@@ -707,5 +707,17 @@
"English speech-to-text": "अंग्रेजी भाषण-से-पाठ",
"Warm embedding model when search opens": "खोज खुलने पर वार्म एंबेडिंग मॉडल",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "आपके टाइप करने से पहले जब हाइब्रिड या सिमेंटिक खोज खुलती है तो एक छोटा एम्बेडिंग अनुरोध भेजता है। दूरस्थ सर्वर को अपना मॉडल लोड करने में कुछ सेकंड की आवश्यकता हो सकती है।",
- "Warming embedding model…": "वार्मिंग एम्बेडिंग मॉडल…"
+ "Warming embedding model…": "वार्मिंग एम्बेडिंग मॉडल…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "लोकल/रिमोट बदलने पर मौजूदा एम्बेडिंग सुरक्षित रहती हैं। समान मॉडल, आयाम, पूलिंग और प्रीप्रोसेसिंग का उपयोग करें। इंडेक्स का पुनर्निर्माण मैन्युअल है।",
+ "Include hidden files and folders": "छिपी फ़ाइलें और फ़ोल्डर शामिल करें",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Quick और Full स्रोतों से Windows, Temp और कैश फ़ोल्डर बाहर रखता है। Quick स्रोत AppData के अन्य नाम खोज सकते हैं। सहेजने पर बाहर रखे गए रिकॉर्ड पृष्ठभूमि में इंडेक्स से हटेंगे।",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "मौजूदा जर्नल पढ़ने के लिए व्यवस्थापक अधिकार आवश्यक हो सकते हैं। गिनती सक्रिय रीडर दिखाती है।",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "जर्नल स्थिति गायब या पुरानी होने या स्रोत बदलने पर प्रभावित स्रोतों की पूरक जाँच होती है। नेटवर्क ड्राइव फ़ोल्डर सूचनाओं और स्रोत-विशिष्ट पूरक जाँच का उपयोग करते हैं।",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "अगले लॉन्च पर लागू करने के लिए सहेजें। Windows अनुमति माँगेगा। व्यवस्थापक मोड में मैप की गई ड्राइव उपलब्ध न हो सकती हैं।",
+ "Always start as administrator": "हमेशा व्यवस्थापक के रूप में शुरू करें",
+ "Running as administrator": "व्यवस्थापक के रूप में चल रहा है",
+ "Relaunch as administrator": "व्यवस्थापक के रूप में पुनः शुरू करें",
+ "Idle": "निष्क्रिय",
+ "Waiting for indexing conditions": "अनुक्रमण की शर्तों की प्रतीक्षा",
+ "Indexing": "अनुक्रमण जारी है"
}
diff --git a/native/locales/it.json b/native/locales/it.json
index b73d62b..14ee710 100644
--- a/native/locales/it.json
+++ b/native/locales/it.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Discorso in testo inglese",
"Warm embedding model when search opens": "Modello di incorporamento a caldo all'apertura della ricerca",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Invia una piccola richiesta di incorporamento all'apertura della ricerca ibrida o semantica, prima della digitazione. Il server remoto potrebbe richiedere alcuni secondi per caricare il proprio modello.",
- "Warming embedding model…": "Modello di incorporamento del riscaldamento…"
+ "Warming embedding model…": "Modello di incorporamento del riscaldamento…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Passare da Locale a Remoto conserva gli embedding esistenti. Usa lo stesso modello, dimensioni, pooling e pre-elaborazione. La ricostruzione è manuale.",
+ "Include hidden files and folders": "Includi file e cartelle nascosti",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Esclude le cartelle Windows, Temp e cache dalle fonti Quick e Full. Le fonti Quick possono ancora cercare gli altri nomi in AppData. Salva per rimuovere in background i record esclusi dall’indice.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Potrebbero servire privilegi di amministratore per leggere i journal esistenti. Il conteggio indica i lettori attivi.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Le posizioni del diario mancanti o scadute e le modifiche alle origini richiedono un aggiornamento delle origini interessate. Le unità di rete usano notifiche delle cartelle e aggiornamenti per origine.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Salva per applicare al prossimo avvio. Windows chiederà conferma. Le unità mappate potrebbero non essere disponibili con privilegi elevati.",
+ "Always start as administrator": "Avvia sempre come amministratore",
+ "Running as administrator": "In esecuzione come amministratore",
+ "Relaunch as administrator": "Riavvia come amministratore",
+ "Idle": "Inattivo",
+ "Waiting for indexing conditions": "In attesa delle condizioni di indicizzazione",
+ "Indexing": "Indicizzazione in corso"
}
diff --git a/native/locales/ja.json b/native/locales/ja.json
index aa99a90..0011baf 100644
--- a/native/locales/ja.json
+++ b/native/locales/ja.json
@@ -707,5 +707,17 @@
"English speech-to-text": "英語の音声合成",
"Warm embedding model when search opens": "検索を開いたときのウォームエンベディングモデル",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "ハイブリッド検索またはセマンティック検索が開いたときに、入力する前に小さな埋め込みリクエストを送信します。リモート サーバーがモデルをロードするのに数秒かかる場合があります。",
- "Warming embedding model…": "埋め込みモデルを温めています…"
+ "Warming embedding model…": "埋め込みモデルを温めています…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "ローカルとリモートを切り替えても既存の埋め込みは保持されます。同じモデル、次元数、プーリング、前処理を使用してください。再構築は手動で行います。",
+ "Include hidden files and folders": "隠しファイルとフォルダーを含める",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Quick と Full の対象から Windows、Temp、キャッシュフォルダーを除外します。Quick では AppData 内の他の名前を引き続き検索できます。保存すると、除外されたレコードがバックグラウンドでインデックスから削除されます。",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "既存のジャーナルの読み取りに管理者権限が必要な場合があります。件数は動作中の読み取りを示します。",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "ジャーナル位置の欠落・期限切れやソースの変更時は、影響を受けたソースを補完スキャンします。ネットワークドライブはフォルダー通知とソースごとの補完スキャンを使用します。",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "保存すると次回起動時に適用されます。Windows が承認を求めます。管理者として実行すると、割り当てたドライブが利用できない場合があります。",
+ "Always start as administrator": "常に管理者として起動",
+ "Running as administrator": "管理者として実行中",
+ "Relaunch as administrator": "管理者として再起動",
+ "Idle": "待機中",
+ "Waiting for indexing conditions": "インデックス作成条件を待機中",
+ "Indexing": "インデックス作成中"
}
diff --git a/native/locales/ko.json b/native/locales/ko.json
index dd2aeae..4260753 100644
--- a/native/locales/ko.json
+++ b/native/locales/ko.json
@@ -707,5 +707,17 @@
"English speech-to-text": "영어 음성을 텍스트로",
"Warm embedding model when search opens": "검색이 열릴 때 웜 임베딩 모델",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "하이브리드 또는 의미 체계 검색이 열리면 입력하기 전에 작은 포함 요청을 보냅니다. 원격 서버가 해당 모델을 로드하는 데 몇 초가 필요할 수 있습니다.",
- "Warming embedding model…": "온난화 임베딩 모델…"
+ "Warming embedding model…": "온난화 임베딩 모델…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "로컬/원격 전환 시 기존 임베딩이 유지됩니다. 동일한 모델, 차원, 풀링 및 전처리 설정을 사용하세요. 재구축은 수동으로 실행합니다.",
+ "Include hidden files and folders": "숨김 파일 및 폴더 포함",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Quick 및 Full 소스에서 Windows, Temp 및 캐시 폴더를 제외합니다. Quick 소스는 AppData의 다른 이름을 계속 검색할 수 있습니다. 저장하면 제외된 레코드가 백그라운드에서 인덱스에서 삭제됩니다.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "기존 저널을 읽으려면 관리자 권한이 필요할 수 있습니다. 개수는 활성 저널 읽기를 나타냅니다.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "저널 위치가 없거나 만료되었거나 소스가 변경되면 해당 소스만 보완 검사합니다. 네트워크 드라이브는 폴더 알림과 소스별 보완 검사를 사용합니다.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "저장하면 다음 실행부터 적용됩니다. Windows가 승인을 요청합니다. 관리자 권한에서는 매핑된 드라이브를 사용하지 못할 수 있습니다.",
+ "Always start as administrator": "항상 관리자 권한으로 시작",
+ "Running as administrator": "관리자 권한으로 실행 중",
+ "Relaunch as administrator": "관리자 권한으로 다시 시작",
+ "Idle": "유휴",
+ "Waiting for indexing conditions": "색인 조건 대기 중",
+ "Indexing": "색인 생성 중"
}
diff --git a/native/locales/pt-BR.json b/native/locales/pt-BR.json
index eeaee2e..b18ac04 100644
--- a/native/locales/pt-BR.json
+++ b/native/locales/pt-BR.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Fala para texto em inglês",
"Warm embedding model when search opens": "Modelo de incorporação quente quando a pesquisa é aberta",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Envia uma pequena solicitação de incorporação quando a pesquisa híbrida ou semântica é aberta, antes de você digitar. O servidor remoto pode precisar de alguns segundos para carregar seu modelo.",
- "Warming embedding model…": "Modelo de incorporação de aquecimento…"
+ "Warming embedding model…": "Modelo de incorporação de aquecimento…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Alternar entre Local e Remoto preserva os embeddings existentes. Use o mesmo modelo, dimensões, pooling e pré-processamento. A reconstrução é manual.",
+ "Include hidden files and folders": "Incluir arquivos e pastas ocultos",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Exclui pastas Windows, Temp e cache das fontes Quick e Full. As fontes Quick ainda podem pesquisar outros nomes em AppData. Salve para remover os registros excluídos do índice em segundo plano.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Pode ser necessário acesso de administrador para ler diários existentes. A contagem mostra os leitores ativos.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Posições do diário ausentes ou expiradas e alterações nas fontes exigem atualização das fontes afetadas. Unidades de rede usam notificações de pastas e atualizações por fonte.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Salve para aplicar na próxima inicialização. O Windows pedirá aprovação. Unidades mapeadas podem ficar indisponíveis com privilégios elevados.",
+ "Always start as administrator": "Sempre iniciar como administrador",
+ "Running as administrator": "Executando como administrador",
+ "Relaunch as administrator": "Reiniciar como administrador",
+ "Idle": "Ocioso",
+ "Waiting for indexing conditions": "Aguardando condições de indexação",
+ "Indexing": "Indexando"
}
diff --git a/native/locales/ru.json b/native/locales/ru.json
index 0e5cbf0..39a375c 100644
--- a/native/locales/ru.json
+++ b/native/locales/ru.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Преобразование речи в текст на английском языке",
"Warm embedding model when search opens": "Теплая модель встраивания при открытии поиска",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Отправляет небольшой запрос на внедрение, когда открывается гибридный или семантический поиск, прежде чем вы вводите текст. Удаленному серверу может потребоваться несколько секунд для загрузки модели.",
- "Warming embedding model…": "Потепление модели встраивания…"
+ "Warming embedding model…": "Потепление модели встраивания…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Переключение между локальным и удалённым сервером сохраняет существующие эмбеддинги. Используйте одинаковую модель, размерность, пулинг и предобработку. Перестроение запускается вручную.",
+ "Include hidden files and folders": "Включать скрытые файлы и папки",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Исключает папки Windows, Temp и кэша из источников Quick и Full. Quick по-прежнему ищет другие имена в AppData. Сохраните, чтобы удалить исключённые записи из индекса в фоновом режиме.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Для чтения существующих журналов могут требоваться права администратора. Счётчик показывает активные считыватели.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "При отсутствии или устаревании позиций журнала либо изменении источников проверяются затронутые источники. Сетевые диски используют уведомления о папках и отдельную проверку каждого источника.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Сохраните для применения при следующем запуске. Windows запросит разрешение. Подключённые сетевые диски могут быть недоступны с повышенными правами.",
+ "Always start as administrator": "Всегда запускать от имени администратора",
+ "Running as administrator": "Запущено от имени администратора",
+ "Relaunch as administrator": "Перезапустить от имени администратора",
+ "Idle": "Бездействие",
+ "Waiting for indexing conditions": "Ожидание условий индексирования",
+ "Indexing": "Индексирование"
}
diff --git a/native/locales/vi.json b/native/locales/vi.json
index 913f383..986dd92 100644
--- a/native/locales/vi.json
+++ b/native/locales/vi.json
@@ -707,5 +707,17 @@
"English speech-to-text": "Chuyển giọng nói thành văn bản tiếng Anh",
"Warm embedding model when search opens": "Mô hình nhúng ấm khi tìm kiếm mở ra",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "Gửi một yêu cầu nhúng nhỏ khi tìm kiếm Kết hợp hoặc Ngữ nghĩa mở ra, trước khi bạn nhập. Máy chủ từ xa có thể cần vài giây để tải mô hình của nó.",
- "Warming embedding model…": "Mô hình nhúng nóng lên…"
+ "Warming embedding model…": "Mô hình nhúng nóng lên…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "Chuyển giữa Cục bộ và Từ xa vẫn giữ các vector nhúng hiện có. Hãy dùng cùng mô hình, số chiều, cách gộp và tiền xử lý. Việc xây dựng lại được thực hiện thủ công.",
+ "Include hidden files and folders": "Bao gồm tệp và thư mục ẩn",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "Loại trừ thư mục Windows, Temp và bộ nhớ đệm khỏi nguồn Quick và Full. Nguồn Quick vẫn tìm được các tên khác trong AppData. Lưu để xóa các bản ghi bị loại trừ khỏi chỉ mục trong nền.",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "Có thể cần quyền quản trị viên để đọc nhật ký hiện có. Số lượng thể hiện các bộ đọc đang hoạt động.",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "Vị trí nhật ký bị thiếu, hết hạn hoặc nguồn thay đổi sẽ yêu cầu quét bù các nguồn bị ảnh hưởng. Ổ mạng dùng thông báo thư mục và quét bù riêng từng nguồn.",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "Lưu để áp dụng vào lần mở tiếp theo. Windows sẽ yêu cầu chấp thuận. Ổ đĩa được ánh xạ có thể không khả dụng khi chạy với quyền quản trị.",
+ "Always start as administrator": "Luôn khởi động với quyền quản trị viên",
+ "Running as administrator": "Đang chạy với quyền quản trị viên",
+ "Relaunch as administrator": "Khởi động lại với quyền quản trị viên",
+ "Idle": "Nhàn rỗi",
+ "Waiting for indexing conditions": "Đang chờ điều kiện lập chỉ mục",
+ "Indexing": "Đang lập chỉ mục"
}
diff --git a/native/locales/zh-CN.json b/native/locales/zh-CN.json
index 7ded4de..754bf21 100644
--- a/native/locales/zh-CN.json
+++ b/native/locales/zh-CN.json
@@ -707,5 +707,17 @@
"English speech-to-text": "英语语音转文本",
"Warm embedding model when search opens": "搜索打开时的热嵌入模型",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "当混合或语义搜索打开时,在您键入之前发送一个小的嵌入请求。远程服务器可能需要几秒钟来加载其模型。",
- "Warming embedding model…": "变暖的嵌入模型..."
+ "Warming embedding model…": "变暖的嵌入模型...",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "切换本地/远程会保留现有嵌入向量。请使用相同的模型、维度、池化和预处理设置。重建需要手动执行。",
+ "Include hidden files and folders": "包含隐藏文件和文件夹",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "从 Quick 和 Full 来源中排除 Windows、Temp 和缓存文件夹。Quick 来源仍可搜索 AppData 中的其他名称。保存后将在后台从索引中删除排除的记录。",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "读取现有日志可能需要管理员权限。计数表示活动的日志读取器。",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "日志位置缺失、过期或来源变更时,仅对受影响的来源进行补充扫描。网络驱动器使用文件夹通知和按来源进行的补充扫描。",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "保存后在下次启动时生效。Windows 将请求授权。以管理员身份运行时,映射驱动器可能不可用。",
+ "Always start as administrator": "始终以管理员身份启动",
+ "Running as administrator": "正在以管理员身份运行",
+ "Relaunch as administrator": "以管理员身份重新启动",
+ "Idle": "空闲",
+ "Waiting for indexing conditions": "等待索引条件",
+ "Indexing": "正在索引"
}
diff --git a/native/locales/zh-TW.json b/native/locales/zh-TW.json
index 09532c3..d99c4c8 100644
--- a/native/locales/zh-TW.json
+++ b/native/locales/zh-TW.json
@@ -707,5 +707,17 @@
"English speech-to-text": "英語語音轉文本",
"Warm embedding model when search opens": "Warm embedding model when search opens",
"Sends a small embedding request when Hybrid or Semantic search opens, before you type. The remote server may need a few seconds to load its model.": "當混合或語義搜尋打開時,在您鍵入之前發送一個小的嵌入請求。遠端伺服器可能需要幾秒鐘來載入其模型。",
- "Warming embedding model…": "Warming embedding model…"
+ "Warming embedding model…": "Warming embedding model…",
+ "Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual.": "切換本機/遠端會保留現有嵌入向量。請使用相同的模型、維度、池化和前處理設定。重建需要手動執行。",
+ "Include hidden files and folders": "包含隱藏檔案和資料夾",
+ "Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background.": "從 Quick 和 Full 來源中排除 Windows、Temp 和快取資料夾。Quick 來源仍可搜尋 AppData 中的其他名稱。儲存後將在背景從索引中刪除排除的記錄。",
+ "Administrator access may be required to read existing journals. The count shows active readers.": "讀取現有日誌可能需要系統管理員權限。計數表示作用中的日誌讀取器。",
+ "Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up.": "日誌位置遺失、過期或來源變更時,僅對受影響的來源進行補充掃描。網路磁碟使用資料夾通知及個別來源的補充掃描。",
+ "Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated.": "儲存後於下次啟動時生效。Windows 將要求授權。以系統管理員身分執行時,對應磁碟機可能無法使用。",
+ "Always start as administrator": "一律以系統管理員身分啟動",
+ "Running as administrator": "正以系統管理員身分執行",
+ "Relaunch as administrator": "以系統管理員身分重新啟動",
+ "Idle": "閒置",
+ "Waiting for indexing conditions": "等待索引條件",
+ "Indexing": "正在建立索引"
}
diff --git a/native/src/admin.rs b/native/src/admin.rs
new file mode 100644
index 0000000..716794a
--- /dev/null
+++ b/native/src/admin.rs
@@ -0,0 +1,252 @@
+use anyhow::{Context, Result};
+use std::path::Path;
+
+pub fn should_elevate(always: bool, elevated: bool, args: &[String]) -> bool {
+ always
+ && !elevated
+ && !args
+ .iter()
+ .any(|a| a == "--admin-relaunch" || a == "--smoke-report")
+}
+fn quote(value: &str) -> String {
+ let mut out = String::from("\"");
+ let mut slashes = 0;
+ for ch in value.chars() {
+ if ch == '\\' {
+ slashes += 1;
+ continue;
+ }
+ out.extend(std::iter::repeat_n(
+ '\\',
+ if ch == '"' { slashes * 2 + 1 } else { slashes },
+ ));
+ slashes = 0;
+ out.push(ch);
+ }
+ out.extend(std::iter::repeat_n('\\', slashes * 2));
+ out.push('"');
+ out
+}
+fn arguments(home: &Path, args: &[String], pid: u32) -> String {
+ let mut result = vec![
+ "--admin-relaunch".to_owned(),
+ "--admin-data-home".into(),
+ home.to_string_lossy().into_owned(),
+ "--wait-for-process".into(),
+ pid.to_string(),
+ ];
+ // Forward only supported GUI launch state, never a worker/test invocation.
+ result.extend(
+ args.iter()
+ .filter(|a| matches!(a.as_str(), "--startup" | "--portable"))
+ .cloned(),
+ );
+ result
+ .iter()
+ .map(|a| quote(a))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+#[cfg(windows)]
+pub fn elevated() -> bool {
+ use windows::Win32::{
+ Foundation::{CloseHandle, HANDLE},
+ Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation},
+ System::Threading::{GetCurrentProcess, OpenProcessToken},
+ };
+ unsafe {
+ let mut token = HANDLE::default();
+ if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).is_err() {
+ return false;
+ }
+ let mut value = TOKEN_ELEVATION::default();
+ let mut size = 0;
+ let ok = GetTokenInformation(
+ token,
+ TokenElevation,
+ Some(&mut value as *mut _ as _),
+ std::mem::size_of_val(&value) as u32,
+ &mut size,
+ )
+ .is_ok();
+ let _ = CloseHandle(token);
+ ok && value.TokenIsElevated != 0
+ }
+}
+#[cfg(not(windows))]
+pub fn elevated() -> bool {
+ false
+}
+
+#[cfg(windows)]
+pub fn relaunch(home: &Path, args: &[String]) -> Result<()> {
+ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoUninitialize};
+ use windows::{
+ Win32::UI::{
+ Shell::{SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW},
+ WindowsAndMessaging::SW_SHOWNORMAL,
+ },
+ core::PCWSTR,
+ };
+ struct Apartment(bool);
+ impl Drop for Apartment {
+ fn drop(&mut self) {
+ if self.0 {
+ unsafe {
+ CoUninitialize();
+ }
+ }
+ }
+ }
+ let _apartment = Apartment(unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).is_ok() });
+ let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+ let exe = wide(&std::env::current_exe()?.to_string_lossy());
+ let verb = wide("runas");
+ let params = wide(&arguments(home, args, std::process::id()));
+ let mut info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ fMask: SEE_MASK_NOASYNC,
+ lpVerb: PCWSTR(verb.as_ptr()),
+ lpFile: PCWSTR(exe.as_ptr()),
+ lpParameters: PCWSTR(params.as_ptr()),
+ nShow: SW_SHOWNORMAL.0,
+ ..Default::default()
+ };
+ unsafe { ShellExecuteExW(&mut info) }
+ .context("Administrator relaunch was canceled or failed")?;
+ Ok(())
+}
+#[cfg(not(windows))]
+pub fn relaunch(_: &Path, _: &[String]) -> Result<()> {
+ anyhow::bail!("Administrator relaunch requires Windows")
+}
+
+pub fn prepare_handoff(args: &[String]) -> Result<()> {
+ if !args.iter().any(|a| a == "--admin-relaunch") {
+ return Ok(());
+ }
+ let value = |flag: &str| {
+ args.iter()
+ .position(|a| a == flag)
+ .and_then(|i| args.get(i + 1))
+ };
+ if let Some(home) = value("--admin-data-home") {
+ anyhow::ensure!(
+ Path::new(home).is_absolute(),
+ "Administrator profile path must be absolute"
+ );
+ unsafe {
+ std::env::set_var("VECTORDASH_DATA_HOME", home);
+ }
+ }
+ if let Some(pid) = value("--wait-for-process") {
+ wait_parent(pid.parse()?)?;
+ }
+ Ok(())
+}
+#[cfg(windows)]
+fn wait_parent(pid: u32) -> Result<()> {
+ use windows::Win32::{
+ Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0},
+ System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
+ };
+ anyhow::ensure!(pid != std::process::id(), "Cannot wait for current process");
+ let handle = match unsafe { OpenProcess(PROCESS_SYNCHRONIZE, false, pid) } {
+ Ok(h) => h,
+ Err(e) if e.code() == ERROR_INVALID_PARAMETER.to_hresult() => return Ok(()),
+ Err(e) => return Err(e).context("Could not wait for the previous VectorDash process"),
+ };
+ let status = unsafe { WaitForSingleObject(handle, 30_000) };
+ unsafe {
+ let _ = CloseHandle(handle);
+ }
+ anyhow::ensure!(
+ status == WAIT_OBJECT_0,
+ "Previous VectorDash process did not exit; administrator relaunch stopped"
+ );
+ Ok(())
+}
+#[cfg(not(windows))]
+fn wait_parent(_: u32) -> Result<()> {
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn elevation_policy_avoids_prompt_loops_and_smoke_tests() {
+ assert!(should_elevate(true, false, &[]));
+ assert!(!should_elevate(false, false, &[]));
+ assert!(!should_elevate(true, true, &[]));
+ assert!(!should_elevate(true, false, &["--admin-relaunch".into()]));
+ assert!(!should_elevate(
+ true,
+ false,
+ &["--smoke-report".into(), "report.json".into()]
+ ));
+ }
+ #[test]
+ fn administrator_preference_defaults_off_and_round_trips() {
+ let old: crate::config::Settings = serde_json::from_str("{}").unwrap();
+ assert!(!old.always_admin);
+ let mut enabled = old;
+ enabled.always_admin = true;
+ let restored: crate::config::Settings =
+ serde_json::from_str(&serde_json::to_string(&enabled).unwrap()).unwrap();
+ assert!(restored.always_admin);
+ }
+ #[cfg(windows)]
+ #[test]
+ fn handoff_waits_for_the_previous_process_to_exit() {
+ let mut command = std::process::Command::new("cmd.exe");
+ command.args(["/d", "/c", "exit", "0"]);
+ crate::content::hidden(&mut command);
+ let mut child = command.spawn().unwrap();
+ wait_parent(child.id()).unwrap();
+ assert!(child.wait().unwrap().success());
+ }
+ #[cfg(windows)]
+ #[test]
+ fn launch_arguments_round_trip_windows_paths_and_unicode() {
+ use windows::{
+ Win32::{
+ Foundation::{HLOCAL, LocalFree},
+ UI::Shell::CommandLineToArgvW,
+ },
+ core::PCWSTR,
+ };
+ let values = [
+ "app",
+ "",
+ r"C:\",
+ r"C:\My profile\",
+ "C:\\Tệp dữ liệu\\模型",
+ "quote\"test",
+ "space and & symbols",
+ ];
+ let command = values
+ .iter()
+ .map(|a| quote(a))
+ .collect::<Vec<_>>()
+ .join(" ");
+ let wide: Vec<_> = command.encode_utf16().chain(Some(0)).collect();
+ unsafe {
+ let mut count = 0;
+ let parsed = CommandLineToArgvW(PCWSTR(wide.as_ptr()), &mut count);
+ assert!(!parsed.is_null());
+ let actual: Vec<String> = std::slice::from_raw_parts(parsed, count as usize)
+ .iter()
+ .map(|p| p.to_string().unwrap())
+ .collect();
+ let _ = LocalFree(Some(HLOCAL(parsed as _)));
+ assert_eq!(actual, values);
+ }
+ let params = arguments(
+ Path::new(r"C:\My profile"),
+ &["--startup".into(), "--extract-worker".into()],
+ 42,
+ );
+ assert!(params.contains("--startup") && !params.contains("--extract-worker"));
+ }
+}
diff --git a/native/src/app.rs b/native/src/app.rs
index d49864d..6fb650e 100644
--- a/native/src/app.rs
+++ b/native/src/app.rs
@@ -76,6 +76,7 @@ pub struct App {
dirty: bool,
searching: bool,
search_pending: bool,
+ search_inflight: Option<u64>,
search_ms: f64,
search_error: Option<String>,
indexing: bool,
@@ -345,6 +346,7 @@ impl App {
dirty: false,
searching: false,
search_pending: false,
+ search_inflight: None,
search_ms: 0.0,
search_error: None,
indexing: false,
@@ -544,9 +546,9 @@ impl App {
.and_then(|v| v.parse().ok())
.unwrap_or(4);
app.quick = args.iter().any(|a| a == "--smoke-quick");
- app.qa_hidden = args
- .iter()
- .any(|a| a == "--smoke-hidden" || a == "--smoke-tray");
+ app.qa_hidden = args.iter().any(|a| {
+ a == "--smoke-hidden" || a == "--smoke-tray" || a == "--smoke-tray-saturated"
+ });
app.qa_screenshot = get("--smoke-screenshot").map(PathBuf::from);
app.qa_selection = get("--smoke-selection").and_then(|v| v.parse().ok());
if args.iter().any(|a| a == "--smoke-dirty") {
@@ -938,7 +940,14 @@ impl App {
}
}
fn events(&mut self, ctx: &egui::Context) {
- for event in self.rx.try_iter().take(100).collect::<Vec<_>>() {
+ let mut events = self
+ .engine
+ .tx
+ .take_full_request()
+ .into_iter()
+ .collect::<Vec<_>>();
+ events.extend(self.rx.try_iter().take(100));
+ for event in events {
let voice_summon = matches!(&event, Event::VoiceSummon(..));
if voice_summon
&& self.page == 0
@@ -1269,7 +1278,10 @@ impl App {
}
}
Event::Launcher(id, result) => {
- self.searching = false;
+ if self.search_inflight == Some(id) {
+ self.searching = false;
+ self.search_inflight = None;
+ }
if id == self.sequence {
match result {
Ok(items) => {
@@ -1410,6 +1422,9 @@ impl App {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
Event::Full => {
+ if self.qa_hidden {
+ self.qa_hidden_reopened = true;
+ }
if !self.search_visible {
self.model_warm_attempted = false;
self.model_warm_error = None;
@@ -1474,7 +1489,8 @@ impl App {
self.preview_pending = None;
self.preview_error = None;
self.search_ms = ms;
- self.selected = self.selected.min(self.hits.len().saturating_sub(1));
+ self.selected = 0;
+ self.result_scroll_offset = 0.0;
self.scroll_to_selection = true;
}
}
@@ -1484,7 +1500,10 @@ impl App {
}
}
Event::Search(seq, result, ms) => {
- self.searching = false;
+ if self.search_inflight == Some(seq) {
+ self.searching = false;
+ self.search_inflight = None;
+ }
if seq == self.sequence {
match result {
Ok(h) => {
@@ -1507,7 +1526,7 @@ impl App {
}
}
}
- if self.search_pending {
+ if self.search_inflight.is_none() && self.search_pending {
self.search_pending = false;
self.dispatch();
}
@@ -1590,8 +1609,7 @@ impl App {
self.query = text;
}
self.hits.clear();
- self.dirty = true;
- self.changed = Instant::now();
+ self.changed();
ctx.memory_mut(|m| {
m.move_focus(egui::FocusDirection::None);
m.request_focus(egui::Id::new("query"));
@@ -1672,7 +1690,13 @@ impl App {
self.last_search_mode = self.mode.clone();
self.model_warm_attempted = false;
}
- if !self.search_visible || self.page != 0 || self.mode == "Names" || self.tool != "Search" {
+ if !self.search_visible
+ || self.page != 0
+ || self.mode == "Names"
+ || self.tool != "Search"
+ || (!self.query.trim().is_empty() && !self.query_uses_embeddings())
+ || (!self.scope.is_empty() && self.query.trim().is_empty())
+ {
self.engine
.models
.session_override
@@ -1735,6 +1759,7 @@ impl App {
let settings = self.saved_settings.clone();
let models = self.engine.models.clone();
let id = self.sequence;
+ self.search_inflight = Some(id);
let tx = self.engine.tx.clone();
std::thread::spawn(move || {
let result = store
@@ -1752,11 +1777,12 @@ impl App {
self.hits.clear();
return;
}
- if self.searching {
- self.search_pending = true;
+ if self.searching && self.search_inflight == Some(self.sequence) {
return;
}
+ self.search_pending = false;
self.searching = true;
+ self.search_inflight = Some(self.sequence);
self.engine.search(
self.sequence,
self.query.clone(),
@@ -1767,7 +1793,16 @@ impl App {
self.exclude_types.clone(),
);
}
+ fn reset_result_selection(&mut self) {
+ self.selected = 0;
+ self.result_scroll_offset = 0.0;
+ self.scroll_to_selection = true;
+ self.texture = None;
+ self.preview_pending = None;
+ self.preview_error = None;
+ }
fn changed(&mut self) {
+ self.reset_result_selection();
self.engine.models.cancel_query();
self.search_error = None;
self.scope_indexed = None;
@@ -3235,14 +3270,18 @@ impl App {
"{} files · {} Full · {} Quick · {} vectors",
self.stats.files, self.stats.full, self.stats.quick, self.stats.vectors
)));
- ui.label(tr(&format!(
- "{} · {} found · {} done · {} unchanged · {} skipped",
- self.progress.phase,
- self.progress.found,
- self.progress.completed,
- self.progress.reused,
- self.progress.skipped
- )));
+ if self.progress.phase == "Removing deleted index records" {
+ ui.label(tr(&format!("{} · {}", self.progress.phase, self.progress.current)));
+ } else {
+ ui.label(tr(&format!(
+ "{} · {} found · {} done · {} unchanged · {} skipped",
+ self.progress.phase,
+ self.progress.found,
+ self.progress.completed,
+ self.progress.reused,
+ self.progress.skipped
+ )));
+ }
if self.indexing {
if let Some(total) = self.progress.total {
ui.add(
@@ -3254,7 +3293,6 @@ impl App {
} else {
ui.spinner();
}
- ui.label(&self.progress.phase);
if self.progress.phase.starts_with("EmbeddingGemma") {
ui.label(tr(&format!(
"{} chunks embedded in this file",
@@ -3351,6 +3389,11 @@ impl App {
&mut self.s.skip_windows_churn,
t("Exclude common Windows/cache folders"),
);
+ ui.weak(t("Excludes Windows, Temp and cache folders from Quick and Full sources. Quick sources can still search other AppData names. Save to remove excluded records from the index in the background."));
+ ui.checkbox(
+ &mut self.s.include_hidden,
+ t("Include hidden files and folders"),
+ );
ui.horizontal(|ui| {
combo(ui, "add_mode", &mut self.source_mode, &["quick", "full"]);
if ui.button(t("Add folder / drive")).clicked() {
@@ -3792,10 +3835,14 @@ impl App {
);
}
}
+ fn query_uses_embeddings(&self) -> bool {
+ crate::search_filters::Filters::parse(&self.query).is_ok_and(|f| f.uses_embeddings())
+ }
fn embedding_activity(&self) -> bool {
self.page == 0
&& self.tool == "Search"
&& self.mode != "Names"
+ && self.query_uses_embeddings()
&& (self.searching
|| self.model_warm_busy
|| self.engine.models.loading.load(Ordering::Acquire))
@@ -3804,7 +3851,7 @@ impl App {
if self.page != 0 {
return t(&self.status).to_owned();
}
- if self.model_warm_busy {
+ if self.model_warm_busy && self.query_uses_embeddings() {
return t("Warming embedding model…").to_owned();
}
if self.dictation_busy {
@@ -3830,7 +3877,11 @@ impl App {
.map(|s| format!("{state} · AI {s:.1} s"))
.unwrap_or_else(|| state.into());
}
- if self.tool == "Search" && self.mode != "Names" && !self.s.remote_embeddings() {
+ if self.tool == "Search"
+ && self.mode != "Names"
+ && self.query_uses_embeddings()
+ && !self.s.remote_embeddings()
+ {
if let Some(reason) = self.engine.models.search_hold(&self.s) {
return format!("EmbeddingGemma 2 paused: {reason}");
}
@@ -3964,6 +4015,7 @@ impl App {
let playback = self.page == 0 && self.tts_busy;
let load_override = self.page == 0
&& self.tool == "Search"
+ && self.query_uses_embeddings()
&& self.mode != "Names"
&& !self.s.remote_embeddings()
&& (self.engine.models.search_hold(&self.s).is_some()
@@ -4279,6 +4331,7 @@ impl App {
));
}
ui.weak(t("Used as a conservative input budget; oversized text is split. Remote servers receive indexed text/media and semantic queries. Server configuration determines actual context and media support. Changing the embedding model requires re-indexing full-indexed files to keep vectors compatible."));
+ ui.weak(t("Switching Local/Remote preserves existing embeddings. Use the same model, dimensions, pooling and preprocessing. Rebuilding is manual."));
check = ui
.add_enabled(
!busy && !model.is_empty(),
@@ -6016,6 +6069,23 @@ impl App {
t("Use NTFS change journal when available"),
);
ui.label(t("Requires volume-read permission and an existing NTFS journal. Unsupported or inaccessible drives keep using folder notifications and recovery scans."));
+ ui.weak(t("Administrator access may be required to read existing journals. The count shows active readers."));
+ ui.weak(t("Missing/expired journal positions or changed sources require catch-up for affected sources. Network drives use folder notifications and source-specific catch-up."));
+ ui.checkbox(&mut self.s.always_admin, t("Always start as administrator"));
+ ui.weak(t("Save to apply on next launch. Windows will ask for approval. Mapped drives may be unavailable when elevated."));
+ if crate::admin::elevated() {
+ ui.label(t("Running as administrator"));
+ } else if ui.button(t("Relaunch as administrator")).clicked() {
+ if self.save() {
+ match crate::admin::relaunch(&self.home, &[]) {
+ Ok(()) => {
+ self.exiting = true;
+ ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
+ }
+ Err(e) => self.status = e.to_string(),
+ }
+ }
+ }
ui.separator();
combo(
ui,
@@ -6243,6 +6313,37 @@ impl eframe::App for App {
}
use raw_window_handle::HasWindowHandle;
+ if self.smoke.is_some()
+ && self.startup.elapsed() > Duration::from_secs(2)
+ && self.qa_selection.is_some()
+ && !self.hits.is_empty()
+ && !self.searching
+ {
+ let repeat = std::env::args().any(|a| a == "--smoke-repeat-search");
+ let focus = std::env::args().any(|a| a == "--smoke-ctrl-f");
+ if repeat || focus {
+ ctx.data_mut(|d| {
+ d.insert_temp(egui::Id::new("qa-reset-selected"), self.selected);
+ d.insert_temp(egui::Id::new("qa-reset-offset"), self.result_scroll_offset);
+ });
+ self.qa_selection = None;
+ if repeat {
+ self.query.push(' ');
+ self.changed();
+ } else {
+ ctx.input_mut(|i| {
+ i.modifiers = egui::Modifiers::CTRL;
+ i.events.push(egui::Event::Key {
+ key: egui::Key::F,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::CTRL,
+ });
+ });
+ }
+ }
+ }
if self.smoke.is_some() && self.tool == "AI" {
let args = std::env::args().collect::<Vec<_>>();
if let Some(question) = args
@@ -6300,6 +6401,7 @@ impl eframe::App for App {
self.query.clear();
}
if ctx.input(|i| i.modifiers.ctrl && i.key_pressed(egui::Key::F)) {
+ self.reset_result_selection();
self.page = 0;
self.select_query = true;
self.filter_open = false;
@@ -6504,7 +6606,17 @@ impl eframe::App for App {
{
self.qa_hide_sent = true;
self.close_window(ctx);
- if !std::env::args().any(|a| a == "--smoke-tray") {
+ if std::env::args().any(|a| a == "--smoke-tray-saturated") {
+ let tx = self.engine.tx.clone();
+ let legacy = std::env::args().any(|a| a == "--smoke-tray-legacy");
+ let accent = self.saved_settings.accent;
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(700));
+ let count = tx.smoke_fill_notifications();
+ assert_eq!(count, 512);
+ let _ = crate::platform::smoke_tray_open(tx, legacy, accent);
+ });
+ } else if !std::env::args().any(|a| a == "--smoke-tray") {
let tx = self.engine.tx.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(700));
@@ -6664,6 +6776,7 @@ impl eframe::App for App {
self.clipboard_thumbs.clear();
self.clipboard_preview_id = -1;
self.color_emoji.clear(ctx);
+ self.engine.vectors.clear();
self.preview_pending = None;
self.engine.models.cancel_query();
self.search_visible = false;
@@ -7488,6 +7601,16 @@ impl eframe::App for App {
&& (self.qa_screenshot.is_none() || self.qa_captured)
{
let mut data = serde_json::json!({"ok":true,"native_rust":true,"tool":self.tool,"tools":self.saved_settings.search_tools(),"footer":self.footer_text(),"embedding_activity":self.embedding_activity(),"ai_elapsed":self.ai_elapsed,"dictation_status":self.dictation_status,"query":self.query,"ai_busy":self.ai_busy,"ai_answer":self.ai_answer,"model_loaded":self.engine.models.loaded.load(Ordering::Relaxed),"frames":self.frames,"max_frame_interval_ms":self.max_frame_ms,"dark_mode":ctx.style().visuals.dark_mode,"hidden_reopened":self.qa_hidden_reopened,"ocr_enabled":self.s.ocr_enabled,"ocr_setup_selected":self.ocr_setup,"results":self.hits.len(),"selected":self.selected,"result_scroll_offset":self.result_scroll_offset,"scope":self.scope,"quick_look":self.large_preview,"quick_look_size":self.qa_child_size,"cpu":crate::scheduling::metrics().cpu,"gpu":crate::scheduling::metrics().gpu,"query_focus":ctx.memory(|m|m.has_focus(egui::Id::new("query"))),"ai_metrics":self.ai_metrics.label(),"tts_busy":self.tts_busy,"tts_paused":self.tts_paused.load(Ordering::Acquire),"connection_results":self.connections.iter().map(|s|s.result.as_ref().map(|r|r.is_ok())).collect::<Vec<_>>(),"ai_scroll_offset":self.ai_scroll_offset,"qa_ai_scroll_before":self.qa_ai_scroll_before,"qa_ai_followup_sent":self.qa_ai_followup_sent,"tts_status":self.tts_status,"tts_notice":self.tts_notice,"tts_voices":self.tts_voices,"response_length":self.response_length,"toolbar_top":self.qa_toolbar_top,"filters_top":self.qa_filter_top,"query_selected":egui::text_edit::TextEditState::load(ctx,egui::Id::new("query")).and_then(|s|s.cursor.char_range()).map(|r|r.as_sorted_char_range().len()).unwrap_or(0)});
+ data["main_visible"] = serde_json::json!(crate::platform::main_window_visible());
+ data["tray_color"] = serde_json::json!(crate::tray::current().color());
+ data["administrator"] = serde_json::json!(crate::admin::elevated());
+ data["always_admin"] = serde_json::json!(self.s.always_admin);
+ data["selection_before_reset"] = serde_json::json!(
+ ctx.data(|d| d.get_temp::<usize>(egui::Id::new("qa-reset-selected")))
+ );
+ data["scroll_before_reset"] = serde_json::json!(
+ ctx.data(|d| d.get_temp::<f32>(egui::Id::new("qa-reset-offset")))
+ );
data["language"] = serde_json::json!(self.s.language);
data["localized_search"] = serde_json::json!(t("Search"));
data["source_list"] = serde_json::json!(
diff --git a/native/src/changes.rs b/native/src/changes.rs
index 54be6e7..410a0f0 100644
--- a/native/src/changes.rs
+++ b/native/src/changes.rs
@@ -4,7 +4,7 @@ use crate::{
};
use notify::{RecursiveMode, Watcher};
use std::{
- collections::HashSet,
+ collections::{BTreeMap, HashSet},
path::{Path, PathBuf},
time::{Duration, Instant},
};
@@ -15,6 +15,7 @@ use std::{
struct NotificationSpill {
paths: HashSet<PathBuf>,
roots: HashSet<PathBuf>,
+ failed: HashSet<PathBuf>,
}
impl NotificationSpill {
fn insert(&mut self, path: PathBuf, settings: &Settings) {
@@ -37,16 +38,96 @@ impl NotificationSpill {
}
}
}
+fn deliver_notification(
+ event: notify::Result<notify::Event>,
+ origin: &Path,
+ filter: &Settings,
+ data_home: &Path,
+ sender: &std::sync::mpsc::SyncSender<notify::Result<notify::Event>>,
+ spill: &std::sync::Mutex<NotificationSpill>,
+) {
+ let event = event
+ .map(|mut e| {
+ if e.need_rescan() {
+ if e.paths.is_empty() {
+ e.paths.push(origin.to_path_buf());
+ }
+ } else {
+ e.paths.retain(|p| {
+ !directory_metadata_only(&e.kind, p)
+ && !under(&p.to_string_lossy(), &data_home.to_string_lossy())
+ && filter
+ .roots
+ .iter()
+ .filter(|r| under(&p.to_string_lossy(), &r.path))
+ .max_by_key(|r| r.path.len())
+ .is_some_and(|root| {
+ p.ancestors()
+ .take_while(|a| under(&a.to_string_lossy(), &root.path))
+ .all(|a| filter.allowed(a))
+ })
+ });
+ }
+ e
+ })
+ .map_err(|mut e| {
+ if e.paths.is_empty() {
+ e.paths.push(origin.to_path_buf());
+ }
+ e
+ });
+ if event
+ .as_ref()
+ .is_ok_and(|e| e.paths.is_empty() && !e.need_rescan())
+ {
+ return;
+ }
+ if let Err(std::sync::mpsc::TrySendError::Full(event)) = sender.try_send(event) {
+ let mut spill = spill.lock().unwrap_or_else(|e| e.into_inner());
+ match event {
+ Ok(e) if !e.need_rescan() => {
+ for path in e.paths {
+ spill.insert(path, filter);
+ }
+ }
+ Ok(e) => {
+ spill.roots.extend(e.paths);
+ }
+ Err(e) => {
+ spill.failed.extend(e.paths);
+ }
+ }
+ }
+}
+/// One callback per watched root retains the origin even when Windows supplies
+/// an empty overflow/error event. A shared watcher cannot identify that source.
+fn source_watcher(
+ target: &Path,
+ settings: &Settings,
+ home: &Path,
+ sender: std::sync::mpsc::SyncSender<notify::Result<notify::Event>>,
+ spill: std::sync::Arc<std::sync::Mutex<NotificationSpill>>,
+) -> notify::Result<notify::RecommendedWatcher> {
+ let origin = target.to_path_buf();
+ let filter = settings.clone();
+ let data_home = home.to_path_buf();
+ let mut watcher = notify::recommended_watcher(move |event| {
+ deliver_notification(event, &origin, &filter, &data_home, &sender, &spill);
+ })?;
+ watcher.watch(target, RecursiveMode::Recursive)?;
+ Ok(watcher)
+}
#[derive(Default)]
pub struct Monitor {
- watcher: Option<notify::RecommendedWatcher>,
+ watchers: BTreeMap<PathBuf, notify::RecommendedWatcher>,
+ sender: Option<std::sync::mpsc::SyncSender<notify::Result<notify::Event>>>,
rx: Option<std::sync::mpsc::Receiver<notify::Result<notify::Event>>>,
signature: String,
settings: Option<Settings>,
logger: Option<NotifySender>,
- overflow: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
spill: Option<std::sync::Arc<std::sync::Mutex<NotificationSpill>>>,
recovery_reason: String,
+ journal_notification_log: BTreeMap<PathBuf, Instant>,
pending: HashSet<PathBuf>,
recovery: bool,
recovery_saved: bool,
@@ -56,6 +137,9 @@ pub struct Monitor {
last: Option<Instant>,
first: Option<Instant>,
watched: usize,
+ watched_roots: HashSet<PathBuf>,
+ watcher_retries: BTreeMap<PathBuf, (u32, Instant)>,
+ watcher_failures: BTreeMap<PathBuf, u32>,
journal: crate::journal::Tracker,
journal_inflight: bool,
store: Option<crate::db::Database>,
@@ -69,13 +153,13 @@ pub struct Monitor {
impl Monitor {
pub fn configure(&mut self, s: &Settings, home: &Path, tx: &NotifySender) {
let signature = format!(
- "{}|{}|{:?}|{:?}|{}|{}",
+ "{}|{}|{:?}|{:?}|{}|{:?}",
s.watch_changes,
s.ntfs_journal,
s.roots,
s.exclusions,
s.excluded_types,
- s.skip_windows_churn
+ (s.skip_windows_churn, s.include_hidden)
);
if signature == self.signature {
return;
@@ -84,13 +168,18 @@ impl Monitor {
self.settings = Some(s.clone());
self.logger = Some(tx.clone());
self.recovery_reason.clear();
- self.watcher = None;
+ self.journal_notification_log.clear();
+ self.watchers.clear();
+ self.sender = None;
self.rx = None;
self.pending.clear();
self.recovery = false;
self.last = None;
self.first = None;
self.watched = 0;
+ self.watched_roots.clear();
+ self.watcher_retries.clear();
+ self.watcher_failures.clear();
self.journal = crate::journal::Tracker::default();
self.journal_inflight = false;
if !s.watch_changes {
@@ -131,65 +220,7 @@ impl Monitor {
}
}
let (sender, rx) = std::sync::mpsc::sync_channel(1024);
- let overflow = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- let flag = overflow.clone();
let spill = std::sync::Arc::new(std::sync::Mutex::new(NotificationSpill::default()));
- let callback_spill = spill.clone();
- let filter = s.clone();
- let data_home = home.to_path_buf();
- let mut watcher =
- match notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
- let event = event.map(|mut e| {
- if !e.need_rescan() {
- e.paths.retain(|p| {
- !directory_metadata_only(&e.kind, p)
- && !under(&p.to_string_lossy(), &data_home.to_string_lossy())
- && filter
- .roots
- .iter()
- .filter(|r| under(&p.to_string_lossy(), &r.path))
- .max_by_key(|r| r.path.len())
- .is_some_and(|root| {
- p.ancestors()
- .take_while(|a| under(&a.to_string_lossy(), &root.path))
- .all(|a| filter.allowed(a))
- })
- });
- }
- e
- });
- if event
- .as_ref()
- .is_ok_and(|e| e.paths.is_empty() && !e.need_rescan())
- {
- return;
- }
- if let Err(std::sync::mpsc::TrySendError::Full(event)) = sender.try_send(event) {
- match event {
- Ok(e) if !e.need_rescan() => {
- if let Ok(mut spill) = callback_spill.lock() {
- for path in e.paths {
- spill.insert(path, &filter);
- }
- } else {
- flag.store(true, std::sync::atomic::Ordering::Relaxed);
- }
- }
- _ => {
- flag.store(true, std::sync::atomic::Ordering::Relaxed);
- }
- }
- }
- }) {
- Ok(w) => w,
- Err(e) => {
- let _ = tx.send(Event::Log(
- "Warning".into(),
- format!("Folder monitoring unavailable: {e}"),
- ));
- return;
- }
- };
let mut roots = s
.roots
.iter()
@@ -206,31 +237,31 @@ impl Monitor {
if watched.iter().any(|p| target.starts_with(p)) || target.starts_with(home) {
continue;
}
- match watcher.watch(&target, RecursiveMode::Recursive) {
- Ok(()) => watched.push(target),
+ match source_watcher(&target, s, home, sender.clone(), spill.clone()) {
+ Ok(watcher) => {
+ self.watchers.insert(target.clone(), watcher);
+ watched.push(target);
+ }
Err(e) => {
+ self.watcher_retries
+ .insert(target.clone(), (1, Instant::now() + Duration::from_secs(5)));
+ self.watcher_failures.insert(target.clone(), 1);
let _ = tx.send(Event::Log(
"Warning".into(),
- format!("Cannot monitor {}: {e}", target.display()),
+ format!("Cannot monitor {}; retry in 5s: {e}", target.display()),
));
}
}
}
self.watched = watched.len();
- let journal_covered = self.journal.configure(s, home, tx);
- if self.watched > 0 && !journal_covered {
- // Replay durable interrupted work before a startup catch-up crawl.
- if !self.pending.is_empty() && !self.recovery {
- self.startup_recovery = true;
- } else {
- self.request_recovery("startup catch-up without continuous journal coverage");
- self.first = self.last;
- }
+ self.watched_roots = watched.iter().cloned().collect();
+ 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");
}
- self.overflow = Some(overflow);
self.spill = Some(spill);
self.rx = Some(rx);
- self.watcher = Some(watcher);
+ self.sender = Some(sender);
let _ = tx.send(Event::Log(
"Info".into(),
format!(
@@ -239,6 +270,151 @@ impl Monitor {
),
));
}
+ fn schedule_watch_retry(&mut self, paths: &[PathBuf]) {
+ for path in paths {
+ let target = self
+ .watched_roots
+ .iter()
+ .filter(|r| under(&path.to_string_lossy(), &r.to_string_lossy()))
+ .min_by_key(|r| r.components().count())
+ .cloned()
+ .unwrap_or_else(|| path.clone());
+ self.watched_roots.remove(&target);
+ if !self.watcher_retries.contains_key(&target) {
+ let attempts = self
+ .watcher_failures
+ .get(&target)
+ .copied()
+ .unwrap_or(0)
+ .saturating_add(1);
+ let delay = (5u64 << attempts.saturating_sub(1).min(6)).min(300);
+ self.watcher_failures.insert(target.clone(), attempts);
+ self.watcher_retries.insert(
+ target,
+ (attempts, Instant::now() + Duration::from_secs(delay)),
+ );
+ }
+ }
+ self.watched = self.watched_roots.len();
+ }
+ fn retry_watches(&mut self) {
+ let now = Instant::now();
+ let due = self
+ .watcher_retries
+ .iter()
+ .filter(|(_, (_, at))| now >= *at)
+ .map(|(p, (attempts, _))| (p.clone(), *attempts))
+ .collect::<Vec<_>>();
+ for (path, attempts) in due {
+ let (Some(settings), Some(store), Some(sender), Some(spill)) =
+ (&self.settings, &self.store, &self.sender, &self.spill)
+ else {
+ return;
+ };
+ self.watchers.remove(&path);
+ match source_watcher(&path, settings, &store.home, sender.clone(), spill.clone()) {
+ Ok(watcher) => {
+ self.watchers.insert(path.clone(), watcher);
+ self.watcher_retries.remove(&path);
+ self.watched_roots.insert(path.clone());
+ self.watched = self.watched_roots.len();
+ self.watcher_recovery(vec![path.clone()], "folder monitor reconnected");
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Info".into(),
+ format!(
+ "Folder monitor {} reconnected; journal replay or affected-source catch-up will handle missed changes",
+ path.display()
+ ),
+ ));
+ }
+ }
+ Err(error) => {
+ let attempts = attempts.saturating_add(1);
+ let delay = (5u64 << attempts.saturating_sub(1).min(6)).min(300);
+ self.watcher_failures.insert(path.clone(), attempts);
+ self.watcher_retries
+ .insert(path.clone(), (attempts, now + Duration::from_secs(delay)));
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Warning".into(),
+ format!(
+ "Folder monitor {} unavailable; retry in {delay}s: {error}",
+ path.display()
+ ),
+ ));
+ }
+ }
+ }
+ }
+ }
+ fn request_scoped_recovery(&mut self, paths: Vec<PathBuf>, reason: &str) {
+ let mut roots = Vec::new();
+ if let Some(settings) = &self.settings {
+ for path in paths {
+ let contained = settings
+ .roots
+ .iter()
+ .filter(|r| under(&r.path, &path.to_string_lossy()))
+ .collect::<Vec<_>>();
+ if !contained.is_empty() {
+ roots.extend(contained.into_iter().map(|r| PathBuf::from(&r.path)));
+ continue;
+ }
+ if let Some(root) = settings
+ .roots
+ .iter()
+ .filter(|r| under(&path.to_string_lossy(), &r.path))
+ .max_by_key(|r| r.path.len())
+ {
+ roots.push(PathBuf::from(&root.path));
+ }
+ }
+ }
+ roots.sort();
+ roots.dedup();
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Info".into(),
+ format!(
+ "Scoped recovery ({reason}): {}",
+ roots
+ .iter()
+ .map(|r| r.display().to_string())
+ .collect::<Vec<_>>()
+ .join("; ")
+ ),
+ ));
+ }
+ for root in roots {
+ self.queue_path(root);
+ }
+ }
+ fn watcher_recovery(&mut self, paths: Vec<PathBuf>, reason: &str) {
+ // Healthy journal replay already covers notification gaps. Do not create
+ // a second source scan while those exact journal paths are being drained.
+ let now = Instant::now();
+ let mut uncovered = vec![];
+ for path in paths {
+ if !self.journal.covers(&path) {
+ uncovered.push(path);
+ continue;
+ }
+ if self
+ .journal_notification_log
+ .get(&path)
+ .is_none_or(|last| now.saturating_duration_since(*last) >= Duration::from_secs(60))
+ {
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log("Info".into(), format!("Folder notification gap for {} ({reason}): covered by NTFS replay; no source rescan queued", path.display())));
+ }
+ self.journal_notification_log.insert(path, now);
+ }
+ }
+ if !uncovered.is_empty() {
+ self.request_scoped_recovery(uncovered, reason);
+ }
+ }
fn request_recovery(&mut self, reason: &str) {
self.recovery = true;
self.recovery_reason = reason.into();
@@ -246,6 +422,13 @@ impl Monitor {
self.last = Some(Instant::now());
}
fn queue_path(&mut self, path: PathBuf) {
+ if crate::config::ntfs_internal_path(&path.to_string_lossy()) {
+ return;
+ }
+ let path = path
+ .ancestors()
+ .find_map(|p| self.pending.get(p).cloned())
+ .unwrap_or(path);
if self.dirty.len() >= 8192 && !self.dirty.contains(&path) {
let saved = self.persist().is_ok() && self.dirty.is_empty();
if !saved {
@@ -264,34 +447,53 @@ impl Monitor {
// Additional known paths are persisted, then loaded after this batch.
}
pub fn collect(&mut self, s: &Settings, home: &Path) {
+ self.retry_watches();
let (paths, recovery) = self.journal.poll();
if recovery {
self.request_recovery("NTFS journal gap or inaccessible journal");
}
+ if let Some(db) = &self.store {
+ match self.journal.resolve_missing(db) {
+ Ok(candidates) => {
+ for path in candidates {
+ if s.searched(&path)
+ && !under(&path.to_string_lossy(), &home.to_string_lossy())
+ {
+ self.queue_path(path);
+ }
+ }
+ }
+ Err(error) => {
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Warning".into(),
+ format!(
+ "Targeted journal filename lookup pending; retrying: {error:#}"
+ ),
+ ));
+ }
+ }
+ }
+ }
for path in paths {
if !under(&path.to_string_lossy(), &home.to_string_lossy()) && s.searched(&path) {
self.queue_path(path);
}
}
- if self
- .overflow
- .as_ref()
- .is_some_and(|f| f.swap(false, std::sync::atomic::Ordering::Relaxed))
- {
- self.request_recovery("notification information was lost");
- }
let spilled = self.spill.as_ref().and_then(|buffer| {
buffer.lock().ok().map(|mut buffer| {
- let mut paths = buffer.paths.drain().collect::<Vec<_>>();
+ let paths = buffer.paths.drain().collect::<Vec<_>>();
let roots=buffer.roots.drain().collect::<Vec<_>>();
+ let failed=buffer.failed.drain().collect::<Vec<_>>();
if !roots.is_empty() {
- if let Some(tx)=&self.logger {let _=tx.send(Event::Log("Warning".into(),format!("Notification spill reached its memory limit; rechecking only affected sources: {}",roots.iter().map(|r|r.display().to_string()).collect::<Vec<_>>().join("; "))));}
+ if let Some(tx)=&self.logger {let _=tx.send(Event::Log("Warning".into(),format!("Notification overflow retained source identity; journal replay or source-only recovery: {}",roots.iter().map(|r|r.display().to_string()).collect::<Vec<_>>().join("; "))));}
}
- paths.extend(roots);
- paths
+ (paths, roots, failed)
})
});
- if let Some(paths) = spilled {
+ if let Some((paths, roots, failed)) = spilled {
+ self.watcher_recovery(roots, "notification buffer overflow on affected source");
+ self.schedule_watch_retry(&failed);
for path in paths {
self.queue_path(path);
}
@@ -304,10 +506,21 @@ impl Monitor {
for result in events {
match result {
Ok(event) => {
+ if !event.need_rescan() {
+ for path in &event.paths {
+ for root in &self.watched_roots {
+ if under(&path.to_string_lossy(), &root.to_string_lossy()) {
+ self.watcher_failures.remove(root);
+ }
+ }
+ }
+ }
if event.need_rescan() {
- self.request_recovery(
+ self.watcher_recovery(
+ event.paths.clone(),
"Windows/provider requested a rescan after missed events",
);
+ continue;
}
if matches!(event.kind, notify::EventKind::Access(_)) {
continue;
@@ -332,7 +545,19 @@ impl Monitor {
}
}
Err(error) => {
- self.request_recovery(&format!("folder watcher reported an error: {error}"))
+ self.schedule_watch_retry(&error.paths);
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(Event::Log(
+ "Warning".into(),
+ format!("Folder watcher failed; reattachment queued: {error}"),
+ ));
+ }
+ if error.paths.is_empty() {
+ self.watcher_recovery(
+ vec![],
+ "folder watcher failed without a source path",
+ );
+ }
}
}
}
@@ -349,6 +574,7 @@ impl Monitor {
let Some(db) = &self.store else {
return Ok(());
};
+ let checkpoint_home = db.home.clone();
let c = db.connect(false)?;
c.execute("DELETE FROM native_changes WHERE queued<?1", [started])?;
drop(c);
@@ -361,6 +587,8 @@ impl Monitor {
self.retry_after = None;
self.failures = 0;
self.restore(s);
+ self.journal.begin();
+ self.journal.finish(true, &checkpoint_home);
Ok(())
}
fn persist(&mut self) -> anyhow::Result<()> {
@@ -474,11 +702,15 @@ impl Monitor {
"waiting for file changes"
};
format!(
- "Watching {} sources · {} NTFS journals · {pending} · {waiting}",
+ "Watching {} sources · {} NTFS journals ({} retrying) · {pending} · {waiting}",
self.watched,
- self.journal.active()
+ self.journal.active(),
+ self.journal.retrying()
)
}
+ pub fn pending_work(&self) -> bool {
+ self.recovery || !self.pending.is_empty()
+ }
pub fn ready(&self) -> bool {
self.retry_after
.is_none_or(|deadline| Instant::now() >= deadline)
@@ -548,20 +780,26 @@ impl Monitor {
self.restore(&settings);
}
}
- if success && self.startup_recovery {
+ // Startup catch-up is represented by durable source paths, never a
+ // second all-source scan after finishing targeted work.
+ if success {
self.startup_recovery = false;
- self.recovery = true;
- self.last = Some(Instant::now());
- self.first = self.last;
}
}
+ pub fn try_take(&mut self) -> anyhow::Result<Option<Vec<PathBuf>>> {
+ if let Err(error) = self.persist() {
+ self.retry_after = Some(Instant::now() + Duration::from_secs(30));
+ return Err(error);
+ }
+ Ok(self.take())
+ }
pub fn take(&mut self) -> Option<Vec<PathBuf>> {
let _ = self.persist();
self.journal.begin();
self.journal_inflight = true;
self.last = None;
self.first = None;
- let paths = if self.recovery {
+ let queued = if self.recovery {
self.recovery = false;
self.recovery_saved = false;
self.pending.clear();
@@ -569,10 +807,26 @@ impl Monitor {
} else {
Some(self.pending.drain().collect::<Vec<_>>())
};
+ let paths = queued.as_ref().map(|paths| {
+ let mut ordered = paths.clone();
+ ordered.sort_by_key(|p| p.components().count());
+ let mut selected: Vec<PathBuf> = Vec::new();
+ let mut prefixes = HashSet::new();
+ for path in ordered {
+ if !path
+ .ancestors()
+ .any(|p| prefixes.contains(&crate::config::fold(p)))
+ {
+ prefixes.insert(crate::config::fold(&path));
+ selected.push(path);
+ }
+ }
+ selected
+ });
let mut inflight = vec![];
if let Some(db) = &self.store {
if let Ok(c) = db.connect(true) {
- if let Some(paths) = &paths {
+ if let Some(paths) = &queued {
if let Ok(mut statement) =
c.prepare_cached("SELECT generation FROM native_changes WHERE path=?1")
{
@@ -877,10 +1131,10 @@ mod durable_tests {
let mut resumed = Monitor::default();
resumed.configure(&s, home.path(), &tx.into());
assert!(resumed.ready());
- assert_eq!(resumed.take().unwrap(), vec![path.clone()]);
+ assert_eq!(resumed.take().unwrap(), vec![root.path().to_path_buf()]);
resumed.complete(false, home.path());
assert!(!resumed.recovery);
- assert_eq!(resumed.take().unwrap(), vec![path]);
+ assert_eq!(resumed.take().unwrap(), vec![root.path().to_path_buf()]);
resumed.complete(true, home.path());
let c = resumed.store.as_ref().unwrap().connect(true).unwrap();
assert_eq!(
@@ -914,7 +1168,7 @@ mod durable_tests {
let (tx, _) = crossbeam_channel::unbounded();
let mut resumed = Monitor::default();
resumed.configure(&s, home.path(), &tx.into());
- assert_eq!(resumed.take().unwrap(), vec![path]);
+ assert_eq!(resumed.take().unwrap(), vec![root.path().to_path_buf()]);
}
#[test]
fn explicit_cancel_hold_survives_restart_and_resume_clears_it() {
@@ -944,3 +1198,283 @@ mod durable_tests {
assert_eq!(monitor.generation, generation);
}
}
+
+#[cfg(test)]
+mod scoped_recovery_tests {
+ use super::*;
+ #[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();
+ 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 paths = m.take().unwrap();
+ assert_eq!(paths.len(), 2);
+ assert!(paths.contains(&PathBuf::from("T:\\")));
+ assert!(!paths.contains(&PathBuf::from("C:\\")));
+ m.complete(true, Path::new("unused"));
+ assert!(!m.recovery && m.pending.is_empty());
+ }
+ #[test]
+ fn internal_changes_do_not_enter_queue_even_with_exclusions_disabled() {
+ let mut m = Monitor::default();
+ m.queue_path(PathBuf::from("C:\\$Extend\\$Deleted\\abc"));
+ assert!(m.pending.is_empty() && m.dirty.is_empty());
+ }
+ #[test]
+ fn scoped_completion_preserves_change_received_during_source_scan() {
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.roots = vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let mut m = Monitor::default();
+ m.settings = Some(s.clone());
+ 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();
+ m.store = Some(db);
+ m.queue_path(root.path().join("before.txt"));
+ m.queue_path(root.path().to_path_buf());
+ assert_eq!(m.take().unwrap(), vec![root.path().to_path_buf()]);
+ let after = root.path().join("after.txt");
+ m.queue_path(after.clone());
+ m.complete(true, home.path());
+ assert_eq!(m.take().unwrap(), vec![after]);
+ }
+ #[test]
+ fn real_watcher_reconnects_after_root_recreated_and_catches_up_only_that_root() {
+ let home = tempfile::tempdir().unwrap();
+ let parent = tempfile::tempdir().unwrap();
+ let root = parent.path().join("watched");
+ std::fs::create_dir(&root).unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.watch_changes = true;
+ s.roots = vec![crate::config::Source {
+ path: root.to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let (tx, _) = crossbeam_channel::unbounded();
+ let mut m = Monitor::default();
+ m.configure(&s, home.path(), &tx.into());
+ m.take();
+ m.complete(true, home.path());
+ std::fs::remove_dir(&root).unwrap();
+ let start = Instant::now();
+ while m.watcher_retries.is_empty() && start.elapsed() < Duration::from_secs(4) {
+ m.collect(&s, home.path());
+ std::thread::sleep(Duration::from_millis(30));
+ }
+ assert!(
+ !m.watcher_retries.is_empty(),
+ "failed Windows watch must be reported"
+ );
+ std::fs::create_dir(&root).unwrap();
+ for (_, at) in m.watcher_retries.values_mut() {
+ *at = Instant::now();
+ }
+ m.collect(&s, home.path());
+ assert!(m.watcher_retries.is_empty());
+ assert_eq!(m.take().unwrap(), vec![root.clone()]);
+ m.complete(true, home.path());
+ let file = root.join("after-reconnect.txt");
+ std::fs::write(&file, "reconnected").unwrap();
+ let start = Instant::now();
+ while !m.pending.contains(&file) && start.elapsed() < Duration::from_secs(4) {
+ m.collect(&s, home.path());
+ std::thread::sleep(Duration::from_millis(30));
+ }
+ assert!(m.pending.contains(&file));
+ assert!(!m.recovery);
+ }
+}
+
+#[cfg(test)]
+mod recovery_persistence_tests {
+ use super::*;
+ #[test]
+ fn persistence_failure_keeps_pending_work_and_does_not_dispatch() {
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.roots = vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let db = crate::db::Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ c.execute_batch("CREATE TRIGGER refuse_changes BEFORE INSERT ON native_changes BEGIN SELECT RAISE(FAIL,'injected queue failure'); END;").unwrap();
+ let mut m = Monitor::default();
+ m.store = Some(db);
+ let path = root.path().join("pending.txt");
+ m.queue_path(path.clone());
+ assert!(m.try_take().is_err());
+ assert!(m.pending.contains(&path) && m.dirty.contains(&path));
+ assert!(!m.journal_inflight);
+ assert!(!m.ready());
+ c.execute_batch("DROP TRIGGER refuse_changes").unwrap();
+ assert_eq!(m.try_take().unwrap().unwrap(), vec![path]);
+ }
+ #[test]
+ fn asynchronous_watch_errors_keep_exponential_backoff_until_events_resume() {
+ let mut m = Monitor::default();
+ let path = PathBuf::from("T:\\");
+ for n in 1..=4 {
+ m.schedule_watch_retry(&[path.clone()]);
+ assert_eq!(m.watcher_retries[&path].0, n);
+ assert_eq!(m.watcher_failures[&path], n);
+ m.watcher_retries.clear();
+ }
+ }
+}
+
+#[cfg(test)]
+mod notification_origin_tests {
+ use super::*;
+ fn settings() -> Settings {
+ let mut s = Settings::default();
+ s.roots = [r"C:\", r"D:\", r"T:\"]
+ .iter()
+ .map(|p| crate::config::Source {
+ path: (*p).into(),
+ mode: "quick".into(),
+ })
+ .collect();
+ s
+ }
+ #[test]
+ fn empty_windows_overflow_keeps_its_source_even_when_channel_is_full() {
+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
+ let spill = std::sync::Mutex::new(NotificationSpill::default());
+ for _ in 0..1000 {
+ deliver_notification(
+ Ok(notify::Event::new(notify::EventKind::Other)
+ .set_flag(notify::event::Flag::Rescan)),
+ Path::new(r"D:\"),
+ &settings(),
+ Path::new(r"C:\AppData\VectorDash"),
+ &tx,
+ &spill,
+ );
+ }
+ let event = rx.try_recv().unwrap().unwrap();
+ assert_eq!(event.paths, vec![PathBuf::from(r"D:\")]);
+ assert_eq!(
+ spill.lock().unwrap().roots,
+ HashSet::from([PathBuf::from(r"D:\")])
+ );
+ let mut m = Monitor::default();
+ m.settings = Some(settings());
+ m.watcher_recovery(event.paths, "fixture");
+ assert_eq!(m.take().unwrap(), vec![PathBuf::from(r"D:\")]);
+ assert!(!m.recovery);
+ }
+ #[test]
+ fn saturated_error_retains_origin_for_reattachment() {
+ let (tx, _rx) = std::sync::mpsc::sync_channel(0);
+ let spill = std::sync::Mutex::new(NotificationSpill::default());
+ deliver_notification(
+ Err(notify::Error::generic("lost connection")),
+ Path::new(r"T:\"),
+ &settings(),
+ Path::new(r"C:\AppData\VectorDash"),
+ &tx,
+ &spill,
+ );
+ assert_eq!(
+ spill.lock().unwrap().failed,
+ HashSet::from([PathBuf::from(r"T:\")])
+ );
+ assert!(spill.lock().unwrap().roots.is_empty());
+ }
+}
+
+#[cfg(all(test, windows))]
+mod live_journal_overflow_tests {
+ use super::*;
+ #[test]
+ #[ignore = "Requires accessible NTFS journal and explicit test directory"]
+ fn real_changes_survive_repeated_overflows_without_source_rescans() {
+ let base = PathBuf::from(
+ std::env::var("VECTORDASH_JOURNAL_TEST_DIR").expect("explicit fixture directory"),
+ );
+ let home = tempfile::tempdir_in(&base).unwrap();
+ let root = tempfile::Builder::new()
+ .prefix("recovery-live-")
+ .tempdir_in(&base)
+ .unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.watch_changes = true;
+ s.ntfs_journal = true;
+ s.include_hidden = true;
+ s.roots = vec![crate::config::Source {
+ path: root.path().to_string_lossy().into(),
+ mode: "quick".into(),
+ }];
+ let (tx, _rx) = crossbeam_channel::unbounded();
+ let mut m = Monitor::default();
+ m.configure(&s, home.path(), &tx.into());
+ assert!(
+ m.journal.covers(root.path()),
+ "fixture needs an accessible journal"
+ );
+ m.take();
+ m.complete(true, home.path());
+ let file = root.path().join("live-target.txt");
+ assert!(
+ s.searched(&file),
+ "fixture must pass the production source filters"
+ );
+ for step in 0..3 {
+ if step == 2 {
+ std::fs::remove_file(&file).unwrap();
+ } else {
+ std::fs::write(&file, format!("change {step}")).unwrap();
+ }
+ for _ in 0..1500 {
+ deliver_notification(
+ Ok(notify::Event::new(notify::EventKind::Other)
+ .set_flag(notify::event::Flag::Rescan)),
+ root.path(),
+ &s,
+ home.path(),
+ m.sender.as_ref().unwrap(),
+ m.spill.as_ref().unwrap(),
+ );
+ }
+ let start = Instant::now();
+ while start.elapsed() < Duration::from_secs(5) {
+ m.collect(&s, home.path());
+ assert!(
+ !m.pending.contains(root.path()),
+ "overflow must not queue the source root"
+ );
+ assert!(!m.recovery);
+ if m.pending.contains(&file) {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(
+ m.pending.contains(&file),
+ "create/modify/delete must stay targeted: step {step}"
+ );
+ assert_eq!(m.take().unwrap(), vec![file.clone()]);
+ m.complete(true, home.path());
+ }
+ }
+}
diff --git a/native/src/config.rs b/native/src/config.rs
index fdf0cc0..9fa6814 100644
--- a/native/src/config.rs
+++ b/native/src/config.rs
@@ -41,6 +41,7 @@ pub struct Settings {
pub auto_update: bool,
pub update_channel: String,
pub skip_windows_churn: bool,
+ pub include_hidden: bool,
pub embedding_server: String,
pub remote_model: String,
pub remote_context: u32,
@@ -110,6 +111,7 @@ pub struct Settings {
pub type_to_search: bool,
pub close_to_tray: bool,
pub start_with_windows: bool,
+ pub always_admin: bool,
pub start_hidden: bool,
pub schedule: String,
pub schedule_hour: u32,
@@ -191,6 +193,7 @@ impl Default for Settings {
auto_update: false,
update_channel: "Release".into(),
skip_windows_churn: true,
+ include_hidden: true,
embedding_server: String::new(),
remote_model: String::new(),
remote_context: 2048,
@@ -260,6 +263,7 @@ impl Default for Settings {
type_to_search: false,
close_to_tray: true,
start_with_windows: false,
+ always_admin: false,
start_hidden: false,
schedule: "Manual".into(),
schedule_hour: 2,
@@ -473,6 +477,9 @@ impl SearchPolicy {
}
}
pub fn allowed(&self, path: &str, kind: &str) -> bool {
+ if ntfs_internal_path(path) {
+ return false;
+ }
let path = fold(path);
let Some((root, mode)) = self
.roots
@@ -493,7 +500,7 @@ impl SearchPolicy {
}
let start = root.rfind('\\').map_or(0, |i| i + 1);
for name in path[start..].split('\\') {
- if forbidden_name(name, self.churn)
+ if forbidden_name(name, self.churn && (mode == "full" || name != "appdata"))
|| name_matches(name, &self.types)
|| name_matches(name, &self.patterns)
{
@@ -542,6 +549,23 @@ fn name_matches(name: &str, patterns: &[String]) -> bool {
}
})
}
+
+/// Reserved metadata is meaningful only directly below a local volume root.
+/// Do not hide ordinary user folders named `$Extend` deeper in a source.
+pub fn ntfs_internal_path(path: &str) -> bool {
+ let folded = fold(path);
+ let path = folded.strip_prefix("\\\\?\\").unwrap_or(&folded);
+ let bytes = path.as_bytes();
+ if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' || bytes[2] != b'\\' {
+ return false;
+ }
+ let first = path[3..].split('\\').next().unwrap_or("");
+ [
+ "$extend", "$mft", "$mftmirr", "$logfile", "$volume", "$attrdef", "$bitmap", "$boot",
+ "$badclus", "$secure", "$upcase",
+ ]
+ .contains(&first)
+}
fn forbidden_name(name: &str, churn: bool) -> bool {
name.starts_with('.')
|| [
@@ -831,6 +855,16 @@ impl Settings {
})
}
pub fn allowed(&self, p: &Path) -> bool {
+ if ntfs_internal_path(&p.to_string_lossy()) {
+ return false;
+ }
+ #[cfg(windows)]
+ if !self.include_hidden {
+ use std::os::windows::fs::MetadataExt;
+ if std::fs::symlink_metadata(p).is_ok_and(|m| m.file_attributes() & 0x2 != 0) {
+ return false;
+ }
+ }
if self.exclusions.iter().any(|r| {
if r.contains(['*', '?']) {
excluded_type(p, r)
@@ -881,6 +915,7 @@ impl Settings {
return false;
}
if self.skip_windows_churn
+ && (mode(&p.to_string_lossy(), self) == "full" || name != "appdata")
&& ["windows", "appdata", "temp", "cache", "caches"].contains(&name.as_str())
{
return false;
@@ -1310,3 +1345,37 @@ mod server_mode_tests {
assert_eq!(Settings::load(temp.path()).unwrap(), s);
}
}
+
+#[cfg(test)]
+mod ntfs_metadata_tests {
+ use super::*;
+ #[test]
+ fn rooted_ntfs_metadata_filtered_in_scanning_and_search() {
+ let mut s = Settings::default();
+ s.include_hidden = true;
+ s.skip_windows_churn = false;
+ s.roots = vec![Source {
+ path: "C:\\".into(),
+ mode: "quick".into(),
+ }];
+ let policy = SearchPolicy::new(&s, "All files", "", "");
+ for path in [
+ "C:\\$Extend\\$Deleted\\abc",
+ "c:/$MFT",
+ "\\\\?\\C:\\$Extend\\$ObjId",
+ ] {
+ assert!(ntfs_internal_path(path));
+ assert!(!s.allowed(Path::new(path)));
+ assert!(!policy.allowed(path, "file"));
+ }
+ for path in [
+ "C:\\Projects\\$Extend\\notes.txt",
+ "C:\\$Budget.txt",
+ "C:\\Users\\example\\AppData\\Local\\RHI\\nvngx.dll",
+ ] {
+ assert!(!ntfs_internal_path(path));
+ assert!(s.allowed(Path::new(path)));
+ assert!(policy.allowed(path, "file"));
+ }
+ }
+}
diff --git a/native/src/db.rs b/native/src/db.rs
index 23b6fa7..2f982aa 100644
--- a/native/src/db.rs
+++ b/native/src/db.rs
@@ -77,6 +77,9 @@ impl Database {
conn.execute_batch("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS names(path TEXT PRIMARY KEY,name TEXT,parent TEXT,kind TEXT,folded TEXT,base TEXT,mtime INTEGER DEFAULT -1,size INTEGER DEFAULT -1,index_mode TEXT DEFAULT 'full'); CREATE INDEX IF NOT EXISTS names_base ON names(base); CREATE VIRTUAL TABLE IF NOT EXISTS name_words USING fts5(folded,content='names',content_rowid='rowid',tokenize='trigram'); CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY,text TEXT,vector TEXT,mtime INTEGER,size INTEGER); CREATE TABLE IF NOT EXISTS segments(path TEXT,namespace TEXT,kind TEXT,text TEXT,vector TEXT,location TEXT); CREATE INDEX IF NOT EXISTS segments_path ON segments(path,namespace); CREATE VIRTUAL TABLE IF NOT EXISTS words USING fts5(path,text,tokenize='unicode61'); CREATE TABLE IF NOT EXISTS segment_vectors(id INTEGER PRIMARY KEY,namespace TEXT,kind TEXT,channel TEXT,dimension INTEGER,vector BLOB,path TEXT); CREATE INDEX IF NOT EXISTS vectors_path ON segment_vectors(namespace,dimension,path,channel); CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT); CREATE TABLE IF NOT EXISTS source_seen(path TEXT PRIMARY KEY,source TEXT,epoch INTEGER,added INTEGER); CREATE INDEX IF NOT EXISTS seen_source ON source_seen(source,epoch); CREATE TABLE IF NOT EXISTS native_content(path TEXT PRIMARY KEY,fingerprint TEXT,error TEXT); ")?;
conn.execute_batch("CREATE TABLE IF NOT EXISTS native_jobs(path TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,token TEXT NOT NULL,error TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS native_staging(token TEXT,seq INTEGER,kind TEXT,text TEXT,location TEXT,dimension INTEGER,vector BLOB,PRIMARY KEY(token,seq)); CREATE TABLE IF NOT EXISTS native_changes(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,queued INTEGER NOT NULL);")?;
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS native_rebuild_requests(path TEXT PRIMARY KEY);",
+ )?;
crate::index_costs::tables(&conn)?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS native_quick_queue(path TEXT PRIMARY KEY);",
@@ -176,6 +179,8 @@ impl Database {
"native_jobs",
"native_changes",
"native_quick_queue",
+ "native_rebuild_requests",
+ "native_prune_prefixes",
"index_costs",
"index_job_time",
"metadata",
@@ -201,9 +206,69 @@ impl Database {
Err(e) => format!("Entire active index cleared; storage reclamation deferred: {e}. Update index to rebuild when ready."),
})
}
+
+ /// Upgrade cleanup uses direct indexed path ranges, preserving existing policy cursors.
+ pub fn queue_internal_cleanup(&self, s: &Settings) -> Result<bool> {
+ let mut c = self.connect(false)?;
+ let mut volumes = std::collections::BTreeSet::new();
+ for root in &s.roots {
+ let b = root.path.as_bytes();
+ if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
+ volumes.insert(root.path[..2].to_uppercase());
+ }
+ }
+ let signature = format!("{:?}", volumes);
+ let previous: Option<String> = c
+ .query_row(
+ "SELECT value FROM metadata WHERE key='ntfs_internal_cleanup_v1'",
+ [],
+ |r| r.get(0),
+ )
+ .optional()?;
+ if previous.as_deref() == Some(&signature) {
+ return Ok(false);
+ }
+ let tx = c.transaction()?;
+ tx.execute_batch("CREATE TABLE IF NOT EXISTS native_prune_prefixes(path TEXT PRIMARY KEY,cursor TEXT NOT NULL DEFAULT '')")?;
+ for volume in volumes {
+ for name in [
+ "$Extend", "$Mft", "$MftMirr", "$LogFile", "$Volume", "$AttrDef", "$Bitmap",
+ "$Boot", "$BadClus", "$Secure", "$UpCase",
+ ] {
+ tx.execute(
+ "INSERT OR IGNORE INTO native_prune_prefixes VALUES(?1,'')",
+ [format!("{volume}\\{name}")],
+ )?;
+ }
+ }
+ {
+ let mut q=tx.prepare("SELECT path FROM names WHERE base IN ('$extend','$mft','$mftmirr','$logfile','$volume','$attrdef','$bitmap','$boot','$badclus','$secure','$upcase')")?;
+ let rows = q.query_map([], |r| r.get::<_, String>(0))?;
+ for path in rows {
+ let path = path?;
+ if crate::config::ntfs_internal_path(&path) {
+ tx.execute(
+ "INSERT OR IGNORE INTO native_prune_prefixes VALUES(?1,'')",
+ [path],
+ )?;
+ }
+ }
+ }
+ tx.execute(
+ "INSERT OR REPLACE INTO metadata VALUES('ntfs_internal_cleanup_v1',?1)",
+ [signature],
+ )?;
+ tx.execute(
+ "DELETE FROM metadata WHERE key='pruned_source_signature'",
+ [],
+ )?;
+ tx.commit()?;
+ Ok(true)
+ }
/// Bounded metadata-only cleanup; current search policy already hides removed sources.
pub fn prune_step(&self, s: &Settings, signature: &str) -> Result<bool> {
let mut c = self.connect(false)?;
+ c.execute_batch("CREATE TABLE IF NOT EXISTS native_prune_prefixes(path TEXT PRIMARY KEY,cursor TEXT NOT NULL DEFAULT '')")?;
let active = cached_query_row(
&c,
"SELECT value FROM metadata WHERE key='prune_target'",
@@ -212,6 +277,35 @@ impl Database {
)
.optional()?;
if active.as_deref() != Some(signature) {
+ // Discover excluded folder prefixes through names_base once. Drain
+ // them through path-index ranges instead of walking millions of
+ // unrelated names before reaching a Windows/cache subtree.
+ let tx = c.transaction()?;
+ let old_prefixes = {
+ let mut q = tx.prepare("SELECT path FROM native_prune_prefixes")?;
+ q.query_map([], |r| r.get::<_, String>(0))?
+ .collect::<rusqlite::Result<Vec<_>>>()?
+ };
+ for path in old_prefixes {
+ if !crate::config::ntfs_internal_path(&path) {
+ tx.execute("DELETE FROM native_prune_prefixes WHERE path=?1", [path])?;
+ }
+ }
+ if s.skip_windows_churn {
+ let policy = crate::config::SearchPolicy::new(s, "All files", "", "");
+ let mut q = tx.prepare("SELECT path FROM names WHERE base IN ('windows','appdata','temp','cache','caches') AND kind='folder'")?;
+ let paths = q.query_map([], |r| r.get::<_, String>(0))?;
+ for path in paths {
+ let path = path?;
+ if !policy.allowed(&path, "folder") {
+ tx.execute(
+ "INSERT OR IGNORE INTO native_prune_prefixes VALUES(?1,'')",
+ [&path],
+ )?;
+ }
+ }
+ }
+ tx.commit()?;
cached_execute(
&c,
"INSERT OR REPLACE INTO metadata VALUES('prune_target',?1)",
@@ -223,6 +317,45 @@ impl Database {
[],
)?;
}
+ let started = std::time::Instant::now();
+ let policy = crate::config::SearchPolicy::new(s, "All files", "", "");
+ loop {
+ let prefix: Option<(String, String)> = c
+ .query_row(
+ "SELECT path,cursor FROM native_prune_prefixes ORDER BY path LIMIT 1",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()?;
+ let Some((prefix, cursor)) = prefix else {
+ break;
+ };
+ let lower = format!("{}\\", prefix.trim_end_matches(['\\', '/']));
+ let upper = format!("{lower}{}", char::MAX);
+ let paths: Vec<String> = c.prepare_cached("SELECT path FROM names WHERE path>=?1 AND path<?3 AND (path=?1 OR path>=?2) AND path>?4 ORDER BY path LIMIT 128")?
+ .query_map(params![prefix, lower, upper, cursor], |r| r.get(0))?
+ .collect::<rusqlite::Result<_>>()?;
+ if paths.is_empty() {
+ c.execute("DELETE FROM native_prune_prefixes WHERE path=?1", [&prefix])?;
+ } else {
+ let last = paths.last().unwrap();
+ let removed: Vec<String> = paths
+ .iter()
+ .filter(|p| !policy.allowed(p, "file"))
+ .cloned()
+ .collect();
+ let tx = c.transaction()?;
+ Self::delete_batch(&tx, &removed)?;
+ tx.execute(
+ "UPDATE native_prune_prefixes SET cursor=?2 WHERE path=?1",
+ params![prefix, last],
+ )?;
+ tx.commit()?;
+ }
+ if started.elapsed() >= Duration::from_millis(25) {
+ return Ok(false);
+ }
+ }
let cursor = cached_query_row(
&c,
"SELECT value FROM metadata WHERE key='prune_cursor'",
@@ -247,15 +380,17 @@ impl Database {
let tx = c.transaction()?;
let started = std::time::Instant::now();
let mut cursor = String::new();
+ let mut removed = vec![];
for path in paths {
if !policy.allowed(&path, "file") {
- Self::delete(&tx, &path)?;
+ removed.push(path.clone());
}
cursor = path;
if started.elapsed() > Duration::from_millis(25) {
break;
}
}
+ Self::delete_batch(&tx, &removed)?;
tx.execute(
"INSERT OR REPLACE INTO metadata VALUES('prune_cursor',?1)",
[cursor],
@@ -434,45 +569,72 @@ impl Database {
)?;
Ok(reason)
}
- pub fn delete(c: &Connection, path: &str) -> Result<()> {
- if let Some((id, folded)) = c
- .query_row(
- "SELECT rowid,folded FROM names WHERE path=?1",
- [path],
- |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)),
- )
- .optional()?
- {
- cached_execute(
- &c,
- "INSERT INTO name_words(name_words,rowid,folded) VALUES('delete',?1,?2)",
- params![id, folded],
- )?;
- cached_execute(&c, "DELETE FROM names WHERE rowid=?1", [id])?;
- }
+ /// words.rowid and segment_vectors.id are the owning segments.rowid.
+ /// Resolve those IDs through segments_path before deleting the segments.
+ fn delete_content(c: &Connection, path: &str) -> Result<()> {
cached_execute(
- &c,
- "INSERT INTO metadata VALUES('native_vectors_generation','1') ON CONFLICT(key) DO UPDATE SET value=cast(value AS INTEGER)+1",
- [],
+ c,
+ "DELETE FROM words WHERE rowid IN (SELECT rowid FROM segments WHERE path=?1)",
+ [path],
)?;
cached_execute(
- &c,
- "DELETE FROM native_staging WHERE token IN (SELECT token FROM native_jobs WHERE path=?1)",
+ c,
+ "DELETE FROM segment_vectors WHERE id IN (SELECT rowid FROM segments WHERE path=?1)",
[path],
)?;
- for table in [
- "native_jobs",
- "native_changes",
- "native_quick_queue",
- "index_job_time",
- "words",
- "segments",
- "segment_vectors",
- "files",
- "source_seen",
- "native_content",
- ] {
- cached_execute(&c, &format!("DELETE FROM {table} WHERE path=?1"), [path])?;
+ cached_execute(c, "DELETE FROM segments WHERE path=?1", [path])?;
+ Ok(())
+ }
+ pub fn delete(c: &Connection, path: &str) -> Result<()> {
+ Self::delete_batch(c, &[path.to_owned()])
+ }
+ /// Atomic, bounded batches avoid per-path FTS/vector table scans. The temp
+ /// table belongs only to this connection; no schema migration is required.
+ pub fn delete_batch(c: &Connection, paths: &[String]) -> Result<()> {
+ for paths in paths.chunks(128) {
+ c.execute_batch("CREATE TEMP TABLE IF NOT EXISTS cleanup_paths(path TEXT PRIMARY KEY) WITHOUT ROWID; SAVEPOINT cleanup_batch;")?;
+ let result = (|| -> Result<()> {
+ c.execute("DELETE FROM cleanup_paths", [])?;
+ for path in paths {
+ cached_execute(c, "INSERT OR IGNORE INTO cleanup_paths VALUES(?1)", [path])?;
+ }
+ c.execute_batch("INSERT INTO name_words(name_words,rowid,folded) SELECT 'delete',rowid,folded FROM names WHERE path IN (SELECT path FROM cleanup_paths);
+ DELETE FROM words WHERE rowid IN (SELECT rowid FROM segments WHERE path IN (SELECT path FROM cleanup_paths));
+ DELETE FROM segment_vectors WHERE id IN (SELECT rowid FROM segments WHERE path IN (SELECT path FROM cleanup_paths));
+ DELETE FROM segments WHERE path IN (SELECT path FROM cleanup_paths);
+ DELETE FROM native_staging WHERE token IN (SELECT token FROM native_jobs WHERE path IN (SELECT path FROM cleanup_paths));")?;
+ for table in [
+ "names",
+ "native_jobs",
+ "native_changes",
+ "native_quick_queue",
+ "native_rebuild_requests",
+ "index_job_time",
+ "files",
+ "source_seen",
+ "native_content",
+ ] {
+ c.execute(
+ &format!(
+ "DELETE FROM {table} WHERE path IN (SELECT path FROM cleanup_paths)"
+ ),
+ [],
+ )?;
+ }
+ cached_execute(
+ c,
+ "INSERT INTO metadata VALUES('native_vectors_generation','1') ON CONFLICT(key) DO UPDATE SET value=cast(value AS INTEGER)+1",
+ [],
+ )?;
+ c.execute("DELETE FROM cleanup_paths", [])?;
+ Ok(())
+ })();
+ if result.is_ok() {
+ c.execute_batch("RELEASE cleanup_batch")?;
+ } else {
+ c.execute_batch("ROLLBACK TO cleanup_batch; RELEASE cleanup_batch")?;
+ }
+ result?;
}
Ok(())
}
@@ -490,9 +652,7 @@ impl Database {
[],
)?;
let result = (|| -> Result<()> {
- for table in ["words", "segments", "segment_vectors"] {
- cached_execute(&c, &format!("DELETE FROM {table} WHERE path=?1"), [path])?;
- }
+ Self::delete_content(c, path)?;
for (i, segment) in records.iter().enumerate() {
let v = vectors.get(i).cloned().unwrap_or_default();
let location=serde_json::json!({"page":segment.page,"seconds":segment.seconds,"line":segment.line,"embedding_source":if segment.media.is_empty(){"text"}else{"media"}}).to_string();
@@ -641,6 +801,16 @@ pub fn names(
excluded: &str,
) -> Result<Vec<Hit>> {
let filters = crate::search_filters::Filters::parse(query)?;
+ if let Some(path_query) = path_query(&filters.text) {
+ return path_names(db, &path_query, &filters, s, category, scope, excluded);
+ }
+ if let Some(pattern) = filters
+ .pattern
+ .as_deref()
+ .filter(|_| filters.text.is_empty())
+ {
+ return path_names(db, pattern, &filters, s, category, scope, excluded);
+ }
if filters.active() {
return filtered_names(db, &filters, s, category, scope, excluded);
}
@@ -698,6 +868,137 @@ pub fn names(
result.truncate(100);
Ok(result)
}
+/// Explicit path fragments constrain the ancestor folders and final name.
+/// Leading separators mean "in any parent folder", rather than a drive root.
+pub fn path_query(query: &str) -> Option<String> {
+ let query = query.trim().trim_matches('"');
+ if !query.contains(['\\', '/']) || query.contains("://") {
+ return None;
+ }
+ let normalized = query.replace('/', "\\").to_lowercase();
+ let parts: Vec<_> = normalized.split('\\').filter(|p| !p.is_empty()).collect();
+ if parts.is_empty() {
+ return None;
+ }
+ Some(parts.join("\\"))
+}
+
+fn path_fragment_matches(path: &str, query: &str) -> bool {
+ let path = crate::config::fold(path);
+ let (parent, name) = path.rsplit_once('\\').unwrap_or(("", &path));
+ let (folders, last) = query.rsplit_once('\\').unwrap_or(("", query));
+ let name_matches = if last.contains(['*', '?']) {
+ crate::config::wildcard_match(name, last)
+ } else {
+ name.starts_with(last)
+ };
+ if !name_matches || folders.is_empty() {
+ return name_matches;
+ }
+ let pattern = format!("*\\{folders}");
+ let mut ancestor = parent;
+ loop {
+ if crate::config::wildcard_match(&format!("\\{ancestor}"), &pattern) {
+ return true;
+ }
+ let Some((next, _)) = ancestor.rsplit_once('\\') else {
+ return false;
+ };
+ ancestor = next;
+ }
+}
+
+fn path_names(
+ db: &Database,
+ query: &str,
+ filters: &crate::search_filters::Filters,
+ s: &Settings,
+ category: &str,
+ scope: &str,
+ excluded: &str,
+) -> Result<Vec<Hit>> {
+ let c = db.connect(true)?;
+ register_search(&c, s, category, scope, excluded, Some(filters))?;
+ let query_owned = query.to_owned();
+ c.create_scalar_function(
+ "vd_path_match",
+ 1,
+ rusqlite::functions::FunctionFlags::SQLITE_UTF8
+ | rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC,
+ move |ctx| {
+ Ok(path_fragment_matches(
+ ctx.get_raw(0).as_str()?,
+ &query_owned,
+ ))
+ },
+ )?;
+ // Descendants may separate the parent fragment and final filename, so use
+ // indexed literal terms rather than requiring one contiguous FTS phrase.
+ let mut terms = query
+ .split(['\\', '*', '?'])
+ .filter(|s| s.chars().count() >= 3)
+ .map(|s| format!("\"{}\"", s.replace('"', "\"\"")))
+ .collect::<Vec<_>>()
+ .join(" AND ");
+ // Explorer-scoped short wildcards such as *nr* cannot use name trigrams,
+ // but their folder scope can. Restrict candidates in the existing index.
+ let scope_folded = crate::config::fold(scope);
+ if scope_folded.chars().count() >= 3 {
+ if !terms.is_empty() {
+ terms.push_str(" AND ");
+ }
+ terms.push_str(&format!("\"{}\"", scope_folded.replace('"', "\"\"")));
+ }
+ let use_fts = !terms.is_empty();
+ let sql = format!(
+ "SELECT n.path,n.name,n.kind FROM names n WHERE {} vd_path_match(n.path) AND vd_match(n.path,n.kind,n.mtime,n.size) ORDER BY length(n.path),n.path LIMIT 400",
+ if use_fts {
+ "n.rowid IN (SELECT rowid FROM name_words WHERE name_words MATCH ?1) AND"
+ } else {
+ ""
+ }
+ );
+ let mut stmt = c.prepare_cached(&sql)?;
+ let values = if use_fts { vec![terms] } else { vec![] };
+ let mut result = vec![];
+ for row in stmt.query_map(rusqlite::params_from_iter(values), |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ ))
+ })? {
+ let (path, name, kind) = row?;
+ let exact = crate::config::fold(&path).ends_with(query);
+ add_name(
+ &mut result,
+ (path, name, kind),
+ query,
+ s,
+ category,
+ scope,
+ excluded,
+ );
+ if let Some(hit) = result.last_mut() {
+ hit.score = if exact { 2.0 } else { 1.5 };
+ hit.reason = if query.contains('\\') {
+ "Matches the folder path"
+ } else {
+ "Matches the file or folder name"
+ }
+ .into();
+ }
+ }
+ result.sort_by(|a, b| {
+ b.score
+ .total_cmp(&a.score)
+ .then(a.path.len().cmp(&b.path.len()))
+ .then(a.path.cmp(&b.path))
+ });
+ result.truncate(100);
+ Ok(result)
+}
+
fn add_name(
out: &mut Vec<Hit>,
(path, name, kind): (String, String, String),
@@ -943,6 +1244,26 @@ mod tests {
}
}
impl Database {
+ /// Remove an obsolete queued attempt without touching completed embeddings.
+ pub fn discard_job(c: &Connection, path: &str) -> Result<()> {
+ c.execute_batch("SAVEPOINT discard_job")?;
+ let result = (|| -> Result<()> {
+ cached_execute(
+ c,
+ "DELETE FROM native_staging WHERE token IN (SELECT token FROM native_jobs WHERE path=?1)",
+ [path],
+ )?;
+ cached_execute(c, "DELETE FROM native_jobs WHERE path=?1", [path])?;
+ cached_execute(c, "DELETE FROM index_job_time WHERE path=?1", [path])?;
+ Ok(())
+ })();
+ if result.is_ok() {
+ c.execute_batch("RELEASE discard_job")?;
+ } else {
+ c.execute_batch("ROLLBACK TO discard_job; RELEASE discard_job")?;
+ }
+ result
+ }
pub fn prepare_job(c: &Connection, path: &str, fingerprint: &str) -> Result<(String, usize)> {
c.execute_batch("CREATE TABLE IF NOT EXISTS native_jobs(path TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,token TEXT NOT NULL,error TEXT NOT NULL DEFAULT ''); CREATE TABLE IF NOT EXISTS native_staging(token TEXT,seq INTEGER,kind TEXT,text TEXT,location TEXT,dimension INTEGER,vector BLOB,PRIMARY KEY(token,seq));")?;
let old = c
@@ -953,8 +1274,18 @@ impl Database {
)
.optional()?;
if let Some((stamp, token)) = &old {
- if stamp == fingerprint {
- cached_execute(&c, "UPDATE native_jobs SET error='' WHERE path=?1", [path])?;
+ if stamp == fingerprint
+ || crate::engine::content_equivalent(
+ stamp,
+ fingerprint,
+ &crate::content::extension(Path::new(path)),
+ )
+ {
+ cached_execute(
+ &c,
+ "UPDATE native_jobs SET fingerprint=?2,error='' WHERE path=?1",
+ params![path, fingerprint],
+ )?;
let next = cached_query_row(
&c,
"SELECT coalesce(max(seq)+1,0) FROM native_staging WHERE token=?1",
@@ -1029,6 +1360,22 @@ impl Database {
) -> Result<()> {
c.execute_batch("CREATE TABLE IF NOT EXISTS native_staging(token TEXT,seq INTEGER,kind TEXT,text TEXT,location TEXT,dimension INTEGER,vector BLOB,PRIMARY KEY(token,seq)); BEGIN IMMEDIATE")?;
let result = (|| -> Result<()> {
+ let previous: Option<usize> = c
+ .query_row(
+ "SELECT dimension FROM native_staging WHERE token=?1 AND dimension>0 LIMIT 1",
+ [token],
+ |r| r.get(0),
+ )
+ .optional()?;
+ let expected =
+ previous.or_else(|| vectors.iter().find(|v| !v.is_empty()).map(Vec::len));
+ anyhow::ensure!(
+ vectors
+ .iter()
+ .filter(|v| !v.is_empty())
+ .all(|v| Some(v.len()) == expected),
+ "Embedding dimensions differ from saved chunks. Select a compatible model or explicitly rebuild full content."
+ );
for (i, record) in records.iter().enumerate() {
let vector = vectors.get(i).cloned().unwrap_or_default();
let bytes: Vec<u8> = vector.iter().flat_map(|v| v.to_le_bytes()).collect();
@@ -1059,9 +1406,7 @@ impl Database {
pub fn finish_stage(c: &Connection, token: &str, path: &str, fingerprint: &str) -> Result<()> {
c.execute_batch("CREATE TABLE IF NOT EXISTS native_jobs(path TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,token TEXT NOT NULL,error TEXT NOT NULL DEFAULT ''); SAVEPOINT file_update")?;
let result = (|| -> Result<()> {
- for table in ["words", "segment_vectors", "segments"] {
- cached_execute(&c, &format!("DELETE FROM {table} WHERE path=?1"), [path])?;
- }
+ Self::delete_content(c, path)?;
let mut stmt=c.prepare_cached("SELECT kind,text,location,dimension,vector FROM native_staging WHERE token=?1 ORDER BY seq")?;
let mut rows = stmt.query([token])?;
while let Some(row) = rows.next()? {
@@ -1112,6 +1457,11 @@ impl Database {
"DELETE FROM native_jobs WHERE path=?1 AND token=?2",
params![path, token],
)?;
+ cached_execute(
+ c,
+ "DELETE FROM native_rebuild_requests WHERE path=?1",
+ [path],
+ )?;
cached_execute(
&c,
"INSERT INTO metadata VALUES('index_session_completed','1') ON CONFLICT(key) DO UPDATE SET value=cast(value AS INTEGER)+1",
@@ -1529,3 +1879,461 @@ mod clear_index_tests {
}
}
}
+
+#[cfg(test)]
+mod path_search_tests {
+ use super::*;
+ #[test]
+ fn path_fragments_match_consecutive_folders_and_files() {
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ encrypt_index: false,
+ excluded_sensitive: false,
+ skip_windows_churn: false,
+ roots: [r"C:\", r"D:\"]
+ .iter()
+ .map(|p| crate::config::Source {
+ path: (*p).into(),
+ mode: "quick".into(),
+ })
+ .collect(),
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for (path, kind) in [
+ (r"C:\Users\test\AppData\Local", "folder"),
+ (r"C:\Users\test\AppData\Local\RHI", "folder"),
+ (r"C:\Users\test\AppData\Local\RHI\nvngx_dlssnr.dll", "file"),
+ (r"D:\Games\RHI\nvngx_dlssnr.dll", "file"),
+ (r"D:\Games\NotRHI\nvngx_dlssnr.dll", "file"),
+ (r"D:\Games\RHI\nested\nvngx_dlssnr.dll", "file"),
+ (r"D:\Games\Local\other\RHI", "folder"),
+ (r"D:\AppData\LocalBackup", "folder"),
+ (r"D:\Space Folder\RHI\note.txt", "file"),
+ ] {
+ Database::touch_name(&c, Path::new(path), kind, 10, 20, "quick", r"C:\", 1).unwrap();
+ }
+ for (query, count) in [
+ (r"\Local\RHI", 2),
+ (r"appdata\local", 2),
+ (r"\RHI\nvngx_dlssnr.dll", 3),
+ ("/rhi/NVNGX_DLSSNR.DLL", 3),
+ (r"\RHI\nvngx", 3),
+ (r"C:\Users\test\AppData\Local\RHI", 1),
+ (r"\RHI\nvngx_dlssnr.dll ext:dll size:>10", 3),
+ (r"\RHI\nvngx_dlssnr.dll ext:txt", 0),
+ (r"Space Folder\RHI\note", 1),
+ (r"*\*nr*", 4),
+ (r"RHI\*nr*", 3),
+ (r"*nr*", 4),
+ ] {
+ let hits = names(&db, query, &s, "All files", "", "").unwrap();
+ assert_eq!(hits.len(), count, "{query}: {hits:?}");
+ }
+ let hits = names(
+ &db,
+ r"\RHI\nvngx_dlssnr.dll",
+ &s,
+ "All files",
+ r"D:\Games",
+ "",
+ )
+ .unwrap();
+ assert_eq!(hits.len(), 2);
+ assert!(
+ names(&db, r"\RHI\nvngx_dlssnr.dll", &s, "All files", "", "dll")
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ names(&db, r"\RHI\nvngx_dlssnr.dll", &s, "Folders", "", "")
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ names(&db, "nvngx_dlssnr.dll", &s, "All files", "", "")
+ .unwrap()
+ .len(),
+ 4
+ );
+ assert!(path_query("https://example.com").is_none());
+ }
+}
+
+#[cfg(test)]
+mod cleanup_tests {
+ use super::*;
+ fn fixture(encrypted: bool) -> (tempfile::TempDir, Database) {
+ let home = tempfile::tempdir().unwrap();
+ let s = Settings {
+ encrypt_index: encrypted,
+ ..Default::default()
+ };
+ let db = Database::new(home.path(), &s).unwrap();
+ (home, db)
+ }
+ fn insert(c: &Connection, path: &str, content: bool) {
+ Database::touch_name(
+ c,
+ Path::new(path),
+ "file",
+ 1,
+ 20,
+ if content { "full" } else { "quick" },
+ r"C:\",
+ 1,
+ )
+ .unwrap();
+ if content {
+ Database::save_segments(
+ c,
+ path,
+ &[crate::content::Segment::text(
+ "text",
+ format!("unique {path}"),
+ 1,
+ 0,
+ )],
+ &[vec![1.0, 0.0]],
+ "fixture",
+ )
+ .unwrap();
+ }
+ }
+ #[test]
+ fn batched_cleanup_is_atomic_and_preserves_unrelated_search_records() {
+ for encrypted in [false, true] {
+ let (_h, db) = fixture(encrypted);
+ let c = db.connect(false).unwrap();
+ insert(&c, r"C:\keep.txt", true);
+ insert(&c, r"C:\remove.txt", true);
+ insert(&c, r"C:\quick.txt", false);
+ c.execute(
+ "INSERT INTO native_jobs VALUES(?1,'f','token','')",
+ [r"C:\remove.txt"],
+ )
+ .unwrap();
+ c.execute_batch("INSERT INTO native_staging VALUES('token',0,'text','pending','{}',2,X'0000000000000000');").unwrap();
+ c.execute_batch("CREATE TEMP TRIGGER fail_cleanup BEFORE DELETE ON names BEGIN SELECT RAISE(ABORT,'fixture failure'); END;").unwrap();
+ let paths = vec![r"C:\remove.txt".into(), r"C:\quick.txt".into()];
+ assert!(Database::delete_batch(&c, &paths).is_err());
+ for table in ["names", "source_seen"] {
+ assert_eq!(
+ c.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 3
+ );
+ }
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM words WHERE words MATCH 'unique'",
+ [],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 2
+ );
+ c.execute_batch("DROP TRIGGER fail_cleanup").unwrap();
+ Database::delete_batch(&c, &paths).unwrap();
+ Database::delete_batch(&c, &paths).unwrap(); // retry is safe
+ for table in [
+ "names",
+ "source_seen",
+ "segments",
+ "segment_vectors",
+ "words",
+ "native_content",
+ ] {
+ assert_eq!(
+ c.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 1,
+ "{table}"
+ );
+ }
+ for table in ["native_jobs", "native_staging"] {
+ assert_eq!(
+ c.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ }
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM name_words WHERE name_words MATCH 'keep'",
+ [],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 1
+ );
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM name_words WHERE name_words MATCH 'remove'",
+ [],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 0
+ );
+ // Replacing content must use the same indexed route and retain new content.
+ Database::save_segments(
+ &c,
+ r"C:\keep.txt",
+ &[crate::content::Segment::text(
+ "text",
+ "replacement".into(),
+ 1,
+ 0,
+ )],
+ &[vec![0.0, 1.0]],
+ "new",
+ )
+ .unwrap();
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM words WHERE words MATCH 'unique'",
+ [],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM words WHERE words MATCH 'replacement'",
+ [],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 1
+ );
+ for sql in [
+ "DELETE FROM words WHERE rowid IN (SELECT rowid FROM segments WHERE path=?1)",
+ "DELETE FROM segment_vectors WHERE id IN (SELECT rowid FROM segments WHERE path=?1)",
+ ] {
+ let plans = c
+ .prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
+ .unwrap()
+ .query_map([r"C:\quick.txt"], |r| r.get::<_, String>(3))
+ .unwrap()
+ .collect::<rusqlite::Result<Vec<_>>>()
+ .unwrap()
+ .join("; ");
+ assert!(plans.contains("segments_path"), "{plans}");
+ assert!(!plans.contains("SCAN segment_vectors"), "{plans}");
+ assert!(
+ !plans
+ .split(';')
+ .any(|p| p.trim() == "SCAN words VIRTUAL TABLE INDEX 0:"),
+ "{plans}"
+ );
+ }
+ }
+ }
+ #[test]
+ #[ignore = "explicit cleanup performance comparison"]
+ fn cleanup_benchmark_old_vs_batched() {
+ let (_h, db) = fixture(false);
+ let c = db.connect(false).unwrap();
+ let records: Vec<_> = (0..20000)
+ .map(|i| {
+ crate::content::Segment::text(
+ "text",
+ format!("retained chunk {i} with searchable content"),
+ 1,
+ 0,
+ )
+ })
+ .collect();
+ Database::save_segments(
+ &c,
+ r"C:\retained.txt",
+ &records,
+ &vec![vec![1.0, 0.0]; records.len()],
+ "fixture",
+ )
+ .unwrap();
+ let paths: Vec<String> = (0..500).map(|i| format!(r"C:\stale{i}.txt")).collect();
+ c.execute_batch("BEGIN").unwrap();
+ for path in &paths {
+ insert(&c, path, false);
+ }
+ c.execute_batch("COMMIT").unwrap();
+ let mut legacy = Connection::open_in_memory().unwrap();
+ rusqlite::backup::Backup::new(&c, &mut legacy)
+ .unwrap()
+ .run_to_completion(1000, Duration::from_millis(1), None)
+ .unwrap();
+ let began = std::time::Instant::now();
+ legacy.execute_batch("BEGIN").unwrap();
+ for path in &paths {
+ let (id, folded): (i64, String) = legacy
+ .query_row(
+ "SELECT rowid,folded FROM names WHERE path=?1",
+ [path],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ legacy
+ .execute(
+ "INSERT INTO name_words(name_words,rowid,folded) VALUES('delete',?1,?2)",
+ params![id, folded],
+ )
+ .unwrap();
+ for table in [
+ "names",
+ "words",
+ "segments",
+ "segment_vectors",
+ "source_seen",
+ "native_content",
+ ] {
+ legacy
+ .execute(&format!("DELETE FROM {table} WHERE path=?1"), [path])
+ .unwrap();
+ }
+ }
+ legacy.execute_batch("COMMIT").unwrap();
+ let old = began.elapsed().as_secs_f64();
+ let began = std::time::Instant::now();
+ Database::delete_batch(&c, &paths).unwrap();
+ let new = began.elapsed().as_secs_f64();
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM words", [], |r| r.get::<_, i64>(0))
+ .unwrap(),
+ 20000
+ );
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM segment_vectors", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 20000
+ );
+ assert_eq!(
+ c.query_row("SELECT count(*) FROM names", [], |r| r.get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ println!(
+ "CLEANUP BENCHMARK: 20,000 retained content chunks + 500 stale Quick files; old {old:.4}s; batched {new:.4}s; {:.1}x faster",
+ old / new
+ );
+ }
+}
+
+#[cfg(test)]
+mod deployment_resume_tests {
+ use super::*;
+ #[test]
+ fn provider_switch_keeps_staged_chunks_and_rejects_mixed_dimensions() {
+ let h = tempfile::tempdir().unwrap();
+ let db = Database::new(
+ h.path(),
+ &Settings {
+ encrypt_index: false,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let c = db.connect(false).unwrap();
+ let remote = "v3|1|42|model|http://old-server/v1|true|false|ocr:png-v1";
+ let local = "v3|1|42|model||ocr|ocr:png-v1";
+ let (token, _) = Database::prepare_job(&c, "file.pdf", remote).unwrap();
+ let record = crate::content::Segment::text("text", "saved".into(), 1, 0);
+ Database::stage(&c, &token, 0, &[record.clone()], &[vec![1.0, 0.0]]).unwrap();
+ let (same, count) = Database::prepare_job(&c, "file.pdf", local).unwrap();
+ assert_eq!(same, token);
+ assert_eq!(count, 1);
+ assert!(Database::stage(&c, &token, 1, &[record], &[vec![1.0, 0.0, 0.0]]).is_err());
+ assert_eq!(
+ c.query_row(
+ "SELECT count(*) FROM native_staging WHERE token=?1",
+ [&token],
+ |r| r.get::<_, i64>(0)
+ )
+ .unwrap(),
+ 1
+ );
+ let cache = crate::vector_cache::Cache::default();
+ Database::save_segments(
+ &c,
+ "other.txt",
+ &[crate::content::Segment::text("text", "word".into(), 1, 0)],
+ &[vec![1.0, 0.0]],
+ "fixture",
+ )
+ .unwrap();
+ assert!(
+ cache
+ .get(&c, 3, "Balanced", "FP32")
+ .err()
+ .unwrap()
+ .to_string()
+ .contains("dimensions differ")
+ );
+ }
+}
+
+#[cfg(test)]
+mod internal_cleanup_tests {
+ use super::*;
+ #[test]
+ fn metadata_upgrade_purges_internal_records_without_resetting_existing_cleanup_cursor() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings::default();
+ s.encrypt_index = false;
+ s.skip_windows_churn = false;
+ s.roots = vec![crate::config::Source {
+ path: "C:\\".into(),
+ mode: "quick".into(),
+ }];
+ let db = Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for (path, kind) in [
+ ("C:\\$Extend", "folder"),
+ ("C:\\$Extend\\$Deleted\\old", "file"),
+ ("C:\\$MFT", "file"),
+ ("C:\\Projects\\$Extend\\notes.txt", "file"),
+ ("C:\\ordinary.txt", "file"),
+ ] {
+ Database::touch_name(&c, Path::new(path), kind, 1, 20, "quick", "C:\\", 1).unwrap();
+ }
+ c.execute_batch("CREATE TABLE IF NOT EXISTS native_prune_prefixes(path TEXT PRIMARY KEY,cursor TEXT NOT NULL DEFAULT ''); INSERT OR REPLACE INTO metadata VALUES('prune_target','same-target'); INSERT OR REPLACE INTO metadata VALUES('prune_cursor','zzzz'); INSERT OR REPLACE INTO metadata VALUES('pruned_source_signature','same-target');").unwrap();
+ drop(c);
+ assert!(db.queue_internal_cleanup(&s).unwrap());
+ assert!(!db.queue_internal_cleanup(&s).unwrap());
+ let start = std::time::Instant::now();
+ loop {
+ if db.prune_step(&s, "same-target").unwrap() {
+ break;
+ }
+ assert!(start.elapsed() < Duration::from_secs(3));
+ }
+ let c = db.connect(true).unwrap();
+ let paths = c
+ .prepare("SELECT path FROM names ORDER BY path")
+ .unwrap()
+ .query_map([], |r| r.get::<_, String>(0))
+ .unwrap()
+ .collect::<rusqlite::Result<Vec<_>>>()
+ .unwrap();
+ assert_eq!(
+ paths,
+ vec!["C:\\Projects\\$Extend\\notes.txt", "C:\\ordinary.txt"]
+ );
+ assert_eq!(
+ c.query_row(
+ "SELECT value FROM metadata WHERE key='prune_cursor'",
+ [],
+ |r| r.get::<_, String>(0)
+ )
+ .unwrap(),
+ "zzzz"
+ );
+ }
+}
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 5e234a3..fd132e0 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -47,6 +47,7 @@ pub struct Progress {
#[derive(Clone)]
pub struct NotifySender {
inner: crossbeam_channel::Sender<Event>,
+ full_pending: Arc<AtomicBool>,
ctx: Option<eframe::egui::Context>,
log_path: Option<PathBuf>,
}
@@ -57,6 +58,7 @@ impl NotifySender {
) -> Self {
Self {
inner,
+ full_pending: Arc::new(AtomicBool::new(false)),
ctx,
log_path: None,
}
@@ -122,6 +124,22 @@ impl NotifySender {
}
result
}
+ pub fn smoke_fill_notifications(&self) -> usize {
+ if self.inner.capacity().is_none() {
+ return 0;
+ }
+ while self
+ .inner
+ .try_send(Event::Progress(Progress::default()))
+ .is_ok()
+ {}
+ self.inner.len()
+ }
+ pub fn take_full_request(&self) -> Option<Event> {
+ self.full_pending
+ .swap(false, Ordering::AcqRel)
+ .then_some(Event::Full)
+ }
pub fn try_send(&self, event: Event) -> Result<(), crossbeam_channel::TrySendError<Event>> {
self.record(&event);
let wake = matches!(
@@ -132,7 +150,13 @@ impl NotifySender {
| Event::Full
| Event::Quit
);
- let result = self.inner.try_send(event);
+ let result = match self.inner.try_send(event) {
+ Err(crossbeam_channel::TrySendError::Full(Event::Full)) => {
+ self.full_pending.store(true, Ordering::Release);
+ Ok(())
+ }
+ result => result,
+ };
if result.is_ok() {
if let Some(ctx) = &self.ctx {
ctx.request_repaint();
@@ -214,6 +238,7 @@ pub struct Control {
pub automatic: Arc<AtomicBool>,
pub watching: Arc<AtomicBool>,
stats_busy: Arc<AtomicBool>,
+ stats_counts_changed: Arc<AtomicBool>,
stats_requested: Arc<AtomicBool>,
stats_started: Arc<std::sync::Mutex<Option<Instant>>>,
stats_roots: Arc<std::sync::Mutex<Vec<String>>>,
@@ -336,11 +361,11 @@ impl Control {
}
pub fn source_signature(s: &Settings) -> String {
format!(
- "{:?}|{:?}|{}|{}|{}|{}",
+ "{:?}|{:?}|{}|{:?}|{}|{}",
s.roots,
s.exclusions,
s.excluded_types,
- s.skip_windows_churn,
+ (s.skip_windows_churn, s.include_hidden),
s.code_search,
crate::raw::stamp(s)
)
@@ -449,6 +474,7 @@ impl Engine {
let mut changes = crate::changes::Monitor::default();
let mut last_watch_status = String::new();
let mut acknowledged_full_scan = 0;
+ let mut internal_prune_target = String::new();
let mut pruned_signature = engine
.db
.connect(true)
@@ -541,6 +567,23 @@ impl Engine {
} else {
changes.status(&settings, engine.control.running.load(Ordering::Relaxed))
};
+ crate::tray::publish(crate::tray::Visual {
+ accent: settings.accent,
+ status: crate::tray::status(
+ &settings,
+ crate::tray::Work {
+ running: engine.control.running.load(Ordering::Acquire),
+ paused: engine.control.paused.load(Ordering::Acquire),
+ automatic: engine.control.automatic.load(Ordering::Acquire),
+ watching: engine.control.watching.load(Ordering::Acquire),
+ held: engine.control.automatic_hold.load(Ordering::Acquire),
+ pending: changes.pending_work(),
+ restarting: engine.control.restart_requested.load(Ordering::Acquire),
+ },
+ crate::scheduling::metrics(),
+ chrono::Local::now(),
+ ),
+ });
if watch_status != last_watch_status {
engine.log("Info", format!("File monitoring: {watch_status}"));
let _ = engine.tx.send(Event::WatchStatus(watch_status.clone()));
@@ -559,7 +602,15 @@ impl Engine {
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
- let paths = changes.take();
+ let paths = match changes.try_take() {
+ Ok(paths) => paths,
+ Err(error) => {
+ engine.control.running.store(false, Ordering::Release);
+ engine.log("Warning",format!("Automatic changes retained; durable queue unavailable, retry in 30s: {error:#}"));
+ std::thread::sleep(Duration::from_secs(1));
+ continue;
+ }
+ };
engine.control.watching.store(true, Ordering::Relaxed);
engine.control.automatic.store(true, Ordering::Relaxed);
engine
@@ -614,7 +665,20 @@ impl Engine {
}
}
}
- let signature = format!("visibility-v1|{}", source_signature(&settings));
+ let signature = format!("visibility-v2|{}", source_signature(&settings));
+ if internal_prune_target != signature
+ && !engine.control.running.load(Ordering::Acquire)
+ && !engine.control.index_maintenance.load(Ordering::Acquire)
+ && crate::scheduling::idle_allowed(&settings, crate::scheduling::metrics())
+ .is_ok()
+ {
+ if let Ok(queued) = engine.db.queue_internal_cleanup(&settings) {
+ internal_prune_target = signature.clone();
+ if queued {
+ pruned_signature.clear();
+ }
+ }
+ }
if signature != pruned_signature
&& !engine.control.running.load(Ordering::Acquire)
&& !engine.control.index_maintenance.load(Ordering::Acquire)
@@ -624,6 +688,11 @@ impl Engine {
if let Ok(true) = engine.db.prune_step(&settings, &signature) {
pruned_signature = signature;
engine.vectors.clear();
+ engine.refresh_stats(&settings);
+ engine.log(
+ "Info",
+ "Saved exclusions applied; database cleanup complete",
+ );
}
}
std::thread::sleep(Duration::from_secs(1));
@@ -689,6 +758,9 @@ impl Engine {
return;
}
self.control.cancel.store(false, Ordering::Relaxed);
+ self.control
+ .stats_counts_changed
+ .store(false, Ordering::Release);
if self.control.index_maintenance.load(Ordering::Acquire) {
self.control.running.store(false, Ordering::Release);
return;
@@ -733,8 +805,16 @@ impl Engine {
}
owner.control.watching.store(false, Ordering::Relaxed);
owner.control.automatic.store(false, Ordering::Relaxed);
+ let counts_changed = owner
+ .control
+ .stats_counts_changed
+ .swap(false, Ordering::AcqRel);
owner.control.running.store(false, Ordering::SeqCst);
- owner.refresh_stats(&s);
+ // Metadata-only Quick notifications cannot change these totals. Avoid
+ // recounting millions of records after every busy Windows/cache batch.
+ if full_scan || result.is_err() || counts_changed {
+ owner.refresh_stats(&s);
+ }
let _ = owner.tx.send(Event::IndexDone(result));
});
}
@@ -973,11 +1053,9 @@ impl Engine {
"{}|{}|{}|{}|{}|{}|{}|{}",
s.model,
s.projector,
- if s.remote_embeddings() {
- format!("{}|{}", s.remote_url, s.remote_model)
- } else {
- String::new()
- },
+ // Hosting location/model identifiers are not extraction settings.
+ // Keep the field empty to retain a stable legacy stamp layout.
+ String::new(),
s.index_images,
s.index_audio,
s.index_video,
@@ -1023,6 +1101,9 @@ impl Engine {
}
for path in rows {
self.control.file_checkpoint()?;
+ self.control
+ .stats_counts_changed
+ .store(true, Ordering::Release);
Database::delete(&conn, &path)?;
}
}
@@ -1076,7 +1157,8 @@ impl Engine {
{
use std::os::windows::fs::MetadataExt;
let attrs = meta.file_attributes();
- if attrs & (0x2 | 0x400 | 0x1000 | 0x40000 | 0x400000) != 0 {
+ let hidden = if !s.include_hidden { 0x2 } else { 0 };
+ if attrs & (hidden | 0x400 | 0x1000 | 0x40000 | 0x400000) != 0 {
continue;
}
}
@@ -1107,6 +1189,11 @@ impl Engine {
&root_s,
epoch,
)?;
+ if reason == "added" || indexing_mode == "full" {
+ self.control
+ .stats_counts_changed
+ .store(true, Ordering::Release);
+ }
let changed = reason != "unchanged";
if changed {
let line = format!(
@@ -1230,7 +1317,32 @@ impl Engine {
)
.optional()?
.is_some();
+ let rebuild_requested: bool = conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM native_rebuild_requests WHERE path=?1)",
+ [progress.current.as_str()],
+ |r| r.get(0),
+ )?;
+ let completion_current = legacy
+ || previous.as_ref().is_some_and(|p| {
+ p.1.is_empty() && content_equivalent(&p.0, &key, &extension)
+ });
+ if !force && !rebuild_requested && completion_current {
+ let pending: bool = conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM native_jobs WHERE path=?1)",
+ [progress.current.as_str()],
+ |r| r.get(0),
+ )?;
+ if pending {
+ Database::discard_job(&conn, &progress.current)?;
+ self.log("Info", format!("Discarded redundant pending content for {}; completed embeddings are current", progress.current));
+ }
+ }
if !content::supports_content(&extension, s) {
+ Database::discard_job(&conn, &progress.current)?;
+ conn.execute(
+ "DELETE FROM native_rebuild_requests WHERE path=?1",
+ [progress.current.as_str()],
+ )?;
progress.phase = "Filename only — unsupported content type".into();
if previous.as_ref().is_none_or(|p| p.0 != key) {
let has_content = conn
@@ -1258,18 +1370,24 @@ impl Engine {
}
} else if !resumed_done.contains(&progress.current)
&& (force
- || s.index_phase == "resume"
- || resume_paths.contains(&progress.current)
+ || rebuild_requested
|| !legacy
- && previous
- .as_ref()
- .and_then(|p| content_stamp(&p.0, &extension))
- .as_deref()
- != Some(key.as_str())
+ && !previous.as_ref().is_some_and(|p| {
+ content_equivalent(&p.0, &key, &extension)
+ })
|| s.retry_failed
&& previous.as_ref().is_some_and(|p| !p.1.is_empty()))
{
- let reason = if force {
+ if force {
+ // Persist explicit rebuild intent through Quick-first passes,
+ // restart and cancellation, independently of completion stamps.
+ conn.execute(
+ "INSERT OR IGNORE INTO native_rebuild_requests VALUES(?1)",
+ [progress.current.as_str()],
+ )?;
+ Database::discard_job(&conn, &progress.current)?;
+ }
+ let reason = if force || rebuild_requested {
"requested full rebuild"
} else if previous.is_none() {
"missing or unverified completed content metadata"
@@ -1281,12 +1399,24 @@ impl Engine {
.is_some_and(|p| !p.0.contains("html-visible-v1"))
{
"readable HTML extraction upgrade"
+ } else if s.index_phase == "resume"
+ || resume_paths.contains(&progress.current)
+ {
+ "resuming unfinished content"
} else {
- "model or extraction settings changed"
+ "content extraction settings changed"
};
self.log(
"Info",
- format!("Full indexing {}: {reason}", progress.current),
+ format!(
+ "{} {}: {reason}",
+ if s.index_phase == "quick" {
+ "Queued Full content"
+ } else {
+ "Full indexing"
+ },
+ progress.current
+ ),
);
if resume_paths.contains(&progress.current) {
resumed_done.insert(progress.current.clone());
@@ -1569,14 +1699,23 @@ impl Engine {
conn.execute_batch("COMMIT")?;
}
if outcome.is_ok() {
+ let cleanup_started = Instant::now();
+ let mut removed = 0usize;
+ self.log("Info", format!("Deleted-record cleanup started; {} completed source(s); scan counters are separate", complete_roots.len()));
for root in complete_roots {
self.control.file_checkpoint()?;
progress.phase = "Removing deleted index records".into();
+ progress.current = format!(
+ "{removed} records removed · {:.1}s",
+ cleanup_started.elapsed().as_secs_f64()
+ );
let _ = self.tx.send(Event::Progress(progress.clone()));
let mut stmt = conn.prepare(
- "SELECT path FROM source_seen WHERE source=?1 AND epoch<?2 UNION ALL SELECT path FROM source_seen WHERE source=?1 AND epoch>?2 LIMIT 1000",
+ "SELECT path FROM source_seen WHERE source=?1 AND epoch<?2 UNION ALL SELECT path FROM source_seen WHERE source=?1 AND epoch>?2 LIMIT 128",
)?;
loop {
+ // Pause/cancel outside the transaction: never sleep holding
+ // a write lock, and finish at most one 128-path batch.
self.control.file_checkpoint()?;
let paths: Vec<String> = stmt
.query_map(params![root, epoch], |r| r.get(0))?
@@ -1584,14 +1723,22 @@ impl Engine {
if paths.is_empty() {
break;
}
- conn.execute_batch("BEGIN IMMEDIATE")?;
- for path in paths {
- self.control.file_checkpoint()?;
- Database::delete(&conn, &path)?;
- }
- conn.execute_batch("COMMIT")?;
+ Database::delete_batch(&conn, &paths)?;
+ removed += paths.len();
+ progress.current = format!(
+ "{removed} records removed · {:.1}s",
+ cleanup_started.elapsed().as_secs_f64()
+ );
+ let _ = self.tx.send(Event::Progress(progress.clone()));
}
}
+ self.log(
+ "Info",
+ format!(
+ "Deleted-record cleanup complete: {removed} records removed in {:.3}s",
+ cleanup_started.elapsed().as_secs_f64()
+ ),
+ );
}
self.db.generation.fetch_add(1, Ordering::Relaxed);
progress.phase = if outcome.is_ok() {
@@ -1914,6 +2061,19 @@ impl Engine {
}
}
let result = (|| -> Result<Vec<Hit>> {
+ if search_mode != "Semantic" {
+ // Names and launcher actions are independent of model load,
+ // content FTS queries, and previous embedding requests.
+ let names = owner.lexical(&q, &s, "Names", &category, &scope, &excluded)?;
+ let _ = owner.tx.send(Event::SearchPartial(
+ sequence,
+ names.clone(),
+ start.elapsed().as_secs_f64() * 1000.0,
+ ));
+ if search_mode == "Names" {
+ return Ok(names);
+ }
+ }
let hits = owner.lexical(&q, &s, &search_mode, &category, &scope, &excluded)?;
if search_mode != "Semantic" {
let _ = owner.tx.send(Event::SearchPartial(
@@ -2017,6 +2177,11 @@ impl Engine {
if category != "All files" {
hits.clear();
}
+ if crate::db::path_query(&filters.text).is_some()
+ || filters.pattern.is_some() && filters.text.is_empty()
+ {
+ return crate::db::names(&self.db, q, s, category, scope, excluded);
+ }
if mode != "Semantic"
|| category == "Folders"
|| filters.active() && filters.text.is_empty()
@@ -2061,7 +2226,8 @@ impl Engine {
ticket: Option<u64>,
) -> Result<Vec<Hit>> {
let filters = crate::search_filters::Filters::parse(q)?;
- if mode == "Names"
+ if !filters.uses_embeddings()
+ || mode == "Names"
|| category == "Folders"
|| category == "Programs"
|| q.trim().is_empty()
@@ -2255,7 +2421,9 @@ impl Engine {
};
let mut stmt = conn.prepare_cached(sql)?;
let mut rows = stmt.query([vector.len()])?;
+ let mut saw_vector = false;
while let Some(row) = rows.next()? {
+ saw_vector = true;
let id: i64 = row.get(0)?;
let path: String = row.get(1)?;
let kind: String = row.get(2)?;
@@ -2281,6 +2449,15 @@ impl Engine {
pool.truncate(400);
}
}
+ if !saw_vector {
+ let mismatch: Option<usize> = conn.query_row(
+ "SELECT dimension FROM segment_vectors WHERE NOT EXISTS(SELECT 1 FROM segment_vectors WHERE dimension=?1) LIMIT 1",
+ [vector.len()], |r| r.get(0)).optional()?;
+ anyhow::ensure!(
+ mismatch.is_none(),
+ "Embedding dimensions differ from the existing index. Select a compatible model or explicitly use Rebuild full content."
+ );
+ }
}
for ((_, channel), score) in file_maxima {
let total = channel_totals.entry(channel).or_default();
@@ -2425,6 +2602,61 @@ fn content_stamp(raw: &str, ext: &str) -> Option<String> {
}
Some(stamp)
}
+/// Embedding deployment is user-controlled: changing URLs, local paths,
+/// model aliases or projector paths never implicitly rebuilds completed content.
+/// Compare metadata and only the extraction settings encoded by old stamps.
+pub(crate) fn content_equivalent(old: &str, new: &str, ext: &str) -> bool {
+ let (Some(old), Some(new)) = (content_stamp(old, ext), content_stamp(new, ext)) else {
+ return false;
+ };
+ if old == new {
+ return true;
+ }
+ let a: Vec<_> = old.split('|').collect();
+ let b: Vec<_> = new.split('|').collect();
+ if a.len() < 5 || b.len() < 5 || a[1..3] != b[1..3] {
+ return false;
+ }
+ let extras = |fields: &[&str]| {
+ fields
+ .iter()
+ .filter(|v| {
+ v.starts_with("ocr:")
+ || v.starts_with("ocr-lang:")
+ || v.starts_with("visual:")
+ || v.starts_with("pdf:")
+ || v.starts_with("dedupe:")
+ || v.starts_with("video:")
+ || v.starts_with("raw:")
+ || **v == "html-visible-v1"
+ })
+ .map(|v| (*v).to_owned())
+ .collect::<Vec<_>>()
+ };
+ if extras(&a) != extras(&b) {
+ return false;
+ }
+ // Older remote stamps embedded URL|model as two fields in an eight-field
+ // layout, shifting/truncating extractor settings. Those missing values
+ // cannot be reconstructed; adopt the current extraction stamp once without
+ // regenerating unchanged content. Subsequent stamps use the stable layout.
+ if a[4].contains("://") || b[4].contains("://") {
+ return true;
+ }
+ let indices: &[usize] = if content::is_image(ext) {
+ &[6, 7]
+ } else if content::is_video(ext) {
+ &[6, 7]
+ } else if content::is_audio(ext) {
+ &[6]
+ } else if ext == "pdf" || content::is_code(ext) {
+ &[5]
+ } else {
+ &[]
+ };
+ indices.iter().all(|i| a.get(*i) == b.get(*i))
+}
+
/// A child may fail with a network error even though its SMB share is healthy
/// (for example a NAS directory that cannot be enumerated). Only circuit-break
/// the whole source after confirming the root itself is no longer readable.
@@ -2681,15 +2913,27 @@ mod incremental_tests {
};
engine.index_inner(&s, false).unwrap();
assert_eq!(db.stats().unwrap().files, 2);
+ engine
+ .control
+ .stats_counts_changed
+ .store(false, Ordering::Release);
std::fs::write(&a, "changed").unwrap();
let result = engine
.index_paths(&s, false, Some(vec![a.clone()]))
.unwrap();
assert!(result.starts_with("Targeted changes · 1 files"));
+ assert!(
+ !engine.control.stats_counts_changed.load(Ordering::Acquire),
+ "Quick metadata changes must not request a whole-index recount"
+ );
assert_eq!(db.stats().unwrap().files, 2);
std::fs::remove_file(&a).unwrap();
std::fs::remove_dir(&folder).unwrap();
engine.index_paths(&s, false, Some(vec![folder])).unwrap();
+ assert!(
+ engine.control.stats_counts_changed.load(Ordering::Acquire),
+ "Deletions must refresh totals"
+ );
assert_eq!(db.stats().unwrap().files, 1);
assert!(!engine.models.loaded.load(Ordering::Relaxed));
assert!(b.exists());
@@ -2888,7 +3132,7 @@ mod automatic_watch_tests {
loop {
assert!(start.elapsed() < Duration::from_secs(5));
if let Ok(Event::WatchStatus(status)) = rx.recv_timeout(Duration::from_millis(100)) {
- if status.contains("recovery scan queued") {
+ if status.contains("changed paths queued") {
break;
}
}
@@ -3567,3 +3811,128 @@ impl std::fmt::Display for YieldFile {
}
}
impl std::error::Error for YieldFile {}
+
+#[cfg(test)]
+mod deployment_stamp_tests {
+ use super::*;
+ #[test]
+ fn local_remote_aliases_and_paths_preserve_embeddings() {
+ for ext in ["txt", "csv", "png", "mp4", "mp3", "pdf", "rs"] {
+ let a = "1|42|old-model|old-encoder||true|true|true|ocr|false";
+ let b = "1|42|new-model-path|new-encoder-path||true|true|true|ocr|false";
+ let a = content_stamp(a, ext).unwrap();
+ let b = content_stamp(b, ext).unwrap();
+ assert!(content_equivalent(&a, &b, ext), "{ext}");
+ assert!(!content_equivalent(
+ &a,
+ &b.replacen("v3|1|42", "v3|2|42", 1),
+ ext
+ ));
+ }
+ let remote = "v3|1|42|old-model|http://old-server/v1|true|false|ocr:png-v1";
+ let local = "v3|1|42|new-local-model||ocr|ocr:png-v1";
+ assert!(content_equivalent(remote, local, "pdf"));
+ assert!(!content_equivalent(
+ remote,
+ &local.replace("ocr:png-v1", "ocr:off"),
+ "pdf"
+ ));
+ assert!(!content_equivalent(
+ remote,
+ &format!("{local}|pdf:visual"),
+ "pdf"
+ ));
+ let image = "v3|1|42|model||projector|true|ocr|ocr:png-v1";
+ assert!(!content_equivalent(
+ image,
+ &image.replace("|true|ocr", "|false|ocr"),
+ "png"
+ ));
+ }
+}
+
+#[cfg(test)]
+mod actual_quick_user_source_test {
+ use super::*;
+ #[test]
+ #[ignore = "explicit read-only real-user RHI indexing check"]
+ fn actual_user_quick_source_finds_rhi_without_embedding() {
+ let local = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap());
+ let user = local.parent().unwrap().parent().unwrap();
+ let rhi = local.join("RHI");
+ assert!(rhi.is_dir());
+ let home = tempfile::tempdir().unwrap();
+ let mut s = Settings {
+ roots: vec![crate::config::Source {
+ path: user.to_string_lossy().into(),
+ mode: "quick".into(),
+ }],
+ encrypt_index: false,
+ skip_windows_churn: true,
+ include_programs: false,
+ pause_for_game: false,
+ pause_for_fullscreen: false,
+ ..Default::default()
+ };
+ s.index_phase = "quick-final".into();
+ let (tx, _) = crossbeam_channel::unbounded();
+ let e = Engine {
+ db: Database::new(home.path(), &s).unwrap(),
+ models: Models::default(),
+ control: Control::default(),
+ tx: tx.into(),
+ searching: Arc::new(AtomicBool::new(false)),
+ vectors: crate::vector_cache::Cache::default(),
+ };
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_paths(&s, false, Some(vec![rhi.clone()])).unwrap();
+ let folders = crate::db::names(&e.db, r"\Local\RHI", &s, "All files", "", "").unwrap();
+ assert!(folders.iter().any(|h| Path::new(&h.path) == rhi));
+ let dlls =
+ crate::db::names(&e.db, r"\RHI\nvngx_dlssnr.dll", &s, "All files", "", "").unwrap();
+ assert!(dlls.len() >= 3);
+ assert_eq!(e.db.stats().unwrap().vectors, 0);
+ println!(
+ "REAL QUICK USER SOURCE: {} RHI folder results; {} DLL results; zero embeddings; isolated index",
+ folders.len(),
+ dlls.len()
+ );
+ }
+}
+
+#[cfg(test)]
+mod tray_delivery_tests {
+ use super::*;
+ #[test]
+ fn saturated_queue_retains_and_coalesces_tray_open_without_blocking() {
+ let (tx, rx) = crossbeam_channel::bounded(1);
+ let sender = NotifySender::from(tx);
+ sender
+ .try_send(Event::Progress(Progress::default()))
+ .unwrap();
+ for _ in 0..10000 {
+ sender.try_send(Event::Full).unwrap();
+ }
+ assert_eq!(rx.len(), 1);
+ assert!(matches!(sender.take_full_request(), Some(Event::Full)));
+ assert!(sender.take_full_request().is_none());
+ assert!(matches!(rx.recv().unwrap(), Event::Progress(_)));
+ }
+ #[test]
+ fn retained_request_is_shared_by_sender_clones_and_wakes_after_retention() {
+ let (tx, _rx) = crossbeam_channel::bounded(1);
+ let ctx = eframe::egui::Context::default();
+ let sender = NotifySender::new(tx, Some(ctx.clone()));
+ let probe = sender.clone();
+ let seen = Arc::new(AtomicBool::new(false));
+ let check = seen.clone();
+ sender.smoke_fill_notifications();
+ ctx.set_request_repaint_callback(move |_| {
+ assert!(probe.full_pending.load(Ordering::Acquire));
+ check.store(true, Ordering::Release);
+ });
+ sender.try_send(Event::Full).unwrap();
+ assert!(seen.load(Ordering::Acquire));
+ assert!(matches!(sender.take_full_request(), Some(Event::Full)));
+ }
+}
diff --git a/native/src/journal.rs b/native/src/journal.rs
index c1744a6..19f2f08 100644
--- a/native/src/journal.rs
+++ b/native/src/journal.rs
@@ -1,9 +1,12 @@
//! Bounded optional NTFS USN replay; persist cursors only after successful indexing.
+mod directory;
use anyhow::{Context, Result};
+use directory::DirectoryCache;
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
+ time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
struct Mark {
@@ -14,10 +17,40 @@ struct Mark {
struct Saved {
signature: String,
marks: BTreeMap<String, Mark>,
+ #[serde(default)]
+ coverage: BTreeMap<String, String>,
+}
+struct Retry {
+ attempts: u32,
+ bad_batch: bool,
+ after: Instant,
+}
+fn malformed(error: &anyhow::Error) -> bool {
+ #[cfg(windows)]
+ {
+ !error.chain().any(|e| e.is::<windows::core::Error>())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = error;
+ true
+ }
+}
+fn retry_delay(attempts: u32) -> Duration {
+ Duration::from_secs((5u64 << attempts.saturating_sub(1).min(6)).min(300))
}
#[derive(Default)]
pub struct Tracker {
signature: String,
+ coverage: BTreeMap<String, String>,
+ directory_cache: DirectoryCache,
+ flight_cache: Option<DirectoryCache>,
+ encrypt_cache: bool,
+ retries: BTreeMap<String, Retry>,
+ logger: Option<crate::engine::NotifySender>,
+ roots: Vec<PathBuf>,
+ resolution_warning: BTreeMap<String, Instant>,
+ missing_names: BTreeMap<(String, String), i64>,
read: BTreeMap<String, Mark>,
committed: BTreeMap<String, Mark>,
flight: Option<BTreeMap<String, Mark>>,
@@ -28,11 +61,23 @@ impl Tracker {
s: &crate::config::Settings,
home: &Path,
tx: &crate::engine::NotifySender,
- ) -> bool {
+ ) -> Vec<PathBuf> {
+ self.configure_with(s, home, tx, query, journal_supported)
+ }
+ fn configure_with(
+ &mut self,
+ s: &crate::config::Settings,
+ home: &Path,
+ tx: &crate::engine::NotifySender,
+ mut query: impl FnMut(&str) -> Result<(u64, i64, i64)>,
+ mut supported: impl FnMut(&str) -> bool,
+ ) -> Vec<PathBuf> {
*self = Self::default();
if !s.ntfs_journal {
- return false;
+ return s.roots.iter().map(|r| PathBuf::from(&r.path)).collect();
}
+ self.logger = Some(tx.clone());
+ self.roots = s.roots.iter().map(|r| PathBuf::from(&r.path)).collect();
self.signature = format!(
"{:?}|{:?}|{}|{}",
s.roots, s.exclusions, s.excluded_types, s.skip_windows_churn
@@ -41,33 +86,96 @@ impl Tracker {
.ok()
.and_then(|b| serde_json::from_slice::<Saved>(&b).ok())
.unwrap_or_default();
+ self.encrypt_cache = s.encrypt_index;
+ self.directory_cache = DirectoryCache::load(home, s.encrypt_index, &saved.marks)
+ .unwrap_or_else(|error| {
+ self.log(
+ "Info",
+ format!("NTFS directory cache will be rebuilt: {error:#}"),
+ );
+ DirectoryCache::default()
+ });
let signature_matches = saved.signature == self.signature;
- let mut covered = signature_matches;
+ let mut uncovered = vec![];
+ for root in &s.roots {
+ self.coverage.insert(
+ crate::config::fold(&root.path),
+ format!(
+ "{}|{:?}|{}|{}|{}",
+ root.mode,
+ s.exclusions,
+ s.excluded_types,
+ s.skip_windows_churn,
+ s.include_hidden
+ ),
+ );
+ }
let mut volumes = BTreeMap::new();
for root in &s.roots {
let path = root.path.as_bytes();
if path.len() >= 3 && path[0].is_ascii_alphabetic() && path[1] == b':' {
- volumes.insert(root.path[..2].to_uppercase(), ());
+ let volume = root.path[..2].to_uppercase();
+ if supported(&volume) {
+ volumes.insert(volume, ());
+ } else {
+ uncovered.push(PathBuf::from(&root.path));
+ self.log("Info",format!("NTFS journal {volume}: network or unsupported filesystem; folder notifications only, journal retries disabled"));
+ }
} else {
- covered = false;
+ uncovered.push(PathBuf::from(&root.path));
}
}
for (volume, _) in volumes {
match query(&volume) {
Ok((id, first, next)) => {
- let old = saved.marks.get(&volume).copied().filter(|m| {
- signature_matches && m.id == id && m.usn >= first && m.usn <= next
- });
- if old.is_none() {
- covered = false;
+ let old = saved
+ .marks
+ .get(&volume)
+ .copied()
+ .filter(|m| m.id == id && m.usn >= first && m.usn <= next);
+ for root in &s.roots {
+ let key = crate::config::fold(&root.path);
+ 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)
+ }))
+ {
+ uncovered.push(PathBuf::from(&root.path));
+ }
}
let mark = old.unwrap_or(Mark { id, usn: next });
+ self.log("Info", format!("NTFS journal {volume}: reader ready; journal={}, cursor={}, retained range={first}..{next}", mark.id, mark.usn));
self.read.insert(volume.clone(), mark);
self.committed.insert(volume, mark);
}
Err(e) => {
- covered = false;
- let _=tx.send(crate::engine::Event::Log("Warning".into(),format!("NTFS journal {volume} unavailable; folder notifications remain active: {e}")));
+ self.retries.insert(
+ volume.clone(),
+ Retry {
+ attempts: 1,
+ bad_batch: false,
+ after: Instant::now() + retry_delay(1),
+ },
+ );
+ // Startup access failures do not prove that saved history
+ // was lost. Wait for retry validation before requesting a
+ // volume catch-up; only genuinely new/changed sources need it.
+ if let Some(mark) = saved.marks.get(&volume) {
+ self.committed.insert(volume.clone(), *mark);
+ }
+ for root in &s.roots {
+ let key = crate::config::fold(&root.path);
+ 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)
+ }))
+ {
+ uncovered.push(PathBuf::from(&root.path));
+ }
+ }
+ let _=tx.send(crate::engine::Event::Log("Warning".into(),format!("NTFS journal {volume} unavailable; retry in 5s; folder notifications remain active: {e:#}")));
}
}
}
@@ -76,41 +184,198 @@ impl Tracker {
format!(
"NTFS journal: {} accessible volumes; {}",
self.read.len(),
- if covered {
+ if uncovered.is_empty() {
"replaying saved cursors"
} else {
- "recovery scan establishes cursors"
+ "catch-up queued only for sources without continuous coverage"
}
),
));
- covered && !self.read.is_empty()
+ uncovered.sort();
+ uncovered.dedup();
+ uncovered
+ }
+ fn log(&self, level: &str, message: String) {
+ if let Some(tx) = &self.logger {
+ let _ = tx.send(crate::engine::Event::Log(level.into(), message));
+ }
+ }
+ fn recover_volume(&self, volume: &str, paths: &mut Vec<PathBuf>) {
+ // Never broaden a journal failure to unrelated drives or unwatched folders.
+ for root in &self.roots {
+ if crate::config::under(&root.to_string_lossy(), &format!("{volume}\\")) {
+ paths.push(root.clone());
+ }
+ }
+ }
+ pub fn covers(&self, path: &Path) -> bool {
+ let text = path.to_string_lossy();
+ text.get(..2).is_some_and(|v| {
+ let v = v.to_ascii_uppercase();
+ self.read.contains_key(&v) && !self.retries.contains_key(&v)
+ })
+ }
+ /// Indexed basename seeks recover deleted/unavailable parents without walking
+ /// the volume. New live paths are resolved by file ID and folder notifications.
+ pub fn resolve_missing(&mut self, db: &crate::db::Database) -> Result<Vec<PathBuf>> {
+ if self.missing_names.is_empty() {
+ return Ok(vec![]);
+ }
+ let c = db.connect(true)?;
+ // 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",
+ )?;
+ let mut paths = std::collections::BTreeSet::new();
+ let keys = self
+ .missing_names
+ .keys()
+ .take(4)
+ .cloned()
+ .collect::<Vec<_>>();
+ let mut completed = vec![];
+ 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 mut count = 0;
+ let mut last = i64::MIN;
+ for row in rows {
+ let (id, path) = row?;
+ last = id;
+ count += 1;
+ if crate::config::under(&path, &format!("{volume}\\")) {
+ paths.insert(PathBuf::from(path));
+ }
+ }
+ completed.push((key.clone(), if count < 256 { None } else { Some(last) }));
+ }
+ // Do not acknowledge earlier pages if a later query fails.
+ for (key, cursor) in completed {
+ if let Some(cursor) = cursor {
+ self.missing_names.insert(key, cursor);
+ } else {
+ self.missing_names.remove(&key);
+ }
+ }
+ Ok(paths.into_iter().collect())
+ }
+ pub fn retrying(&self) -> usize {
+ self.retries.len()
}
pub fn poll(&mut self) -> (Vec<PathBuf>, bool) {
+ let mut cache = std::mem::take(&mut self.directory_cache);
+ let result = self.poll_with(Instant::now(), query, |volume, mark| {
+ read_cached(volume, mark, &mut cache)
+ });
+ self.directory_cache = cache;
+ result
+ }
+ fn poll_with(
+ &mut self,
+ now: Instant,
+ mut query_volume: impl FnMut(&str) -> Result<(u64, i64, i64)>,
+ mut read_volume: impl FnMut(&str, Mark) -> Result<Batch>,
+ ) -> (Vec<PathBuf>, bool) {
let mut paths = vec![];
- let mut recovery = false;
- let mut failed = vec![];
- for (volume, mark) in &mut self.read {
- match read(volume, *mark) {
- Ok((next, mut batch)) => {
- mark.usn = next;
- paths.append(&mut batch)
+ let volumes: std::collections::BTreeSet<_> = self
+ .read
+ .keys()
+ .chain(self.retries.keys())
+ .cloned()
+ .collect();
+ for volume in volumes {
+ let attempts = if let Some(retry) = self.retries.get(&volume) {
+ if now < retry.after {
+ continue;
}
- Err(_) => {
- failed.push(volume.clone());
- recovery = true;
+ retry.attempts
+ } else {
+ 0
+ };
+ let result = (|| -> Result<Batch> {
+ if attempts > 0 {
+ let (id, first, next) =
+ query_volume(&volume).context("query journal before retry")?;
+ let previous = self
+ .read
+ .get(&volume)
+ .or_else(|| self.committed.get(&volume))
+ .copied();
+ let valid = previous.filter(|m| m.id == id && m.usn >= first && m.usn <= next);
+ // Rebase only a confirmed gap, or a repeatedly unreadable batch.
+ if valid.is_none() || (attempts >= 3 && self.retries[&volume].bad_batch) {
+ self.recover_volume(&volume, &mut paths);
+ self.log("Warning", format!("NTFS journal {volume}: scoped recovery queued; previous={previous:?}, journal={id}, first={first}, next={next}, attempts={attempts}"));
+ self.read.insert(volume.clone(), Mark { id, usn: next });
+ } else {
+ self.read.insert(volume.clone(), valid.unwrap());
+ }
+ }
+ read_volume(&volume, self.read[&volume]).context("read journal batch")
+ })();
+ match result {
+ Ok(batch) => {
+ self.read.get_mut(&volume).unwrap().usn = batch.next;
+ paths.extend(batch.paths);
+ if let Some(issue) = batch.unresolved {
+ for name in batch.missing_names {
+ self.missing_names
+ .entry((volume.clone(), name))
+ .or_insert(i64::MIN);
+ }
+ if self.resolution_warning.get(&volume).is_none_or(|last| {
+ now.saturating_duration_since(*last) >= Duration::from_secs(60)
+ }) {
+ self.log("Warning", format!("NTFS journal {volume}: {issue}; reader retained, cursor advanced to {}; targeted indexed-name checks queued; live folder notifications remain active (similar warnings limited to once per minute)", batch.next));
+ self.resolution_warning.insert(volume.clone(), now);
+ }
+ }
+ if attempts > 0 {
+ self.log("Info", format!("NTFS journal {volume}: reader resumed after {attempts} failed attempt(s), cursor={}", batch.next));
+ }
+ self.retries.remove(&volume);
+ }
+ Err(error) => {
+ // Permission/sharing/I/O errors must preserve a valid cursor.
+ let bad_batch = malformed(&error);
+ let attempts = attempts.saturating_add(1);
+ let delay = retry_delay(attempts);
+ self.log("Warning", format!("NTFS journal {volume}: attempt {attempts} failed; cursor={:?}; retry in {}s; folder notifications remain active: {error:#}", self.read.get(&volume), delay.as_secs()));
+ self.retries.insert(
+ volume,
+ Retry {
+ attempts,
+ bad_batch,
+ after: now + delay,
+ },
+ );
}
}
}
- for v in failed {
- self.read.remove(&v);
- }
- (paths, recovery)
+ paths.sort();
+ paths.dedup();
+ (paths, false) // scoped recovery paths use the existing durable targeted queue
}
pub fn begin(&mut self) {
+ self.flight_cache = Some(self.directory_cache.clone());
self.flight = if self.read.is_empty() {
None
} else {
- Some(self.read.clone())
+ let mut marks = self.committed.clone();
+ // A crash must replay unresolved names whose bounded DB checks have
+ // not yet reached the durable change queue.
+ marks.extend(
+ self.read
+ .iter()
+ .filter(|(volume, _)| !self.missing_names.keys().any(|(v, _)| v == *volume))
+ .map(|(v, m)| (v.clone(), *m)),
+ );
+ Some(marks)
};
}
pub fn finish(&mut self, success: bool, home: &Path) {
@@ -118,27 +383,49 @@ impl Tracker {
if success {
let saved = Saved {
signature: self.signature.clone(),
+ coverage: self.coverage.clone(),
marks: marks.clone(),
};
- if let Ok(bytes) = serde_json::to_vec(&saved) {
+ let persisted = (|| -> Result<()> {
+ let bytes = serde_json::to_vec(&saved)?;
let temp = home.join("ntfs-journal.pending");
- if std::fs::write(&temp, bytes).is_ok()
- && std::fs::rename(temp, home.join("ntfs-journal.json")).is_ok()
- {
+ std::fs::write(&temp, bytes).context("write journal checkpoint")?;
+ std::fs::rename(temp, home.join("ntfs-journal.json"))
+ .context("replace journal checkpoint")?;
+ Ok(())
+ })();
+ match persisted {
+ Ok(()) => {
self.committed = marks;
- }
+ if let Some(cache)=self.flight_cache.take() {
+ if let Err(error)=cache.save(home,self.encrypt_cache){self.log("Warning",format!("NTFS directory cache not saved (journal checkpoints remain valid): {error:#}"));}
+ }
+ },
+ Err(error) => self.log("Warning", format!("NTFS journal checkpoint not saved; previous durable cursors retained: {error:#}")),
}
} else {
self.read = self.committed.clone();
+ self.directory_cache = DirectoryCache::default();
}
}
+ self.flight_cache = None;
}
pub fn active(&self) -> usize {
- self.read.len()
+ self.read
+ .keys()
+ .filter(|v| !self.retries.contains_key(*v))
+ .count()
}
}
+struct Batch {
+ next: i64,
+ paths: Vec<PathBuf>,
+ unresolved: Option<String>,
+ missing_names: Vec<String>,
+}
#[derive(Debug)]
struct Record {
+ id: u64,
parent: u64,
name: String,
reason: u32,
@@ -174,6 +461,7 @@ fn parse(buffer: &[u8]) -> Result<(i64, Vec<Record>)> {
"Invalid journal path component"
);
records.push(Record {
+ id: u64::from_le_bytes(r[8..16].try_into()?),
parent: u64::from_le_bytes(r[16..24].try_into()?),
reason: u32::from_le_bytes(r[40..44].try_into()?),
attributes: u32::from_le_bytes(r[52..56].try_into()?),
@@ -183,6 +471,35 @@ fn parse(buffer: &[u8]) -> Result<(i64, Vec<Record>)> {
}
Ok((next, records))
}
+
+#[cfg(windows)]
+fn journal_supported(volume: &str) -> bool {
+ use windows::{
+ Win32::Storage::FileSystem::{GetDriveTypeW, GetVolumeInformationW},
+ core::PCWSTR,
+ };
+ let root = format!("{volume}\\")
+ .encode_utf16()
+ .chain(Some(0))
+ .collect::<Vec<_>>();
+ let kind = unsafe { GetDriveTypeW(PCWSTR(root.as_ptr())) };
+ if kind == 0 || kind == 1 || kind == 4 || kind == 5 {
+ return false;
+ }
+ let mut fs = [0u16; 32];
+ let info = unsafe {
+ GetVolumeInformationW(PCWSTR(root.as_ptr()), None, None, None, None, Some(&mut fs))
+ };
+ if info.is_ok() {
+ let end = fs.iter().position(|c| *c == 0).unwrap_or(fs.len());
+ return String::from_utf16_lossy(&fs[..end]).eq_ignore_ascii_case("NTFS");
+ }
+ true
+}
+#[cfg(not(windows))]
+fn journal_supported(_: &str) -> bool {
+ false
+}
#[cfg(windows)]
mod win {
use super::*;
@@ -219,6 +536,36 @@ mod win {
)
}?))
}
+
+ fn seed_metadata(volume: &str, cache: &mut DirectoryCache) {
+ for suffix in ["", "$Extend", "$Extend\\$Deleted", "$Extend\\$Delete"] {
+ let path = PathBuf::from(format!("{volume}\\{suffix}"));
+ let name = path
+ .as_os_str()
+ .to_string_lossy()
+ .encode_utf16()
+ .chain(Some(0))
+ .collect::<Vec<_>>();
+ if let Ok(handle) = unsafe {
+ CreateFileW(
+ PCWSTR(name.as_ptr()),
+ 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ None,
+ OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS,
+ None,
+ )
+ } {
+ let handle = Volume(handle);
+ let mut info = BY_HANDLE_FILE_INFORMATION::default();
+ if unsafe { GetFileInformationByHandle(handle.0, &mut info) }.is_ok() {
+ let id = ((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64;
+ cache.insert(volume, id, path);
+ }
+ }
+ }
+ }
pub(super) fn query(volume: &str) -> Result<(u64, i64, i64)> {
let handle = open(volume)?;
let mut data = USN_JOURNAL_DATA_V0::default();
@@ -245,11 +592,26 @@ mod win {
data.NextUsn,
))
}
- pub(super) fn read(volume: &str, mark: Mark) -> Result<(i64, Vec<PathBuf>)> {
+ pub(super) fn read(volume: &str, mark: Mark) -> Result<Batch> {
+ read_cached(volume, mark, &mut DirectoryCache::default())
+ }
+ pub(super) fn read_cached(
+ volume: &str,
+ mark: Mark,
+ cache: &mut DirectoryCache,
+ ) -> Result<Batch> {
+ let fresh = cache.align(volume, mark);
+ if fresh {
+ seed_metadata(volume, cache);
+ }
let handle = open(volume)?;
- let input = READ_USN_JOURNAL_DATA_V0 {
+ let input = READ_USN_JOURNAL_DATA_V1 {
+ MinMajorVersion: 2,
+ MaxMajorVersion: 2,
StartUsn: mark.usn,
- ReasonMask: u32::MAX,
+ // Content/name/attribute changes affect the index; security-only,
+ // close-only and object-ID bookkeeping do not.
+ ReasonMask: 0x0011_b377,
ReturnOnlyOnClose: 0,
Timeout: 0,
BytesToWaitFor: 0,
@@ -273,68 +635,57 @@ mod win {
count as usize <= buffer.len(),
"Invalid journal buffer size"
);
- let (next, records) = parse(&buffer[..count as usize])?;
- let mut parents = BTreeMap::new();
- let mut paths = vec![];
- for r in records {
- if r.reason & !0x80000000 == 0 {
- continue;
- }
- if r.attributes & 0x10 != 0 && r.reason & (0x100 | 0x200 | 0x1000 | 0x2000) == 0 {
- continue;
- }
- let parent = if let Some(p) = parents.get(&r.parent) {
- PathBuf::clone(p)
- } else {
- let id = FILE_ID_DESCRIPTOR {
- dwSize: std::mem::size_of::<FILE_ID_DESCRIPTOR>() as u32,
- Type: FileIdType,
- Anonymous: FILE_ID_DESCRIPTOR_0 {
- FileId: r.parent as i64,
- },
- };
- let parent = Volume(
- unsafe {
- OpenFileById(
- handle.0,
- &id,
- 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- None,
- FILE_FLAG_BACKUP_SEMANTICS,
- )
- }
- .context("Journal parent unavailable; recovery needed")?,
- );
- let mut text = vec![0u16; 32768];
- let n = unsafe {
- GetFinalPathNameByHandleW(
- parent.0,
- &mut text,
- GETFINALPATHNAMEBYHANDLE_FLAGS(0),
+ let (next, records) =
+ parse(&buffer[..count as usize]).context("decode V2 journal buffer")?;
+ anyhow::ensure!(next >= mark.usn, "Journal cursor moved backwards");
+ directory::resolve_records(volume, mark, next, records, cache, |parent_id| {
+ let id = FILE_ID_DESCRIPTOR {
+ dwSize: std::mem::size_of::<FILE_ID_DESCRIPTOR>() as u32,
+ Type: FileIdType,
+ Anonymous: FILE_ID_DESCRIPTOR_0 {
+ FileId: parent_id as i64,
+ },
+ };
+
+ let parent = Volume(
+ unsafe {
+ OpenFileById(
+ handle.0,
+ &id,
+ 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ None,
+ FILE_FLAG_BACKUP_SEMANTICS,
)
- } as usize;
- anyhow::ensure!(n > 0 && n < text.len(), "Cannot resolve journal parent");
- let text = String::from_utf16(&text[..n])?;
- let path = PathBuf::from(text.strip_prefix("\\\\?\\").unwrap_or(&text));
- if parents.len() < 512 {
- parents.insert(r.parent, path.clone());
}
- path
- };
- paths.push(parent.join(r.name));
- }
- Ok((next, paths))
+ .context("Journal parent unavailable; recovery needed")?,
+ );
+ let mut text = vec![0u16; 32768];
+ let n = unsafe {
+ GetFinalPathNameByHandleW(parent.0, &mut text, GETFINALPATHNAMEBYHANDLE_FLAGS(0))
+ } as usize;
+ if n == 0 {
+ return Err(windows::core::Error::from_win32())
+ .context("resolve parent final path");
+ }
+ anyhow::ensure!(n < text.len(), "Journal parent path exceeds buffer");
+ let text = String::from_utf16(&text[..n])?;
+ Ok(PathBuf::from(text.strip_prefix("\\\\?\\").unwrap_or(&text)))
+ })
}
}
#[cfg(windows)]
-use win::{query, read};
+use win::{query, read, read_cached};
#[cfg(not(windows))]
fn query(_: &str) -> Result<(u64, i64, i64)> {
anyhow::bail!("NTFS journals require Windows")
}
#[cfg(not(windows))]
-fn read(_: &str, _: Mark) -> Result<(i64, Vec<PathBuf>)> {
+fn read(_: &str, _: Mark) -> Result<Batch> {
+ anyhow::bail!("NTFS journals require Windows")
+}
+#[cfg(not(windows))]
+fn read_cached(_: &str, _: Mark, _: &mut DirectoryCache) -> Result<Batch> {
anyhow::bail!("NTFS journals require Windows")
}
#[cfg(test)]
@@ -383,8 +734,556 @@ mod checkpoint_tests {
pub fn probe(volume: &str) -> Result<serde_json::Value> {
let (id, first, next) = query(volume)?;
- let (_, records) = read(volume, Mark { id, usn: next })?;
+ let batch = read(volume, Mark { id, usn: next })?;
Ok(
- serde_json::json!({"accessible":true,"id":id,"first":first,"next":next,"pending_paths":records.len()}),
+ serde_json::json!({"accessible":true,"id":id,"first":first,"next":next,"pending_paths":batch.paths.len(),"unresolved":batch.unresolved}),
)
}
+
+#[cfg(test)]
+mod retry_tests {
+ use super::*;
+ fn tracker() -> Tracker {
+ let mut t = Tracker::default();
+ t.read.insert("C:".into(), Mark { id: 1, usn: 10 });
+ t.read.insert("D:".into(), Mark { id: 2, usn: 10 });
+ t.roots = vec![PathBuf::from("C:\\Users"), PathBuf::from("D:\\Work")];
+ t
+ }
+ fn batch(next: i64) -> Batch {
+ Batch {
+ next,
+ paths: vec![],
+ unresolved: None,
+ missing_names: vec![],
+ }
+ }
+ #[test]
+ fn transient_failure_preserves_cursor_and_healthy_drive_then_retries() {
+ let mut t = tracker();
+ let now = Instant::now();
+ let (paths, recovery) = t.poll_with(
+ now,
+ |_| unreachable!(),
+ |v, _| {
+ if v == "C:" {
+ anyhow::bail!("temporary failure")
+ } else {
+ Ok(batch(20))
+ }
+ },
+ );
+ assert!(paths.is_empty() && !recovery);
+ assert_eq!(t.read["C:"].usn, 10);
+ assert_eq!(t.read["D:"].usn, 20);
+ assert_eq!(t.active(), 1);
+ t.poll_with(
+ now + Duration::from_secs(4),
+ |_| unreachable!(),
+ |v, _| {
+ assert_eq!(v, "D:");
+ Ok(batch(21))
+ },
+ );
+ let (paths, recovery) = t.poll_with(
+ now + Duration::from_secs(5),
+ |_| Ok((1, 0, 100)),
+ |_, mark| Ok(batch(mark.usn + 1)),
+ );
+ assert!(paths.is_empty() && !recovery);
+ assert_eq!(t.read["C:"].usn, 11);
+ assert_eq!(t.active(), 2);
+ assert_eq!(t.retrying(), 0);
+ }
+ #[test]
+ fn confirmed_gap_queues_only_sources_on_affected_volume() {
+ let mut t = tracker();
+ let now = Instant::now();
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 1,
+ bad_batch: false,
+ after: now,
+ },
+ );
+ let (paths, global) = t.poll_with(now, |_| Ok((7, 50, 100)), |_, m| Ok(batch(m.usn)));
+ assert!(!global);
+ assert_eq!(paths, vec![PathBuf::from("C:\\Users")]);
+ assert_eq!(t.read["C:"].id, 7);
+ assert_eq!(t.read["C:"].usn, 100);
+ assert_eq!(t.read["D:"].usn, 10);
+ }
+ #[test]
+ fn expired_cursor_is_rebased_once() {
+ let mut t = tracker();
+ let now = Instant::now();
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 1,
+ bad_batch: false,
+ after: now,
+ },
+ );
+ let (paths, _) = t.poll_with(now, |_| Ok((1, 50, 100)), |_, m| Ok(batch(m.usn)));
+ assert_eq!(paths.len(), 1);
+ let (paths, _) = t.poll_with(now, |_| unreachable!(), |_, m| Ok(batch(m.usn)));
+ assert!(paths.is_empty());
+ }
+ #[test]
+ fn unresolved_parent_advances_batch_without_removing_reader() {
+ let mut t = tracker();
+ let (paths, global) = t.poll_with(
+ Instant::now(),
+ |_| unreachable!(),
+ |v, _| {
+ let mut b = batch(40);
+ if v == "C:" {
+ b.paths.push(PathBuf::from("C:\\Users\\good.txt"));
+ b.unresolved = Some("deleted parent".into());
+ }
+ Ok(b)
+ },
+ );
+ assert!(!global);
+ assert!(paths.contains(&PathBuf::from("C:\\Users\\good.txt")));
+ assert!(!paths.contains(&PathBuf::from("C:\\Users")));
+ assert_eq!(t.read["C:"].usn, 40);
+ assert_eq!(t.active(), 2);
+ }
+ #[test]
+ fn repeated_missing_parents_never_queue_volume_roots_and_lookup_is_paged() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = crate::config::Settings::default();
+ s.encrypt_index = false;
+ let db = crate::db::Database::new(home.path(), &s).unwrap();
+ let c = db.connect(false).unwrap();
+ for n in 0..600 {
+ c.execute(
+ "INSERT INTO names(path,name,base) VALUES(?1,'gone.txt','gone.txt')",
+ [format!(r"C:\Users\folder-{n:04}\gone.txt")],
+ )
+ .unwrap();
+ }
+ c.execute(
+ r"INSERT INTO names(path,name,base) VALUES('D:\Work\gone.txt','gone.txt','gone.txt')",
+ [],
+ )
+ .unwrap();
+ let mut t = tracker();
+ for _ in 0..100 {
+ let (paths, global) = t.poll_with(
+ Instant::now(),
+ |_| unreachable!(),
+ |v, m| {
+ let mut b = batch(m.usn + 1);
+ if v == "C:" {
+ b.unresolved = Some("parent unavailable".into());
+ b.missing_names = vec!["gone.txt".into()];
+ }
+ Ok(b)
+ },
+ );
+ assert!(paths.is_empty() && !global);
+ }
+ let mut found = std::collections::BTreeSet::new();
+ while !t.missing_names.is_empty() {
+ let paths = t.resolve_missing(&db).unwrap();
+ assert!(paths.len() <= 256);
+ assert!(paths.iter().all(|p| p.starts_with(r"C:\Users")));
+ found.extend(paths);
+ }
+ assert_eq!(found.len(), 600);
+ assert_eq!(t.read["C:"].usn, 110);
+ }
+ #[test]
+ fn unresolved_names_hold_durable_cursor_until_targeted_checks_are_queued() {
+ let home = tempfile::tempdir().unwrap();
+ let mut t = tracker();
+ t.committed = t.read.clone();
+ t.read.get_mut("C:").unwrap().usn = 30;
+ t.missing_names
+ .insert(("C:".into(), "gone.txt".into()), i64::MIN);
+ t.begin();
+ t.finish(true, home.path());
+ assert_eq!(t.committed["C:"].usn, 10);
+ assert_eq!(t.read["C:"].usn, 30);
+ t.missing_names.clear();
+ t.begin();
+ t.finish(true, home.path());
+ assert_eq!(t.committed["C:"].usn, 30);
+ }
+ #[test]
+ fn journal_coverage_is_volume_specific_and_not_assumed_for_networks() {
+ let mut t = tracker();
+ assert!(t.covers(Path::new(r"C:\Users\file.txt")));
+ assert!(!t.covers(Path::new(r"T:\Work")));
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 1,
+ bad_batch: false,
+ after: Instant::now(),
+ },
+ );
+ assert!(!t.covers(Path::new(r"C:\Users")));
+ }
+ #[test]
+ fn initially_unavailable_volume_rejoins_automatically() {
+ let mut t = tracker();
+ let now = Instant::now();
+ t.read.remove("C:");
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 1,
+ bad_batch: false,
+ after: now,
+ },
+ );
+ let (paths, _) = t.poll_with(now, |_| Ok((1, 0, 100)), |_, m| Ok(batch(m.usn)));
+ assert_eq!(paths, vec![PathBuf::from("C:\\Users")]);
+ assert_eq!(t.active(), 2);
+ }
+ #[test]
+ fn backoff_is_bounded_and_no_poll_storm() {
+ assert_eq!(retry_delay(1).as_secs(), 5);
+ assert_eq!(retry_delay(2).as_secs(), 10);
+ assert_eq!(retry_delay(u32::MAX).as_secs(), 300);
+ let mut t = tracker();
+ let now = Instant::now();
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 2,
+ bad_batch: false,
+ after: now,
+ },
+ );
+ t.poll_with(
+ now,
+ |_| anyhow::bail!("volume offline"),
+ |_, m| Ok(batch(m.usn)),
+ );
+ assert_eq!(t.retries["C:"].attempts, 3);
+ t.poll_with(
+ now + Duration::from_secs(19),
+ |_| unreachable!(),
+ |v, m| {
+ assert_eq!(v, "D:");
+ Ok(batch(m.usn))
+ },
+ );
+ assert_eq!(t.read["C:"].usn, 10);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn repeated_access_errors_do_not_skip_valid_journal_entries() {
+ let mut t = tracker();
+ let mut now = Instant::now();
+ for attempt in 1..=5 {
+ let (paths, global) = t.poll_with(
+ now,
+ |_| Ok((1, 0, 100)),
+ |v, m| {
+ if v == "C:" {
+ return Err(windows::core::Error::from_hresult(windows::core::HRESULT(
+ 0x80070005u32 as i32,
+ ))
+ .into());
+ }
+ Ok(batch(m.usn))
+ },
+ );
+ assert!(paths.is_empty() && !global);
+ assert_eq!(t.read["C:"].usn, 10);
+ assert_eq!(t.retries["C:"].attempts, attempt);
+ now += retry_delay(attempt);
+ }
+ let (paths, _) = t.poll_with(now, |_| Ok((1, 0, 100)), |_, m| Ok(batch(m.usn + 1)));
+ assert!(paths.is_empty());
+ assert_eq!(t.read["C:"].usn, 11);
+ }
+ #[test]
+ fn repeated_malformed_batch_recovers_scope_and_resumes() {
+ let mut t = tracker();
+ let now = Instant::now();
+ t.retries.insert(
+ "C:".into(),
+ Retry {
+ attempts: 3,
+ bad_batch: true,
+ after: now,
+ },
+ );
+ let (paths, global) = t.poll_with(now, |_| Ok((1, 0, 100)), |_, m| Ok(batch(m.usn)));
+ assert!(!global);
+ assert_eq!(paths, vec![PathBuf::from("C:\\Users")]);
+ assert_eq!(t.read["C:"].usn, 100);
+ assert_eq!(t.active(), 2);
+ }
+ #[test]
+ fn repeated_unresolved_warnings_are_rate_limited_but_paths_not_lost() {
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let mut t = tracker();
+ t.logger = Some(tx.into());
+ let now = Instant::now();
+ for second in [0, 1, 60] {
+ let (paths, _) = t.poll_with(
+ now + Duration::from_secs(second),
+ |_| unreachable!(),
+ |v, m| {
+ let mut b = batch(m.usn + 1);
+ if v == "C:" {
+ b.unresolved = Some("unavailable parent".into());
+ }
+ Ok(b)
+ },
+ );
+ assert!(paths.is_empty());
+ }
+ assert_eq!(rx.try_iter().count(), 2);
+ }
+ #[test]
+ fn checkpoints_preserve_unavailable_volume_cursor() {
+ let mut t = tracker();
+ let home = tempfile::tempdir().unwrap();
+ t.committed.insert("E:".into(), Mark { id: 3, usn: 5 });
+ t.begin();
+ t.finish(true, home.path());
+ let saved: Saved =
+ serde_json::from_slice(&std::fs::read(home.path().join("ntfs-journal.json")).unwrap())
+ .unwrap();
+ assert_eq!(saved.marks["E:"].usn, 5);
+ }
+ #[test]
+ fn diagnostics_include_volume_cause_retry_and_resume() {
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let mut t = tracker();
+ t.logger = Some(tx.into());
+ let now = Instant::now();
+ t.poll_with(
+ now,
+ |_| unreachable!(),
+ |v, m| {
+ if v == "C:" {
+ anyhow::bail!("injected access failure")
+ }
+ Ok(batch(m.usn))
+ },
+ );
+ t.poll_with(
+ now + Duration::from_secs(5),
+ |_| Ok((1, 0, 100)),
+ |_, m| Ok(batch(m.usn)),
+ );
+ let logs: Vec<_> = rx
+ .try_iter()
+ .filter_map(|e| {
+ if let crate::engine::Event::Log(_, s) = e {
+ Some(s)
+ } else {
+ None
+ }
+ })
+ .collect();
+ assert!(logs.iter().any(|s| s.contains("C:")
+ && s.contains("retry in 5s")
+ && s.contains("injected access failure")));
+ assert!(
+ logs.iter()
+ .any(|s| s.contains("C:") && s.contains("resumed"))
+ );
+ }
+}
+
+#[cfg(all(test, windows))]
+mod windows_replay_test {
+ use super::*;
+ #[test]
+ #[ignore = "Requires an accessible NTFS journal; writes only to explicit test directory"]
+ fn live_create_delete_and_parent_resolution() {
+ let base = PathBuf::from(
+ std::env::var("VECTORDASH_JOURNAL_TEST_DIR").expect("explicit test directory"),
+ );
+ let text = base.to_string_lossy();
+ let volume = &text[..2];
+ let (id, _, start) = query(volume).unwrap();
+ let root = tempfile::tempdir_in(&base).unwrap();
+ let live = root.path().join("journal-live.txt");
+ std::fs::write(&live, b"journal replay fixture").unwrap();
+ let gone = root.path().join("deleted-parent");
+ std::fs::create_dir(&gone).unwrap();
+ std::fs::write(gone.join("child.txt"), b"deleted fixture").unwrap();
+ std::fs::remove_file(gone.join("child.txt")).unwrap();
+ std::fs::remove_dir(&gone).unwrap();
+ let (_, _, end) = query(volume).unwrap();
+ let mut mark = Mark { id, usn: start };
+ let mut found = false;
+ let mut unresolved = false;
+ for _ in 0..128 {
+ let batch =
+ read(volume, mark).expect("V2 replay must tolerate unresolved deleted parents");
+ found |= batch.paths.iter().any(|p| p == &live);
+ unresolved |= batch.unresolved.is_some();
+ if batch.next == mark.usn || batch.next >= end {
+ break;
+ }
+ mark.usn = batch.next;
+ }
+ assert!(found, "new file must be present in replay");
+ eprintln!(
+ "Live NTFS replay: created file found={found}, unresolved deleted parent tolerated={unresolved}"
+ );
+ }
+}
+
+#[cfg(test)]
+mod source_coverage_tests {
+ use super::*;
+ fn settings() -> crate::config::Settings {
+ let mut s = crate::config::Settings::default();
+ s.encrypt_index = false;
+ s.ntfs_journal = true;
+ s.roots = ["C:\\", "D:\\", "T:\\"]
+ .iter()
+ .map(|p| crate::config::Source {
+ path: (*p).into(),
+ mode: "quick".into(),
+ })
+ .collect();
+ s
+ }
+ fn logger() -> crate::engine::NotifySender {
+ let (tx, _) = crossbeam_channel::unbounded();
+ tx.into()
+ }
+ #[test]
+ fn network_source_never_queries_journal_or_invalidates_healthy_sources() {
+ let home = tempfile::tempdir().unwrap();
+ let s = settings();
+ let mut first = Tracker::default();
+ first.configure_with(
+ &s,
+ home.path(),
+ &logger(),
+ |v| {
+ assert_ne!(v, "T:");
+ Ok((1, 0, 100))
+ },
+ |v| v != "T:",
+ );
+ first.begin();
+ first.finish(true, home.path());
+ let mut resumed = Tracker::default();
+ let uncovered = resumed.configure_with(
+ &s,
+ home.path(),
+ &logger(),
+ |v| {
+ assert_ne!(v, "T:");
+ Ok((1, 0, 101))
+ },
+ |v| v != "T:",
+ );
+ assert_eq!(uncovered, vec![PathBuf::from("T:\\")]);
+ assert_eq!(resumed.active(), 2);
+ assert_eq!(resumed.retrying(), 0);
+ }
+ #[test]
+ fn startup_access_retry_waits_for_saved_cursor_validation_without_scan() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = settings();
+ s.roots.truncate(2);
+ let mut first = Tracker::default();
+ first.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 100)), |_| true);
+ first.begin();
+ first.finish(true, home.path());
+ let mut resumed = Tracker::default();
+ let uncovered = resumed.configure_with(
+ &s,
+ home.path(),
+ &logger(),
+ |v| {
+ if v == "C:" {
+ anyhow::bail!("not ready after boot")
+ }
+ Ok((1, 0, 101))
+ },
+ |_| true,
+ );
+ assert!(uncovered.is_empty());
+ assert_eq!(resumed.committed["C:"].usn, 100);
+ resumed.retries.get_mut("C:").unwrap().after = Instant::now();
+ let (paths, global) = resumed.poll_with(
+ Instant::now(),
+ |_| Ok((1, 0, 120)),
+ |_, m| {
+ Ok(super::Batch {
+ next: m.usn + 1,
+ paths: vec![],
+ unresolved: None,
+ missing_names: vec![],
+ })
+ },
+ );
+ assert!(paths.is_empty() && !global);
+ assert_eq!(resumed.read["C:"].usn, 101);
+ }
+ #[test]
+ fn adding_source_on_healthy_volume_only_catches_up_new_source() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = settings();
+ s.roots.truncate(2);
+ let mut first = Tracker::default();
+ first.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 100)), |_| true);
+ first.begin();
+ first.finish(true, home.path());
+ s.roots.push(crate::config::Source {
+ path: "C:\\New photos".into(),
+ mode: "full".into(),
+ });
+ let mut resumed = Tracker::default();
+ let uncovered =
+ resumed.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 101)), |_| true);
+ assert_eq!(uncovered, vec![PathBuf::from("C:\\New photos")]);
+ assert_eq!(resumed.read["C:"].usn, 100);
+ }
+ #[test]
+ fn one_expired_drive_does_not_invalidate_other_drive() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = settings();
+ s.roots.truncate(2);
+ let mut first = Tracker::default();
+ first.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 100)), |_| true);
+ first.begin();
+ first.finish(true, home.path());
+ let mut resumed = Tracker::default();
+ let uncovered = resumed.configure_with(
+ &s,
+ home.path(),
+ &logger(),
+ |v| Ok((1, if v == "C:" { 101 } else { 0 }, 200)),
+ |_| true,
+ );
+ assert_eq!(uncovered, vec![PathBuf::from("C:\\")]);
+ assert_eq!(resumed.read["D:"].usn, 100);
+ }
+ #[test]
+ fn hidden_policy_change_requires_source_catchup_even_if_legacy_signature_matches() {
+ let home = tempfile::tempdir().unwrap();
+ let mut s = settings();
+ s.roots.truncate(1);
+ let mut first = Tracker::default();
+ first.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 100)), |_| true);
+ first.begin();
+ first.finish(true, home.path());
+ s.include_hidden = !s.include_hidden;
+ let mut resumed = Tracker::default();
+ let uncovered =
+ resumed.configure_with(&s, home.path(), &logger(), |_| Ok((1, 0, 101)), |_| true);
+ assert_eq!(uncovered, vec![PathBuf::from("C:\\")]);
+ }
+}
diff --git a/native/src/journal/directory.rs b/native/src/journal/directory.rs
new file mode 100644
index 0000000..f3236bd
--- /dev/null
+++ b/native/src/journal/directory.rs
@@ -0,0 +1,485 @@
+use super::{Batch, Mark, Record};
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use std::{
+ collections::BTreeMap,
+ path::{Path, PathBuf},
+};
+const MAX_ENTRIES: usize = 4096;
+const MAX_BYTES: usize = 2 * 1024 * 1024;
+#[derive(Clone)]
+struct Entry {
+ path: PathBuf,
+ tick: u64,
+ cost: usize,
+}
+#[derive(Clone, Default)]
+pub(super) struct DirectoryCache {
+ entries: BTreeMap<(String, u64), Entry>,
+ order: BTreeMap<u64, (String, u64)>,
+ clock: u64,
+ bytes: usize,
+ cursors: BTreeMap<String, Mark>,
+}
+#[derive(Serialize, Deserialize)]
+struct Stored {
+ marks: BTreeMap<String, Mark>,
+ entries: Vec<(String, u64, PathBuf)>,
+}
+impl DirectoryCache {
+ pub(super) fn align(&mut self, volume: &str, mark: Mark) -> bool {
+ if self
+ .cursors
+ .get(volume)
+ .is_some_and(|old| old.id == mark.id && old.usn == mark.usn)
+ {
+ return false;
+ }
+ let keys = self
+ .entries
+ .keys()
+ .filter(|(v, _)| v == volume)
+ .cloned()
+ .collect::<Vec<_>>();
+ for key in keys {
+ self.remove(&key);
+ }
+ self.cursors.insert(volume.into(), mark);
+ true
+ }
+ fn remove(&mut self, key: &(String, u64)) {
+ if let Some(old) = self.entries.remove(key) {
+ self.order.remove(&old.tick);
+ self.bytes -= old.cost;
+ }
+ }
+ pub(super) fn insert(&mut self, volume: &str, id: u64, path: PathBuf) {
+ let cost = path.to_string_lossy().len() * 2 + 192;
+ if cost > MAX_BYTES / 4 {
+ return;
+ }
+ let key = (volume.to_owned(), id);
+ self.remove(&key);
+ self.clock = self.clock.saturating_add(1);
+ self.entries.insert(
+ key.clone(),
+ Entry {
+ path,
+ tick: self.clock,
+ cost,
+ },
+ );
+ self.order.insert(self.clock, key);
+ self.bytes += cost;
+ while self.entries.len() > MAX_ENTRIES || self.bytes > MAX_BYTES {
+ let Some((_, key)) = self.order.first_key_value().map(|(t, k)| (*t, k.clone())) else {
+ break;
+ };
+ self.remove(&key);
+ }
+ }
+ pub(super) fn get(&mut self, volume: &str, id: u64) -> Option<PathBuf> {
+ let path = self.entries.get(&(volume.to_owned(), id))?.path.clone();
+ self.insert(volume, id, path.clone());
+ Some(path)
+ }
+ fn rename(&mut self, volume: &str, id: u64, new_path: PathBuf) {
+ if let Some(old) = self
+ .entries
+ .get(&(volume.to_owned(), id))
+ .map(|e| e.path.clone())
+ {
+ let changed = self
+ .entries
+ .iter()
+ .filter(|((v, _), e)| v == volume && e.path.starts_with(&old))
+ .filter_map(|((_, id), e)| {
+ e.path
+ .strip_prefix(&old)
+ .ok()
+ .map(|tail| (*id, new_path.join(tail)))
+ })
+ .collect::<Vec<_>>();
+ for (id, path) in changed {
+ self.insert(volume, id, path);
+ }
+ }
+ self.insert(volume, id, new_path);
+ }
+ pub(super) fn save(&self, home: &Path, encrypt: bool) -> Result<()> {
+ let stored = Stored {
+ marks: self.cursors.clone(),
+ entries: self
+ .order
+ .values()
+ .filter_map(|key| {
+ self.entries
+ .get(key)
+ .map(|e| (key.0.clone(), key.1, e.path.clone()))
+ })
+ .collect(),
+ };
+ let bytes = serde_json::to_vec(&stored)?;
+ let mut envelope = vec![if encrypt { b'E' } else { b'P' }];
+ envelope.extend(if encrypt {
+ crate::config::crypt(&bytes, false)?
+ } else {
+ bytes
+ });
+ let temporary = home.join("ntfs-directories.pending");
+ std::fs::write(&temporary, envelope)?;
+ std::fs::rename(temporary, home.join("ntfs-directories.cache"))?;
+ Ok(())
+ }
+ pub(super) fn load(home: &Path, encrypt: bool, marks: &BTreeMap<String, Mark>) -> Result<Self> {
+ let path = home.join("ntfs-directories.cache");
+ if !path.exists() {
+ return Ok(Self::default());
+ }
+ anyhow::ensure!(
+ std::fs::metadata(&path)?.len() <= 8 * 1024 * 1024,
+ "Directory cache exceeds size limit"
+ );
+ let bytes = std::fs::read(path)?;
+ let bytes = match bytes.first() {
+ Some(b'E') => crate::config::crypt(&bytes[1..], true)?,
+ Some(b'P') if !encrypt => bytes[1..].to_vec(),
+ _ => anyhow::bail!("Directory cache protection differs from index settings"),
+ };
+ let stored: Stored = serde_json::from_slice(&bytes)?;
+ let mut cache = Self::default();
+ for (volume, mark) in stored.marks {
+ if marks
+ .get(&volume)
+ .is_some_and(|m| m.id == mark.id && m.usn == mark.usn)
+ {
+ cache.cursors.insert(volume, mark);
+ }
+ }
+ for (volume, id, path) in stored.entries.into_iter().take(MAX_ENTRIES) {
+ if cache.cursors.contains_key(&volume)
+ && crate::config::under(&path.to_string_lossy(), &format!("{volume}\\"))
+ {
+ cache.insert(&volume, id, path);
+ }
+ }
+ Ok(cache)
+ }
+}
+/// Interpret records in order, retaining directory tombstones until LRU eviction.
+/// The complete file reference (including its reuse sequence) is the cache key.
+pub(super) fn resolve_records(
+ volume: &str,
+ mark: Mark,
+ next: i64,
+ records: Vec<Record>,
+ cache: &mut DirectoryCache,
+ mut resolve: impl FnMut(u64) -> Result<PathBuf>,
+) -> Result<Batch> {
+ anyhow::ensure!(next >= mark.usn, "Journal cursor moved backwards");
+ cache.align(volume, mark);
+ let mut paths = vec![];
+ let mut unresolved = None;
+ let mut missing_names = std::collections::BTreeSet::new();
+ let mut missing = std::collections::BTreeSet::new();
+ for record in records {
+ if record.reason & !0x80000000 == 0 {
+ continue;
+ }
+ let directory = record.attributes & 0x10 != 0;
+ if directory && record.reason & (0x100 | 0x200 | 0x1000 | 0x2000) == 0 {
+ continue;
+ }
+ if directory && record.reason & 0x200 != 0 {
+ if let Some(path) = cache.get(volume, record.id) {
+ if !crate::config::ntfs_internal_path(&path.to_string_lossy()) {
+ paths.push(path);
+ }
+ continue;
+ }
+ }
+ let parent = match cache.get(volume, record.parent) {
+ Some(path) => path,
+ None => match (if missing.contains(&record.parent) {
+ Err(anyhow::anyhow!("parent already unavailable in this batch"))
+ } else {
+ resolve(record.parent)
+ })
+ .with_context(|| format!("resolve journal parent ID {}", record.parent))
+ {
+ Ok(path) => {
+ cache.insert(volume, record.parent, path.clone());
+ path
+ }
+ Err(error) => {
+ // A live child can still identify its full path when the
+ // parent's directory handle is inaccessible. Deleted/old-name
+ // records instead use indexed-name checks for stale entries.
+ if record.reason & (0x200 | 0x1000) == 0 {
+ if let Ok(path) = resolve(record.id) {
+ if directory {
+ cache.insert(volume, record.id, path.clone());
+ }
+ if !crate::config::ntfs_internal_path(&path.to_string_lossy()) {
+ paths.push(path);
+ }
+ continue;
+ }
+ }
+ missing_names.insert(record.name.clone());
+ unresolved.get_or_insert_with(|| {
+ format!("parent ID {} unavailable: {error:#}", record.parent)
+ });
+ missing.insert(record.parent);
+ continue;
+ }
+ },
+ };
+ let path = parent.join(&record.name);
+ if directory {
+ if record.reason & 0x2000 != 0 {
+ cache.rename(volume, record.id, path.clone());
+ } else {
+ cache.insert(volume, record.id, path.clone());
+ }
+ }
+ if !crate::config::ntfs_internal_path(&path.to_string_lossy()) {
+ paths.push(path);
+ }
+ }
+ if let Some(sample) = unresolved.as_mut() {
+ *sample = format!("{} unresolved parent ID(s); {sample}", missing.len());
+ }
+ cache.cursors.insert(
+ volume.into(),
+ Mark {
+ id: mark.id,
+ usn: next,
+ },
+ );
+ Ok(Batch {
+ next,
+ paths,
+ unresolved,
+ missing_names: missing_names.into_iter().collect(),
+ })
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn rec(id: u64, parent: u64, name: &str, reason: u32, directory: bool) -> Record {
+ Record {
+ id,
+ parent,
+ name: name.into(),
+ reason,
+ attributes: if directory { 16 } else { 0 },
+ }
+ }
+ #[test]
+ fn deleted_parent_is_resolved_from_bounded_tombstone_cache() {
+ let mark = Mark { id: 1, usn: 10 };
+ let mut cache = DirectoryCache::default();
+ cache.align("C:", mark);
+ cache.insert("C:", 100, PathBuf::from("C:\\Users\\Photos"));
+ let batch = resolve_records(
+ "C:",
+ mark,
+ 20,
+ vec![rec(200, 100, "gone.jpg", 0x200, false)],
+ &mut cache,
+ |_| anyhow::bail!("parent deleted"),
+ )
+ .unwrap();
+ assert_eq!(
+ batch.paths,
+ vec![PathBuf::from("C:\\Users\\Photos\\gone.jpg")]
+ );
+ assert!(batch.unresolved.is_none());
+ }
+ #[test]
+ fn rename_updates_cached_descendants_and_retains_old_path_event() {
+ let mark = Mark { id: 1, usn: 10 };
+ let mut c = DirectoryCache::default();
+ c.align("C:", mark);
+ c.insert("C:", 1, PathBuf::from("C:\\Users"));
+ c.insert("C:", 2, PathBuf::from("C:\\Users\\old"));
+ c.insert("C:", 3, PathBuf::from("C:\\Users\\old\\child"));
+ let batch = resolve_records(
+ "C:",
+ mark,
+ 20,
+ vec![
+ rec(2, 1, "old", 0x1000, true),
+ rec(2, 1, "new", 0x2000, true),
+ rec(4, 3, "file.txt", 1, false),
+ ],
+ &mut c,
+ |_| unreachable!(),
+ )
+ .unwrap();
+ assert!(batch.paths.contains(&PathBuf::from("C:\\Users\\old")));
+ assert!(
+ batch
+ .paths
+ .contains(&PathBuf::from("C:\\Users\\new\\child\\file.txt"))
+ );
+ }
+ #[test]
+ fn internal_metadata_never_queues_work_and_user_dollar_names_survive() {
+ let mark = Mark { id: 1, usn: 10 };
+ let mut c = DirectoryCache::default();
+ let batch = resolve_records(
+ "C:",
+ mark,
+ 20,
+ vec![
+ rec(2, 1, "$Extend", 0x100, true),
+ rec(4, 2, "$Deleted", 0x100, true),
+ rec(5, 4, "abc", 1, false),
+ rec(6, 1, "$Budget.txt", 1, false),
+ ],
+ &mut c,
+ |id| {
+ assert_eq!(id, 1);
+ Ok(PathBuf::from("C:\\"))
+ },
+ )
+ .unwrap();
+ assert_eq!(batch.paths, vec![PathBuf::from("C:\\$Budget.txt")]);
+ assert!(batch.unresolved.is_none());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn protected_cache_roundtrips_without_plaintext_directory_names() {
+ let home = tempfile::tempdir().unwrap();
+ let mark = Mark { id: 1, usn: 10 };
+ let mut c = DirectoryCache::default();
+ c.align("C:", mark);
+ c.insert(
+ "C:",
+ 2,
+ PathBuf::from("C:\\UniquePrivateDirectoryForCacheTest"),
+ );
+ c.save(home.path(), true).unwrap();
+ let raw = std::fs::read(home.path().join("ntfs-directories.cache")).unwrap();
+ assert_eq!(raw[0], b'E');
+ assert!(
+ !raw.windows(b"UniquePrivateDirectoryForCacheTest".len())
+ .any(|w| w == b"UniquePrivateDirectoryForCacheTest")
+ );
+ let mut loaded =
+ DirectoryCache::load(home.path(), true, &BTreeMap::from([("C:".into(), mark)]))
+ .unwrap();
+ assert!(loaded.get("C:", 2).is_some());
+ }
+ #[test]
+ fn warm_directory_cache_avoids_repeat_handle_lookups() {
+ let mut c = DirectoryCache::default();
+ let mut mark = Mark { id: 1, usn: 0 };
+ let mut resolutions = 0;
+ for n in 1..=100 {
+ let batch = resolve_records(
+ "C:",
+ mark,
+ n,
+ vec![rec(2, 1, "file.txt", 1, false)],
+ &mut c,
+ |_| {
+ resolutions += 1;
+ Ok(PathBuf::from("C:\\Users\\Photos"))
+ },
+ )
+ .unwrap();
+ assert!(batch.unresolved.is_none());
+ mark.usn = n;
+ }
+ assert_eq!(resolutions, 1);
+ }
+ #[test]
+ fn journal_gap_invalidates_cached_file_references() {
+ let mark = Mark { id: 1, usn: 10 };
+ let mut c = DirectoryCache::default();
+ c.align("C:", mark);
+ c.insert("C:", 2, PathBuf::from("C:\\old"));
+ c.align("C:", Mark { id: 1, usn: 11 });
+ assert!(c.get("C:", 2).is_none());
+ c.insert("C:", 2, PathBuf::from("C:\\old"));
+ c.align("C:", Mark { id: 2, usn: 11 });
+ assert!(c.get("C:", 2).is_none());
+ }
+ #[test]
+ fn cache_is_bounded_and_persistent_only_for_matching_durable_cursor() {
+ let home = tempfile::tempdir().unwrap();
+ let mark = Mark { id: 1, usn: 10 };
+ let mut c = DirectoryCache::default();
+ c.align("C:", mark);
+ for i in 0..10000 {
+ c.insert("C:", i, PathBuf::from(format!("C:\\folder-{i}")));
+ }
+ assert!(c.entries.len() <= MAX_ENTRIES && c.bytes <= MAX_BYTES);
+ assert!(c.get("C:", 0).is_none());
+ c.save(home.path(), false).unwrap();
+ let mut loaded =
+ DirectoryCache::load(home.path(), false, &BTreeMap::from([("C:".into(), mark)]))
+ .unwrap();
+ assert!(loaded.get("C:", 9999).is_some());
+ let loaded = DirectoryCache::load(
+ home.path(),
+ false,
+ &BTreeMap::from([("C:".into(), Mark { id: 1, usn: 11 })]),
+ )
+ .unwrap();
+ assert!(loaded.entries.is_empty());
+ }
+}
+
+#[cfg(test)]
+mod targeted_missing_tests {
+ use super::*;
+ #[test]
+ fn inaccessible_parent_resolves_live_child_and_retains_deleted_name_for_lookup() {
+ let mut cache = DirectoryCache::default();
+ let batch = resolve_records(
+ "C:",
+ Mark { id: 1, usn: 10 },
+ 20,
+ vec![
+ Record {
+ id: 2,
+ parent: 1,
+ name: "new.txt".into(),
+ reason: 0x100,
+ attributes: 0,
+ },
+ Record {
+ id: 3,
+ parent: 1,
+ name: "gone.txt".into(),
+ reason: 0x200,
+ attributes: 0,
+ },
+ Record {
+ id: 4,
+ parent: 1,
+ name: "other.txt".into(),
+ reason: 0x200,
+ attributes: 0,
+ },
+ ],
+ &mut cache,
+ |id| {
+ if id == 2 {
+ Ok(PathBuf::from(r"C:\Users\new.txt"))
+ } else {
+ anyhow::bail!("access denied")
+ }
+ },
+ )
+ .unwrap();
+ assert_eq!(batch.paths, vec![PathBuf::from(r"C:\Users\new.txt")]);
+ assert_eq!(batch.missing_names, vec!["gone.txt", "other.txt"]);
+ assert!(batch.unresolved.is_some());
+ }
+}
diff --git a/native/src/main.rs b/native/src/main.rs
index e17f670..b7d9b6c 100644
--- a/native/src/main.rs
+++ b/native/src/main.rs
@@ -1,4 +1,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod admin;
mod ai;
mod app;
mod appearance;
@@ -34,6 +35,7 @@ mod setup;
mod speech_ffi;
#[cfg(test)]
mod stability_tests;
+mod tray;
mod tts;
mod updates;
mod vector_cache;
@@ -52,6 +54,7 @@ fn run() -> anyhow::Result<()> {
if args.iter().any(|x| x == "--extract-worker") {
return worker::worker_main();
}
+ admin::prepare_handoff(&args)?;
let home = config::home(args.iter().any(|x| x == "--portable"))?;
unsafe {
std::env::set_var("VECTORDASH_MODEL_LOG", home.join("model.log"));
@@ -150,6 +153,29 @@ fn run() -> anyhow::Result<()> {
if cli::run(&home, &args)? {
return Ok(());
}
+ if admin::should_elevate(
+ config::Settings::load(&home)?.always_admin,
+ admin::elevated(),
+ &args,
+ ) {
+ match admin::relaunch(&home, &args) {
+ Ok(()) => return Ok(()),
+ Err(e) => {
+ use std::io::Write;
+ if let Ok(mut log) = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(home.join("vectordash.log"))
+ {
+ let _ = writeln!(
+ log,
+ "Warning {} {e}; continuing without administrator access",
+ chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
+ );
+ }
+ }
+ }
+ }
let smoke = args
.iter()
.position(|x| x == "--smoke-report")
diff --git a/native/src/platform.rs b/native/src/platform.rs
index 042ab86..d22e03f 100644
--- a/native/src/platform.rs
+++ b/native/src/platform.rs
@@ -358,7 +358,12 @@ pub fn hotkeys(
) {
std::thread::spawn(move || unsafe {
use windows::Win32::UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*};
- let tray = match tray_window(tx.clone()) {
+ crate::tray::publish(crate::tray::Visual {
+ status: crate::tray::current().status,
+ accent: s.accent,
+ });
+ let mut tray_visual = crate::tray::current();
+ let mut tray = match tray_window(tx.clone(), tray_visual) {
Ok(v) => Some(v),
Err(e) => {
let _ = tx.send(crate::engine::Event::Log(
@@ -368,6 +373,7 @@ pub fn hotkeys(
None
}
};
+ let mut tray_attempt = Instant::now() - Duration::from_secs(2);
let requested = [(777, &s.hotkey), (778, &s.dictation_hotkey)];
let mut bindings = Vec::new();
for (id, text) in requested {
@@ -420,6 +426,22 @@ pub fn hotkeys(
};
}
}
+ if let Some((_, data)) = tray.as_mut() {
+ if (crate::tray::current() != tray_visual
+ || TRAY_READD.load(std::sync::atomic::Ordering::Relaxed))
+ && tray_attempt.elapsed() >= Duration::from_secs(1)
+ {
+ tray_attempt = Instant::now();
+ let force = TRAY_READD.swap(false, std::sync::atomic::Ordering::Relaxed);
+ if let Err(error) = refresh_tray(data, &mut tray_visual, force) {
+ TRAY_READD.store(true, std::sync::atomic::Ordering::Relaxed);
+ let _ = tx.try_send(crate::engine::Event::Log(
+ "Warning".into(),
+ format!("Tray icon update: {error:#}"),
+ ));
+ }
+ }
+ }
let pressed = GetAsyncKeyState(VK_CONTROL.0 as i32) < 0;
if pressed && !down {
if last.elapsed() < Duration::from_millis(350) {
@@ -764,7 +786,23 @@ pub fn explorer_folder(target: isize) -> Result<String> {
}
}
#[cfg(windows)]
-static TRAY_TX: std::sync::OnceLock<crate::engine::NotifySender> = std::sync::OnceLock::new();
+static TRAY_TX: std::sync::Mutex<Option<crate::engine::NotifySender>> = std::sync::Mutex::new(None);
+#[cfg(windows)]
+static TASKBAR_CREATED: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+#[cfg(windows)]
+static TRAY_READD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+#[cfg(windows)]
+fn tray_sender() -> Option<crate::engine::NotifySender> {
+ TRAY_TX.lock().ok().and_then(|tx| tx.clone())
+}
+#[cfg(windows)]
+fn tray_open(tx: &crate::engine::NotifySender) {
+ let _ = tx.try_send(crate::engine::Event::Log(
+ "Info".into(),
+ "Tray requested main window".into(),
+ ));
+ let _ = tx.try_send(crate::engine::Event::Full);
+}
#[cfg(windows)]
unsafe extern "system" fn tray_proc(
hwnd: windows::Win32::Foundation::HWND,
@@ -777,13 +815,26 @@ unsafe extern "system" fn tray_proc(
UI::WindowsAndMessaging::*,
};
unsafe {
+ if TASKBAR_CREATED
+ .get()
+ .is_some_and(|id| *id != 0 && msg == *id)
+ {
+ TRAY_READD.store(true, std::sync::atomic::Ordering::Relaxed);
+ return LRESULT(0);
+ }
if msg == WM_APP + 9 {
- if l.0 as u32 == WM_LBUTTONDBLCLK {
- if let Some(tx) = TRAY_TX.get() {
- let _ = tx.try_send(crate::engine::Event::Full);
+ // Version 4 packs the icon ID in HIWORD; legacy callbacks use the whole LPARAM.
+ let event = (l.0 as u32) & 0xffff;
+ if event == WM_LBUTTONDBLCLK
+ || event == windows::Win32::UI::Shell::NIN_SELECT
+ || event
+ == (windows::Win32::UI::Shell::NIN_SELECT | windows::Win32::UI::Shell::NINF_KEY)
+ {
+ if let Some(tx) = tray_sender() {
+ tray_open(&tx);
}
}
- if l.0 as u32 == WM_RBUTTONUP {
+ if event == WM_RBUTTONUP || event == WM_CONTEXTMENU {
if let Ok(menu) = CreatePopupMenu() {
let _ = AppendMenuW(
menu,
@@ -803,6 +854,10 @@ unsafe extern "system" fn tray_proc(
);
let mut point = POINT::default();
let _ = GetCursorPos(&mut point);
+ if event == WM_CONTEXTMENU {
+ point.x = (w.0 as u16 as i16) as i32;
+ point.y = ((w.0 >> 16) as u16 as i16) as i32;
+ }
let _ = SetForegroundWindow(hwnd);
let choice = TrackPopupMenu(
menu,
@@ -813,9 +868,9 @@ unsafe extern "system" fn tray_proc(
hwnd,
None,
);
- if let Some(tx) = TRAY_TX.get() {
+ if let Some(tx) = tray_sender() {
if choice.0 == 1 {
- let _ = tx.try_send(crate::engine::Event::Full);
+ tray_open(&tx);
} else if choice.0 == 2 {
let _ = tx.send(crate::engine::Event::Quit);
}
@@ -835,12 +890,10 @@ unsafe extern "system" fn tray_proc(
}
}
#[cfg(windows)]
-fn tray_icon() -> Result<windows::Win32::UI::WindowsAndMessaging::HICON> {
- let image = image::load_from_memory(include_bytes!("../assets/vectordash.png"))?
- .resize_exact(32, 32, image::imageops::FilterType::Lanczos3)
- .to_rgba8();
- let pixels: Vec<u8> = image
- .pixels()
+fn tray_icon(color: [u8; 3]) -> Result<windows::Win32::UI::WindowsAndMessaging::HICON> {
+ let rgba = crate::tray::pixels(color);
+ let pixels: Vec<u8> = rgba
+ .chunks_exact(4)
.flat_map(|p| {
[
((p[2] as u16 * p[3] as u16) / 255) as u8,
@@ -864,8 +917,62 @@ fn tray_icon() -> Result<windows::Win32::UI::WindowsAndMessaging::HICON> {
})
}
#[cfg(windows)]
+fn tray_tip(data: &mut windows::Win32::UI::Shell::NOTIFYICONDATAW, visual: crate::tray::Visual) {
+ data.szTip.fill(0);
+ let text = format!("VectorDash — {}", crate::i18n::tray_text(visual.label()));
+ for (dst, src) in data.szTip.iter_mut().take(127).zip(text.encode_utf16()) {
+ *dst = src;
+ }
+}
+#[cfg(windows)]
+fn refresh_tray(
+ data: &mut windows::Win32::UI::Shell::NOTIFYICONDATAW,
+ previous: &mut crate::tray::Visual,
+ force: bool,
+) -> Result<()> {
+ use windows::Win32::UI::{Shell::*, WindowsAndMessaging::DestroyIcon};
+ let visual = crate::tray::current();
+ if visual == *previous && !force {
+ return Ok(());
+ }
+ let old = data.hIcon;
+ let replacement = if visual != *previous {
+ tray_icon(visual.color())?
+ } else {
+ old
+ };
+ let mut update = *data;
+ update.hIcon = replacement;
+ tray_tip(&mut update, visual);
+ unsafe {
+ let restored = if force {
+ Shell_NotifyIconW(NIM_ADD, &update).as_bool()
+ } else {
+ false
+ };
+ let ok = restored
+ || Shell_NotifyIconW(NIM_MODIFY, &update).as_bool()
+ || Shell_NotifyIconW(NIM_ADD, &update).as_bool();
+ if !ok {
+ if replacement != old {
+ let _ = DestroyIcon(replacement);
+ }
+ anyhow::bail!("Windows could not refresh tray icon");
+ }
+ update.Anonymous.uVersion = NOTIFYICON_VERSION_4;
+ let _ = Shell_NotifyIconW(NIM_SETVERSION, &update);
+ *data = update;
+ *previous = visual;
+ if replacement != old {
+ let _ = DestroyIcon(old);
+ }
+ }
+ Ok(())
+}
+#[cfg(windows)]
fn tray_window(
tx: crate::engine::NotifySender,
+ visual: crate::tray::Visual,
) -> Result<(
windows::Win32::Foundation::HWND,
windows::Win32::UI::Shell::NOTIFYICONDATAW,
@@ -878,9 +985,14 @@ fn tray_window(
core::PCWSTR,
};
unsafe {
- let _ = TRAY_TX.set(tx);
+ *TRAY_TX
+ .lock()
+ .map_err(|_| anyhow::anyhow!("Tray sender lock unavailable"))? = Some(tx);
+ let restart = *TASKBAR_CREATED
+ .get_or_init(|| RegisterWindowMessageW(PCWSTR(wide("TaskbarCreated").as_ptr())));
let class = wide("VectorDashRustTray");
let registration = WNDCLASSW {
+ style: CS_DBLCLKS,
lpfnWndProc: Some(tray_proc),
lpszClassName: PCWSTR(class.as_ptr()),
hInstance: HINSTANCE::default(),
@@ -905,22 +1017,23 @@ fn tray_window(
cbSize: std::mem::size_of::<NOTIFYICONDATAW>() as u32,
hWnd: hwnd,
uID: 1,
- uFlags: NIF_ICON | NIF_MESSAGE | NIF_TIP,
+ uFlags: NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP,
uCallbackMessage: WM_APP + 9,
- hIcon: tray_icon()?,
+ hIcon: tray_icon(visual.color())?,
..Default::default()
};
- for (dst, src) in icon
- .szTip
- .iter_mut()
- .zip("VectorDash — double-click to open".encode_utf16())
- {
- *dst = src;
+ tray_tip(&mut icon, visual);
+ let _ = ChangeWindowMessageFilterEx(hwnd, WM_APP + 9, MSGFLT_ALLOW, None);
+ if restart != 0 {
+ let _ = ChangeWindowMessageFilterEx(hwnd, restart, MSGFLT_ALLOW, None);
}
- anyhow::ensure!(
- Shell_NotifyIconW(NIM_ADD, &icon).as_bool(),
- "Windows could not add the tray icon"
- );
+ if !Shell_NotifyIconW(NIM_ADD, &icon).as_bool() {
+ let _ = DestroyIcon(icon.hIcon);
+ let _ = DestroyWindow(hwnd);
+ anyhow::bail!("Windows could not add the tray icon");
+ }
+ icon.Anonymous.uVersion = NOTIFYICON_VERSION_4;
+ let _ = Shell_NotifyIconW(NIM_SETVERSION, &icon);
Ok((hwnd, icon))
}
}
@@ -2314,3 +2427,66 @@ pub fn windows_build() -> u32 {
pub fn development_overrides() -> bool {
cfg!(debug_assertions) || std::env::args().any(|a| a == "--allow-development-overrides")
}
+
+/// Test the real Shell callback without touching another running instance.
+#[cfg(windows)]
+pub fn smoke_tray_open(
+ tx: crate::engine::NotifySender,
+ legacy: bool,
+ accent: [u8; 3],
+) -> Result<()> {
+ use windows::Win32::{
+ Foundation::{LPARAM, WPARAM},
+ UI::{Shell::*, WindowsAndMessaging::*},
+ };
+ let mut visual = crate::tray::Visual {
+ status: crate::tray::Status::Idle,
+ accent,
+ };
+ crate::tray::publish(visual);
+ let (hwnd, mut data) = tray_window(tx, visual)?;
+ unsafe {
+ // Simulate Explorer losing registration; do not restart the user's Explorer.
+ let _ = Shell_NotifyIconW(NIM_DELETE, &data);
+ let message = *TASKBAR_CREATED.get().unwrap();
+ SendMessageW(hwnd, message, Some(WPARAM(0)), Some(LPARAM(0)));
+ anyhow::ensure!(
+ TRAY_READD.swap(false, std::sync::atomic::Ordering::Relaxed),
+ "Explorer-restart callback not received"
+ );
+ refresh_tray(&mut data, &mut visual, true)?;
+ for state in [
+ crate::tray::Status::Waiting,
+ crate::tray::Status::Indexing,
+ crate::tray::Status::Idle,
+ ] {
+ let old = data.hIcon;
+ crate::tray::publish(crate::tray::Visual {
+ status: state,
+ accent,
+ });
+ refresh_tray(&mut data, &mut visual, false)?;
+ anyhow::ensure!(data.hIcon != old, "State transition did not update icon");
+ }
+ let payload = if legacy {
+ WM_LBUTTONDBLCLK
+ } else {
+ (1 << 16) | WM_LBUTTONDBLCLK
+ };
+ SendMessageW(
+ hwnd,
+ WM_APP + 9,
+ Some(WPARAM(1)),
+ Some(LPARAM(payload as isize)),
+ );
+ let _ = Shell_NotifyIconW(NIM_DELETE, &data);
+ let _ = DestroyIcon(data.hIcon);
+ let _ = DestroyWindow(hwnd);
+ }
+ Ok(())
+}
+#[cfg(not(windows))]
+pub fn smoke_tray_open(tx: crate::engine::NotifySender, _: bool, _: [u8; 3]) -> Result<()> {
+ let _ = tx.try_send(crate::engine::Event::Full);
+ Ok(())
+}
diff --git a/native/src/scheduling.rs b/native/src/scheduling.rs
index bbfccc8..bde1e38 100644
--- a/native/src/scheduling.rs
+++ b/native/src/scheduling.rs
@@ -71,7 +71,18 @@ pub fn idle_allowed(s: &Settings, m: Metrics) -> Result<(), &'static str> {
Ok(())
}
pub fn due(s: &Settings, now: DateTime<Local>, m: Metrics) -> Result<i64, String> {
- if let Some(reason) = resource_pause(s, m) {
+ due_impl(s, now, m, true)
+}
+pub fn work_due(s: &Settings, now: DateTime<Local>) -> bool {
+ due_impl(s, now, Metrics::default(), false).is_ok()
+}
+fn due_impl(
+ s: &Settings,
+ now: DateTime<Local>,
+ m: Metrics,
+ conditions: bool,
+) -> Result<i64, String> {
+ if let Some(reason) = resource_pause(s, m).filter(|_| conditions) {
return Err(reason.into());
}
if s.schedule == "Manual" {
@@ -81,7 +92,9 @@ pub fn due(s: &Settings, now: DateTime<Local>, m: Metrics) -> Result<i64, String
if now.timestamp() < s.last_success + s.idle_interval_minutes as i64 * 60 {
return Err("Waiting for the next idle interval".into());
}
- idle_allowed(s, m).map_err(str::to_string)?;
+ if conditions {
+ idle_allowed(s, m).map_err(str::to_string)?;
+ }
return Ok(now.timestamp());
}
let mut slot = None;
@@ -104,11 +117,13 @@ pub fn due(s: &Settings, now: DateTime<Local>, m: Metrics) -> Result<i64, String
if slot < s.schedule_enabled_at || slot <= s.last_schedule_slot {
return Err("Waiting for the next scheduled time".into());
}
- if s.ac_only && m.on_ac != Some(true) {
+ if conditions && s.ac_only && m.on_ac != Some(true) {
return Err("Waiting for AC power".into());
}
if s.schedule == "Time + idle" {
- idle_allowed(s, m).map_err(str::to_string)?;
+ if conditions {
+ idle_allowed(s, m).map_err(str::to_string)?;
+ }
}
Ok(slot)
}
diff --git a/native/src/search_filters.rs b/native/src/search_filters.rs
index f7e0fb5..628af7d 100644
--- a/native/src/search_filters.rs
+++ b/native/src/search_filters.rs
@@ -90,7 +90,7 @@ impl Filters {
f.extension = Some(v.trim_start_matches('.').into());
} else if let Some(v) = word.strip_prefix("name:") {
f.pattern = Some(v.to_lowercase());
- } else if word.contains(['*', '?']) {
+ } else if word.contains(['*', '?']) && !word.contains(['\\', '/']) {
f.pattern = Some(low);
} else {
words.push(word);
@@ -99,6 +99,9 @@ impl Filters {
f.text = words.join(" ");
Ok(f)
}
+ pub fn uses_embeddings(&self) -> bool {
+ !self.text.is_empty() && crate::db::path_query(&self.text).is_none()
+ }
pub fn matches(&self, name: &str, size: i64, mtime: i64) -> bool {
size >= self.min_size
&& size <= self.max_size
@@ -154,3 +157,24 @@ mod tests {
assert!(Filters::parse("modified:no-date").is_err());
}
}
+
+#[cfg(test)]
+mod semantic_intent_tests {
+ use super::*;
+ #[test]
+ fn explicit_filename_syntax_never_uses_embeddings() {
+ for query in [
+ "*nr*",
+ r"*\*nr*",
+ r"\Local\RHI",
+ r"\RHI\nvngx_dlssnr.dll",
+ "name:*.dll",
+ "ext:dll",
+ "size:>1MB",
+ ] {
+ assert!(!Filters::parse(query).unwrap().uses_embeddings(), "{query}");
+ }
+ assert!(Filters::parse("photos of dogs").unwrap().uses_embeddings());
+ assert!(Filters::parse("dogs ext:jpg").unwrap().uses_embeddings());
+ }
+}
diff --git a/native/src/stability_tests.rs b/native/src/stability_tests.rs
index 049ca7d..17d4fd1 100644
--- a/native/src/stability_tests.rs
+++ b/native/src/stability_tests.rs
@@ -583,3 +583,402 @@ fn visual_queries_do_not_promote_infographics_for_exact_ocr_words() {
}
reply.join().unwrap();
}
+
+#[test]
+fn explicit_path_search_bypasses_embeddings_in_every_mode() {
+ let (_home, root, mut s, e, _) = fixture();
+ let path = root.path().join("RHI").join("nvngx_dlssnr.dll");
+ add(&e, &s, &path, "fixture contents");
+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
+ s.remote_url = format!("http://{}", server.server_addr());
+ let started = Instant::now();
+ for query in [r"\RHI\nvngx_dlssnr.dll", "*nr*", r"*\*nr*"] {
+ for mode in ["Names", "Both", "Semantic"] {
+ let hits = e
+ .search_inner(query, &s, mode, "All files", &s.roots[0].path, "")
+ .unwrap();
+ assert_eq!(hits.len(), 1, "{mode}");
+ assert_eq!(hits[0].path, path.to_string_lossy());
+ }
+ }
+ assert!(
+ server.try_recv().unwrap().is_none(),
+ "Path searches must not request embeddings"
+ );
+ println!(
+ "Three search modes: {:.2} ms; zero embedding requests",
+ started.elapsed().as_secs_f64() * 1000.0
+ );
+}
+
+#[test]
+fn changing_embedding_deployment_does_not_reembed_completed_files() {
+ let (_home, root, mut s, e, _) = fixture();
+ let path = root.path().join("deployment.txt");
+ std::fs::write(&path, "already indexed deployment fixture").unwrap();
+ s.pause_for_game = false;
+ s.pause_for_fullscreen = false;
+ let server = Arc::new(tiny_http::Server::http("127.0.0.1:0").unwrap());
+ s.embedding_server = "Remote".into();
+ s.remote_url = format!("http://{}", server.server_addr());
+ let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let stopped = Arc::new(AtomicBool::new(false));
+ let reply = server.clone();
+ let requests = count.clone();
+ let stop = stopped.clone();
+ let worker = std::thread::spawn(move || {
+ while !stop.load(Ordering::Acquire) {
+ if let Ok(Some(request)) = reply.recv_timeout(Duration::from_millis(20)) {
+ requests.fetch_add(1, Ordering::SeqCst);
+ let _ = request.respond(tiny_http::Response::from_string(
+ "{\"data\":[{\"index\":0,\"embedding\":[1,0]}]}",
+ ));
+ }
+ }
+ });
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ assert!(count.load(Ordering::SeqCst) > 0);
+ let before = count.load(Ordering::SeqCst);
+ let c = e.db.connect(true).unwrap();
+ let blob: Vec<u8> = c
+ .query_row("SELECT vector FROM segment_vectors LIMIT 1", [], |r| {
+ r.get(0)
+ })
+ .unwrap();
+ s.embedding_server = "Local".into();
+ s.model = "renamed-local-model.gguf".into();
+ s.projector = "renamed-encoder.gguf".into();
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ s.embedding_server = "Remote".into();
+ s.remote_model = "server-model-alias".into();
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ before,
+ "Provider/model aliases must not trigger inference"
+ );
+ assert_eq!(
+ blob,
+ c.query_row("SELECT vector FROM segment_vectors LIMIT 1", [], |r| r
+ .get::<_, Vec<u8>>(0))
+ .unwrap()
+ );
+ // Reproduce an old-version job left behind for already-completed content.
+ let writer = e.db.connect(false).unwrap();
+ let stamp: String = writer
+ .query_row(
+ "SELECT fingerprint FROM native_content WHERE path=?1",
+ [path.to_string_lossy().as_ref()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let (token, _) = Database::prepare_job(&writer, &path.to_string_lossy(), &stamp).unwrap();
+ Database::stage(
+ &writer,
+ &token,
+ 0,
+ &[crate::content::Segment::text(
+ "text",
+ "redundant".into(),
+ 1,
+ 0,
+ )],
+ &[vec![1.0, 0.0]],
+ )
+ .unwrap();
+ e.index_inner(&s, false).unwrap();
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ before,
+ "A redundant resume job must not override completed content"
+ );
+ assert_eq!(
+ writer
+ .query_row("SELECT count(*) FROM native_jobs", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ writer
+ .query_row("SELECT count(*) FROM native_staging", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ blob,
+ c.query_row("SELECT vector FROM segment_vectors LIMIT 1", [], |r| r
+ .get::<_, Vec<u8>>(0))
+ .unwrap()
+ );
+ // Explicit queued rebuilds must survive the same completion check.
+ Database::prepare_job(&writer, &path.to_string_lossy(), &stamp).unwrap();
+ writer
+ .execute(
+ "INSERT INTO native_rebuild_requests VALUES(?1)",
+ [path.to_string_lossy().as_ref()],
+ )
+ .unwrap();
+ e.index_inner(&s, false).unwrap();
+ let rebuilt = count.load(Ordering::SeqCst);
+ assert!(rebuilt > before);
+ assert_eq!(
+ writer
+ .query_row("SELECT count(*) FROM native_rebuild_requests", [], |r| r
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ // A file edit still updates its vectors, and an explicit rebuild still runs.
+ std::fs::write(&path, "file contents changed, requiring another embedding").unwrap();
+ e.index_inner(&s, false).unwrap();
+ let edited = count.load(Ordering::SeqCst);
+ assert!(edited > rebuilt);
+ let quick = root.path().join("quick-only");
+ std::fs::create_dir(&quick).unwrap();
+ s.roots.push(Source {
+ path: quick.to_string_lossy().into(),
+ mode: "quick".into(),
+ });
+ s.index_order = "Quick first".into();
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, true).unwrap();
+ assert!(count.load(Ordering::SeqCst) > edited);
+ stopped.store(true, Ordering::Release);
+ worker.join().unwrap();
+}
+
+#[test]
+fn quick_sources_find_hidden_appdata_names_with_cache_exclusion_enabled() {
+ let (_h, root, mut s, e, _) = fixture();
+ let appdata = root.path().join("AppData");
+ let rhi = appdata.join("Local").join("RHI");
+ std::fs::create_dir_all(rhi.join("DLSS-NR")).unwrap();
+ let dll = rhi.join("DLSS-NR").join("nvngx_dlssnr.dll");
+ std::fs::write(&dll, "fixture").unwrap();
+ #[cfg(windows)]
+ unsafe {
+ use std::os::windows::ffi::OsStrExt;
+ let wide: Vec<u16> = appdata.as_os_str().encode_wide().chain(Some(0)).collect();
+ windows::Win32::Storage::FileSystem::SetFileAttributesW(
+ windows::core::PCWSTR(wide.as_ptr()),
+ windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN,
+ )
+ .unwrap();
+ }
+ s.roots[0].mode = "quick".into();
+ s.skip_windows_churn = true;
+ s.pause_for_game = false;
+ s.pause_for_fullscreen = false;
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ for query in [r"\Local\RHI", r"\RHI\nvngx_dlssnr.dll"] {
+ let hits = names(&e, &s, query);
+ assert_eq!(hits.len(), 1, "{query}: {hits:?}");
+ }
+ assert_eq!(e.db.stats().unwrap().vectors, 0);
+ s.roots[0].mode = "full".into();
+ assert!(!s.searched(&dll));
+ assert!(
+ !crate::config::SearchPolicy::new(&s, "All files", "", "")
+ .allowed(&dll.to_string_lossy(), "file")
+ );
+ s.roots[0].mode = "quick".into();
+ s.exclusions.push(rhi.to_string_lossy().into());
+ assert!(names(&e, &s, r"\RHI\nvngx_dlssnr.dll").is_empty());
+}
+
+#[test]
+fn newer_filename_results_arrive_while_old_embedding_response_is_delayed() {
+ let (_h, root, mut s, e, rx) = fixture();
+ add(&e, &s, &root.path().join("first.txt"), "first passage");
+ add(&e, &s, &root.path().join("second.txt"), "second passage");
+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
+ s.remote_url = format!("http://{}", server.server_addr());
+ let started = Arc::new(AtomicBool::new(false));
+ let marker = started.clone();
+ let reply = std::thread::spawn(move || {
+ for i in 0..2 {
+ let request = server
+ .recv_timeout(Duration::from_secs(5))
+ .unwrap()
+ .unwrap();
+ if i == 0 {
+ marker.store(true, Ordering::Release);
+ std::thread::sleep(Duration::from_millis(700));
+ }
+ let _ = request.respond(tiny_http::Response::from_string(
+ "{\"data\":[{\"index\":0,\"embedding\":[1,0]}]}",
+ ));
+ }
+ });
+ e.search(
+ 1,
+ "first".into(),
+ s.clone(),
+ "Both".into(),
+ "All files".into(),
+ String::new(),
+ String::new(),
+ );
+ let wait = Instant::now();
+ while !started.load(Ordering::Acquire) {
+ assert!(wait.elapsed() < Duration::from_secs(3));
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ e.models.cancel_query();
+ let began = Instant::now();
+ e.search(
+ 2,
+ "second".into(),
+ s,
+ "Both".into(),
+ "All files".into(),
+ String::new(),
+ String::new(),
+ );
+ loop {
+ if let Event::SearchPartial(2, hits, _) = rx.recv_timeout(Duration::from_secs(2)).unwrap() {
+ assert!(began.elapsed() < Duration::from_millis(500));
+ assert!(hits.iter().any(|h| h.path.ends_with("second.txt")));
+ break;
+ }
+ }
+ reply.join().unwrap();
+}
+
+#[cfg(windows)]
+#[test]
+fn hidden_option_prunes_hidden_folders_and_files_and_preserves_visible_names() {
+ let (_home, root, mut s, e, _) = fixture();
+ s.roots[0].mode = "quick".into();
+ s.pause_for_game = false;
+ s.pause_for_fullscreen = false;
+ let folder = root.path().join("HiddenFolder");
+ std::fs::create_dir(&folder).unwrap();
+ let hidden_file = root.path().join("hidden.txt");
+ std::fs::write(&hidden_file, "hidden").unwrap();
+ std::fs::write(folder.join("nested.txt"), "nested").unwrap();
+ std::fs::write(root.path().join("visible.txt"), "visible").unwrap();
+ for path in [&folder, &hidden_file] {
+ use std::os::windows::ffi::OsStrExt;
+ let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ unsafe {
+ windows::Win32::Storage::FileSystem::SetFileAttributesW(
+ windows::core::PCWSTR(wide.as_ptr()),
+ windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN,
+ )
+ .unwrap();
+ }
+ }
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ assert_eq!(e.db.stats().unwrap().files, 3);
+ s.include_hidden = false;
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ assert_eq!(e.db.stats().unwrap().files, 1);
+ assert_eq!(names(&e, &s, "visible").len(), 1);
+ assert!(names(&e, &s, "nested").is_empty());
+ s.include_hidden = true;
+ *e.control.schedule.lock().unwrap() = s.clone();
+ e.index_inner(&s, false).unwrap();
+ assert_eq!(e.db.stats().unwrap().files, 3);
+ assert_eq!(e.db.stats().unwrap().vectors, 0);
+}
+
+#[test]
+fn enabling_windows_exclusion_purges_existing_quick_names_and_content_but_keeps_appdata() {
+ let (_home, root, mut s, e, _) = fixture();
+ s.roots[0].mode = "quick".into();
+ s.skip_windows_churn = false;
+ let retained = root.path().join("AppData/Local/RHI/retained.dll");
+ add(&e, &s, &retained, "retained passage");
+ let nested = root.path().join("Windows/MyDocs");
+ s.roots.push(Source {
+ path: nested.to_string_lossy().into(),
+ mode: "quick".into(),
+ });
+ add(
+ &e,
+ &s,
+ &nested.join("manual.txt"),
+ "nested retained passage",
+ );
+ for folder in ["Windows", "Temp", "cache"] {
+ let path = root.path().join(folder);
+ let c = e.db.connect(false).unwrap();
+ Database::touch_name(&c, &path, "folder", 1, 0, "quick", &s.roots[0].path, 1).unwrap();
+ drop(c);
+ add(&e, &s, &path.join("excluded.txt"), "excluded passage");
+ }
+ let c = e.db.connect(false).unwrap();
+ for i in 0..260 {
+ Database::touch_name(
+ &c,
+ &root.path().join(format!("Windows/old{i}.dll")),
+ "file",
+ 1,
+ 20,
+ "quick",
+ &s.roots[0].path,
+ 1,
+ )
+ .unwrap();
+ }
+ assert!(!names(&e, &s, "excluded").is_empty());
+ s.skip_windows_churn = true;
+ assert!(
+ names(&e, &s, "excluded").is_empty(),
+ "saved policy must hide existing excluded results before cleanup"
+ );
+ for mode in ["quick", "full"] {
+ s.roots[0].mode = mode.into();
+ assert!(!s.allowed(&root.path().join("Windows")));
+ assert!(
+ !crate::config::SearchPolicy::new(&s, "All files", "", "").allowed(
+ &root.path().join("Windows/excluded.txt").to_string_lossy(),
+ "file"
+ )
+ );
+ }
+ s.roots[0].mode = "quick".into();
+ let mut steps = 0;
+ while !e.db.prune_step(&s, "windows-exclusion-v2").unwrap() {
+ steps += 1;
+ assert!(steps < 100);
+ }
+ assert_eq!(e.db.stats().unwrap().files, 2);
+ assert_eq!(e.db.stats().unwrap().vectors, 2);
+ assert_eq!(
+ names(&e, &s, "manual").len(),
+ 1,
+ "an explicitly retained nested source must survive prefix cleanup"
+ );
+ assert_eq!(names(&e, &s, r"\RHI\retained.dll").len(), 1);
+ let plan: Vec<String> = c.prepare("EXPLAIN QUERY PLAN SELECT path FROM names WHERE path>=?1 AND path<?3 AND (path=?1 OR path>=?2) AND path>?4 ORDER BY path LIMIT 128").unwrap()
+ .query_map(params![r"C:\Windows", r"C:\Windows\", r"C:\Windows]", ""], |r| r.get(3)).unwrap().map(Result::unwrap).collect();
+ assert!(plan.iter().any(|p| p.contains("SEARCH names")), "{plan:?}");
+ assert!(!plan.iter().any(|p| p.contains("SCAN names")), "{plan:?}");
+ for table in [
+ "names",
+ "segments",
+ "words",
+ "segment_vectors",
+ "source_seen",
+ "native_content",
+ ] {
+ let count: i64 = c
+ .query_row(
+ &format!("SELECT count(*) FROM {table} WHERE path LIKE '%excluded.txt'"),
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(count, 0, "{table}");
+ }
+}
diff --git a/native/src/tray.rs b/native/src/tray.rs
new file mode 100644
index 0000000..ac41077
--- /dev/null
+++ b/native/src/tray.rs
@@ -0,0 +1,292 @@
+use crate::{
+ config::Settings,
+ scheduling::{self, Metrics},
+};
+use chrono::{DateTime, Local};
+use std::sync::atomic::{AtomicU32, Ordering};
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Status {
+ Idle,
+ Waiting,
+ Indexing,
+}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Visual {
+ pub status: Status,
+ pub accent: [u8; 3],
+}
+impl Visual {
+ pub fn color(self) -> [u8; 3] {
+ match self.status {
+ Status::Idle => self.accent,
+ Status::Waiting => [245, 190, 45],
+ Status::Indexing => [239, 68, 68],
+ }
+ }
+ pub fn label(self) -> &'static str {
+ match self.status {
+ Status::Idle => "Idle",
+ Status::Waiting => "Waiting for indexing conditions",
+ Status::Indexing => "Indexing",
+ }
+ }
+ fn packed(self) -> u32 {
+ u32::from_le_bytes([
+ self.accent[0],
+ self.accent[1],
+ self.accent[2],
+ match self.status {
+ Status::Idle => 0,
+ Status::Waiting => 1,
+ Status::Indexing => 2,
+ },
+ ])
+ }
+}
+static VISUAL: AtomicU32 = AtomicU32::new(u32::from_le_bytes([133, 115, 255, 0]));
+pub fn publish(visual: Visual) {
+ VISUAL.store(visual.packed(), Ordering::Relaxed);
+}
+pub fn current() -> Visual {
+ let [r, g, b, state] = VISUAL.load(Ordering::Relaxed).to_le_bytes();
+ Visual {
+ accent: [r, g, b],
+ status: match state {
+ 1 => Status::Waiting,
+ 2 => Status::Indexing,
+ _ => Status::Idle,
+ },
+ }
+}
+#[derive(Default)]
+pub struct Work {
+ pub running: bool,
+ pub paused: bool,
+ pub automatic: bool,
+ pub watching: bool,
+ pub held: bool,
+ pub pending: bool,
+ pub restarting: bool,
+}
+pub fn status(s: &Settings, w: Work, m: Metrics, now: DateTime<Local>) -> Status {
+ let idle_blocked = scheduling::idle_allowed(s, m).is_err();
+ let resource_blocked = scheduling::resource_pause(s, m).is_some();
+ if w.running {
+ let idle_applies = w.automatic
+ && (w.watching || ["When idle", "Time + idle"].contains(&s.schedule.as_str()));
+ return if w.paused || resource_blocked || (idle_applies && idle_blocked) {
+ Status::Waiting
+ } else {
+ Status::Indexing
+ };
+ }
+ if w.held && !w.restarting {
+ return Status::Idle;
+ }
+ let periodic = scheduling::work_due(s, now);
+ let periodic_blocked = resource_blocked
+ || (s.ac_only && m.on_ac != Some(true))
+ || (["When idle", "Time + idle"].contains(&s.schedule.as_str()) && idle_blocked);
+ if ((w.pending || w.restarting) && idle_blocked) || (periodic && periodic_blocked) {
+ Status::Waiting
+ } else {
+ Status::Idle
+ }
+}
+/// Antialiased magnifier, generated only when a tray visual changes.
+pub fn pixels(color: [u8; 3]) -> Vec<u8> {
+ let mut rgba = vec![0; 32 * 32 * 4];
+ for y in 0..32 {
+ for x in 0..32 {
+ let mut covered = 0;
+ for sy in 0..4 {
+ for sx in 0..4 {
+ let px = x as f32 + (sx as f32 + 0.5) / 4.;
+ let py = y as f32 + (sy as f32 + 0.5) / 4.;
+ let ring =
+ (((px - 12.8).powi(2) + (py - 12.8).powi(2)).sqrt() - 8.).abs() <= 1.45;
+ let t =
+ (((px - 18.8) * 7.4 + (py - 18.8) * 7.4) / (2. * 7.4 * 7.4)).clamp(0., 1.);
+ let handle = (px - (18.8 + 7.4 * t)).powi(2) + (py - (18.8 + 7.4 * t)).powi(2)
+ <= 1.85f32.powi(2);
+ if ring || handle {
+ covered += 1;
+ }
+ }
+ }
+ let i = (y * 32 + x) * 4;
+ rgba[i..i + 3].copy_from_slice(&color);
+ rgba[i + 3] = (covered * 255 / 16) as u8;
+ }
+ }
+ rgba
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn settings() -> Settings {
+ let mut s = Settings::default();
+ s.check_cpu = true;
+ s.cpu_limit = 20.;
+ s.check_gpu = false;
+ s.check_user_idle = false;
+ s.ac_only = false;
+ s.pause_for_fullscreen = false;
+ s.pause_for_game = false;
+ s.schedule = "Manual".into();
+ s
+ }
+ fn metrics(cpu: f32) -> Metrics {
+ Metrics {
+ cpu: Some(cpu),
+ on_ac: Some(true),
+ ..Default::default()
+ }
+ }
+ #[test]
+ fn colors_follow_real_work_and_conditions() {
+ let s = settings();
+ let now = Local::now();
+ assert_eq!(status(&s, Work::default(), metrics(90.), now), Status::Idle);
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ pending: true,
+ ..Default::default()
+ },
+ metrics(90.),
+ now
+ ),
+ Status::Waiting
+ );
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ pending: true,
+ ..Default::default()
+ },
+ metrics(0.),
+ now
+ ),
+ Status::Idle
+ );
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ running: true,
+ ..Default::default()
+ },
+ metrics(90.),
+ now
+ ),
+ Status::Indexing
+ );
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ running: true,
+ automatic: true,
+ watching: true,
+ ..Default::default()
+ },
+ metrics(90.),
+ now
+ ),
+ Status::Waiting
+ );
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ running: true,
+ paused: true,
+ ..Default::default()
+ },
+ metrics(0.),
+ now
+ ),
+ Status::Waiting
+ );
+ assert_eq!(
+ status(
+ &s,
+ Work {
+ held: true,
+ pending: true,
+ ..Default::default()
+ },
+ metrics(90.),
+ now
+ ),
+ Status::Idle
+ );
+ }
+ #[test]
+ fn periodic_work_only_waits_after_its_interval_and_respects_ac_power() {
+ use chrono::Timelike;
+ let mut s = settings();
+ let now = Local::now();
+ s.schedule = "When idle".into();
+ s.last_success = now.timestamp();
+ s.idle_interval_minutes = 60;
+ assert_eq!(status(&s, Work::default(), metrics(90.), now), Status::Idle);
+ s.last_success = 0;
+ assert_eq!(
+ status(&s, Work::default(), metrics(90.), now),
+ Status::Waiting
+ );
+ s.schedule = "Time".into();
+ s.schedule_hour = now.hour();
+ s.schedule_minute = now.minute();
+ s.schedule_days = [true; 7];
+ s.schedule_enabled_at = 0;
+ s.last_schedule_slot = 0;
+ s.ac_only = true;
+ assert_eq!(
+ status(
+ &s,
+ Work::default(),
+ Metrics {
+ on_ac: Some(false),
+ ..metrics(90.)
+ },
+ now
+ ),
+ Status::Waiting
+ );
+ assert_eq!(status(&s, Work::default(), metrics(90.), now), Status::Idle);
+ }
+ #[test]
+ fn custom_theme_and_antialiased_transparent_icon() {
+ let visual = Visual {
+ status: Status::Idle,
+ accent: [22, 160, 77],
+ };
+ assert_eq!(visual.color(), [22, 160, 77]);
+ let p = pixels(visual.color());
+ assert_eq!(p.len(), 4096);
+ assert_eq!(p[3], 0);
+ assert!(p.chunks_exact(4).any(|v| v[3] > 0 && v[3] < 255));
+ assert!(p.chunks_exact(4).any(|v| v[3] == 255));
+ assert_eq!(
+ Visual {
+ status: Status::Waiting,
+ ..visual
+ }
+ .color(),
+ [245, 190, 45]
+ );
+ assert_eq!(
+ Visual {
+ status: Status::Indexing,
+ ..visual
+ }
+ .color(),
+ [239, 68, 68]
+ );
+ }
+}
diff --git a/native/src/vector_cache.rs b/native/src/vector_cache.rs
index 7aecebb..e8bda4b 100644
--- a/native/src/vector_cache.rs
+++ b/native/src/vector_cache.rs
@@ -67,8 +67,22 @@ impl Cache {
}) {
return Ok(Some(matrix.clone()));
}
+ *lock = None;
let(count,estimated):(usize,usize)=db.query_row("SELECT count(*),coalesce(sum(length(vector)/?2+length(path)+length(kind)+length(channel)+128),0) FROM segment_vectors WHERE dimension=?1",rusqlite::params![dimension, if fp16 {2} else {1}],|r|Ok((r.get(0)?,r.get(1)?)))?;
- if count == 0 || estimated > limit {
+ if count == 0 {
+ let indexed: Option<usize> = db
+ .query_row("SELECT dimension FROM segment_vectors LIMIT 1", [], |r| {
+ r.get(0)
+ })
+ .optional()?;
+ anyhow::ensure!(
+ indexed.is_none(),
+ "Embedding dimensions differ from the existing index (query: {dimension}, indexed: {}). Select a compatible embedding model or explicitly use Rebuild full content.",
+ indexed.unwrap_or(0)
+ );
+ return Ok(None);
+ }
+ if estimated > limit {
return Ok(None);
}
let mut matrix = Matrix {
diff --git a/native/vendor/notify/Cargo.toml b/native/vendor/notify/Cargo.toml
new file mode 100644
index 0000000..ba52fc3
--- /dev/null
+++ b/native/vendor/notify/Cargo.toml
@@ -0,0 +1,121 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.77"
+name = "notify"
+version = "8.2.0"
+authors = [
+ "Félix Saparelli <[email protected]>",
+ "Daniel Faust <[email protected]>",
+ "Aron Heinecke <[email protected]>",
+]
+description = "Cross-platform filesystem notification library"
+homepage = "https://github.com/notify-rs/notify"
+documentation = "https://docs.rs/notify"
+readme = "README.md"
+keywords = [
+ "events",
+ "filesystem",
+ "notify",
+ "watch",
+]
+categories = ["filesystem"]
+license = "CC0-1.0"
+repository = "https://github.com/notify-rs/notify.git"
+
+[dependencies.crossbeam-channel]
+version = "0.5.0"
+optional = true
+
+[dependencies.flume]
+version = "0.11.1"
+optional = true
+
+[dependencies.libc]
+version = "0.2.4"
+
+[dependencies.log]
+version = "0.4.17"
+
+[dependencies.notify-types]
+version = "2.0.0"
+
+[dependencies.walkdir]
+version = "2.4.0"
+
+[dev-dependencies.insta]
+version = "1.34.0"
+
+[dev-dependencies.nix]
+version = "0.29.0"
+
+[dev-dependencies.serde_json]
+version = "1.0.39"
+
+[dev-dependencies.tempfile]
+version = "3.10.0"
+
+[features]
+default = ["macos_fsevent"]
+macos_fsevent = ["fsevent-sys"]
+macos_kqueue = [
+ "kqueue",
+ "mio",
+]
+serde = ["notify-types/serde"]
+serialization-compat-6 = ["notify-types/serialization-compat-6"]
+
+[target."cfg(any(target_os=\"freebsd\", target_os=\"openbsd\", target_os = \"netbsd\", target_os = \"dragonflybsd\", target_os = \"ios\"))".dependencies.kqueue]
+version = "1.1.1"
+
+[target."cfg(any(target_os=\"freebsd\", target_os=\"openbsd\", target_os = \"netbsd\", target_os = \"dragonflybsd\", target_os = \"ios\"))".dependencies.mio]
+version = "1.0"
+features = ["os-ext"]
+
+[target."cfg(any(target_os=\"linux\", target_os=\"android\"))".dependencies.inotify]
+version = "0.11.0"
+default-features = false
+
+[target."cfg(any(target_os=\"linux\", target_os=\"android\"))".dependencies.mio]
+version = "1.0"
+features = ["os-ext"]
+
+[target."cfg(target_os = \"windows\")".dev-dependencies.trash]
+version = "5.2.2"
+
+[target."cfg(target_os=\"macos\")".dependencies.bitflags]
+version = "2.7.0"
+
+[target."cfg(target_os=\"macos\")".dependencies.fsevent-sys]
+version = "4.0.0"
+optional = true
+
+[target."cfg(target_os=\"macos\")".dependencies.kqueue]
+version = "1.1.1"
+optional = true
+
+[target."cfg(target_os=\"macos\")".dependencies.mio]
+version = "1.0"
+features = ["os-ext"]
+optional = true
+
+[target."cfg(windows)".dependencies.windows-sys]
+version = "0.60.1"
+features = [
+ "Win32_System_Threading",
+ "Win32_Foundation",
+ "Win32_Storage_FileSystem",
+ "Win32_Security",
+ "Win32_System_WindowsProgramming",
+ "Win32_System_IO",
+]
diff --git a/native/vendor/notify/Cargo.toml.orig b/native/vendor/notify/Cargo.toml.orig
new file mode 100644
index 0000000..0c50132
--- /dev/null
+++ b/native/vendor/notify/Cargo.toml.orig
@@ -0,0 +1,59 @@
+[package]
+name = "notify"
+version = "8.2.0"
+description = "Cross-platform filesystem notification library"
+documentation = "https://docs.rs/notify"
+readme = "../README.md"
+license = "CC0-1.0"
+keywords = ["events", "filesystem", "notify", "watch"]
+categories = ["filesystem"]
+authors = [
+ "Félix Saparelli <[email protected]>",
+ "Daniel Faust <[email protected]>",
+ "Aron Heinecke <[email protected]>"
+]
+rust-version.workspace = true
+edition.workspace = true
+homepage.workspace = true
+repository.workspace = true
+
+[features]
+default = ["macos_fsevent"]
+serde = ["notify-types/serde"]
+macos_kqueue = ["kqueue", "mio"]
+macos_fsevent = ["fsevent-sys"]
+serialization-compat-6 = ["notify-types/serialization-compat-6"]
+
+[dependencies]
+notify-types.workspace = true
+crossbeam-channel = { workspace = true, optional = true }
+flume = { workspace = true, optional = true }
+libc.workspace = true
+log.workspace = true
+walkdir.workspace = true
+
+[target.'cfg(any(target_os="linux", target_os="android"))'.dependencies]
+inotify = { workspace = true, default-features = false }
+mio.workspace = true
+
+[target.'cfg(target_os="macos")'.dependencies]
+bitflags.workspace = true
+fsevent-sys = { workspace = true, optional = true }
+kqueue = { workspace = true, optional = true }
+mio = { workspace = true, optional = true }
+
+[target.'cfg(windows)'.dependencies]
+windows-sys = { workspace = true, features = ["Win32_System_Threading", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_WindowsProgramming", "Win32_System_IO"] }
+
+[target.'cfg(any(target_os="freebsd", target_os="openbsd", target_os = "netbsd", target_os = "dragonflybsd", target_os = "ios"))'.dependencies]
+kqueue.workspace = true
+mio.workspace = true
+
+[dev-dependencies]
+serde_json.workspace = true
+tempfile.workspace = true
+nix.workspace = true
+insta.workspace = true
+
+[target.'cfg(target_os = "windows")'.dev-dependencies]
+trash.workspace = true
diff --git a/native/vendor/notify/LICENSE-CC0 b/native/vendor/notify/LICENSE-CC0
new file mode 100644
index 0000000..ec1dd6d
--- /dev/null
+++ b/native/vendor/notify/LICENSE-CC0
@@ -0,0 +1,41 @@
+Creative Commons CC0 1.0 Universal
+
+<<beginOptional;name=ccOptionalIntro>> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. <<endOptional>>
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
+
+ ii. moral rights retained by the original author(s) and/or performer(s);
+
+ iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
+
+ iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
+
+ v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
+
+ vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
+
+ vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
+
+ b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
+
+ c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
+
+ d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
\ No newline at end of file
diff --git a/native/vendor/notify/README.md b/native/vendor/notify/README.md
new file mode 100644
index 0000000..a3d7a3c
--- /dev/null
+++ b/native/vendor/notify/README.md
@@ -0,0 +1,87 @@
+# Notify
+
+[![» Crate](https://flat.badgen.net/crates/v/notify)][crate]
+[![» Docs](https://flat.badgen.net/badge/api/docs.rs/df3600)][notify-docs]
+[![» CI](https://flat.badgen.net/github/checks/notify-rs/notify/main)][build]
+[![» Downloads](https://flat.badgen.net/crates/d/notify)][crate]
+[![» Conduct](https://flat.badgen.net/badge/contributor/covenant/5e0d73)][coc]
+[![» Public Domain](https://flat.badgen.net/badge/license/CC0-1.0/purple)][cc0]
+
+_Cross-platform filesystem notification library for Rust._
+
+
+- [Notify Documentation][notify-docs]
+- [Notify Types Documentation][notify-types-docs]
+- [Mini Debouncer Documentation][debouncer-mini-docs]
+- [Full Debouncer Documentation][debouncer-full-docs]
+- [File ID][file-id-docs]
+- [Examples][examples]
+- [Changelog][changelog]
+- [Upgrading notify from v4](UPGRADING_V4_TO_V5.md)
+- Minimum supported Rust version: **1.77**
+
+As used by: [alacritty], [cargo watch], [cobalt], [deno], [docket], [mdBook],
+[rust-analyzer], [watchexec], [watchfiles], [xi-editor],
+and others.
+
+(Looking for desktop notifications instead? Have a look at [notify-rust] or
+[alert-after]!)
+
+## Platforms
+
+- Linux / Android: inotify
+- macOS: FSEvents or kqueue, see features
+- Windows: ReadDirectoryChangesW
+- iOS / FreeBSD / NetBSD / OpenBSD / DragonflyBSD: kqueue
+- All platforms: polling
+
+## License
+
+notify is licensed under the [CC Zero 1.0][cc0].
+notify-types is licensed under the [MIT] or [Apache-2.0][apache] license.
+notify-debouncer-mini is licensed under the [MIT] or [Apache-2.0][apache] license.
+notify-debouncer-full is licensed under the [MIT] or [Apache-2.0][apache] license.
+file-id is licensed under the [MIT] or [Apache-2.0][apache] license.
+
+## Origins
+
+Inspired by Go's [fsnotify] and Node.js's [Chokidar], born out of need for
+[cargo watch], and general frustration at the non-existence of C/Rust
+cross-platform notify libraries.
+
+Originally created by [Félix Saparelli] and awesome [contributors].
+
+[Chokidar]: https://github.com/paulmillr/chokidar
+[FileSystemEventSecurity]: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/FileSystemEventSecurity/FileSystemEventSecurity.html
+[debouncer-full-docs]: https://docs.rs/notify-debouncer-full/latest/notify_debouncer_full/
+[debouncer-mini-docs]: https://docs.rs/notify-debouncer-mini/latest/notify_debouncer_mini/
+[Félix Saparelli]: https://passcod.name
+[alacritty]: https://github.com/jwilm/alacritty
+[alert-after]: https://github.com/frewsxcv/alert-after
+[build]: https://github.com/notify-rs/notify/actions
+[cargo watch]: https://github.com/passcod/cargo-watch
+[cc0]: ./notify/LICENSE-CC0
+[MIT]: ./file-id/LICENSE-MIT
+[apache]: ./file-id/LICENSE-APACHE
+[changelog]: ./CHANGELOG.md
+[cobalt]: https://github.com/cobalt-org/cobalt.rs
+[coc]: http://contributor-covenant.org/version/1/4/
+[contributors]: https://github.com/notify-rs/notify/graphs/contributors
+[crate]: https://crates.io/crates/notify
+[deno]: https://github.com/denoland/deno
+[docket]: https://iwillspeak.github.io/docket/
+[notify-docs]: https://docs.rs/notify/latest/notify/
+[notify-types-docs]: https://docs.rs/notify-types/latest/notify-types/
+[file-id-docs]: https://docs.rs/file-id/latest/file_id/
+[fsnotify]: https://github.com/fsnotify/fsnotify
+[handlebars-iron]: https://github.com/sunng87/handlebars-iron
+[hotwatch]: https://github.com/francesca64/hotwatch
+[mdBook]: https://github.com/rust-lang-nursery/mdBook
+[notify-rust]: https://github.com/hoodie/notify-rust
+[rust-analyzer]: https://github.com/rust-analyzer/rust-analyzer
+[serde]: https://serde.rs/
+[watchexec]: https://github.com/mattgreen/watchexec
+[wiki]: https://github.com/notify-rs/notify/wiki
+[xi-editor]: https://xi-editor.io/
+[watchfiles]: https://watchfiles.helpmanual.io/
+[examples]: examples/
diff --git a/native/vendor/notify/VECTORDASH-PATCH.md b/native/vendor/notify/VECTORDASH-PATCH.md
new file mode 100644
index 0000000..2b43237
--- /dev/null
+++ b/native/vendor/notify/VECTORDASH-PATCH.md
@@ -0,0 +1,7 @@
+# Local notify 8.2.0 patch
+
+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.
diff --git a/native/vendor/notify/src/config.rs b/native/vendor/notify/src/config.rs
new file mode 100644
index 0000000..cc65c65
--- /dev/null
+++ b/native/vendor/notify/src/config.rs
@@ -0,0 +1,125 @@
+//! Configuration types
+
+use std::time::Duration;
+
+/// Indicates whether only the provided directory or its sub-directories as well should be watched
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+pub enum RecursiveMode {
+ /// Watch all sub-directories as well, including directories created after installing the watch
+ Recursive,
+
+ /// Watch only the provided directory
+ NonRecursive,
+}
+
+impl RecursiveMode {
+ pub(crate) fn is_recursive(&self) -> bool {
+ match *self {
+ RecursiveMode::Recursive => true,
+ RecursiveMode::NonRecursive => false,
+ }
+ }
+}
+
+/// Watcher Backend configuration
+///
+/// This contains multiple settings that may relate to only one specific backend,
+/// such as to correctly configure each backend regardless of what is selected during runtime.
+///
+/// ```rust
+/// # use std::time::Duration;
+/// # use notify::Config;
+/// let config = Config::default()
+/// .with_poll_interval(Duration::from_secs(2))
+/// .with_compare_contents(true);
+/// ```
+///
+/// Some options can be changed during runtime, others have to be set when creating the watcher backend.
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
+pub struct Config {
+ /// See [Config::with_poll_interval]
+ poll_interval: Option<Duration>,
+
+ /// See [Config::with_compare_contents]
+ compare_contents: bool,
+
+ follow_symlinks: bool,
+}
+
+impl Config {
+ /// For the [`PollWatcher`](crate::PollWatcher) backend.
+ ///
+ /// Interval between each re-scan attempt. This can be extremely expensive for large
+ /// file trees so it is recommended to measure and tune accordingly.
+ ///
+ /// The default poll frequency is 30 seconds.
+ ///
+ /// This will enable automatic polling, overwriting [`with_manual_polling()`](Config::with_manual_polling).
+ pub fn with_poll_interval(mut self, dur: Duration) -> Self {
+ // TODO: v7.0 break signature to option
+ self.poll_interval = Some(dur);
+ self
+ }
+
+ /// Returns current setting
+ pub fn poll_interval(&self) -> Option<Duration> {
+ // Changed Signature to Option
+ self.poll_interval
+ }
+
+ /// For the [`PollWatcher`](crate::PollWatcher) backend.
+ ///
+ /// Disable automatic polling. Requires calling [`crate::PollWatcher::poll()`] manually.
+ ///
+ /// This will disable automatic polling, overwriting [`with_poll_interval()`](Config::with_poll_interval).
+ pub fn with_manual_polling(mut self) -> Self {
+ self.poll_interval = None;
+ self
+ }
+
+ /// For the [`PollWatcher`](crate::PollWatcher) backend.
+ ///
+ /// Optional feature that will evaluate the contents of changed files to determine if
+ /// they have indeed changed using a fast hashing algorithm. This is especially important
+ /// for pseudo filesystems like those on Linux under /sys and /proc which are not obligated
+ /// to respect any other filesystem norms such as modification timestamps, file sizes, etc.
+ /// By enabling this feature, performance will be significantly impacted as all files will
+ /// need to be read and hashed at each `poll_interval`.
+ ///
+ /// This can't be changed during runtime. Off by default.
+ pub fn with_compare_contents(mut self, compare_contents: bool) -> Self {
+ self.compare_contents = compare_contents;
+ self
+ }
+
+ /// Returns current setting
+ pub fn compare_contents(&self) -> bool {
+ self.compare_contents
+ }
+
+ /// For the [INotifyWatcher](crate::INotifyWatcher), [KqueueWatcher](crate::KqueueWatcher),
+ /// and [PollWatcher](crate::PollWatcher).
+ ///
+ /// Determine if symbolic links should be followed when recursively watching a directory.
+ ///
+ /// This can't be changed during runtime. On by default.
+ pub fn with_follow_symlinks(mut self, follow_symlinks: bool) -> Self {
+ self.follow_symlinks = follow_symlinks;
+ self
+ }
+
+ /// Returns current setting
+ pub fn follow_symlinks(&self) -> bool {
+ self.follow_symlinks
+ }
+}
+
+impl Default for Config {
+ fn default() -> Self {
+ Self {
+ poll_interval: Some(Duration::from_secs(30)),
+ compare_contents: false,
+ follow_symlinks: true,
+ }
+ }
+}
diff --git a/native/vendor/notify/src/error.rs b/native/vendor/notify/src/error.rs
new file mode 100644
index 0000000..3d88bd7
--- /dev/null
+++ b/native/vendor/notify/src/error.rs
@@ -0,0 +1,171 @@
+//! Error types
+
+use crate::Config;
+use std::error::Error as StdError;
+use std::path::PathBuf;
+use std::result::Result as StdResult;
+use std::{self, fmt, io};
+
+/// Type alias to use this library's `Error` type in a Result
+pub type Result<T> = StdResult<T, Error>;
+
+/// Error kinds
+#[derive(Debug)]
+pub enum ErrorKind {
+ /// Generic error
+ ///
+ /// May be used in cases where a platform specific error is mapped to this type, or for opaque
+ /// internal errors.
+ Generic(String),
+
+ /// I/O errors.
+ Io(io::Error),
+
+ /// A path does not exist.
+ PathNotFound,
+
+ /// Attempted to remove a watch that does not exist.
+ WatchNotFound,
+
+ /// An invalid value was passed as runtime configuration.
+ InvalidConfig(Config),
+
+ /// Can't watch (more) files, limit on the total number of inotify watches reached
+ MaxFilesWatch,
+}
+
+/// Notify error type.
+///
+/// Errors are emitted either at creation time of a `Watcher`, or during the event stream. They
+/// range from kernel errors to filesystem errors to argument errors.
+///
+/// Errors can be general, or they can be about specific paths or subtrees. In that later case, the
+/// error's `paths` field will be populated.
+#[derive(Debug)]
+pub struct Error {
+ /// Kind of the error.
+ pub kind: ErrorKind,
+
+ /// Relevant paths to the error, if any.
+ pub paths: Vec<PathBuf>,
+}
+
+impl Error {
+ /// Adds a path to the error.
+ pub fn add_path(mut self, path: PathBuf) -> Self {
+ self.paths.push(path);
+ self
+ }
+
+ /// Replaces the paths for the error.
+ pub fn set_paths(mut self, paths: Vec<PathBuf>) -> Self {
+ self.paths = paths;
+ self
+ }
+
+ /// Creates a new Error with empty paths given its kind.
+ pub fn new(kind: ErrorKind) -> Self {
+ Self {
+ kind,
+ paths: Vec::new(),
+ }
+ }
+
+ /// Creates a new generic Error from a message.
+ pub fn generic(msg: &str) -> Self {
+ Self::new(ErrorKind::Generic(msg.into()))
+ }
+
+ /// Creates a new i/o Error from a stdlib `io::Error`.
+ pub fn io(err: io::Error) -> Self {
+ Self::new(ErrorKind::Io(err))
+ }
+
+ /// Similar to [`Error::io`], but specifically handles [`io::ErrorKind::NotFound`].
+ pub fn io_watch(err: io::Error) -> Self {
+ if err.kind() == io::ErrorKind::NotFound {
+ Self::path_not_found()
+ } else {
+ Self::io(err)
+ }
+ }
+
+ /// Creates a new "path not found" error.
+ pub fn path_not_found() -> Self {
+ Self::new(ErrorKind::PathNotFound)
+ }
+
+ /// Creates a new "watch not found" error.
+ pub fn watch_not_found() -> Self {
+ Self::new(ErrorKind::WatchNotFound)
+ }
+
+ /// Creates a new "invalid config" error from the given `Config`.
+ pub fn invalid_config(config: &Config) -> Self {
+ Self::new(ErrorKind::InvalidConfig(*config))
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ let error = match self.kind {
+ ErrorKind::PathNotFound => "No path was found.".into(),
+ ErrorKind::WatchNotFound => "No watch was found.".into(),
+ ErrorKind::InvalidConfig(ref config) => format!("Invalid configuration: {:?}", config),
+ ErrorKind::Generic(ref err) => err.clone(),
+ ErrorKind::Io(ref err) => err.to_string(),
+ ErrorKind::MaxFilesWatch => "OS file watch limit reached.".into(),
+ };
+
+ if self.paths.is_empty() {
+ write!(f, "{}", error)
+ } else {
+ write!(f, "{} about {:?}", error, self.paths)
+ }
+ }
+}
+
+impl StdError for Error {
+ fn cause(&self) -> Option<&dyn StdError> {
+ match self.kind {
+ ErrorKind::Io(ref cause) => Some(cause),
+ _ => None,
+ }
+ }
+}
+
+impl From<io::Error> for Error {
+ fn from(err: io::Error) -> Self {
+ Error::io(err)
+ }
+}
+
+impl<T> From<std::sync::mpsc::SendError<T>> for Error {
+ fn from(err: std::sync::mpsc::SendError<T>) -> Self {
+ Error::generic(&format!("internal channel disconnect: {:?}", err))
+ }
+}
+
+impl From<std::sync::mpsc::RecvError> for Error {
+ fn from(err: std::sync::mpsc::RecvError) -> Self {
+ Error::generic(&format!("internal channel disconnect: {:?}", err))
+ }
+}
+
+impl<T> From<std::sync::PoisonError<T>> for Error {
+ fn from(err: std::sync::PoisonError<T>) -> Self {
+ Error::generic(&format!("internal mutex poisoned: {:?}", err))
+ }
+}
+
+#[test]
+fn display_formatted_errors() {
+ let expected = "Some error";
+
+ assert_eq!(expected, format!("{}", Error::generic(expected)));
+
+ assert_eq!(
+ expected,
+ format!("{}", Error::io(io::Error::other(expected)))
+ );
+}
diff --git a/native/vendor/notify/src/fsevent.rs b/native/vendor/notify/src/fsevent.rs
new file mode 100644
index 0000000..01a87b6
--- /dev/null
+++ b/native/vendor/notify/src/fsevent.rs
@@ -0,0 +1,651 @@
+//! Watcher implementation for Darwin's FSEvents API
+//!
+//! The FSEvents API provides a mechanism to notify clients about directories they ought to re-scan
+//! in order to keep their internal data structures up-to-date with respect to the true state of
+//! the file system. (For example, when files or directories are created, modified, or removed.) It
+//! sends these notifications "in bulk", possibly notifying the client of changes to several
+//! directories in a single callback.
+//!
+//! For more information see the [FSEvents API reference][ref].
+//!
+//! TODO: document event translation
+//!
+//! [ref]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/
+
+#![allow(non_upper_case_globals, dead_code)]
+
+use crate::event::*;
+use crate::{
+ unbounded, Config, Error, EventHandler, PathsMut, RecursiveMode, Result, Sender, Watcher,
+};
+use fsevent_sys as fs;
+use fsevent_sys::core_foundation as cf;
+use std::collections::HashMap;
+use std::ffi::CStr;
+use std::fmt;
+use std::os::raw;
+use std::path::{Path, PathBuf};
+use std::ptr;
+use std::sync::{Arc, Mutex};
+use std::thread;
+
+bitflags::bitflags! {
+ #[repr(C)]
+ #[derive(Debug)]
+ struct StreamFlags: u32 {
+ const NONE = fs::kFSEventStreamEventFlagNone;
+ const MUST_SCAN_SUBDIRS = fs::kFSEventStreamEventFlagMustScanSubDirs;
+ const USER_DROPPED = fs::kFSEventStreamEventFlagUserDropped;
+ const KERNEL_DROPPED = fs::kFSEventStreamEventFlagKernelDropped;
+ const IDS_WRAPPED = fs::kFSEventStreamEventFlagEventIdsWrapped;
+ const HISTORY_DONE = fs::kFSEventStreamEventFlagHistoryDone;
+ const ROOT_CHANGED = fs::kFSEventStreamEventFlagRootChanged;
+ const MOUNT = fs::kFSEventStreamEventFlagMount;
+ const UNMOUNT = fs::kFSEventStreamEventFlagUnmount;
+ const ITEM_CREATED = fs::kFSEventStreamEventFlagItemCreated;
+ const ITEM_REMOVED = fs::kFSEventStreamEventFlagItemRemoved;
+ const INODE_META_MOD = fs::kFSEventStreamEventFlagItemInodeMetaMod;
+ const ITEM_RENAMED = fs::kFSEventStreamEventFlagItemRenamed;
+ const ITEM_MODIFIED = fs::kFSEventStreamEventFlagItemModified;
+ const FINDER_INFO_MOD = fs::kFSEventStreamEventFlagItemFinderInfoMod;
+ const ITEM_CHANGE_OWNER = fs::kFSEventStreamEventFlagItemChangeOwner;
+ const ITEM_XATTR_MOD = fs::kFSEventStreamEventFlagItemXattrMod;
+ const IS_FILE = fs::kFSEventStreamEventFlagItemIsFile;
+ const IS_DIR = fs::kFSEventStreamEventFlagItemIsDir;
+ const IS_SYMLINK = fs::kFSEventStreamEventFlagItemIsSymlink;
+ const OWN_EVENT = fs::kFSEventStreamEventFlagOwnEvent;
+ const IS_HARDLINK = fs::kFSEventStreamEventFlagItemIsHardlink;
+ const IS_LAST_HARDLINK = fs::kFSEventStreamEventFlagItemIsLastHardlink;
+ const ITEM_CLONED = fs::kFSEventStreamEventFlagItemCloned;
+ }
+}
+
+/// FSEvents-based `Watcher` implementation
+pub struct FsEventWatcher {
+ paths: cf::CFMutableArrayRef,
+ since_when: fs::FSEventStreamEventId,
+ latency: cf::CFTimeInterval,
+ flags: fs::FSEventStreamCreateFlags,
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ runloop: Option<(cf::CFRunLoopRef, thread::JoinHandle<()>)>,
+ recursive_info: HashMap<PathBuf, bool>,
+}
+
+impl fmt::Debug for FsEventWatcher {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("FsEventWatcher")
+ .field("paths", &self.paths)
+ .field("since_when", &self.since_when)
+ .field("latency", &self.latency)
+ .field("flags", &self.flags)
+ .field("event_handler", &Arc::as_ptr(&self.event_handler))
+ .field("runloop", &self.runloop)
+ .field("recursive_info", &self.recursive_info)
+ .finish()
+ }
+}
+
+// CFMutableArrayRef is a type alias to *mut libc::c_void, so FsEventWatcher is not Send/Sync
+// automatically. It's Send because the pointer is not used in other threads.
+unsafe impl Send for FsEventWatcher {}
+
+// It's Sync because all methods that change the mutable state use `&mut self`.
+unsafe impl Sync for FsEventWatcher {}
+
+fn translate_flags(flags: StreamFlags, precise: bool) -> Vec<Event> {
+ let mut evs = Vec::new();
+
+ // «Denotes a sentinel event sent to mark the end of the "historical" events
+ // sent as a result of specifying a `sinceWhen` value in the FSEvents.Create
+ // call that created this event stream. After invoking the client's callback
+ // with all the "historical" events that occurred before now, the client's
+ // callback will be invoked with an event where the HistoryDone flag is set.
+ // The client should ignore the path supplied in this callback.»
+ // — https://www.mbsplugins.eu/FSEventsNextEvent.shtml
+ //
+ // As a result, we just stop processing here and return an empty vec, which
+ // will ignore this completely and not emit any Events whatsoever.
+ if flags.contains(StreamFlags::HISTORY_DONE) {
+ return evs;
+ }
+
+ // FSEvents provides two possible hints as to why events were dropped,
+ // however documentation on what those mean is scant, so we just pass them
+ // through in the info attr field. The intent is clear enough, and the
+ // additional information is provided if the user wants it.
+ if flags.contains(StreamFlags::MUST_SCAN_SUBDIRS) {
+ let e = Event::new(EventKind::Other).set_flag(Flag::Rescan);
+ evs.push(if flags.contains(StreamFlags::USER_DROPPED) {
+ e.set_info("rescan: user dropped")
+ } else if flags.contains(StreamFlags::KERNEL_DROPPED) {
+ e.set_info("rescan: kernel dropped")
+ } else {
+ e
+ });
+ }
+
+ // In imprecise mode, let's not even bother parsing the kind of the event
+ // except for the above very special events.
+ if !precise {
+ evs.push(Event::new(EventKind::Any));
+ return evs;
+ }
+
+ // This is most likely a rename or a removal. We assume rename but may want
+ // to figure out if it was a removal some way later (TODO). To denote the
+ // special nature of the event, we add an info string.
+ if flags.contains(StreamFlags::ROOT_CHANGED) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::From)))
+ .set_info("root changed"),
+ );
+ }
+
+ // A path was mounted at the event path; we treat that as a create.
+ if flags.contains(StreamFlags::MOUNT) {
+ evs.push(Event::new(EventKind::Create(CreateKind::Other)).set_info("mount"));
+ }
+
+ // A path was unmounted at the event path; we treat that as a remove.
+ if flags.contains(StreamFlags::UNMOUNT) {
+ evs.push(Event::new(EventKind::Remove(RemoveKind::Other)).set_info("mount"));
+ }
+
+ if flags.contains(StreamFlags::ITEM_CREATED) {
+ evs.push(if flags.contains(StreamFlags::IS_DIR) {
+ Event::new(EventKind::Create(CreateKind::Folder))
+ } else if flags.contains(StreamFlags::IS_FILE) {
+ Event::new(EventKind::Create(CreateKind::File))
+ } else {
+ let e = Event::new(EventKind::Create(CreateKind::Other));
+ if flags.contains(StreamFlags::IS_SYMLINK) {
+ e.set_info("is: symlink")
+ } else if flags.contains(StreamFlags::IS_HARDLINK) {
+ e.set_info("is: hardlink")
+ } else if flags.contains(StreamFlags::ITEM_CLONED) {
+ e.set_info("is: clone")
+ } else {
+ Event::new(EventKind::Create(CreateKind::Any))
+ }
+ });
+ }
+
+ if flags.contains(StreamFlags::ITEM_REMOVED) {
+ evs.push(if flags.contains(StreamFlags::IS_DIR) {
+ Event::new(EventKind::Remove(RemoveKind::Folder))
+ } else if flags.contains(StreamFlags::IS_FILE) {
+ Event::new(EventKind::Remove(RemoveKind::File))
+ } else {
+ let e = Event::new(EventKind::Remove(RemoveKind::Other));
+ if flags.contains(StreamFlags::IS_SYMLINK) {
+ e.set_info("is: symlink")
+ } else if flags.contains(StreamFlags::IS_HARDLINK) {
+ e.set_info("is: hardlink")
+ } else if flags.contains(StreamFlags::ITEM_CLONED) {
+ e.set_info("is: clone")
+ } else {
+ Event::new(EventKind::Remove(RemoveKind::Any))
+ }
+ });
+ }
+
+ // FSEvents provides no mechanism to associate the old and new sides of a
+ // rename event.
+ if flags.contains(StreamFlags::ITEM_RENAMED) {
+ evs.push(Event::new(EventKind::Modify(ModifyKind::Name(
+ RenameMode::Any,
+ ))));
+ }
+
+ // This is only described as "metadata changed", but it may be that it's
+ // only emitted for some more precise subset of events... if so, will need
+ // amending, but for now we have an Any-shaped bucket to put it in.
+ if flags.contains(StreamFlags::INODE_META_MOD) {
+ evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata(
+ MetadataKind::Any,
+ ))));
+ }
+
+ if flags.contains(StreamFlags::FINDER_INFO_MOD) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other)))
+ .set_info("meta: finder info"),
+ );
+ }
+
+ if flags.contains(StreamFlags::ITEM_CHANGE_OWNER) {
+ evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata(
+ MetadataKind::Ownership,
+ ))));
+ }
+
+ if flags.contains(StreamFlags::ITEM_XATTR_MOD) {
+ evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata(
+ MetadataKind::Extended,
+ ))));
+ }
+
+ // This is specifically described as a data change, which we take to mean
+ // is a content change.
+ if flags.contains(StreamFlags::ITEM_MODIFIED) {
+ evs.push(Event::new(EventKind::Modify(ModifyKind::Data(
+ DataChange::Content,
+ ))));
+ }
+
+ if flags.contains(StreamFlags::OWN_EVENT) {
+ for ev in &mut evs {
+ *ev = std::mem::take(ev).set_process_id(std::process::id());
+ }
+ }
+
+ evs
+}
+
+struct StreamContextInfo {
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ recursive_info: HashMap<PathBuf, bool>,
+}
+
+// Free the context when the stream created by `FSEventStreamCreate` is released.
+extern "C" fn release_context(info: *const libc::c_void) {
+ // Safety:
+ // - The [documentation] for `FSEventStreamContext` states that `release` is only
+ // called when the stream is deallocated, so it is safe to convert `info` back into a
+ // box and drop it.
+ //
+ // [docs]: https://developer.apple.com/documentation/coreservices/fseventstreamcontext?language=objc
+ unsafe {
+ drop(Box::from_raw(
+ info as *const StreamContextInfo as *mut StreamContextInfo,
+ ));
+ }
+}
+
+extern "C" {
+ /// Indicates whether the run loop is waiting for an event.
+ fn CFRunLoopIsWaiting(runloop: cf::CFRunLoopRef) -> cf::Boolean;
+}
+
+struct FsEventPathsMut<'a>(&'a mut FsEventWatcher);
+impl<'a> FsEventPathsMut<'a> {
+ fn new(watcher: &'a mut FsEventWatcher) -> Self {
+ watcher.stop();
+ Self(watcher)
+ }
+}
+impl PathsMut for FsEventPathsMut<'_> {
+ fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.0.append_path(path, recursive_mode)
+ }
+
+ fn remove(&mut self, path: &Path) -> Result<()> {
+ self.0.remove_path(path)
+ }
+
+ fn commit(self: Box<Self>) -> Result<()> {
+ // ignore return error: may be empty path list
+ let _ = self.0.run();
+ Ok(())
+ }
+}
+
+impl FsEventWatcher {
+ fn from_event_handler(event_handler: Arc<Mutex<dyn EventHandler>>) -> Result<Self> {
+ Ok(FsEventWatcher {
+ paths: unsafe {
+ cf::CFArrayCreateMutable(cf::kCFAllocatorDefault, 0, &cf::kCFTypeArrayCallBacks)
+ },
+ since_when: fs::kFSEventStreamEventIdSinceNow,
+ latency: 0.0,
+ flags: fs::kFSEventStreamCreateFlagFileEvents | fs::kFSEventStreamCreateFlagNoDefer,
+ event_handler,
+ runloop: None,
+ recursive_info: HashMap::new(),
+ })
+ }
+
+ fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.stop();
+ let result = self.append_path(path, recursive_mode);
+ // ignore return error: may be empty path list
+ let _ = self.run();
+ result
+ }
+
+ fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
+ self.stop();
+ let result = self.remove_path(path);
+ // ignore return error: may be empty path list
+ let _ = self.run();
+ result
+ }
+
+ #[inline]
+ fn is_running(&self) -> bool {
+ self.runloop.is_some()
+ }
+
+ fn stop(&mut self) {
+ if !self.is_running() {
+ return;
+ }
+
+ if let Some((runloop, thread_handle)) = self.runloop.take() {
+ unsafe {
+ let runloop = runloop as *mut raw::c_void;
+
+ while CFRunLoopIsWaiting(runloop) == 0 {
+ thread::yield_now();
+ }
+
+ cf::CFRunLoopStop(runloop);
+ }
+
+ // Wait for the thread to shut down.
+ thread_handle.join().expect("thread to shut down");
+ }
+ }
+
+ fn remove_path(&mut self, path: &Path) -> Result<()> {
+ let str_path = path.to_str().unwrap();
+ unsafe {
+ let mut err: cf::CFErrorRef = ptr::null_mut();
+ let cf_path = cf::str_path_to_cfstring_ref(str_path, &mut err);
+ if cf_path.is_null() {
+ cf::CFRelease(err as cf::CFRef);
+ return Err(Error::watch_not_found().add_path(path.into()));
+ }
+
+ let mut to_remove = Vec::new();
+ for idx in 0..cf::CFArrayGetCount(self.paths) {
+ let item = cf::CFArrayGetValueAtIndex(self.paths, idx);
+ if cf::CFStringCompare(item, cf_path, cf::kCFCompareCaseInsensitive)
+ == cf::kCFCompareEqualTo
+ {
+ to_remove.push(idx);
+ }
+ }
+
+ cf::CFRelease(cf_path);
+
+ for idx in to_remove.iter().rev() {
+ cf::CFArrayRemoveValueAtIndex(self.paths, *idx);
+ }
+ }
+ let p = if let Ok(canonicalized_path) = path.canonicalize() {
+ canonicalized_path
+ } else {
+ path.to_owned()
+ };
+ match self.recursive_info.remove(&p) {
+ Some(_) => Ok(()),
+ None => Err(Error::watch_not_found()),
+ }
+ }
+
+ // https://github.com/thibaudgg/rb-fsevent/blob/master/ext/fsevent_watch/main.c
+ fn append_path(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ if !path.exists() {
+ return Err(Error::path_not_found().add_path(path.into()));
+ }
+ let canonical_path = path.to_path_buf().canonicalize()?;
+ let str_path = path.to_str().unwrap();
+ unsafe {
+ let mut err: cf::CFErrorRef = ptr::null_mut();
+ let cf_path = cf::str_path_to_cfstring_ref(str_path, &mut err);
+ if cf_path.is_null() {
+ // Most likely the directory was deleted, or permissions changed,
+ // while the above code was running.
+ cf::CFRelease(err as cf::CFRef);
+ return Err(Error::path_not_found().add_path(path.into()));
+ }
+ cf::CFArrayAppendValue(self.paths, cf_path);
+ cf::CFRelease(cf_path);
+ }
+ self.recursive_info
+ .insert(canonical_path, recursive_mode.is_recursive());
+ Ok(())
+ }
+
+ fn run(&mut self) -> Result<()> {
+ if unsafe { cf::CFArrayGetCount(self.paths) } == 0 {
+ // TODO: Reconstruct and add paths to error
+ return Err(Error::path_not_found());
+ }
+
+ // We need to associate the stream context with our callback in order to propagate events
+ // to the rest of the system. This will be owned by the stream, and will be freed when the
+ // stream is closed. This means we will leak the context if we panic before reaching
+ // `FSEventStreamRelease`.
+ let context = Box::into_raw(Box::new(StreamContextInfo {
+ event_handler: self.event_handler.clone(),
+ recursive_info: self.recursive_info.clone(),
+ }));
+
+ let stream_context = fs::FSEventStreamContext {
+ version: 0,
+ info: context as *mut libc::c_void,
+ retain: None,
+ release: Some(release_context),
+ copy_description: None,
+ };
+
+ let stream = unsafe {
+ fs::FSEventStreamCreate(
+ cf::kCFAllocatorDefault,
+ callback,
+ &stream_context,
+ self.paths,
+ self.since_when,
+ self.latency,
+ self.flags,
+ )
+ };
+
+ // Wrapper to help send CFRef types across threads.
+ struct CFSendWrapper(cf::CFRef);
+
+ // Safety:
+ // - According to the Apple documentation, it's safe to move `CFRef`s across threads.
+ // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
+ unsafe impl Send for CFSendWrapper {}
+
+ // move into thread
+ let stream = CFSendWrapper(stream);
+
+ // channel to pass runloop around
+ let (rl_tx, rl_rx) = unbounded();
+
+ let thread_handle = thread::Builder::new()
+ .name("notify-rs fsevents loop".to_string())
+ .spawn(move || {
+ let _ = &stream;
+ let stream = stream.0;
+
+ unsafe {
+ let cur_runloop = cf::CFRunLoopGetCurrent();
+
+ fs::FSEventStreamScheduleWithRunLoop(
+ stream,
+ cur_runloop,
+ cf::kCFRunLoopDefaultMode,
+ );
+ fs::FSEventStreamStart(stream);
+
+ // the calling to CFRunLoopRun will be terminated by CFRunLoopStop call in drop()
+ rl_tx
+ .send(CFSendWrapper(cur_runloop))
+ .expect("Unable to send runloop to watcher");
+
+ cf::CFRunLoopRun();
+ fs::FSEventStreamStop(stream);
+ // There are edge-cases, when many events are pending,
+ // despite the stream being stopped, that the stream's
+ // associated callback will be invoked. Purging events
+ // is intended to prevent this.
+ let event_id = fs::FSEventsGetCurrentEventId();
+ let device = fs::FSEventStreamGetDeviceBeingWatched(stream);
+ fs::FSEventsPurgeEventsForDeviceUpToEventId(device, event_id);
+ fs::FSEventStreamInvalidate(stream);
+ fs::FSEventStreamRelease(stream);
+ }
+ })?;
+ // block until runloop has been sent
+ self.runloop = Some((rl_rx.recv().unwrap().0, thread_handle));
+
+ Ok(())
+ }
+
+ fn configure_raw_mode(&mut self, _config: Config, tx: Sender<Result<bool>>) {
+ tx.send(Ok(false))
+ .expect("configuration channel disconnect");
+ }
+}
+
+extern "C" fn callback(
+ stream_ref: fs::FSEventStreamRef,
+ info: *mut libc::c_void,
+ num_events: libc::size_t, // size_t numEvents
+ event_paths: *mut libc::c_void, // void *eventPaths
+ event_flags: *const fs::FSEventStreamEventFlags, // const FSEventStreamEventFlags eventFlags[]
+ event_ids: *const fs::FSEventStreamEventId, // const FSEventStreamEventId eventIds[]
+) {
+ unsafe {
+ callback_impl(
+ stream_ref,
+ info,
+ num_events,
+ event_paths,
+ event_flags,
+ event_ids,
+ )
+ }
+}
+
+unsafe fn callback_impl(
+ _stream_ref: fs::FSEventStreamRef,
+ info: *mut libc::c_void,
+ num_events: libc::size_t, // size_t numEvents
+ event_paths: *mut libc::c_void, // void *eventPaths
+ event_flags: *const fs::FSEventStreamEventFlags, // const FSEventStreamEventFlags eventFlags[]
+ _event_ids: *const fs::FSEventStreamEventId, // const FSEventStreamEventId eventIds[]
+) {
+ let event_paths = event_paths as *const *const libc::c_char;
+ let info = info as *const StreamContextInfo;
+ let event_handler = &(*info).event_handler;
+
+ for p in 0..num_events {
+ let path = CStr::from_ptr(*event_paths.add(p))
+ .to_str()
+ .expect("Invalid UTF8 string.");
+ let path = PathBuf::from(path);
+
+ let flag = *event_flags.add(p);
+ let flag = StreamFlags::from_bits(flag).unwrap_or_else(|| {
+ panic!("Unable to decode StreamFlags: {}", flag);
+ });
+
+ let mut handle_event = false;
+ for (p, r) in &(*info).recursive_info {
+ if path.starts_with(p) {
+ if *r || &path == p {
+ handle_event = true;
+ break;
+ } else if let Some(parent_path) = path.parent() {
+ if parent_path == p {
+ handle_event = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if !handle_event {
+ continue;
+ }
+
+ log::trace!("FSEvent: path = `{}`, flag = {:?}", path.display(), flag);
+
+ for ev in translate_flags(flag, true).into_iter() {
+ // TODO: precise
+ let ev = ev.add_path(path.clone());
+ let mut event_handler = event_handler.lock().expect("lock not to be poisoned");
+ event_handler.handle_event(Ok(ev));
+ }
+ }
+}
+
+impl Watcher for FsEventWatcher {
+ /// Create a new watcher.
+ fn new<F: EventHandler>(event_handler: F, _config: Config) -> Result<Self> {
+ Self::from_event_handler(Arc::new(Mutex::new(event_handler)))
+ }
+
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.watch_inner(path, recursive_mode)
+ }
+
+ fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
+ Box::new(FsEventPathsMut::new(self))
+ }
+
+ fn unwatch(&mut self, path: &Path) -> Result<()> {
+ self.unwatch_inner(path)
+ }
+
+ fn configure(&mut self, config: Config) -> Result<bool> {
+ let (tx, rx) = unbounded();
+ self.configure_raw_mode(config, tx);
+ rx.recv()?
+ }
+
+ fn kind() -> crate::WatcherKind {
+ crate::WatcherKind::Fsevent
+ }
+}
+
+impl Drop for FsEventWatcher {
+ fn drop(&mut self) {
+ self.stop();
+ unsafe {
+ cf::CFRelease(self.paths);
+ }
+ }
+}
+
+#[test]
+fn test_fsevent_watcher_drop() {
+ use super::*;
+ use std::time::Duration;
+
+ let dir = tempfile::tempdir().unwrap();
+
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ {
+ let mut watcher = FsEventWatcher::new(tx, Default::default()).unwrap();
+ watcher.watch(dir.path(), RecursiveMode::Recursive).unwrap();
+ thread::sleep(Duration::from_millis(2000));
+ println!("is running -> {}", watcher.is_running());
+
+ thread::sleep(Duration::from_millis(1000));
+ watcher.unwatch(dir.path()).unwrap();
+ println!("is running -> {}", watcher.is_running());
+ }
+
+ thread::sleep(Duration::from_millis(1000));
+
+ for res in rx {
+ let e = res.unwrap();
+ println!("debug => {:?} {:?}", e.kind, e.paths);
+ }
+
+ println!("in test: {} works", file!());
+}
+
+#[test]
+fn test_steam_context_info_send_and_sync() {
+ fn check_send<T: Send + Sync>() {}
+ check_send::<StreamContextInfo>();
+}
diff --git a/native/vendor/notify/src/inotify.rs b/native/vendor/notify/src/inotify.rs
new file mode 100644
index 0000000..fd27a39
--- /dev/null
+++ b/native/vendor/notify/src/inotify.rs
@@ -0,0 +1,765 @@
+//! Watcher implementation for the inotify Linux API
+//!
+//! The inotify API provides a mechanism for monitoring filesystem events. Inotify can be used to
+//! monitor individual files, or to monitor directories. When a directory is monitored, inotify
+//! will return events for the directory itself, and for files inside the directory.
+
+use super::event::*;
+use super::{Config, Error, ErrorKind, EventHandler, RecursiveMode, Result, Watcher};
+use crate::{bounded, unbounded, BoundSender, Receiver, Sender};
+use inotify as inotify_sys;
+use inotify_sys::{EventMask, Inotify, WatchDescriptor, WatchMask};
+use std::collections::HashMap;
+use std::env;
+use std::ffi::OsStr;
+use std::fs::metadata;
+use std::os::unix::io::AsRawFd;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::thread;
+use walkdir::WalkDir;
+
+const INOTIFY: mio::Token = mio::Token(0);
+const MESSAGE: mio::Token = mio::Token(1);
+
+// The EventLoop will set up a mio::Poll and use it to wait for the following:
+//
+// - messages telling it what to do
+//
+// - events telling it that something has happened on one of the watched files.
+
+struct EventLoop {
+ running: bool,
+ poll: mio::Poll,
+ event_loop_waker: Arc<mio::Waker>,
+ event_loop_tx: Sender<EventLoopMsg>,
+ event_loop_rx: Receiver<EventLoopMsg>,
+ inotify: Option<Inotify>,
+ event_handler: Box<dyn EventHandler>,
+ /// PathBuf -> (WatchDescriptor, WatchMask, is_recursive, is_dir)
+ watches: HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
+ paths: HashMap<WatchDescriptor, PathBuf>,
+ rename_event: Option<Event>,
+ follow_links: bool,
+}
+
+/// Watcher implementation based on inotify
+#[derive(Debug)]
+pub struct INotifyWatcher {
+ channel: Sender<EventLoopMsg>,
+ waker: Arc<mio::Waker>,
+}
+
+enum EventLoopMsg {
+ AddWatch(PathBuf, RecursiveMode, Sender<Result<()>>),
+ RemoveWatch(PathBuf, Sender<Result<()>>),
+ Shutdown,
+ Configure(Config, BoundSender<Result<bool>>),
+}
+
+#[inline]
+fn add_watch_by_event(
+ path: &PathBuf,
+ event: &inotify_sys::Event<&OsStr>,
+ watches: &HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
+ add_watches: &mut Vec<PathBuf>,
+) {
+ if event.mask.contains(EventMask::ISDIR) {
+ if let Some(parent_path) = path.parent() {
+ if let Some(&(_, _, is_recursive, _)) = watches.get(parent_path) {
+ if is_recursive {
+ add_watches.push(path.to_owned());
+ }
+ }
+ }
+ }
+}
+
+#[inline]
+fn remove_watch_by_event(
+ path: &PathBuf,
+ watches: &HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
+ remove_watches: &mut Vec<PathBuf>,
+) {
+ if watches.contains_key(path) {
+ remove_watches.push(path.to_owned());
+ }
+}
+
+impl EventLoop {
+ pub fn new(
+ inotify: Inotify,
+ event_handler: Box<dyn EventHandler>,
+ follow_links: bool,
+ ) -> Result<Self> {
+ let (event_loop_tx, event_loop_rx) = unbounded::<EventLoopMsg>();
+ let poll = mio::Poll::new()?;
+
+ let event_loop_waker = Arc::new(mio::Waker::new(poll.registry(), MESSAGE)?);
+
+ let inotify_fd = inotify.as_raw_fd();
+ let mut evented_inotify = mio::unix::SourceFd(&inotify_fd);
+ poll.registry()
+ .register(&mut evented_inotify, INOTIFY, mio::Interest::READABLE)?;
+
+ let event_loop = EventLoop {
+ running: true,
+ poll,
+ event_loop_waker,
+ event_loop_tx,
+ event_loop_rx,
+ inotify: Some(inotify),
+ event_handler,
+ watches: HashMap::new(),
+ paths: HashMap::new(),
+ rename_event: None,
+ follow_links,
+ };
+ Ok(event_loop)
+ }
+
+ // Run the event loop.
+ pub fn run(self) {
+ let _ = thread::Builder::new()
+ .name("notify-rs inotify loop".to_string())
+ .spawn(|| self.event_loop_thread());
+ }
+
+ fn event_loop_thread(mut self) {
+ let mut events = mio::Events::with_capacity(16);
+ loop {
+ // Wait for something to happen.
+ match self.poll.poll(&mut events, None) {
+ Err(ref e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
+ // System call was interrupted, we will retry
+ // TODO: Not covered by tests (to reproduce likely need to setup signal handlers)
+ }
+ Err(e) => panic!("poll failed: {}", e),
+ Ok(()) => {}
+ }
+
+ // Process whatever happened.
+ for event in &events {
+ self.handle_event(event);
+ }
+
+ // Stop, if we're done.
+ if !self.running {
+ break;
+ }
+ }
+ }
+
+ // Handle a single event.
+ fn handle_event(&mut self, event: &mio::event::Event) {
+ match event.token() {
+ MESSAGE => {
+ // The channel is readable - handle messages.
+ self.handle_messages()
+ }
+ INOTIFY => {
+ // inotify has something to tell us.
+ self.handle_inotify()
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ fn handle_messages(&mut self) {
+ while let Ok(msg) = self.event_loop_rx.try_recv() {
+ match msg {
+ EventLoopMsg::AddWatch(path, recursive_mode, tx) => {
+ let _ = tx.send(self.add_watch(path, recursive_mode.is_recursive(), true));
+ }
+ EventLoopMsg::RemoveWatch(path, tx) => {
+ let _ = tx.send(self.remove_watch(path, false));
+ }
+ EventLoopMsg::Shutdown => {
+ let _ = self.remove_all_watches();
+ if let Some(inotify) = self.inotify.take() {
+ let _ = inotify.close();
+ }
+ self.running = false;
+ break;
+ }
+ EventLoopMsg::Configure(config, tx) => {
+ self.configure_raw_mode(config, tx);
+ }
+ }
+ }
+ }
+
+ fn configure_raw_mode(&mut self, _config: Config, tx: BoundSender<Result<bool>>) {
+ tx.send(Ok(false))
+ .expect("configuration channel disconnected");
+ }
+
+ fn handle_inotify(&mut self) {
+ let mut add_watches = Vec::new();
+ let mut remove_watches = Vec::new();
+
+ if let Some(ref mut inotify) = self.inotify {
+ let mut buffer = [0; 1024];
+ // Read all buffers available.
+ loop {
+ match inotify.read_events(&mut buffer) {
+ Ok(events) => {
+ let mut num_events = 0;
+ for event in events {
+ log::trace!("inotify event: {event:?}");
+
+ num_events += 1;
+ if event.mask.contains(EventMask::Q_OVERFLOW) {
+ let ev = Ok(Event::new(EventKind::Other).set_flag(Flag::Rescan));
+ self.event_handler.handle_event(ev);
+ }
+
+ let path = match event.name {
+ Some(name) => self.paths.get(&event.wd).map(|root| root.join(name)),
+ None => self.paths.get(&event.wd).cloned(),
+ };
+
+ let path = match path {
+ Some(path) => path,
+ None => {
+ log::debug!("inotify event with unknown descriptor: {event:?}");
+ continue;
+ }
+ };
+
+ let mut evs = Vec::new();
+
+ if event.mask.contains(EventMask::MOVED_FROM) {
+ remove_watch_by_event(&path, &self.watches, &mut remove_watches);
+
+ let event = Event::new(EventKind::Modify(ModifyKind::Name(
+ RenameMode::From,
+ )))
+ .add_path(path.clone())
+ .set_tracker(event.cookie as usize);
+
+ self.rename_event = Some(event.clone());
+
+ evs.push(event);
+ } else if event.mask.contains(EventMask::MOVED_TO) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::To)))
+ .set_tracker(event.cookie as usize)
+ .add_path(path.clone()),
+ );
+
+ let trackers_match =
+ self.rename_event.as_ref().and_then(|e| e.tracker())
+ == Some(event.cookie as usize);
+
+ if trackers_match {
+ let rename_event = self.rename_event.take().unwrap(); // unwrap is safe because `rename_event` must be set at this point
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Name(
+ RenameMode::Both,
+ )))
+ .set_tracker(event.cookie as usize)
+ .add_some_path(rename_event.paths.first().cloned())
+ .add_path(path.clone()),
+ );
+ }
+ add_watch_by_event(&path, &event, &self.watches, &mut add_watches);
+ }
+ if event.mask.contains(EventMask::MOVE_SELF) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Name(
+ RenameMode::From,
+ )))
+ .add_path(path.clone()),
+ );
+ // TODO stat the path and get to new path
+ // - emit To and Both events
+ // - change prefix for further events
+ }
+ if event.mask.contains(EventMask::CREATE) {
+ evs.push(
+ Event::new(EventKind::Create(
+ if event.mask.contains(EventMask::ISDIR) {
+ CreateKind::Folder
+ } else {
+ CreateKind::File
+ },
+ ))
+ .add_path(path.clone()),
+ );
+ add_watch_by_event(&path, &event, &self.watches, &mut add_watches);
+ }
+ if event.mask.contains(EventMask::DELETE) {
+ evs.push(
+ Event::new(EventKind::Remove(
+ if event.mask.contains(EventMask::ISDIR) {
+ RemoveKind::Folder
+ } else {
+ RemoveKind::File
+ },
+ ))
+ .add_path(path.clone()),
+ );
+ remove_watch_by_event(&path, &self.watches, &mut remove_watches);
+ }
+ if event.mask.contains(EventMask::DELETE_SELF) {
+ let remove_kind = match self.watches.get(&path) {
+ Some(&(_, _, _, true)) => RemoveKind::Folder,
+ Some(&(_, _, _, false)) => RemoveKind::File,
+ None => RemoveKind::Other,
+ };
+ evs.push(
+ Event::new(EventKind::Remove(remove_kind))
+ .add_path(path.clone()),
+ );
+ remove_watch_by_event(&path, &self.watches, &mut remove_watches);
+ }
+ if event.mask.contains(EventMask::MODIFY) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Data(
+ DataChange::Any,
+ )))
+ .add_path(path.clone()),
+ );
+ }
+ if event.mask.contains(EventMask::CLOSE_WRITE) {
+ evs.push(
+ Event::new(EventKind::Access(AccessKind::Close(
+ AccessMode::Write,
+ )))
+ .add_path(path.clone()),
+ );
+ }
+ if event.mask.contains(EventMask::CLOSE_NOWRITE) {
+ evs.push(
+ Event::new(EventKind::Access(AccessKind::Close(
+ AccessMode::Read,
+ )))
+ .add_path(path.clone()),
+ );
+ }
+ if event.mask.contains(EventMask::ATTRIB) {
+ evs.push(
+ Event::new(EventKind::Modify(ModifyKind::Metadata(
+ MetadataKind::Any,
+ )))
+ .add_path(path.clone()),
+ );
+ }
+ if event.mask.contains(EventMask::OPEN) {
+ evs.push(
+ Event::new(EventKind::Access(AccessKind::Open(
+ AccessMode::Any,
+ )))
+ .add_path(path.clone()),
+ );
+ }
+
+ for ev in evs {
+ self.event_handler.handle_event(Ok(ev));
+ }
+ }
+
+ // All events read. Break out.
+ if num_events == 0 {
+ break;
+ }
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+ // No events read. Break out.
+ break;
+ }
+ Err(e) => {
+ self.event_handler.handle_event(Err(Error::io(e)));
+ }
+ }
+ }
+ }
+
+ for path in remove_watches {
+ self.remove_watch(path, true).ok();
+ }
+
+ for path in add_watches {
+ if let Err(add_watch_error) = self.add_watch(path, true, false) {
+ // The handler should be notified if we have reached the limit.
+ // Otherwise, the user might expect that a recursive watch
+ // is continuing to work correctly, but it's not.
+ if let ErrorKind::MaxFilesWatch = add_watch_error.kind {
+ self.event_handler.handle_event(Err(add_watch_error));
+
+ // After that kind of a error we should stop adding watches,
+ // because the limit has already reached and all next calls
+ // will return us only the same error.
+ break;
+ }
+ }
+ }
+ }
+
+ fn add_watch(&mut self, path: PathBuf, is_recursive: bool, mut watch_self: bool) -> Result<()> {
+ // If the watch is not recursive, or if we determine (by stat'ing the path to get its
+ // metadata) that the watched path is not a directory, add a single path watch.
+ if !is_recursive || !metadata(&path).map_err(Error::io_watch)?.is_dir() {
+ return self.add_single_watch(path, false, true);
+ }
+
+ for entry in WalkDir::new(path)
+ .follow_links(self.follow_links)
+ .into_iter()
+ .filter_map(filter_dir)
+ {
+ self.add_single_watch(entry.into_path(), is_recursive, watch_self)?;
+ watch_self = false;
+ }
+
+ Ok(())
+ }
+
+ fn add_single_watch(
+ &mut self,
+ path: PathBuf,
+ is_recursive: bool,
+ watch_self: bool,
+ ) -> Result<()> {
+ let mut watchmask = WatchMask::ATTRIB
+ | WatchMask::CREATE
+ | WatchMask::OPEN
+ | WatchMask::DELETE
+ | WatchMask::CLOSE_WRITE
+ | WatchMask::MODIFY
+ | WatchMask::MOVED_FROM
+ | WatchMask::MOVED_TO;
+
+ if watch_self {
+ watchmask.insert(WatchMask::DELETE_SELF);
+ watchmask.insert(WatchMask::MOVE_SELF);
+ }
+
+ if let Some(&(_, old_watchmask, _, _)) = self.watches.get(&path) {
+ watchmask.insert(old_watchmask);
+ watchmask.insert(WatchMask::MASK_ADD);
+ }
+
+ if let Some(ref mut inotify) = self.inotify {
+ log::trace!("adding inotify watch: {}", path.display());
+
+ match inotify.watches().add(&path, watchmask) {
+ Err(e) => {
+ Err(if e.raw_os_error() == Some(libc::ENOSPC) {
+ // do not report inotify limits as "no more space" on linux #266
+ Error::new(ErrorKind::MaxFilesWatch)
+ } else if e.kind() == std::io::ErrorKind::NotFound {
+ Error::new(ErrorKind::PathNotFound)
+ } else {
+ Error::io(e)
+ }
+ .add_path(path))
+ }
+ Ok(w) => {
+ watchmask.remove(WatchMask::MASK_ADD);
+ let is_dir = metadata(&path).map_err(Error::io)?.is_dir();
+ self.watches
+ .insert(path.clone(), (w.clone(), watchmask, is_recursive, is_dir));
+ self.paths.insert(w, path);
+ Ok(())
+ }
+ }
+ } else {
+ Ok(())
+ }
+ }
+
+ fn remove_watch(&mut self, path: PathBuf, remove_recursive: bool) -> Result<()> {
+ match self.watches.remove(&path) {
+ None => return Err(Error::watch_not_found().add_path(path)),
+ Some((w, _, is_recursive, _)) => {
+ if let Some(ref mut inotify) = self.inotify {
+ let mut inotify_watches = inotify.watches();
+ log::trace!("removing inotify watch: {}", path.display());
+
+ inotify_watches
+ .remove(w.clone())
+ .map_err(|e| Error::io(e).add_path(path.clone()))?;
+ self.paths.remove(&w);
+
+ if is_recursive || remove_recursive {
+ let mut remove_list = Vec::new();
+ for (w, p) in &self.paths {
+ if p.starts_with(&path) {
+ inotify_watches
+ .remove(w.clone())
+ .map_err(|e| Error::io(e).add_path(p.into()))?;
+ self.watches.remove(p);
+ remove_list.push(w.clone());
+ }
+ }
+ for w in remove_list {
+ self.paths.remove(&w);
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn remove_all_watches(&mut self) -> Result<()> {
+ if let Some(ref mut inotify) = self.inotify {
+ let mut inotify_watches = inotify.watches();
+ for (w, p) in &self.paths {
+ inotify_watches
+ .remove(w.clone())
+ .map_err(|e| Error::io(e).add_path(p.into()))?;
+ }
+ self.watches.clear();
+ self.paths.clear();
+ }
+ Ok(())
+ }
+}
+
+/// return `DirEntry` when it is a directory
+fn filter_dir(e: walkdir::Result<walkdir::DirEntry>) -> Option<walkdir::DirEntry> {
+ if let Ok(e) = e {
+ if let Ok(metadata) = e.metadata() {
+ if metadata.is_dir() {
+ return Some(e);
+ }
+ }
+ }
+ None
+}
+
+impl INotifyWatcher {
+ fn from_event_handler(
+ event_handler: Box<dyn EventHandler>,
+ follow_links: bool,
+ ) -> Result<Self> {
+ let inotify = Inotify::init()?;
+ let event_loop = EventLoop::new(inotify, event_handler, follow_links)?;
+ let channel = event_loop.event_loop_tx.clone();
+ let waker = event_loop.event_loop_waker.clone();
+ event_loop.run();
+ Ok(INotifyWatcher { channel, waker })
+ }
+
+ fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ let (tx, rx) = unbounded();
+ let msg = EventLoopMsg::AddWatch(pb, recursive_mode, tx);
+
+ // we expect the event loop to live and reply => unwraps must not panic
+ self.channel.send(msg).unwrap();
+ self.waker.wake().unwrap();
+ rx.recv().unwrap()
+ }
+
+ fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ let (tx, rx) = unbounded();
+ let msg = EventLoopMsg::RemoveWatch(pb, tx);
+
+ // we expect the event loop to live and reply => unwraps must not panic
+ self.channel.send(msg).unwrap();
+ self.waker.wake().unwrap();
+ rx.recv().unwrap()
+ }
+}
+
+impl Watcher for INotifyWatcher {
+ /// Create a new watcher.
+ fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
+ Self::from_event_handler(Box::new(event_handler), config.follow_symlinks())
+ }
+
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.watch_inner(path, recursive_mode)
+ }
+
+ fn unwatch(&mut self, path: &Path) -> Result<()> {
+ self.unwatch_inner(path)
+ }
+
+ fn configure(&mut self, config: Config) -> Result<bool> {
+ let (tx, rx) = bounded(1);
+ self.channel.send(EventLoopMsg::Configure(config, tx))?;
+ self.waker.wake()?;
+ rx.recv()?
+ }
+
+ fn kind() -> crate::WatcherKind {
+ crate::WatcherKind::Inotify
+ }
+}
+
+impl Drop for INotifyWatcher {
+ fn drop(&mut self) {
+ // we expect the event loop to live => unwrap must not panic
+ self.channel.send(EventLoopMsg::Shutdown).unwrap();
+ self.waker.wake().unwrap();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ sync::{atomic::AtomicBool, mpsc},
+ thread::available_parallelism,
+ };
+
+ use super::*;
+
+ #[test]
+ fn inotify_watcher_is_send_and_sync() {
+ fn check<T: Send + Sync>() {}
+ check::<INotifyWatcher>();
+ }
+
+ #[test]
+ fn native_error_type_on_missing_path() {
+ let mut watcher = INotifyWatcher::new(|_| {}, Config::default()).unwrap();
+
+ let result = watcher.watch(
+ &PathBuf::from("/some/non/existant/path"),
+ RecursiveMode::NonRecursive,
+ );
+
+ assert!(matches!(
+ result,
+ Err(Error {
+ paths: _,
+ kind: ErrorKind::PathNotFound
+ })
+ ))
+ }
+
+ /// Runs manually.
+ ///
+ /// * Save actual value of the limit: `MAX_USER_WATCHES=$(sysctl -n fs.inotify.max_user_watches)`
+ /// * Run the test.
+ /// * Set the limit to 0: `sudo sysctl fs.inotify.max_user_watches=0` while test is running
+ /// * Wait for the test to complete
+ /// * Restore the limit `sudo sysctl fs.inotify.max_user_watches=$MAX_USER_WATCHES`
+ #[test]
+ #[ignore = "requires changing sysctl fs.inotify.max_user_watches while test is running"]
+ fn recursive_watch_calls_handler_if_creating_a_file_raises_max_files_watch() {
+ use std::time::Duration;
+
+ let tmpdir = tempfile::tempdir().unwrap();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let (proc_changed_tx, proc_changed_rx) = std::sync::mpsc::channel();
+ let proc_path = Path::new("/proc/sys/fs/inotify/max_user_watches");
+ let mut watcher = INotifyWatcher::new(
+ move |result: Result<Event>| match result {
+ Ok(event) => {
+ if event.paths.first().is_some_and(|path| path == proc_path) {
+ proc_changed_tx.send(()).unwrap();
+ }
+ }
+ Err(e) => tx.send(e).unwrap(),
+ },
+ Config::default(),
+ )
+ .unwrap();
+
+ watcher
+ .watch(tmpdir.path(), RecursiveMode::Recursive)
+ .unwrap();
+ watcher
+ .watch(proc_path, RecursiveMode::NonRecursive)
+ .unwrap();
+
+ // give the time to set the limit
+ proc_changed_rx
+ .recv_timeout(Duration::from_secs(30))
+ .unwrap();
+
+ let child_dir = tmpdir.path().join("child");
+ std::fs::create_dir(child_dir).unwrap();
+
+ let result = rx.recv_timeout(Duration::from_millis(500));
+
+ assert!(
+ matches!(
+ &result,
+ Ok(Error {
+ kind: ErrorKind::MaxFilesWatch,
+ paths: _,
+ })
+ ),
+ "expected {:?}, found: {:#?}",
+ ErrorKind::MaxFilesWatch,
+ result
+ );
+ }
+
+ /// https://github.com/notify-rs/notify/issues/678
+ #[test]
+ fn race_condition_on_unwatch_and_pending_events_with_deleted_descriptor() {
+ let tmpdir = tempfile::tempdir().expect("tmpdir");
+ let (tx, rx) = mpsc::channel();
+ let mut inotify = INotifyWatcher::new(
+ move |e: Result<Event>| {
+ let e = match e {
+ Ok(e) if e.paths.is_empty() => e,
+ Ok(_) | Err(_) => return,
+ };
+ let _ = tx.send(e);
+ },
+ Config::default(),
+ )
+ .expect("inotify creation");
+
+ let dir_path = tmpdir.path();
+ let file_path = dir_path.join("foo");
+ std::fs::File::create(&file_path).unwrap();
+
+ let stop = Arc::new(AtomicBool::new(false));
+
+ let handles: Vec<_> = (0..available_parallelism().unwrap().get().max(4))
+ .map(|_| {
+ let file_path = file_path.clone();
+ let stop = stop.clone();
+ thread::spawn(move || {
+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {
+ let _ = std::fs::File::open(&file_path).unwrap();
+ }
+ })
+ })
+ .collect();
+
+ let non_recursive = RecursiveMode::NonRecursive;
+ for _ in 0..(handles.len() * 4) {
+ inotify.watch(dir_path, non_recursive).unwrap();
+ inotify.unwatch(dir_path).unwrap();
+ }
+
+ stop.store(true, std::sync::atomic::Ordering::Relaxed);
+ handles
+ .into_iter()
+ .for_each(|handle| handle.join().ok().unwrap_or_default());
+
+ drop(inotify);
+
+ let events: Vec<_> = rx.into_iter().map(|e| format!("{e:?}")).collect();
+
+ const LOG_LEN: usize = 10;
+ let events_len = events.len();
+ assert!(
+ events.is_empty(),
+ "expected no events without path, but got {events_len}. first 10: {:#?}",
+ &events[..LOG_LEN.min(events_len)]
+ );
+ }
+}
diff --git a/native/vendor/notify/src/kqueue.rs b/native/vendor/notify/src/kqueue.rs
new file mode 100644
index 0000000..0f814b7
--- /dev/null
+++ b/native/vendor/notify/src/kqueue.rs
@@ -0,0 +1,481 @@
+//! Watcher implementation for the kqueue API
+//!
+//! The kqueue() system call provides a generic method of notifying the user
+//! when an event happens or a condition holds, based on the results of small
+//! pieces of kernel code termed filters.
+
+use super::event::*;
+use super::{Config, Error, EventHandler, RecursiveMode, Result, Watcher};
+use crate::{unbounded, Receiver, Sender};
+use kqueue::{EventData, EventFilter, FilterFlag, Ident};
+use std::collections::HashMap;
+use std::env;
+use std::fs::metadata;
+use std::os::unix::io::AsRawFd;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::thread;
+use walkdir::WalkDir;
+
+const KQUEUE: mio::Token = mio::Token(0);
+const MESSAGE: mio::Token = mio::Token(1);
+
+// The EventLoop will set up a mio::Poll and use it to wait for the following:
+//
+// - messages telling it what to do
+//
+// - events telling it that something has happened on one of the watched files.
+struct EventLoop {
+ running: bool,
+ poll: mio::Poll,
+ event_loop_waker: Arc<mio::Waker>,
+ event_loop_tx: Sender<EventLoopMsg>,
+ event_loop_rx: Receiver<EventLoopMsg>,
+ kqueue: kqueue::Watcher,
+ event_handler: Box<dyn EventHandler>,
+ watches: HashMap<PathBuf, bool>,
+ follow_symlinks: bool,
+}
+
+/// Watcher implementation based on inotify
+#[derive(Debug)]
+pub struct KqueueWatcher {
+ channel: Sender<EventLoopMsg>,
+ waker: Arc<mio::Waker>,
+}
+
+enum EventLoopMsg {
+ AddWatch(PathBuf, RecursiveMode, Sender<Result<()>>),
+ RemoveWatch(PathBuf, Sender<Result<()>>),
+ Shutdown,
+}
+
+impl EventLoop {
+ pub fn new(
+ kqueue: kqueue::Watcher,
+ event_handler: Box<dyn EventHandler>,
+ follow_symlinks: bool,
+ ) -> Result<Self> {
+ let (event_loop_tx, event_loop_rx) = unbounded::<EventLoopMsg>();
+ let poll = mio::Poll::new()?;
+
+ let event_loop_waker = Arc::new(mio::Waker::new(poll.registry(), MESSAGE)?);
+
+ let kqueue_fd = kqueue.as_raw_fd();
+ let mut evented_kqueue = mio::unix::SourceFd(&kqueue_fd);
+ poll.registry()
+ .register(&mut evented_kqueue, KQUEUE, mio::Interest::READABLE)?;
+
+ let event_loop = EventLoop {
+ running: true,
+ poll,
+ event_loop_waker,
+ event_loop_tx,
+ event_loop_rx,
+ kqueue,
+ event_handler,
+ watches: HashMap::new(),
+ follow_symlinks,
+ };
+ Ok(event_loop)
+ }
+
+ // Run the event loop.
+ pub fn run(self) {
+ let _ = thread::Builder::new()
+ .name("notify-rs kqueue loop".to_string())
+ .spawn(|| self.event_loop_thread());
+ }
+
+ fn event_loop_thread(mut self) {
+ let mut events = mio::Events::with_capacity(16);
+ loop {
+ // Wait for something to happen.
+ match self.poll.poll(&mut events, None) {
+ Err(ref e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
+ // System call was interrupted, we will retry
+ // TODO: Not covered by tests (to reproduce likely need to setup signal handlers)
+ }
+ Err(e) => panic!("poll failed: {}", e),
+ Ok(()) => {}
+ }
+
+ // Process whatever happened.
+ for event in &events {
+ self.handle_event(event);
+ }
+
+ // Stop, if we're done.
+ if !self.running {
+ break;
+ }
+ }
+ }
+
+ // Handle a single event.
+ fn handle_event(&mut self, event: &mio::event::Event) {
+ match event.token() {
+ MESSAGE => {
+ // The channel is readable - handle messages.
+ self.handle_messages()
+ }
+ KQUEUE => {
+ // inotify has something to tell us.
+ self.handle_kqueue()
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ fn handle_messages(&mut self) {
+ while let Ok(msg) = self.event_loop_rx.try_recv() {
+ match msg {
+ EventLoopMsg::AddWatch(path, recursive_mode, tx) => {
+ let _ = tx.send(self.add_watch(path, recursive_mode.is_recursive()));
+ }
+ EventLoopMsg::RemoveWatch(path, tx) => {
+ let _ = tx.send(self.remove_watch(path, false));
+ }
+ EventLoopMsg::Shutdown => {
+ self.running = false;
+ break;
+ }
+ }
+ }
+ }
+
+ fn handle_kqueue(&mut self) {
+ let mut add_watches = Vec::new();
+ let mut remove_watches = Vec::new();
+
+ while let Some(event) = self.kqueue.poll(None) {
+ log::trace!("kqueue event: {event:?}");
+
+ match event {
+ kqueue::Event {
+ data: EventData::Vnode(data),
+ ident: Ident::Filename(_, path),
+ } => {
+ let path = PathBuf::from(path);
+ let event = match data {
+ /*
+ TODO: Differentiate folders and files
+ kqueue doesn't tell us if this was a file or a dir, so we
+ could only emulate this inotify behavior if we keep track of
+ all files and directories internally and then perform a
+ lookup.
+ */
+ kqueue::Vnode::Delete => {
+ remove_watches.push(path.clone());
+ Ok(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path))
+ }
+
+ // a write to a directory means that a new file was created in it, let's
+ // figure out which file this was
+ kqueue::Vnode::Write if path.is_dir() => {
+ // find which file is new in the directory by comparing it with our
+ // list of known watches
+ std::fs::read_dir(&path)
+ .map(|dir| {
+ dir.filter_map(std::result::Result::ok)
+ .map(|f| f.path())
+ .find(|f| !self.watches.contains_key(f))
+ })
+ .map(|file| {
+ if let Some(file) = file {
+ // watch this new file
+ add_watches.push(file.clone());
+
+ Event::new(EventKind::Create(if file.is_dir() {
+ CreateKind::Folder
+ } else if file.is_file() {
+ CreateKind::File
+ } else {
+ CreateKind::Other
+ }))
+ .add_path(file)
+ } else {
+ Event::new(EventKind::Modify(ModifyKind::Data(
+ DataChange::Any,
+ )))
+ .add_path(path)
+ }
+ })
+ .map_err(Into::into)
+ }
+
+ // data was written to this file
+ kqueue::Vnode::Write => Ok(Event::new(EventKind::Modify(
+ ModifyKind::Data(DataChange::Any),
+ ))
+ .add_path(path)),
+
+ /*
+ Extend and Truncate are just different names for the same
+ operation, extend is only used on FreeBSD, truncate everywhere
+ else
+ */
+ kqueue::Vnode::Extend | kqueue::Vnode::Truncate => Ok(Event::new(
+ EventKind::Modify(ModifyKind::Data(DataChange::Size)),
+ )
+ .add_path(path)),
+
+ /*
+ this kevent has the same problem as the delete kevent. The
+ only way i can think of providing "better" event with more
+ information is to do the diff our self, while this maybe do
+ able of delete. In this case it would somewhat expensive to
+ keep track and compare ever peace of metadata for every file
+ */
+ kqueue::Vnode::Attrib => Ok(Event::new(EventKind::Modify(
+ ModifyKind::Metadata(MetadataKind::Any),
+ ))
+ .add_path(path)),
+
+ /*
+ The link count on a file changed => subdirectory created or
+ delete.
+ */
+ kqueue::Vnode::Link => {
+ // As we currently don't have a solution that would allow us
+ // to only add/remove the new/delete directory and that dosn't include a
+ // possible race condition. On possible solution would be to
+ // create a `HashMap<PathBuf, Vec<PathBuf>>` which would
+ // include every directory and this content add the time of
+ // adding it to kqueue. While this should allow us to do the
+ // diff and only add/remove the files necessary. This would
+ // also introduce a race condition, where multiple files could
+ // all ready be remove from the directory, and we could get out
+ // of sync.
+ // So for now, until we find a better solution, let remove and
+ // readd the whole directory.
+ // This is a expensive operation, as we recursive through all
+ // subdirectories.
+ remove_watches.push(path.clone());
+ add_watches.push(path.clone());
+ Ok(Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path))
+ }
+
+ // Kqueue not provide us with the information necessary to provide
+ // the new file name to the event.
+ kqueue::Vnode::Rename => {
+ remove_watches.push(path.clone());
+ Ok(
+ Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Any)))
+ .add_path(path),
+ )
+ }
+
+ // Access to the file was revoked via revoke(2) or the underlying file system was unmounted.
+ kqueue::Vnode::Revoke => {
+ remove_watches.push(path.clone());
+ Ok(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path))
+ }
+
+ // On different BSD variants, different extra events may be present
+ #[allow(unreachable_patterns)]
+ _ => Ok(Event::new(EventKind::Other)),
+ };
+ self.event_handler.handle_event(event);
+ }
+ // as we don't add any other EVFILTER to kqueue we should never get here
+ kqueue::Event { ident: _, data: _ } => unreachable!(),
+ }
+ }
+
+ for path in remove_watches {
+ self.remove_watch(path, true).ok();
+ }
+
+ for path in add_watches {
+ self.add_watch(path, true).ok();
+ }
+ }
+
+ fn add_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<()> {
+ // If the watch is not recursive, or if we determine (by stat'ing the path to get its
+ // metadata) that the watched path is not a directory, add a single path watch.
+ if !is_recursive || !metadata(&path).map_err(Error::io)?.is_dir() {
+ self.add_single_watch(path, false)?;
+ } else {
+ for entry in WalkDir::new(path)
+ .follow_links(self.follow_symlinks)
+ .into_iter()
+ {
+ let entry = entry.map_err(map_walkdir_error)?;
+ self.add_single_watch(entry.into_path(), is_recursive)?;
+ }
+ }
+
+ // Only make a single `kevent` syscall to add all the watches.
+ self.kqueue.watch()?;
+
+ Ok(())
+ }
+
+ /// Adds a single watch to the kqueue.
+ ///
+ /// The caller of this function must call `self.kqueue.watch()` afterwards to register the new watch.
+ fn add_single_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<()> {
+ let event_filter = EventFilter::EVFILT_VNODE;
+ let filter_flags = FilterFlag::NOTE_DELETE
+ | FilterFlag::NOTE_WRITE
+ | FilterFlag::NOTE_EXTEND
+ | FilterFlag::NOTE_ATTRIB
+ | FilterFlag::NOTE_LINK
+ | FilterFlag::NOTE_RENAME
+ | FilterFlag::NOTE_REVOKE;
+
+ log::trace!("adding kqueue watch: {}", path.display());
+
+ self.kqueue
+ .add_filename(&path, event_filter, filter_flags)
+ .map_err(|e| Error::io(e).add_path(path.clone()))?;
+ self.watches.insert(path, is_recursive);
+
+ Ok(())
+ }
+
+ fn remove_watch(&mut self, path: PathBuf, remove_recursive: bool) -> Result<()> {
+ log::trace!("removing kqueue watch: {}", path.display());
+
+ match self.watches.remove(&path) {
+ None => return Err(Error::watch_not_found()),
+ Some(is_recursive) => {
+ if is_recursive || remove_recursive {
+ for entry in WalkDir::new(path)
+ .follow_links(self.follow_symlinks)
+ .into_iter()
+ {
+ let p = entry.map_err(map_walkdir_error)?.into_path();
+ self.kqueue
+ .remove_filename(&p, EventFilter::EVFILT_VNODE)
+ .map_err(|e| Error::io(e).add_path(p))?;
+ }
+ } else {
+ self.kqueue
+ .remove_filename(&path, EventFilter::EVFILT_VNODE)
+ .map_err(|e| Error::io(e).add_path(path.clone()))?;
+ }
+
+ self.kqueue.watch()?;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn map_walkdir_error(e: walkdir::Error) -> Error {
+ if e.io_error().is_some() {
+ // save to unwrap otherwise we whouldn't be in this branch
+ Error::io(e.into_io_error().unwrap())
+ } else {
+ Error::generic(&e.to_string())
+ }
+}
+
+impl KqueueWatcher {
+ fn from_event_handler(
+ event_handler: Box<dyn EventHandler>,
+ follow_symlinks: bool,
+ ) -> Result<Self> {
+ let kqueue = kqueue::Watcher::new()?;
+ let event_loop = EventLoop::new(kqueue, event_handler, follow_symlinks)?;
+ let channel = event_loop.event_loop_tx.clone();
+ let waker = event_loop.event_loop_waker.clone();
+ event_loop.run();
+ Ok(KqueueWatcher { channel, waker })
+ }
+
+ fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ let (tx, rx) = unbounded();
+ let msg = EventLoopMsg::AddWatch(pb, recursive_mode, tx);
+
+ self.channel
+ .send(msg)
+ .map_err(|e| Error::generic(&e.to_string()))?;
+ self.waker
+ .wake()
+ .map_err(|e| Error::generic(&e.to_string()))?;
+ rx.recv()
+ .unwrap()
+ .map_err(|e| Error::generic(&e.to_string()))
+ }
+
+ fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ let (tx, rx) = unbounded();
+ let msg = EventLoopMsg::RemoveWatch(pb, tx);
+
+ self.channel
+ .send(msg)
+ .map_err(|e| Error::generic(&e.to_string()))?;
+ self.waker
+ .wake()
+ .map_err(|e| Error::generic(&e.to_string()))?;
+ rx.recv()
+ .unwrap()
+ .map_err(|e| Error::generic(&e.to_string()))
+ }
+}
+
+impl Watcher for KqueueWatcher {
+ /// Create a new watcher.
+ fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
+ Self::from_event_handler(Box::new(event_handler), config.follow_symlinks())
+ }
+
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.watch_inner(path, recursive_mode)
+ }
+
+ fn unwatch(&mut self, path: &Path) -> Result<()> {
+ self.unwatch_inner(path)
+ }
+
+ fn kind() -> crate::WatcherKind {
+ crate::WatcherKind::Kqueue
+ }
+}
+
+impl Drop for KqueueWatcher {
+ fn drop(&mut self) {
+ // we expect the event loop to live => unwrap must not panic
+ self.channel.send(EventLoopMsg::Shutdown).unwrap();
+ self.waker.wake().unwrap();
+ }
+}
+
+mod tests {
+ use super::{Config, KqueueWatcher, RecursiveMode};
+ use crate::Watcher;
+ use std::error::Error;
+ use std::path::PathBuf;
+ use std::result::Result;
+
+ #[test]
+ fn test_remove_recursive() -> Result<(), Box<dyn Error>> {
+ let path = PathBuf::from("src");
+
+ let mut watcher = KqueueWatcher::new(|event| println!("{:?}", event), Config::default())?;
+ watcher.watch(&path, RecursiveMode::Recursive)?;
+ let result = watcher.unwatch(&path);
+ assert!(
+ result.is_ok(),
+ "unwatch yielded error: {}",
+ result.unwrap_err()
+ );
+ Ok(())
+ }
+}
diff --git a/native/vendor/notify/src/lib.rs b/native/vendor/notify/src/lib.rs
new file mode 100644
index 0000000..0eb73c7
--- /dev/null
+++ b/native/vendor/notify/src/lib.rs
@@ -0,0 +1,615 @@
+//! Cross-platform file system notification library
+//!
+//! # Installation
+//!
+//! ```toml
+//! [dependencies]
+//! notify = "8.1.0"
+//! ```
+//!
+//! If you want debounced events (or don't need them in-order), see [notify-debouncer-mini](https://docs.rs/notify-debouncer-mini/latest/notify_debouncer_mini/)
+//! or [notify-debouncer-full](https://docs.rs/notify-debouncer-full/latest/notify_debouncer_full/).
+//!
+//! ## Features
+//!
+//! List of compilation features, see below for details
+//!
+//! - `serde` for serialization of events
+//! - `macos_fsevent` enabled by default, for fsevent backend on macos
+//! - `macos_kqueue` for kqueue backend on macos
+//! - `serialization-compat-6` restores the serialization behavior of notify 6, off by default
+//!
+//! ### Serde
+//!
+//! Events are serializable via [serde](https://serde.rs) if the `serde` feature is enabled:
+//!
+//! ```toml
+//! notify = { version = "8.1.0", features = ["serde"] }
+//! ```
+//!
+//! # Known Problems
+//!
+//! ### Network filesystems
+//!
+//! Network mounted filesystems like NFS may not emit any events for notify to listen to.
+//! This applies especially to WSL programs watching windows paths ([issue #254](https://github.com/notify-rs/notify/issues/254)).
+//!
+//! A workaround is the [`PollWatcher`] backend.
+//!
+//! ### Docker with Linux on macOS M1
+//!
+//! Docker on macOS M1 [throws](https://github.com/notify-rs/notify/issues/423) `Function not implemented (os error 38)`.
+//! You have to manually use the [`PollWatcher`], as the native backend isn't available inside the emulation.
+//!
+//! ### macOS, FSEvents and unowned files
+//!
+//! Due to the inner security model of FSEvents (see [FileSystemEventSecurity](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/FileSystemEventSecurity/FileSystemEventSecurity.html)),
+//! some events cannot be observed easily when trying to follow files that do not
+//! belong to you. In this case, reverting to the pollwatcher can fix the issue,
+//! with a slight performance cost.
+//!
+//! ### Editor Behaviour
+//!
+//! If you rely on precise events (Write/Delete/Create..), you will notice that the actual events
+//! can differ a lot between file editors. Some truncate the file on save, some create a new one and replace the old one.
+//! See also [this](https://github.com/notify-rs/notify/issues/247) and [this](https://github.com/notify-rs/notify/issues/113#issuecomment-281836995) issues for example.
+//!
+//! ### Parent folder deletion
+//!
+//! If you want to receive an event for a deletion of folder `b` for the path `/a/b/..`, you will have to watch its parent `/a`.
+//! See [here](https://github.com/notify-rs/notify/issues/403) for more details.
+//!
+//! ### Pseudo Filesystems like /proc, /sys
+//!
+//! Some filesystems like `/proc` and `/sys` on *nix do not emit change events or use correct file change dates.
+//! To circumvent that problem you can use the [`PollWatcher`] with the `compare_contents` option.
+//!
+//! ### Linux: Bad File Descriptor / No space left on device
+//!
+//! This may be the case of running into the max-files watched limits of your user or system.
+//! (Files also includes folders.) Note that for recursive watched folders each file and folder inside counts towards the limit.
+//!
+//! You may increase this limit in linux via
+//! ```sh
+//! sudo sysctl fs.inotify.max_user_instances=8192 # example number
+//! sudo sysctl fs.inotify.max_user_watches=524288 # example number
+//! sudo sysctl -p
+//! ```
+//!
+//! Note that the [`PollWatcher`] is not restricted by this limitation, so it may be an alternative if your users can't increase the limit.
+//!
+//! ### Watching large directories
+//!
+//! When watching a very large amount of files, notify may fail to receive all events.
+//! For example the linux backend is documented to not be a 100% reliable source. See also issue [#412](https://github.com/notify-rs/notify/issues/412).
+//!
+//! # Examples
+//!
+//! For more examples visit the [examples folder](https://github.com/notify-rs/notify/tree/main/examples) in the repository.
+//!
+//! ```rust
+//! use notify::{Event, RecursiveMode, Result, Watcher};
+//! use std::{path::Path, sync::mpsc};
+//!
+//! fn main() -> Result<()> {
+//! let (tx, rx) = mpsc::channel::<Result<Event>>();
+//!
+//! // Use recommended_watcher() to automatically select the best implementation
+//! // for your platform. The `EventHandler` passed to this constructor can be a
+//! // closure, a `std::sync::mpsc::Sender`, a `crossbeam_channel::Sender`, or
+//! // another type the trait is implemented for.
+//! let mut watcher = notify::recommended_watcher(tx)?;
+//!
+//! // Add a path to be watched. All files and directories at that path and
+//! // below will be monitored for changes.
+//! # #[cfg(not(any(
+//! # target_os = "freebsd",
+//! # target_os = "openbsd",
+//! # target_os = "dragonfly",
+//! # target_os = "netbsd")))]
+//! # { // "." doesn't exist on BSD for some reason in CI
+//! watcher.watch(Path::new("."), RecursiveMode::Recursive)?;
+//! # }
+//! # #[cfg(any())]
+//! # { // don't run this in doctests, it blocks forever
+//! // Block forever, printing out events as they come in
+//! for res in rx {
+//! match res {
+//! Ok(event) => println!("event: {:?}", event),
+//! Err(e) => println!("watch error: {:?}", e),
+//! }
+//! }
+//! # }
+//!
+//! Ok(())
+//! }
+//! ```
+//!
+//! ## With different configurations
+//!
+//! It is possible to create several watchers with different configurations or implementations that
+//! all call the same event function. This can accommodate advanced behaviour or work around limits.
+//!
+//! ```rust
+//! # use notify::{RecursiveMode, Result, Watcher};
+//! # use std::path::Path;
+//! #
+//! # fn main() -> Result<()> {
+//! fn event_fn(res: Result<notify::Event>) {
+//! match res {
+//! Ok(event) => println!("event: {:?}", event),
+//! Err(e) => println!("watch error: {:?}", e),
+//! }
+//! }
+//!
+//! let mut watcher1 = notify::recommended_watcher(event_fn)?;
+//! // we will just use the same watcher kind again here
+//! let mut watcher2 = notify::recommended_watcher(event_fn)?;
+//! # #[cfg(not(any(
+//! # target_os = "freebsd",
+//! # target_os = "openbsd",
+//! # target_os = "dragonfly",
+//! # target_os = "netbsd")))]
+//! # { // "." doesn't exist on BSD for some reason in CI
+//! # watcher1.watch(Path::new("."), RecursiveMode::Recursive)?;
+//! # watcher2.watch(Path::new("."), RecursiveMode::Recursive)?;
+//! # }
+//! // dropping the watcher1/2 here (no loop etc) will end the program
+//! #
+//! # Ok(())
+//! # }
+//! ```
+
+#![deny(missing_docs)]
+
+pub use config::{Config, RecursiveMode};
+pub use error::{Error, ErrorKind, Result};
+pub use notify_types::event::{self, Event, EventKind};
+use std::path::Path;
+
+pub(crate) type Receiver<T> = std::sync::mpsc::Receiver<T>;
+pub(crate) type Sender<T> = std::sync::mpsc::Sender<T>;
+#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
+pub(crate) type BoundSender<T> = std::sync::mpsc::SyncSender<T>;
+
+#[inline]
+pub(crate) fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
+ std::sync::mpsc::channel()
+}
+
+#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
+#[inline]
+pub(crate) fn bounded<T>(cap: usize) -> (BoundSender<T>, Receiver<T>) {
+ std::sync::mpsc::sync_channel(cap)
+}
+
+#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
+pub use crate::fsevent::FsEventWatcher;
+#[cfg(any(target_os = "linux", target_os = "android"))]
+pub use crate::inotify::INotifyWatcher;
+#[cfg(any(
+ target_os = "freebsd",
+ target_os = "openbsd",
+ target_os = "netbsd",
+ target_os = "dragonfly",
+ target_os = "ios",
+ all(target_os = "macos", feature = "macos_kqueue")
+))]
+pub use crate::kqueue::KqueueWatcher;
+pub use null::NullWatcher;
+pub use poll::PollWatcher;
+#[cfg(target_os = "windows")]
+pub use windows::ReadDirectoryChangesWatcher;
+
+#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
+pub mod fsevent;
+#[cfg(any(target_os = "linux", target_os = "android"))]
+pub mod inotify;
+#[cfg(any(
+ target_os = "freebsd",
+ target_os = "openbsd",
+ target_os = "dragonfly",
+ target_os = "netbsd",
+ target_os = "ios",
+ all(target_os = "macos", feature = "macos_kqueue")
+))]
+pub mod kqueue;
+#[cfg(target_os = "windows")]
+pub mod windows;
+
+pub mod null;
+pub mod poll;
+
+mod config;
+mod error;
+
+/// The set of requirements for watcher event handling functions.
+///
+/// # Example implementation
+///
+/// ```no_run
+/// use notify::{Event, Result, EventHandler};
+///
+/// /// Prints received events
+/// struct EventPrinter;
+///
+/// impl EventHandler for EventPrinter {
+/// fn handle_event(&mut self, event: Result<Event>) {
+/// if let Ok(event) = event {
+/// println!("Event: {:?}", event);
+/// }
+/// }
+/// }
+/// ```
+pub trait EventHandler: Send + 'static {
+ /// Handles an event.
+ fn handle_event(&mut self, event: Result<Event>);
+}
+
+impl<F> EventHandler for F
+where
+ F: FnMut(Result<Event>) + Send + 'static,
+{
+ fn handle_event(&mut self, event: Result<Event>) {
+ (self)(event);
+ }
+}
+
+#[cfg(feature = "crossbeam-channel")]
+impl EventHandler for crossbeam_channel::Sender<Result<Event>> {
+ fn handle_event(&mut self, event: Result<Event>) {
+ let _ = self.send(event);
+ }
+}
+
+#[cfg(feature = "flume")]
+impl EventHandler for flume::Sender<Result<Event>> {
+ fn handle_event(&mut self, event: Result<Event>) {
+ let _ = self.send(event);
+ }
+}
+
+impl EventHandler for std::sync::mpsc::Sender<Result<Event>> {
+ fn handle_event(&mut self, event: Result<Event>) {
+ let _ = self.send(event);
+ }
+}
+
+/// Watcher kind enumeration
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[non_exhaustive]
+pub enum WatcherKind {
+ /// inotify backend (linux)
+ Inotify,
+ /// FS-Event backend (mac)
+ Fsevent,
+ /// KQueue backend (bsd,optionally mac)
+ Kqueue,
+ /// Polling based backend (fallback)
+ PollWatcher,
+ /// Windows backend
+ ReadDirectoryChangesWatcher,
+ /// Fake watcher for testing
+ NullWatcher,
+}
+
+/// Providing methods for adding and removing paths to watch.
+///
+/// `Box<dyn PathsMut>` is created by [`Watcher::paths_mut`]. See its documentation for more.
+pub trait PathsMut {
+ /// Add a new path to watch. See [`Watcher::watch`] for more.
+ fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>;
+
+ /// Remove a path from watching. See [`Watcher::unwatch`] for more.
+ fn remove(&mut self, path: &Path) -> Result<()>;
+
+ /// Ensure added/removed paths are applied.
+ ///
+ /// The behaviour of dropping a [`PathsMut`] without calling [`commit`] is unspecified.
+ /// The implementation is free to ignore the changes or not, and may leave the watcher in a started or stopped state.
+ fn commit(self: Box<Self>) -> Result<()>;
+}
+
+/// Type that can deliver file activity notifications
+///
+/// `Watcher` is implemented per platform using the best implementation available on that platform.
+/// In addition to such event driven implementations, a polling implementation is also provided
+/// that should work on any platform.
+pub trait Watcher {
+ /// Create a new watcher with an initial Config.
+ fn new<F: EventHandler>(event_handler: F, config: config::Config) -> Result<Self>
+ where
+ Self: Sized;
+ /// Begin watching a new path.
+ ///
+ /// If the `path` is a directory, `recursive_mode` will be evaluated. If `recursive_mode` is
+ /// `RecursiveMode::Recursive` events will be delivered for all files in that tree. Otherwise
+ /// only the directory and its immediate children will be watched.
+ ///
+ /// If the `path` is a file, `recursive_mode` will be ignored and events will be delivered only
+ /// for the file.
+ ///
+ /// On some platforms, if the `path` is renamed or removed while being watched, behaviour may
+ /// be unexpected. See discussions in [#165] and [#166]. If less surprising behaviour is wanted
+ /// one may non-recursively watch the _parent_ directory as well and manage related events.
+ ///
+ /// [#165]: https://github.com/notify-rs/notify/issues/165
+ /// [#166]: https://github.com/notify-rs/notify/issues/166
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()>;
+
+ /// Stop watching a path.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error in the case that `path` has not been watched or if removing the watch
+ /// fails.
+ fn unwatch(&mut self, path: &Path) -> Result<()>;
+
+ /// Add/remove paths to watch.
+ ///
+ /// For some watcher implementations this method provides better performance than multiple calls to [`Watcher::watch`] and [`Watcher::unwatch`] if you want to add/remove many paths at once.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use notify::{Watcher, RecursiveMode, Result};
+ /// # use std::path::Path;
+ /// # fn main() -> Result<()> {
+ /// # let many_paths_to_add = vec![];
+ /// let mut watcher = notify::recommended_watcher(|_event| { /* event handler */ })?;
+ /// let mut watcher_paths = watcher.paths_mut();
+ /// for path in many_paths_to_add {
+ /// watcher_paths.add(path, RecursiveMode::Recursive)?;
+ /// }
+ /// watcher_paths.commit()?;
+ /// # Ok(())
+ /// # }
+ /// ```
+ fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
+ struct DefaultPathsMut<'a, T: ?Sized>(&'a mut T);
+ impl<'a, T: Watcher + ?Sized> PathsMut for DefaultPathsMut<'a, T> {
+ fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.0.watch(path, recursive_mode)
+ }
+ fn remove(&mut self, path: &Path) -> Result<()> {
+ self.0.unwatch(path)
+ }
+ fn commit(self: Box<Self>) -> Result<()> {
+ Ok(())
+ }
+ }
+ Box::new(DefaultPathsMut(self))
+ }
+
+ /// Configure the watcher at runtime.
+ ///
+ /// See the [`Config`](config/struct.Config.html) struct for all configuration options.
+ ///
+ /// # Returns
+ ///
+ /// - `Ok(true)` on success.
+ /// - `Ok(false)` if the watcher does not support or implement the option.
+ /// - `Err(notify::Error)` on failure.
+ fn configure(&mut self, _option: Config) -> Result<bool> {
+ Ok(false)
+ }
+
+ /// Returns the watcher kind, allowing to perform backend-specific tasks
+ fn kind() -> WatcherKind
+ where
+ Self: Sized;
+}
+
+/// The recommended [`Watcher`] implementation for the current platform
+#[cfg(any(target_os = "linux", target_os = "android"))]
+pub type RecommendedWatcher = INotifyWatcher;
+/// The recommended [`Watcher`] implementation for the current platform
+#[cfg(all(target_os = "macos", not(feature = "macos_kqueue")))]
+pub type RecommendedWatcher = FsEventWatcher;
+/// The recommended [`Watcher`] implementation for the current platform
+#[cfg(target_os = "windows")]
+pub type RecommendedWatcher = ReadDirectoryChangesWatcher;
+/// The recommended [`Watcher`] implementation for the current platform
+#[cfg(any(
+ target_os = "freebsd",
+ target_os = "openbsd",
+ target_os = "netbsd",
+ target_os = "dragonfly",
+ target_os = "ios",
+ all(target_os = "macos", feature = "macos_kqueue")
+))]
+pub type RecommendedWatcher = KqueueWatcher;
+/// The recommended [`Watcher`] implementation for the current platform
+#[cfg(not(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "macos",
+ target_os = "windows",
+ target_os = "freebsd",
+ target_os = "openbsd",
+ target_os = "netbsd",
+ target_os = "dragonfly",
+ target_os = "ios"
+)))]
+pub type RecommendedWatcher = PollWatcher;
+
+/// Convenience method for creating the [`RecommendedWatcher`] for the current platform.
+pub fn recommended_watcher<F>(event_handler: F) -> Result<RecommendedWatcher>
+where
+ F: EventHandler,
+{
+ // All recommended watchers currently implement `new`, so just call that.
+ RecommendedWatcher::new(event_handler, Config::default())
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ fs, iter,
+ time::{Duration, Instant},
+ };
+
+ use tempfile::tempdir;
+
+ use super::*;
+
+ #[test]
+ fn test_object_safe() {
+ let _watcher: &dyn Watcher = &NullWatcher;
+ }
+
+ #[test]
+ fn test_debug_impl() {
+ macro_rules! assert_debug_impl {
+ ($t:ty) => {{
+ #[allow(dead_code)]
+ trait NeedsDebug: std::fmt::Debug {}
+ impl NeedsDebug for $t {}
+ }};
+ }
+
+ assert_debug_impl!(Config);
+ assert_debug_impl!(Error);
+ assert_debug_impl!(ErrorKind);
+ assert_debug_impl!(NullWatcher);
+ assert_debug_impl!(PollWatcher);
+ assert_debug_impl!(RecommendedWatcher);
+ assert_debug_impl!(RecursiveMode);
+ assert_debug_impl!(WatcherKind);
+ }
+
+ fn iter_with_timeout(rx: &Receiver<Result<Event>>) -> impl Iterator<Item = Event> + '_ {
+ // wait for up to 10 seconds for the events
+ let deadline = Instant::now() + Duration::from_secs(10);
+ iter::from_fn(move || {
+ if Instant::now() >= deadline {
+ return None;
+ }
+ Some(
+ rx.recv_timeout(deadline - Instant::now())
+ .expect("did not receive expected event")
+ .expect("received an error"),
+ )
+ })
+ }
+
+ #[test]
+ fn integration() -> std::result::Result<(), Box<dyn std::error::Error>> {
+ let dir = tempdir()?;
+
+ // set up the watcher
+ let (tx, rx) = std::sync::mpsc::channel();
+ let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
+ watcher.watch(dir.path(), RecursiveMode::Recursive)?;
+
+ // create a new file
+ let file_path = dir.path().join("file.txt");
+ fs::write(&file_path, b"Lorem ipsum")?;
+
+ println!("waiting for event at {}", file_path.display());
+
+ // wait for the create event, ignore all other events
+ for event in iter_with_timeout(&rx) {
+ if event.paths == vec![file_path.clone()]
+ || event.paths == vec![file_path.canonicalize()?]
+ {
+ return Ok(());
+ }
+
+ println!("unexpected event: {event:?}");
+ }
+
+ panic!("did not receive expected event");
+ }
+
+ #[test]
+ #[cfg(target_os = "windows")]
+ fn test_windows_trash_dir() -> std::result::Result<(), Box<dyn std::error::Error>> {
+ let dir = tempdir()?;
+ let child_dir = dir.path().join("child");
+ fs::create_dir(&child_dir)?;
+
+ let mut watcher = recommended_watcher(|_| {
+ // Do something with the event
+ })?;
+ watcher.watch(&child_dir, RecursiveMode::NonRecursive)?;
+
+ trash::delete(&child_dir)?;
+
+ watcher.watch(dir.path(), RecursiveMode::NonRecursive)?;
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_paths_mut() -> std::result::Result<(), Box<dyn std::error::Error>> {
+ let dir = tempdir()?;
+
+ let dir_a = dir.path().join("a");
+ let dir_b = dir.path().join("b");
+
+ fs::create_dir(&dir_a)?;
+ fs::create_dir(&dir_b)?;
+
+ let (tx, rx) = std::sync::mpsc::channel();
+ let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
+
+ // start watching a and b
+ {
+ let mut watcher_paths = watcher.paths_mut();
+ watcher_paths.add(&dir_a, RecursiveMode::Recursive)?;
+ watcher_paths.add(&dir_b, RecursiveMode::Recursive)?;
+ watcher_paths.commit()?;
+ }
+
+ // create file1 in both a and b
+ let a_file1 = dir_a.join("file1");
+ let b_file1 = dir_b.join("file1");
+ fs::write(&a_file1, b"Lorem ipsum")?;
+ fs::write(&b_file1, b"Lorem ipsum")?;
+
+ // wait for create events of a/file1 and b/file1
+ let mut a_file1_encountered: bool = false;
+ let mut b_file1_encountered: bool = false;
+ for event in iter_with_timeout(&rx) {
+ for path in event.paths {
+ a_file1_encountered =
+ a_file1_encountered || (path == a_file1 || path == a_file1.canonicalize()?);
+ b_file1_encountered =
+ b_file1_encountered || (path == b_file1 || path == b_file1.canonicalize()?);
+ }
+ if a_file1_encountered && b_file1_encountered {
+ break;
+ }
+ }
+ assert!(a_file1_encountered, "Did not receive event of {a_file1:?}");
+ assert!(b_file1_encountered, "Did not receive event of {b_file1:?}");
+
+ // stop watching a
+ {
+ let mut watcher_paths = watcher.paths_mut();
+ watcher_paths.remove(&dir_a)?;
+ watcher_paths.commit()?;
+ }
+
+ // create file2 in both a and b
+ let a_file2 = dir_a.join("file2");
+ let b_file2 = dir_b.join("file2");
+ fs::write(&a_file2, b"Lorem ipsum")?;
+ fs::write(&b_file2, b"Lorem ipsum")?;
+
+ // wait for the create event of b/file2 only
+ for event in iter_with_timeout(&rx) {
+ for path in event.paths {
+ assert!(
+ path != a_file2 || path != a_file2.canonicalize()?,
+ "Event of {a_file2:?} should not be received"
+ );
+ if path == b_file2 || path == b_file2.canonicalize()? {
+ return Ok(());
+ }
+ }
+ }
+ panic!("Did not receive the event of {b_file2:?}");
+ }
+}
diff --git a/native/vendor/notify/src/null.rs b/native/vendor/notify/src/null.rs
new file mode 100644
index 0000000..bbcd80d
--- /dev/null
+++ b/native/vendor/notify/src/null.rs
@@ -0,0 +1,39 @@
+//! Stub Watcher implementation
+
+#![allow(unused_variables)]
+
+use crate::Config;
+
+use super::{RecursiveMode, Result, Watcher};
+use std::path::Path;
+
+/// Stub `Watcher` implementation
+///
+/// Events are never delivered from this watcher.
+#[derive(Debug)]
+pub struct NullWatcher;
+
+impl Watcher for NullWatcher {
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ Ok(())
+ }
+
+ fn unwatch(&mut self, path: &Path) -> Result<()> {
+ Ok(())
+ }
+
+ fn new<F: crate::EventHandler>(event_handler: F, config: Config) -> Result<Self>
+ where
+ Self: Sized,
+ {
+ Ok(NullWatcher)
+ }
+
+ fn configure(&mut self, config: Config) -> Result<bool> {
+ Ok(false)
+ }
+
+ fn kind() -> crate::WatcherKind {
+ crate::WatcherKind::NullWatcher
+ }
+}
diff --git a/native/vendor/notify/src/poll.rs b/native/vendor/notify/src/poll.rs
new file mode 100644
index 0000000..fecaf22
--- /dev/null
+++ b/native/vendor/notify/src/poll.rs
@@ -0,0 +1,676 @@
+//! Generic Watcher implementation based on polling
+//!
+//! Checks the `watch`ed paths periodically to detect changes. This implementation only uses
+//! Rust stdlib APIs and should work on all of the platforms it supports.
+
+use crate::{unbounded, Config, Error, EventHandler, Receiver, RecursiveMode, Sender, Watcher};
+use std::{
+ collections::HashMap,
+ path::{Path, PathBuf},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+ thread,
+ time::Duration,
+};
+
+/// Event sent for registered handlers on initial directory scans
+pub type ScanEvent = crate::Result<PathBuf>;
+
+/// Handler trait for receivers of [`ScanEvent`].
+/// Very much the same as [`EventHandler`], but including the Result.
+///
+/// See the full example for more information.
+pub trait ScanEventHandler: Send + 'static {
+ /// Handles an event.
+ fn handle_event(&mut self, event: ScanEvent);
+}
+
+impl<F> ScanEventHandler for F
+where
+ F: FnMut(ScanEvent) + Send + 'static,
+{
+ fn handle_event(&mut self, event: ScanEvent) {
+ (self)(event);
+ }
+}
+
+#[cfg(feature = "crossbeam-channel")]
+impl ScanEventHandler for crossbeam_channel::Sender<ScanEvent> {
+ fn handle_event(&mut self, event: ScanEvent) {
+ let _ = self.send(event);
+ }
+}
+
+#[cfg(feature = "flume")]
+impl ScanEventHandler for flume::Sender<ScanEvent> {
+ fn handle_event(&mut self, event: ScanEvent) {
+ let _ = self.send(event);
+ }
+}
+
+impl ScanEventHandler for std::sync::mpsc::Sender<ScanEvent> {
+ fn handle_event(&mut self, event: ScanEvent) {
+ let _ = self.send(event);
+ }
+}
+
+impl ScanEventHandler for () {
+ fn handle_event(&mut self, _event: ScanEvent) {}
+}
+
+use data::{DataBuilder, WatchData};
+mod data {
+ use crate::{
+ event::{CreateKind, DataChange, Event, EventKind, MetadataKind, ModifyKind, RemoveKind},
+ EventHandler,
+ };
+ use std::{
+ cell::RefCell,
+ collections::{hash_map::RandomState, HashMap},
+ fmt::{self, Debug},
+ fs::{self, File, Metadata},
+ hash::{BuildHasher, Hasher},
+ io::{self, Read},
+ path::{Path, PathBuf},
+ time::Instant,
+ };
+ use walkdir::WalkDir;
+
+ use super::ScanEventHandler;
+
+ fn system_time_to_seconds(time: std::time::SystemTime) -> i64 {
+ match time.duration_since(std::time::SystemTime::UNIX_EPOCH) {
+ Ok(d) => d.as_secs() as i64,
+ Err(e) => -(e.duration().as_secs() as i64),
+ }
+ }
+
+ /// Builder for [`WatchData`] & [`PathData`].
+ pub(super) struct DataBuilder {
+ emitter: EventEmitter,
+ scan_emitter: Option<Box<RefCell<dyn ScanEventHandler>>>,
+
+ // TODO: May allow user setup their custom BuildHasher / BuildHasherDefault
+ // in future.
+ build_hasher: Option<RandomState>,
+
+ // current timestamp for building Data.
+ now: Instant,
+ }
+
+ impl DataBuilder {
+ pub(super) fn new<F, G>(
+ event_handler: F,
+ compare_content: bool,
+ scan_emitter: Option<G>,
+ ) -> Self
+ where
+ F: EventHandler,
+ G: ScanEventHandler,
+ {
+ let scan_emitter = match scan_emitter {
+ None => None,
+ Some(v) => {
+ // workaround for a weird type resolution bug when directly going to dyn Trait
+ let intermediate: Box<RefCell<dyn ScanEventHandler>> =
+ Box::new(RefCell::new(v));
+ Some(intermediate)
+ }
+ };
+ Self {
+ emitter: EventEmitter::new(event_handler),
+ scan_emitter,
+ build_hasher: compare_content.then(RandomState::default),
+ now: Instant::now(),
+ }
+ }
+
+ /// Update internal timestamp.
+ pub(super) fn update_timestamp(&mut self) {
+ self.now = Instant::now();
+ }
+
+ /// Create [`WatchData`].
+ ///
+ /// This function will return `Err(_)` if can not retrieve metadata from
+ /// the path location. (e.g., not found).
+ pub(super) fn build_watch_data(
+ &self,
+ root: PathBuf,
+ is_recursive: bool,
+ follow_symlinks: bool,
+ ) -> Option<WatchData> {
+ WatchData::new(self, root, is_recursive, follow_symlinks)
+ }
+
+ /// Create [`PathData`].
+ fn build_path_data(&self, meta_path: &MetaPath) -> PathData {
+ PathData::new(self, meta_path)
+ }
+ }
+
+ impl Debug for DataBuilder {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("DataBuilder")
+ .field("build_hasher", &self.build_hasher)
+ .field("now", &self.now)
+ .finish()
+ }
+ }
+
+ #[derive(Debug)]
+ pub(super) struct WatchData {
+ // config part, won't change.
+ root: PathBuf,
+ is_recursive: bool,
+ follow_symlinks: bool,
+
+ // current status part.
+ all_path_data: HashMap<PathBuf, PathData>,
+ }
+
+ impl WatchData {
+ /// Scan filesystem and create a new `WatchData`.
+ ///
+ /// # Side effect
+ ///
+ /// This function may send event by `data_builder.emitter`.
+ fn new(
+ data_builder: &DataBuilder,
+ root: PathBuf,
+ is_recursive: bool,
+ follow_symlinks: bool,
+ ) -> Option<Self> {
+ // If metadata read error at `root` path, it will emit
+ // a error event and stop to create the whole `WatchData`.
+ //
+ // QUESTION: inconsistent?
+ //
+ // When user try to *CREATE* a watch by `poll_watcher.watch(root, ..)`,
+ // if `root` path hit an io error, then watcher will reject to
+ // create this new watch.
+ //
+ // This may inconsistent with *POLLING* a watch. When watcher
+ // continue polling, io error at root path will not delete
+ // a existing watch. polling still working.
+ //
+ // So, consider a config file may not exists at first time but may
+ // create after a while, developer cannot watch it.
+ //
+ // FIXME: Can we always allow to watch a path, even file not
+ // found at this path?
+ if let Err(e) = fs::metadata(&root) {
+ data_builder.emitter.emit_io_err(e, Some(&root));
+ return None;
+ }
+
+ let all_path_data = Self::scan_all_path_data(
+ data_builder,
+ root.clone(),
+ is_recursive,
+ follow_symlinks,
+ true,
+ )
+ .collect();
+
+ Some(Self {
+ root,
+ is_recursive,
+ follow_symlinks,
+ all_path_data,
+ })
+ }
+
+ /// Rescan filesystem and update this `WatchData`.
+ ///
+ /// # Side effect
+ ///
+ /// This function may emit event by `data_builder.emitter`.
+ pub(super) fn rescan(&mut self, data_builder: &mut DataBuilder) {
+ // scan current filesystem.
+ for (path, new_path_data) in Self::scan_all_path_data(
+ data_builder,
+ self.root.clone(),
+ self.is_recursive,
+ self.follow_symlinks,
+ false,
+ ) {
+ let old_path_data = self
+ .all_path_data
+ .insert(path.clone(), new_path_data.clone());
+
+ // emit event
+ let event =
+ PathData::compare_to_event(path, old_path_data.as_ref(), Some(&new_path_data));
+ if let Some(event) = event {
+ data_builder.emitter.emit_ok(event);
+ }
+ }
+
+ // scan for disappeared paths.
+ let mut disappeared_paths = Vec::new();
+ for (path, path_data) in self.all_path_data.iter() {
+ if path_data.last_check < data_builder.now {
+ disappeared_paths.push(path.clone());
+ }
+ }
+
+ // remove disappeared paths
+ for path in disappeared_paths {
+ let old_path_data = self.all_path_data.remove(&path);
+
+ // emit event
+ let event = PathData::compare_to_event(path, old_path_data.as_ref(), None);
+ if let Some(event) = event {
+ data_builder.emitter.emit_ok(event);
+ }
+ }
+ }
+
+ /// Get all `PathData` by given configuration.
+ ///
+ /// # Side Effect
+ ///
+ /// This function may emit some IO Error events by `data_builder.emitter`.
+ fn scan_all_path_data(
+ data_builder: &'_ DataBuilder,
+ root: PathBuf,
+ is_recursive: bool,
+ follow_symlinks: bool,
+ // whether this is an initial scan, used only for events
+ is_initial: bool,
+ ) -> impl Iterator<Item = (PathBuf, PathData)> + '_ {
+ log::trace!("rescanning {root:?}");
+ // WalkDir return only one entry if root is a file (not a folder),
+ // so we can use single logic to do the both file & dir's jobs.
+ //
+ // See: https://docs.rs/walkdir/2.0.1/walkdir/struct.WalkDir.html#method.new
+ WalkDir::new(root)
+ .follow_links(follow_symlinks)
+ .max_depth(Self::dir_scan_depth(is_recursive))
+ .into_iter()
+ .filter_map(|entry_res| match entry_res {
+ Ok(entry) => Some(entry),
+ Err(err) => {
+ log::warn!("walkdir error scanning {err:?}");
+ if let Some(io_error) = err.io_error() {
+ // clone an io::Error, so we have to create a new one.
+ let new_io_error = io::Error::new(io_error.kind(), err.to_string());
+ data_builder.emitter.emit_io_err(new_io_error, err.path());
+ } else {
+ let crate_err =
+ crate::Error::new(crate::ErrorKind::Generic(err.to_string()));
+ data_builder.emitter.emit(Err(crate_err));
+ }
+ None
+ }
+ })
+ .filter_map(move |entry| match entry.metadata() {
+ Ok(metadata) => {
+ let path = entry.into_path();
+ if is_initial {
+ // emit initial scans
+ if let Some(ref emitter) = data_builder.scan_emitter {
+ emitter.borrow_mut().handle_event(Ok(path.clone()));
+ }
+ }
+ let meta_path = MetaPath::from_parts_unchecked(path, metadata);
+ let data_path = data_builder.build_path_data(&meta_path);
+
+ Some((meta_path.into_path(), data_path))
+ }
+ Err(e) => {
+ // emit event.
+ let path = entry.into_path();
+ data_builder.emitter.emit_io_err(e, Some(path));
+
+ None
+ }
+ })
+ }
+
+ fn dir_scan_depth(is_recursive: bool) -> usize {
+ if is_recursive {
+ usize::MAX
+ } else {
+ 1
+ }
+ }
+ }
+
+ /// Stored data for a one path locations.
+ ///
+ /// See [`WatchData`] for more detail.
+ #[derive(Debug, Clone)]
+ struct PathData {
+ /// File updated time.
+ mtime: i64,
+
+ /// Content's hash value, only available if user request compare file
+ /// contents and read successful.
+ hash: Option<u64>,
+
+ /// Checked time.
+ last_check: Instant,
+ }
+
+ impl PathData {
+ /// Create a new `PathData`.
+ fn new(data_builder: &DataBuilder, meta_path: &MetaPath) -> PathData {
+ let metadata = meta_path.metadata();
+
+ PathData {
+ mtime: metadata.modified().map_or(0, system_time_to_seconds),
+ hash: data_builder
+ .build_hasher
+ .as_ref()
+ .filter(|_| metadata.is_file())
+ .and_then(|build_hasher| {
+ Self::get_content_hash(build_hasher, meta_path.path()).ok()
+ }),
+
+ last_check: data_builder.now,
+ }
+ }
+
+ /// Get hash value for the data content in given file `path`.
+ fn get_content_hash(build_hasher: &RandomState, path: &Path) -> io::Result<u64> {
+ let mut hasher = build_hasher.build_hasher();
+ let mut file = File::open(path)?;
+ let mut buf = [0; 512];
+
+ loop {
+ let n = match file.read(&mut buf) {
+ Ok(0) => break,
+ Ok(len) => len,
+ Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
+ Err(e) => return Err(e),
+ };
+
+ hasher.write(&buf[..n]);
+ }
+
+ Ok(hasher.finish())
+ }
+
+ /// Get [`Event`] by compare two optional [`PathData`].
+ fn compare_to_event<P>(
+ path: P,
+ old: Option<&PathData>,
+ new: Option<&PathData>,
+ ) -> Option<Event>
+ where
+ P: Into<PathBuf>,
+ {
+ match (old, new) {
+ (Some(old), Some(new)) => {
+ if new.mtime > old.mtime {
+ Some(EventKind::Modify(ModifyKind::Metadata(
+ MetadataKind::WriteTime,
+ )))
+ } else if new.hash != old.hash {
+ Some(EventKind::Modify(ModifyKind::Data(DataChange::Any)))
+ } else {
+ None
+ }
+ }
+ (None, Some(_new)) => Some(EventKind::Create(CreateKind::Any)),
+ (Some(_old), None) => Some(EventKind::Remove(RemoveKind::Any)),
+ (None, None) => None,
+ }
+ .map(|event_kind| Event::new(event_kind).add_path(path.into()))
+ }
+ }
+
+ /// Compose path and its metadata.
+ ///
+ /// This data structure designed for make sure path and its metadata can be
+ /// transferred in consistent way, and may avoid some duplicated
+ /// `fs::metadata()` function call in some situations.
+ #[derive(Debug)]
+ pub(super) struct MetaPath {
+ path: PathBuf,
+ metadata: Metadata,
+ }
+
+ impl MetaPath {
+ /// Create `MetaPath` by given parts.
+ ///
+ /// # Invariant
+ ///
+ /// User must make sure the input `metadata` are associated with `path`.
+ fn from_parts_unchecked(path: PathBuf, metadata: Metadata) -> Self {
+ Self { path, metadata }
+ }
+
+ fn path(&self) -> &Path {
+ &self.path
+ }
+
+ fn metadata(&self) -> &Metadata {
+ &self.metadata
+ }
+
+ fn into_path(self) -> PathBuf {
+ self.path
+ }
+ }
+
+ /// Thin wrapper for outer event handler, for easy to use.
+ struct EventEmitter(
+ // Use `RefCell` to make sure `emit()` only need shared borrow of self (&self).
+ // Use `Box` to make sure EventEmitter is Sized.
+ Box<RefCell<dyn EventHandler>>,
+ );
+
+ impl EventEmitter {
+ fn new<F: EventHandler>(event_handler: F) -> Self {
+ Self(Box::new(RefCell::new(event_handler)))
+ }
+
+ /// Emit single event.
+ fn emit(&self, event: crate::Result<Event>) {
+ self.0.borrow_mut().handle_event(event);
+ }
+
+ /// Emit event.
+ fn emit_ok(&self, event: Event) {
+ self.emit(Ok(event))
+ }
+
+ /// Emit io error event.
+ fn emit_io_err<E, P>(&self, err: E, path: Option<P>)
+ where
+ E: Into<io::Error>,
+ P: Into<PathBuf>,
+ {
+ let e = crate::Error::io(err.into());
+ if let Some(path) = path {
+ self.emit(Err(e.add_path(path.into())));
+ } else {
+ self.emit(Err(e));
+ }
+ }
+ }
+}
+
+/// Polling based `Watcher` implementation.
+///
+/// By default scans through all files and checks for changed entries based on their change date.
+/// Can also be changed to perform file content change checks.
+///
+/// See [Config] for more details.
+#[derive(Debug)]
+pub struct PollWatcher {
+ watches: Arc<Mutex<HashMap<PathBuf, WatchData>>>,
+ data_builder: Arc<Mutex<DataBuilder>>,
+ want_to_stop: Arc<AtomicBool>,
+ /// channel to the poll loop
+ /// currently used only for manual polling
+ message_channel: Sender<()>,
+ delay: Option<Duration>,
+ follow_sylinks: bool,
+}
+
+impl PollWatcher {
+ /// Create a new [`PollWatcher`], configured as needed.
+ pub fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<PollWatcher> {
+ Self::with_opt::<_, ()>(event_handler, config, None)
+ }
+
+ /// Actively poll for changes. Can be combined with a timeout of 0 to perform only manual polling.
+ pub fn poll(&self) -> crate::Result<()> {
+ self.message_channel
+ .send(())
+ .map_err(|_| Error::generic("failed to send poll message"))?;
+ Ok(())
+ }
+
+ /// Create a new [`PollWatcher`] with an scan event handler.
+ ///
+ /// `scan_fallback` is called on the initial scan with all files seen by the pollwatcher.
+ pub fn with_initial_scan<F: EventHandler, G: ScanEventHandler>(
+ event_handler: F,
+ config: Config,
+ scan_callback: G,
+ ) -> crate::Result<PollWatcher> {
+ Self::with_opt(event_handler, config, Some(scan_callback))
+ }
+
+ /// create a new [`PollWatcher`] with all options.
+ fn with_opt<F: EventHandler, G: ScanEventHandler>(
+ event_handler: F,
+ config: Config,
+ scan_callback: Option<G>,
+ ) -> crate::Result<PollWatcher> {
+ let data_builder =
+ DataBuilder::new(event_handler, config.compare_contents(), scan_callback);
+
+ let (tx, rx) = unbounded();
+
+ let poll_watcher = PollWatcher {
+ watches: Default::default(),
+ data_builder: Arc::new(Mutex::new(data_builder)),
+ want_to_stop: Arc::new(AtomicBool::new(false)),
+ delay: config.poll_interval(),
+ follow_sylinks: config.follow_symlinks(),
+ message_channel: tx,
+ };
+
+ poll_watcher.run(rx);
+
+ Ok(poll_watcher)
+ }
+
+ fn run(&self, rx: Receiver<()>) {
+ let watches = Arc::clone(&self.watches);
+ let data_builder = Arc::clone(&self.data_builder);
+ let want_to_stop = Arc::clone(&self.want_to_stop);
+ let delay = self.delay;
+
+ let _ = thread::Builder::new()
+ .name("notify-rs poll loop".to_string())
+ .spawn(move || {
+ loop {
+ if want_to_stop.load(Ordering::SeqCst) {
+ break;
+ }
+
+ // HINT: Make sure always lock in the same order to avoid deadlock.
+ //
+ // FIXME: inconsistent: some place mutex poison cause panic,
+ // some place just ignore.
+ if let (Ok(mut watches), Ok(mut data_builder)) =
+ (watches.lock(), data_builder.lock())
+ {
+ data_builder.update_timestamp();
+
+ let vals = watches.values_mut();
+ for watch_data in vals {
+ watch_data.rescan(&mut data_builder);
+ }
+ }
+ // TODO: v7.0 use delay - (Instant::now().saturating_duration_since(start))
+ if let Some(delay) = delay {
+ let _ = rx.recv_timeout(delay);
+ } else {
+ let _ = rx.recv();
+ }
+ }
+ });
+ }
+
+ /// Watch a path location.
+ ///
+ /// QUESTION: this function never return an Error, is it as intend?
+ /// Please also consider the IO Error event problem.
+ fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) {
+ // HINT: Make sure always lock in the same order to avoid deadlock.
+ //
+ // FIXME: inconsistent: some place mutex poison cause panic, some place just ignore.
+ if let (Ok(mut watches), Ok(mut data_builder)) =
+ (self.watches.lock(), self.data_builder.lock())
+ {
+ data_builder.update_timestamp();
+
+ let watch_data = data_builder.build_watch_data(
+ path.to_path_buf(),
+ recursive_mode.is_recursive(),
+ self.follow_sylinks,
+ );
+
+ // if create watch_data successful, add it to watching list.
+ if let Some(watch_data) = watch_data {
+ watches.insert(path.to_path_buf(), watch_data);
+ }
+ }
+ }
+
+ /// Unwatch a path.
+ ///
+ /// Return `Err(_)` if given path has't be monitored.
+ fn unwatch_inner(&mut self, path: &Path) -> crate::Result<()> {
+ // FIXME: inconsistent: some place mutex poison cause panic, some place just ignore.
+ self.watches
+ .lock()
+ .unwrap()
+ .remove(path)
+ .map(|_| ())
+ .ok_or_else(crate::Error::watch_not_found)
+ }
+}
+
+impl Watcher for PollWatcher {
+ /// Create a new [`PollWatcher`].
+ fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<Self> {
+ Self::new(event_handler, config)
+ }
+
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> crate::Result<()> {
+ self.watch_inner(path, recursive_mode);
+
+ Ok(())
+ }
+
+ fn unwatch(&mut self, path: &Path) -> crate::Result<()> {
+ self.unwatch_inner(path)
+ }
+
+ fn kind() -> crate::WatcherKind {
+ crate::WatcherKind::PollWatcher
+ }
+}
+
+impl Drop for PollWatcher {
+ fn drop(&mut self) {
+ self.want_to_stop.store(true, Ordering::Relaxed);
+ }
+}
+
+#[test]
+fn poll_watcher_is_send_and_sync() {
+ fn check<T: Send + Sync>() {}
+ check::<PollWatcher>();
+}
diff --git a/native/vendor/notify/src/windows.rs b/native/vendor/notify/src/windows.rs
new file mode 100644
index 0000000..b7849e5
--- /dev/null
+++ b/native/vendor/notify/src/windows.rs
@@ -0,0 +1,622 @@
+#![allow(missing_docs)]
+//! Watcher implementation for Windows' directory management APIs
+//!
+//! For more information see the [ReadDirectoryChangesW reference][ref].
+//!
+//! [ref]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363950(v=vs.85).aspx
+
+use crate::{bounded, unbounded, BoundSender, Config, Receiver, Sender};
+use crate::{event::*, WatcherKind};
+use crate::{Error, EventHandler, RecursiveMode, Result, Watcher};
+use std::alloc;
+use std::collections::HashMap;
+use std::env;
+use std::ffi::OsString;
+use std::os::raw::c_void;
+use std::os::windows::ffi::{OsStrExt, OsStringExt};
+use std::path::{Path, PathBuf};
+use std::ptr;
+use std::slice;
+use std::sync::{Arc, Mutex};
+use std::thread;
+use windows_sys::Win32::Foundation::{
+ CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_OPERATION_ABORTED, ERROR_SUCCESS, HANDLE,
+ INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
+};
+use windows_sys::Win32::Storage::FileSystem::{
+ CreateFileW, ReadDirectoryChangesW, FILE_ACTION_ADDED, FILE_ACTION_MODIFIED,
+ FILE_ACTION_REMOVED, FILE_ACTION_RENAMED_NEW_NAME, FILE_ACTION_RENAMED_OLD_NAME,
+ FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY,
+ FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_DIR_NAME,
+ FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY,
+ FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_INFORMATION, FILE_SHARE_DELETE, FILE_SHARE_READ,
+ FILE_SHARE_WRITE, OPEN_EXISTING,
+};
+use windows_sys::Win32::System::Threading::{
+ CreateSemaphoreW, ReleaseSemaphore, WaitForSingleObjectEx, INFINITE,
+};
+use windows_sys::Win32::System::IO::{CancelIo, OVERLAPPED};
+
+const BUF_SIZE: u32 = 16384;
+
+#[derive(Clone)]
+struct ReadData {
+ dir: PathBuf, // directory that is being watched
+ file: Option<PathBuf>, // if a file is being watched, this is its full path
+ complete_sem: HANDLE,
+ is_recursive: bool,
+}
+
+struct ReadDirectoryRequest {
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ buffer: [u8; BUF_SIZE as usize],
+ handle: HANDLE,
+ data: ReadData,
+ action_tx: Sender<Action>,
+}
+
+impl ReadDirectoryRequest {
+ fn unwatch(&self) {
+ let _ = self.action_tx.send(Action::Unwatch(self.data.dir.clone()));
+ }
+}
+
+enum Action {
+ Watch(PathBuf, RecursiveMode),
+ Unwatch(PathBuf),
+ Stop,
+ Configure(Config, BoundSender<Result<bool>>),
+}
+
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub enum MetaEvent {
+ SingleWatchComplete,
+ WatcherAwakened,
+}
+
+struct WatchState {
+ dir_handle: HANDLE,
+ complete_sem: HANDLE,
+}
+
+struct ReadDirectoryChangesServer {
+ tx: Sender<Action>,
+ rx: Receiver<Action>,
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ meta_tx: Sender<MetaEvent>,
+ cmd_tx: Sender<Result<PathBuf>>,
+ watches: HashMap<PathBuf, WatchState>,
+ wakeup_sem: HANDLE,
+}
+
+impl ReadDirectoryChangesServer {
+ fn start(
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ meta_tx: Sender<MetaEvent>,
+ cmd_tx: Sender<Result<PathBuf>>,
+ wakeup_sem: HANDLE,
+ ) -> Sender<Action> {
+ let (action_tx, action_rx) = unbounded();
+ // it is, in fact, ok to send the semaphore across threads
+ let sem_temp = wakeup_sem as u64;
+ let _ = thread::Builder::new()
+ .name("notify-rs windows loop".to_string())
+ .spawn({
+ let tx = action_tx.clone();
+ move || {
+ let wakeup_sem = sem_temp as HANDLE;
+ let server = ReadDirectoryChangesServer {
+ tx,
+ rx: action_rx,
+ event_handler,
+ meta_tx,
+ cmd_tx,
+ watches: HashMap::new(),
+ wakeup_sem,
+ };
+ server.run();
+ }
+ });
+ action_tx
+ }
+
+ fn run(mut self) {
+ loop {
+ // process all available actions first
+ let mut stopped = false;
+
+ while let Ok(action) = self.rx.try_recv() {
+ match action {
+ Action::Watch(path, recursive_mode) => {
+ let res = self.add_watch(path, recursive_mode.is_recursive());
+ let _ = self.cmd_tx.send(res);
+ }
+ Action::Unwatch(path) => self.remove_watch(path),
+ Action::Stop => {
+ stopped = true;
+ for ws in self.watches.values() {
+ stop_watch(ws, &self.meta_tx);
+ }
+ break;
+ }
+ Action::Configure(config, tx) => {
+ self.configure_raw_mode(config, tx);
+ }
+ }
+ }
+
+ if stopped {
+ break;
+ }
+
+ unsafe {
+ // wait with alertable flag so that the completion routine fires
+ let waitres = WaitForSingleObjectEx(self.wakeup_sem, 100, 1);
+ if waitres == WAIT_OBJECT_0 {
+ let _ = self.meta_tx.send(MetaEvent::WatcherAwakened);
+ }
+ }
+ }
+
+ // we have to clean this up, since the watcher may be long gone
+ unsafe {
+ CloseHandle(self.wakeup_sem);
+ }
+ }
+
+ fn add_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<PathBuf> {
+ // path must exist and be either a file or directory
+ if !path.is_dir() && !path.is_file() {
+ return Err(
+ Error::generic("Input watch path is neither a file nor a directory.")
+ .add_path(path),
+ );
+ }
+
+ let (watching_file, dir_target) = {
+ if path.is_dir() {
+ (false, path.clone())
+ } else {
+ // emulate file watching by watching the parent directory
+ (true, path.parent().unwrap().to_path_buf())
+ }
+ };
+
+ let encoded_path: Vec<u16> = dir_target
+ .as_os_str()
+ .encode_wide()
+ .chain(Some(0))
+ .collect();
+ let handle;
+ unsafe {
+ handle = CreateFileW(
+ encoded_path.as_ptr(),
+ FILE_LIST_DIRECTORY,
+ FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
+ ptr::null_mut(),
+ OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
+ ptr::null_mut(),
+ );
+
+ if handle == INVALID_HANDLE_VALUE {
+ return Err(if watching_file {
+ Error::generic(
+ "You attempted to watch a single file, but parent \
+ directory could not be opened.",
+ )
+ .add_path(path)
+ } else {
+ // TODO: Call GetLastError for better error info?
+ Error::path_not_found().add_path(path)
+ });
+ }
+ }
+ let wf = if watching_file {
+ Some(path.clone())
+ } else {
+ None
+ };
+ // every watcher gets its own semaphore to signal completion
+ let semaphore = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
+ if semaphore.is_null() || semaphore == INVALID_HANDLE_VALUE {
+ unsafe {
+ CloseHandle(handle);
+ }
+ return Err(Error::generic("Failed to create semaphore for watch.").add_path(path));
+ }
+ let rd = ReadData {
+ dir: dir_target,
+ file: wf,
+ complete_sem: semaphore,
+ is_recursive,
+ };
+ let ws = WatchState {
+ dir_handle: handle,
+ complete_sem: semaphore,
+ };
+ self.watches.insert(path.clone(), ws);
+ start_read(&rd, self.event_handler.clone(), handle, self.tx.clone());
+ Ok(path)
+ }
+
+ fn remove_watch(&mut self, path: PathBuf) {
+ if let Some(ws) = self.watches.remove(&path) {
+ stop_watch(&ws, &self.meta_tx);
+ }
+ }
+
+ fn configure_raw_mode(&mut self, _config: Config, tx: BoundSender<Result<bool>>) {
+ tx.send(Ok(false))
+ .expect("configuration channel disconnect");
+ }
+}
+
+fn stop_watch(ws: &WatchState, meta_tx: &Sender<MetaEvent>) {
+ unsafe {
+ let cio = CancelIo(ws.dir_handle);
+ let ch = CloseHandle(ws.dir_handle);
+ // have to wait for it, otherwise we leak the memory allocated for there read request
+ if cio != 0 && ch != 0 {
+ while WaitForSingleObjectEx(ws.complete_sem, INFINITE, 1) != WAIT_OBJECT_0 {
+ // drain the apc queue, fix for https://github.com/notify-rs/notify/issues/287#issuecomment-801465550
+ }
+ }
+ CloseHandle(ws.complete_sem);
+ }
+ let _ = meta_tx.send(MetaEvent::SingleWatchComplete);
+}
+
+fn start_read(
+ rd: &ReadData,
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ handle: HANDLE,
+ action_tx: Sender<Action>,
+) {
+ let request = Box::new(ReadDirectoryRequest {
+ event_handler,
+ handle,
+ buffer: [0u8; BUF_SIZE as usize],
+ data: rd.clone(),
+ action_tx,
+ });
+
+ let flags = FILE_NOTIFY_CHANGE_FILE_NAME
+ | FILE_NOTIFY_CHANGE_DIR_NAME
+ | FILE_NOTIFY_CHANGE_ATTRIBUTES
+ | FILE_NOTIFY_CHANGE_SIZE
+ | FILE_NOTIFY_CHANGE_LAST_WRITE
+ | FILE_NOTIFY_CHANGE_CREATION
+ | FILE_NOTIFY_CHANGE_SECURITY;
+
+ let monitor_subdir = if request.data.file.is_none() && request.data.is_recursive {
+ 1
+ } else {
+ 0
+ };
+
+ unsafe {
+ let overlapped = alloc::alloc_zeroed(alloc::Layout::new::<OVERLAPPED>()) as *mut OVERLAPPED;
+ // When using callback based async requests, we are allowed to use the hEvent member
+ // for our own purposes
+
+ let request = Box::leak(request);
+ (*overlapped).hEvent = request as *mut _ as _;
+
+ // This is using an asynchronous call with a completion routine for receiving notifications
+ // An I/O completion port would probably be more performant
+ let ret = ReadDirectoryChangesW(
+ handle,
+ request.buffer.as_mut_ptr() as *mut c_void,
+ BUF_SIZE,
+ monitor_subdir,
+ flags,
+ &mut 0u32 as *mut u32, // not used for async reqs
+ overlapped,
+ Some(handle_event),
+ );
+
+ if ret == 0 {
+ // error reading. retransmute request memory to allow drop.
+ // Because of the error, ownership of the `overlapped` alloc was not passed
+ // over to `ReadDirectoryChangesW`.
+ // So we can claim ownership back.
+ let _overlapped = Box::from_raw(overlapped);
+ let request = Box::from_raw(request);
+ report_read_failure(&request, GetLastError());
+ request.unwatch();
+ ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
+ }
+ }
+}
+
+fn report_read_failure(request:&ReadDirectoryRequest,code:u32) {
+ if let Ok(mut handler)=request.event_handler.lock() {
+ handler.handle_event(Err(Error::io(std::io::Error::from_raw_os_error(code as i32)).add_path(request.data.dir.clone())));
+ }
+}
+
+unsafe extern "system" fn handle_event(
+ error_code: u32,
+ bytes_written: u32,
+ overlapped: *mut OVERLAPPED,
+) {
+ let overlapped: Box<OVERLAPPED> = Box::from_raw(overlapped);
+ let request: Box<ReadDirectoryRequest> = Box::from_raw(overlapped.hEvent as *mut _);
+
+ match error_code {
+ ERROR_OPERATION_ABORTED => {
+ // received when dir is unwatched or watcher is shutdown; return and let overlapped/request get drop-cleaned
+ ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
+ return;
+ }
+ ERROR_ACCESS_DENIED => {
+ // This could happen when the watched directory is deleted or trashed, first check if it's the case.
+ // If so, unwatch the directory and return, otherwise, continue to handle the event.
+ if !request.data.dir.exists() {
+ report_read_failure(&request,error_code);
+ request.unwatch();
+ ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
+ return;
+ }
+ }
+ ERROR_SUCCESS => {
+ // Success, continue to handle the event
+ }
+ _ => {
+ // Some unidentified error occurred, log and unwatch the directory, then return.
+ log::error!(
+ "unknown error in ReadDirectoryChangesW for directory {}: {}",
+ request.data.dir.display(),
+ error_code
+ );
+ report_read_failure(&request,error_code);
+ request.unwatch();
+ ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
+ return;
+ }
+ }
+
+ // Get the next request queued up as soon as possible
+ start_read(
+ &request.data,
+ request.event_handler.clone(),
+ request.handle,
+ request.action_tx,
+ );
+
+ // An overflow returns a successful completion with zero bytes. Keep the
+ // watcher armed and report only the originating subtree; never parse an
+ // empty FILE_NOTIFY_INFORMATION buffer.
+ if bytes_written == 0 {
+ if let Ok(mut handler)=request.event_handler.lock() {
+ handler.handle_event(Ok(Event::new(EventKind::Other).add_path(request.data.dir.clone()).set_flag(Flag::Rescan)));
+ }
+ return;
+ }
+
+ // The FILE_NOTIFY_INFORMATION struct has a variable length due to the variable length
+ // string as its last member. Each struct contains an offset for getting the next entry in
+ // the buffer.
+ let mut cur_offset: *const u8 = request.buffer.as_ptr();
+ // In Wine, FILE_NOTIFY_INFORMATION structs are packed placed in the buffer;
+ // they are aligned to 16bit (WCHAR) boundary instead of 32bit required by FILE_NOTIFY_INFORMATION.
+ // Hence, we need to use `read_unaligned` here to avoid UB.
+ let mut cur_entry = ptr::read_unaligned(cur_offset as *const FILE_NOTIFY_INFORMATION);
+ loop {
+ // filename length is size in bytes, so / 2
+ let len = cur_entry.FileNameLength as usize / 2;
+ let encoded_path: &[u16] = slice::from_raw_parts(
+ cur_offset.offset(std::mem::offset_of!(FILE_NOTIFY_INFORMATION, FileName) as isize)
+ as _,
+ len,
+ );
+ // prepend root to get a full path
+ let path = request
+ .data
+ .dir
+ .join(PathBuf::from(OsString::from_wide(encoded_path)));
+
+ // if we are watching a single file, ignore the event unless the path is exactly
+ // the watched file
+ let skip = match request.data.file {
+ None => false,
+ Some(ref watch_path) => *watch_path != path,
+ };
+
+ if !skip {
+ log::trace!(
+ "Event: path = `{}`, action = {:?}",
+ path.display(),
+ cur_entry.Action
+ );
+
+ let newe = Event::new(EventKind::Any).add_path(path);
+
+ fn emit_event(event_handler: &Mutex<dyn EventHandler>, res: Result<Event>) {
+ if let Ok(mut guard) = event_handler.lock() {
+ let f: &mut dyn EventHandler = &mut *guard;
+ f.handle_event(res);
+ }
+ }
+
+ let event_handler = |res| emit_event(&request.event_handler, res);
+
+ if cur_entry.Action == FILE_ACTION_RENAMED_OLD_NAME {
+ let mode = RenameMode::From;
+ let kind = ModifyKind::Name(mode);
+ let kind = EventKind::Modify(kind);
+ let ev = newe.set_kind(kind);
+ event_handler(Ok(ev))
+ } else {
+ match cur_entry.Action {
+ FILE_ACTION_RENAMED_NEW_NAME => {
+ let kind = EventKind::Modify(ModifyKind::Name(RenameMode::To));
+ let ev = newe.set_kind(kind);
+ event_handler(Ok(ev));
+ }
+ FILE_ACTION_ADDED => {
+ let kind = EventKind::Create(CreateKind::Any);
+ let ev = newe.set_kind(kind);
+ event_handler(Ok(ev));
+ }
+ FILE_ACTION_REMOVED => {
+ let kind = EventKind::Remove(RemoveKind::Any);
+ let ev = newe.set_kind(kind);
+ event_handler(Ok(ev));
+ }
+ FILE_ACTION_MODIFIED => {
+ let kind = EventKind::Modify(ModifyKind::Any);
+ let ev = newe.set_kind(kind);
+ event_handler(Ok(ev));
+ }
+ _ => (),
+ };
+ }
+ }
+
+ if cur_entry.NextEntryOffset == 0 {
+ break;
+ }
+ cur_offset = cur_offset.offset(cur_entry.NextEntryOffset as isize);
+ cur_entry = ptr::read_unaligned(cur_offset as *const FILE_NOTIFY_INFORMATION);
+ }
+}
+
+/// Watcher implementation based on ReadDirectoryChanges
+#[derive(Debug)]
+pub struct ReadDirectoryChangesWatcher {
+ tx: Sender<Action>,
+ cmd_rx: Receiver<Result<PathBuf>>,
+ wakeup_sem: HANDLE,
+}
+
+impl ReadDirectoryChangesWatcher {
+ pub fn create(
+ event_handler: Arc<Mutex<dyn EventHandler>>,
+ meta_tx: Sender<MetaEvent>,
+ ) -> Result<ReadDirectoryChangesWatcher> {
+ let (cmd_tx, cmd_rx) = unbounded();
+
+ let wakeup_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
+ if wakeup_sem.is_null() || wakeup_sem == INVALID_HANDLE_VALUE {
+ return Err(Error::generic("Failed to create wakeup semaphore."));
+ }
+
+ let action_tx =
+ ReadDirectoryChangesServer::start(event_handler, meta_tx, cmd_tx, wakeup_sem);
+
+ Ok(ReadDirectoryChangesWatcher {
+ tx: action_tx,
+ cmd_rx,
+ wakeup_sem,
+ })
+ }
+
+ fn wakeup_server(&mut self) {
+ // breaks the server out of its wait state. right now this is really just an optimization,
+ // so that if you add a watch you don't block for 100ms in watch() while the
+ // server sleeps.
+ unsafe {
+ ReleaseSemaphore(self.wakeup_sem, 1, ptr::null_mut());
+ }
+ }
+
+ fn send_action_require_ack(&mut self, action: Action, pb: &PathBuf) -> Result<()> {
+ self.tx
+ .send(action)
+ .map_err(|_| Error::generic("Error sending to internal channel"))?;
+
+ // wake 'em up, we don't want to wait around for the ack
+ self.wakeup_server();
+
+ let ack_pb = self
+ .cmd_rx
+ .recv()
+ .map_err(|_| Error::generic("Error receiving from command channel"))?
+ .map_err(|e| Error::generic(&format!("Error in watcher: {:?}", e)))?;
+
+ if pb.as_path() != ack_pb.as_path() {
+ Err(Error::generic(&format!(
+ "Expected ack for {:?} but got \
+ ack for {:?}",
+ pb, ack_pb
+ )))
+ } else {
+ Ok(())
+ }
+ }
+
+ fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ // path must exist and be either a file or directory
+ if !pb.is_dir() && !pb.is_file() {
+ return Err(Error::generic(
+ "Input watch path is neither a file nor a directory.",
+ ));
+ }
+ self.send_action_require_ack(Action::Watch(pb.clone(), recursive_mode), &pb)
+ }
+
+ fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
+ let pb = if path.is_absolute() {
+ path.to_owned()
+ } else {
+ let p = env::current_dir().map_err(Error::io)?;
+ p.join(path)
+ };
+ let res = self
+ .tx
+ .send(Action::Unwatch(pb))
+ .map_err(|_| Error::generic("Error sending to internal channel"));
+ self.wakeup_server();
+ res
+ }
+}
+
+impl Watcher for ReadDirectoryChangesWatcher {
+ fn new<F: EventHandler>(event_handler: F, _config: Config) -> Result<Self> {
+ // create dummy channel for meta event
+ // TODO: determine the original purpose of this - can we remove it?
+ let (meta_tx, _) = unbounded();
+ let event_handler = Arc::new(Mutex::new(event_handler));
+ Self::create(event_handler, meta_tx)
+ }
+
+ fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
+ self.watch_inner(path, recursive_mode)
+ }
+
+ fn unwatch(&mut self, path: &Path) -> Result<()> {
+ self.unwatch_inner(path)
+ }
+
+ fn configure(&mut self, config: Config) -> Result<bool> {
+ let (tx, rx) = bounded(1);
+ self.tx.send(Action::Configure(config, tx))?;
+ rx.recv()?
+ }
+
+ fn kind() -> crate::WatcherKind {
+ WatcherKind::ReadDirectoryChangesWatcher
+ }
+}
+
+impl Drop for ReadDirectoryChangesWatcher {
+ fn drop(&mut self) {
+ let _ = self.tx.send(Action::Stop);
+ // better wake it up
+ self.wakeup_server();
+ }
+}
+
+// `ReadDirectoryChangesWatcher` is not Send/Sync because of the semaphore Handle.
+// As said elsewhere it's perfectly safe to send it across threads.
+unsafe impl Send for ReadDirectoryChangesWatcher {}
+// Because all public methods are `&mut self` it's also perfectly safe to share references.
+unsafe impl Sync for ReadDirectoryChangesWatcher {}
diff --git a/packaging/VectorDash-Rust.iss b/packaging/VectorDash-Rust.iss
index aaa7593..ffbe87c 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.25
-VersionInfoVersion=0.3.25.0
+AppVersion=0.3.40
+VersionInfoVersion=0.3.40.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.25-x64
+OutputBaseFilename=VectorDash-Rust-Setup-0.3.40-x64
SetupIconFile=VectorDash.ico
UninstallDisplayIcon={app}\VectorDash.exe
LicenseFile=..\LICENSE