Compare commits
200 Commits
site
...
alpha-v202
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05a9aacd1e | ||
|
|
701ebe3f07 | ||
|
|
f49b8f60dc | ||
|
|
39615f49f3 | ||
|
|
3d7a0ee936 | ||
|
|
9faee02e04 | ||
|
|
dfff3a848b | ||
|
|
aaf0336733 | ||
|
|
5b906cb3a4 | ||
|
|
0a40f12a6a | ||
|
|
033759598a | ||
|
|
871b62fbd3 | ||
|
|
aa310b25df | ||
|
|
dbb12e96fe | ||
|
|
c795f118d0 | ||
|
|
d96d6efd57 | ||
|
|
67623d848b | ||
|
|
45d72297b3 | ||
|
|
4f86b97e8d | ||
|
|
b6dd6189a2 | ||
|
|
ba07bafc97 | ||
|
|
6d86770abf | ||
|
|
e23ba0ae27 | ||
|
|
7a97f24a0e | ||
|
|
20f34ab9d1 | ||
|
|
19b31cc96a | ||
|
|
e5ed863d5d | ||
|
|
4f7f5a31e4 | ||
|
|
439e2b7f66 | ||
|
|
048d27243d | ||
|
|
58e129cdbc | ||
|
|
713b486750 | ||
|
|
7d66e2f8e1 | ||
|
|
cd6847d59e | ||
|
|
74c9841ad7 | ||
|
|
ba41854f0e | ||
|
|
6532ee125a | ||
|
|
c9698b853e | ||
|
|
db16f2ff5e | ||
|
|
1e5d83d4a3 | ||
|
|
062de2656e | ||
|
|
65d14ebf6f | ||
|
|
0b5149ba8d | ||
|
|
c23a3c1caf | ||
|
|
44e2870697 | ||
|
|
802b6b77d9 | ||
|
|
bb09fcfd6f | ||
|
|
c8ac12f3dc | ||
|
|
fbfda2f15c | ||
|
|
c4c7737e83 | ||
|
|
c24c60b433 | ||
|
|
21532de941 | ||
|
|
f92efd72df | ||
|
|
6e41328f21 | ||
|
|
5b2b4cd569 | ||
|
|
494aeb9533 | ||
|
|
8272e68934 | ||
|
|
7ba20c1e83 | ||
|
|
3384b9acd0 | ||
|
|
8b36ff6b00 | ||
|
|
acb35cb5df | ||
|
|
a8bda0a11b | ||
|
|
4acbe17e1e | ||
|
|
09759d204c | ||
|
|
7a01ef6952 | ||
|
|
1c010ddc22 | ||
|
|
0df5c7882d | ||
|
|
2d138f1564 | ||
|
|
c9ee81c5dc | ||
|
|
04fa74e8d8 | ||
|
|
b42ed35596 | ||
|
|
75e1a82ff0 | ||
|
|
2af2156526 | ||
|
|
568ada8992 | ||
|
|
0987946cff | ||
|
|
81b03f05b6 | ||
|
|
ee71a00c6f | ||
|
|
adcaa8a387 | ||
|
|
4a03f1675e | ||
|
|
50c304fce5 | ||
|
|
aa4d4fd12e | ||
|
|
b31f0b57da | ||
|
|
d3a577b488 | ||
|
|
fbb0927401 | ||
|
|
687d6403a3 | ||
|
|
1738dd2405 | ||
|
|
8c286a4856 | ||
|
|
0331b40ae2 | ||
|
|
d53c3fa7e5 | ||
|
|
3c14d60be7 | ||
|
|
765a16a4e8 | ||
|
|
886ded9575 | ||
|
|
831f6eb72b | ||
|
|
45efb08b23 | ||
|
|
fdc7d8fd84 | ||
|
|
690ace2d1f | ||
|
|
a267a00716 | ||
|
|
536cab3491 | ||
|
|
e49af5855b | ||
|
|
9012cd901b | ||
|
|
0d6e3853f2 | ||
|
|
8754b1bc77 | ||
|
|
ec5751711f | ||
|
|
0995c90cc0 | ||
|
|
dede400296 | ||
|
|
65ff44eb50 | ||
|
|
2c06c8dcc2 | ||
|
|
bc56eec35e | ||
|
|
388d389ba4 | ||
|
|
a1a4cb50d0 | ||
|
|
a7ed9adaae | ||
|
|
f8f08f4160 | ||
|
|
c0afae2296 | ||
|
|
176f983dc9 | ||
|
|
01a87ed478 | ||
|
|
18b4f9d078 | ||
|
|
fd3afc2493 | ||
|
|
0ad207e318 | ||
|
|
2e40945c2d | ||
|
|
54d53b882f | ||
|
|
848d718373 | ||
|
|
ec83e9b839 | ||
|
|
ce859aa0e7 | ||
|
|
1f4889fe66 | ||
|
|
2a2ea1b8ef | ||
|
|
b2a50d9870 | ||
|
|
cca72a9d6a | ||
|
|
ef0e85b053 | ||
|
|
2624d32b50 | ||
|
|
9c42da5745 | ||
|
|
454acb5ded | ||
|
|
2a691f68db | ||
|
|
c4de154410 | ||
|
|
670aae9f2e | ||
|
|
f3b4e5e61d | ||
|
|
4c4f01af43 | ||
|
|
79d7eb9795 | ||
|
|
d1ed826714 | ||
|
|
2e8286d2b3 | ||
|
|
cb9ebaadad | ||
|
|
c295c9f2b5 | ||
|
|
a4b11089c0 | ||
|
|
6f29542528 | ||
|
|
dcd0d73848 | ||
|
|
0e8c8fb61a | ||
|
|
42bdd559ef | ||
|
|
3a6c97272d | ||
|
|
f53a3746d3 | ||
|
|
23145a05f5 | ||
|
|
5b86b0b50d | ||
|
|
dc1b1783b6 | ||
|
|
3dc520abea | ||
|
|
792b3009dd | ||
|
|
6ee7f219f5 | ||
|
|
3db1ed9dc5 | ||
|
|
7a7ef5d9ca | ||
|
|
4c42cf4d52 | ||
|
|
405b711e16 | ||
|
|
83705e26f5 | ||
|
|
434927160c | ||
|
|
ec2e04a464 | ||
|
|
a17ec689a3 | ||
|
|
eda4d380e0 | ||
|
|
f9b155ba6e | ||
|
|
4a62008b1f | ||
|
|
a08cee7965 | ||
|
|
a7c480af62 | ||
|
|
f4790d5763 | ||
|
|
ed52a9e800 | ||
|
|
2fcd808f09 | ||
|
|
9d15286f7d | ||
|
|
537bd0f3ec | ||
|
|
648241604f | ||
|
|
c6f3d9d945 | ||
|
|
65e54f108a | ||
|
|
58f8a774b5 | ||
|
|
0bf280d3ec | ||
|
|
d2d4746d5c | ||
|
|
91db7c0098 | ||
|
|
87908d982f | ||
|
|
40544fc551 | ||
|
|
f34fdb0289 | ||
|
|
e601a42f41 | ||
|
|
de627c2478 | ||
|
|
46d9aaed48 | ||
|
|
6b96b5caf6 | ||
|
|
595c48ca59 | ||
|
|
fd92ff5e9b | ||
|
|
a39b346a75 | ||
|
|
deac10caa2 | ||
|
|
0e1e0ff47a | ||
|
|
a645edbc19 | ||
|
|
48f1fb0b50 | ||
|
|
1aede09834 | ||
|
|
d51b76f992 | ||
|
|
8e66fb4c19 | ||
|
|
a2843a0cf3 | ||
|
|
38fb8a7370 | ||
|
|
be5a8bb300 | ||
|
|
ce040c75fd |
@@ -1,2 +1,2 @@
|
||||
HOTSPOT_THRESHOLD=10.0
|
||||
AVERAGE_THRESHOLD=9.89
|
||||
AVERAGE_THRESHOLD=9.92
|
||||
|
||||
137
.github/scripts/prefetch-tauri-nsis.ps1
vendored
Normal file
137
.github/scripts/prefetch-tauri-nsis.ps1
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$nsisUrl = "https://github.com/tauri-apps/binary-releases/releases/download/nsis-3.11/nsis-3.11.zip"
|
||||
$nsisSha1 = "EF7FF767E5CBD9EDD22ADD3A32C9B8F4500BB10D"
|
||||
$tauriUtilsUrl = "https://github.com/tauri-apps/nsis-tauri-utils/releases/download/nsis_tauri_utils-v0.5.3/nsis_tauri_utils.dll"
|
||||
$tauriUtilsSha1 = "75197FEE3C6A814FE035788D1C34EAD39349B860"
|
||||
$tauriUtilsRelativePath = "Plugins\x86-unicode\additional\nsis_tauri_utils.dll"
|
||||
|
||||
$nsisRequiredFiles = @(
|
||||
"makensis.exe",
|
||||
"Bin\makensis.exe",
|
||||
"Stubs\lzma-x86-unicode",
|
||||
"Stubs\lzma_solid-x86-unicode",
|
||||
"Include\MUI2.nsh",
|
||||
"Include\FileFunc.nsh",
|
||||
"Include\x64.nsh",
|
||||
"Include\nsDialogs.nsh",
|
||||
"Include\WinMessages.nsh",
|
||||
"Include\Win\COM.nsh",
|
||||
"Include\Win\Propkey.nsh",
|
||||
"Include\Win\RestartManager.nsh"
|
||||
)
|
||||
|
||||
function Get-UpperSha1 {
|
||||
param([Parameter(Mandatory = $true)][string]$Path)
|
||||
|
||||
return (Get-FileHash -Algorithm SHA1 -LiteralPath $Path).Hash.ToUpperInvariant()
|
||||
}
|
||||
|
||||
function Test-FileSha1 {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Path,
|
||||
[Parameter(Mandatory = $true)][string]$ExpectedSha1
|
||||
)
|
||||
|
||||
return (Test-Path -LiteralPath $Path) -and ((Get-UpperSha1 -Path $Path) -eq $ExpectedSha1)
|
||||
}
|
||||
|
||||
function Save-VerifiedDownload {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Uri,
|
||||
[Parameter(Mandatory = $true)][string]$OutFile,
|
||||
[Parameter(Mandatory = $true)][string]$ExpectedSha1
|
||||
)
|
||||
|
||||
$parent = Split-Path -Parent $OutFile
|
||||
New-Item -ItemType Directory -Force -Path $parent | Out-Null
|
||||
|
||||
$tempFile = "$OutFile.download"
|
||||
for ($attempt = 1; $attempt -le 5; $attempt++) {
|
||||
try {
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath $tempFile
|
||||
Invoke-WebRequest -Uri $Uri -OutFile $tempFile -TimeoutSec 120
|
||||
|
||||
$actualSha1 = Get-UpperSha1 -Path $tempFile
|
||||
if ($actualSha1 -ne $ExpectedSha1) {
|
||||
throw "SHA1 mismatch for $Uri. Expected $ExpectedSha1, got $actualSha1."
|
||||
}
|
||||
|
||||
Move-Item -Force -LiteralPath $tempFile -Destination $OutFile
|
||||
return
|
||||
} catch {
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath $tempFile
|
||||
if ($attempt -eq 5) {
|
||||
throw
|
||||
}
|
||||
|
||||
$delaySeconds = [Math]::Min(30, 5 * $attempt)
|
||||
Write-Warning "Download attempt ${attempt} failed: $($_.Exception.Message). Retrying in ${delaySeconds}s."
|
||||
Start-Sleep -Seconds $delaySeconds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Find-MissingFile {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Root,
|
||||
[Parameter(Mandatory = $true)][string[]]$RelativePaths
|
||||
)
|
||||
|
||||
foreach ($relativePath in $RelativePaths) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $Root $relativePath))) {
|
||||
return $relativePath
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
|
||||
throw "LOCALAPPDATA is required to resolve Tauri's Windows tool cache."
|
||||
}
|
||||
|
||||
$tauriToolsPath = Join-Path $env:LOCALAPPDATA "tauri"
|
||||
$nsisPath = Join-Path $tauriToolsPath "NSIS"
|
||||
$downloadRoot = if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) {
|
||||
[System.IO.Path]::GetTempPath()
|
||||
} else {
|
||||
$env:RUNNER_TEMP
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $tauriToolsPath | Out-Null
|
||||
|
||||
$missingNsisFile = Find-MissingFile -Root $nsisPath -RelativePaths $nsisRequiredFiles
|
||||
if ($missingNsisFile) {
|
||||
Write-Host "Tauri NSIS cache is missing $missingNsisFile; downloading NSIS 3.11."
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -LiteralPath $nsisPath
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -LiteralPath (Join-Path $tauriToolsPath "nsis-3.11")
|
||||
|
||||
$zipPath = Join-Path $downloadRoot "nsis-3.11.zip"
|
||||
Save-VerifiedDownload -Uri $nsisUrl -OutFile $zipPath -ExpectedSha1 $nsisSha1
|
||||
Expand-Archive -Force -LiteralPath $zipPath -DestinationPath $tauriToolsPath
|
||||
|
||||
$extractedNsisPath = Join-Path $tauriToolsPath "nsis-3.11"
|
||||
if (-not (Test-Path -LiteralPath $extractedNsisPath)) {
|
||||
throw "Downloaded NSIS archive did not contain the expected nsis-3.11 directory."
|
||||
}
|
||||
|
||||
Move-Item -Force -LiteralPath $extractedNsisPath -Destination $nsisPath
|
||||
} else {
|
||||
Write-Host "Tauri NSIS cache already contains NSIS 3.11."
|
||||
}
|
||||
|
||||
$tauriUtilsPath = Join-Path $nsisPath $tauriUtilsRelativePath
|
||||
if (-not (Test-FileSha1 -Path $tauriUtilsPath -ExpectedSha1 $tauriUtilsSha1)) {
|
||||
Write-Host "Downloading Tauri NSIS utility plugin."
|
||||
Save-VerifiedDownload -Uri $tauriUtilsUrl -OutFile $tauriUtilsPath -ExpectedSha1 $tauriUtilsSha1
|
||||
} else {
|
||||
Write-Host "Tauri NSIS utility plugin is already cached."
|
||||
}
|
||||
|
||||
$missingFile = Find-MissingFile -Root $nsisPath -RelativePaths ($nsisRequiredFiles + @($tauriUtilsRelativePath))
|
||||
if ($missingFile) {
|
||||
throw "Tauri NSIS toolchain is incomplete after prefetch; missing $missingFile."
|
||||
}
|
||||
|
||||
Write-Host "Tauri NSIS toolchain ready at $nsisPath."
|
||||
21
.github/workflows/release-stable.yml
vendored
21
.github/workflows/release-stable.yml
vendored
@@ -274,7 +274,8 @@ jobs:
|
||||
wget \
|
||||
patchelf \
|
||||
build-essential \
|
||||
file
|
||||
file \
|
||||
rpm
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
@@ -326,7 +327,7 @@ jobs:
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,appimage
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,rpm,appimage
|
||||
|
||||
- name: Validate Linux bundles
|
||||
run: |
|
||||
@@ -334,6 +335,7 @@ jobs:
|
||||
installers=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
@@ -341,7 +343,7 @@ jobs:
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no AppImage or deb bundle."
|
||||
echo "::error::Linux build produced no AppImage, deb or rpm bundle."
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
@@ -356,6 +358,7 @@ jobs:
|
||||
path: |
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz
|
||||
@@ -398,6 +401,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Cache Tauri Windows tools
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~\AppData\Local\tauri
|
||||
key: ${{ runner.os }}-tauri-tools-nsis-3.11-nsis-tauri-utils-0.5.3
|
||||
|
||||
- name: Prefetch Tauri NSIS toolchain
|
||||
shell: pwsh
|
||||
run: ./.github/scripts/prefetch-tauri-nsis.ps1
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -664,12 +677,14 @@ jobs:
|
||||
updater-x86_64/*.app.tar.gz.sig
|
||||
linux-x86_64-bundles/*.deb
|
||||
linux-x86_64-bundles/*.deb.sig
|
||||
linux-x86_64-bundles/*.rpm
|
||||
linux-x86_64-bundles/*.AppImage
|
||||
linux-x86_64-bundles/*.AppImage.sig
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz.sig
|
||||
linux-x86_64-bundles/*/*.deb
|
||||
linux-x86_64-bundles/*/*.deb.sig
|
||||
linux-x86_64-bundles/*/*.rpm
|
||||
linux-x86_64-bundles/*/*.AppImage
|
||||
linux-x86_64-bundles/*/*.AppImage.sig
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz
|
||||
|
||||
21
.github/workflows/release.yml
vendored
21
.github/workflows/release.yml
vendored
@@ -328,7 +328,8 @@ jobs:
|
||||
wget \
|
||||
patchelf \
|
||||
build-essential \
|
||||
file
|
||||
file \
|
||||
rpm
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
@@ -380,7 +381,7 @@ jobs:
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,appimage
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,rpm,appimage
|
||||
|
||||
- name: Validate Linux bundles
|
||||
run: |
|
||||
@@ -388,6 +389,7 @@ jobs:
|
||||
installers=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
@@ -395,7 +397,7 @@ jobs:
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no AppImage or deb bundle."
|
||||
echo "::error::Linux build produced no AppImage, deb or rpm bundle."
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
@@ -410,6 +412,7 @@ jobs:
|
||||
path: |
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz
|
||||
@@ -452,6 +455,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Cache Tauri Windows tools
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~\AppData\Local\tauri
|
||||
key: ${{ runner.os }}-tauri-tools-nsis-3.11-nsis-tauri-utils-0.5.3
|
||||
|
||||
- name: Prefetch Tauri NSIS toolchain
|
||||
shell: pwsh
|
||||
run: ./.github/scripts/prefetch-tauri-nsis.ps1
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -715,12 +728,14 @@ jobs:
|
||||
updater-x86_64/*.app.tar.gz.sig
|
||||
linux-x86_64-bundles/*.deb
|
||||
linux-x86_64-bundles/*.deb.sig
|
||||
linux-x86_64-bundles/*.rpm
|
||||
linux-x86_64-bundles/*.AppImage
|
||||
linux-x86_64-bundles/*.AppImage.sig
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz.sig
|
||||
linux-x86_64-bundles/*/*.deb
|
||||
linux-x86_64-bundles/*/*.deb.sig
|
||||
linux-x86_64-bundles/*/*.rpm
|
||||
linux-x86_64-bundles/*/*.AppImage
|
||||
linux-x86_64-bundles/*/*.AppImage.sig
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz
|
||||
|
||||
31
AGENTS.md
31
AGENTS.md
@@ -22,7 +22,7 @@ Run `/laputa-next-task` — fetches next task (To Rework first, then Open), move
|
||||
- Work on `main` branch — **no branches, no PRs, ever**. Pre-commit and pre-push block work from any other branch.
|
||||
- Commit every 20–30 min: `feat:`, `fix:`, `refactor:`, `test:`, `docs:`
|
||||
- **⛔ NEVER use --no-verify**
|
||||
- For UI tasks: open `ui-design.pen` first, study visual language, design in light mode
|
||||
- For UI tasks: open `ui-design.pen` first, study visual language, design in light mode. You don't need Pencil to use it – you can open it as a JSON file.
|
||||
|
||||
### 1c. When done
|
||||
|
||||
@@ -47,16 +47,14 @@ bash ~/.openclaw/skills/tolaria-qa/scripts/screenshot.sh /tmp/qa-native.png
|
||||
|
||||
Use `osascript` for keyboard interactions. Write result as Todoist comment (✅ or ❌). **⚠️ WKWebView:** `osascript keystroke` blocked inside editor — rely on Playwright for text input features.
|
||||
|
||||
After both phases pass, add a **completion comment** to the Todoist task before running `/laputa-done`. The comment must include:
|
||||
- What was implemented (1–2 lines)
|
||||
After both phases pass, add a **completion comment** to the Todoist task. The comment must include:
|
||||
- What was implemented (a few lines covering logic and UX/UI)
|
||||
- QA: what was tested and how (Playwright / native screenshot / osascript)
|
||||
- Refactoring: any files refactored to meet the CodeScene gate (or "none needed")
|
||||
- ADRs: any new/updated ADRs (or "none")
|
||||
- Docs: any updated docs (ARCHITECTURE.md, ABSTRACTIONS.md, etc.) (or "none")
|
||||
- Code health: final Hotspot and Average scores after push
|
||||
|
||||
Then run `/laputa-done <task_id>` → moves to In Review, notifies Brian, self-dispatches next task.
|
||||
|
||||
---
|
||||
|
||||
## 2. Development Process
|
||||
@@ -73,6 +71,22 @@ Red → Green → Refactor → Commit. One cycle per commit. For bugs: write fai
|
||||
|
||||
**Test quality (Kent Beck's Desiderata):** Isolated · Deterministic · Fast · Behavioral · Structure-insensitive · Specific · Predictive. Fix flaky tests first. Prefer E2E over unit tests for user flows.
|
||||
|
||||
### Localization (mandatory for UI copy)
|
||||
|
||||
All user-facing UI labels/copy must live in `src/lib/locales/en.json` and be translated into every target listed in `lara.yaml`. When adding or changing interface copy:
|
||||
|
||||
```bash
|
||||
pnpm l10n:translate
|
||||
```
|
||||
|
||||
Use `pnpm l10n:translate:force` only when intentionally regenerating existing translations. Commit `src/lib/locales/*.json`, `lara.yaml`/`lara.lock` changes if produced, and verify placeholders/product names stayed intact.
|
||||
|
||||
### Product analytics (mandatory for meaningful features)
|
||||
|
||||
New features should almost always emit a PostHog event so we can see whether users actually discover and use them. Skip instrumentation only for very small changes where a dedicated event would create noise. Use clear, stable event names, avoid PII or note content, and include only safe metadata that helps evaluate adoption and failures.
|
||||
|
||||
When adding or changing a meaningful user-facing feature, include the event name(s) in the Todoist completion comment alongside QA, docs, and code health. If intentionally not instrumenting a feature, explain why in the completion comment.
|
||||
|
||||
### Code health (mandatory)
|
||||
|
||||
Pre-commit and pre-push hooks enforce **Hotspot Code Health** and **Average Code Health** ≥ thresholds in `.codescene-thresholds`. Both gates block commit/push. Thresholds are a **ratchet** — only go up. When pre-push sees improved remote scores, it updates `.codescene-thresholds`, stages it, and stops so you can commit the new floor with normal verified hooks before pushing again. Never add `// eslint-disable`, `#[allow(...)]`, or `as any`.
|
||||
@@ -122,10 +136,6 @@ Default to `demo-vault-v2/`. If you must use `~/Laputa/` for testing:
|
||||
- **Delete all test notes from disk** when done — do not leave untitled or temporary notes on the filesystem. Run `cd ~/Laputa && git checkout -- . && git clean -fd` to restore the vault to its last committed state.
|
||||
- **Rationale:** test notes pollute the local vault over time, making it a collection of nonsensical untitled files. The vault must stay clean on disk, not just on the remote.
|
||||
|
||||
### UI design
|
||||
|
||||
Open `ui-design.pen` first (light mode). Create `design/<slug>.pen` for the task; on completion merge into `ui-design.pen` and delete it.
|
||||
|
||||
### UI components — mandatory rules
|
||||
|
||||
**Always use shadcn/ui components.** Never use raw HTML form elements (`<input>`, `<select>`, `<button>`, native `<input type="date">`, etc.) for user-facing UI. Every interactive element must use the shadcn/ui equivalent:
|
||||
@@ -155,10 +165,11 @@ Open `ui-design.pen` first (light mode). Create `design/<slug>.pen` for the task
|
||||
- Tauri menu accelerators: `MenuItemBuilder::new(label).accelerator("CmdOrCtrl+1")`
|
||||
- `app.set_menu()` replaces the ENTIRE menu bar — include all submenus
|
||||
- `mock-tauri.ts` silently swallows Tauri calls — not a substitute for native testing
|
||||
|
||||
### QA scripts
|
||||
|
||||
```bash
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/focus-app.sh laputa
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/focus-app.sh Tolaria
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/screenshot.sh /tmp/out.png
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/shortcut.sh "command" "s"
|
||||
```
|
||||
|
||||
20
README.md
20
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
# 💧 Tolaria
|
||||
|
||||
Tolaria is a desktop app for Mac and Linux for managing **markdown knowledge bases**. People use it for a variety of use cases:
|
||||
Tolaria is a desktop app for macOS, Windows, and Linux for managing **markdown knowledge bases**. People use it for a variety of use cases:
|
||||
|
||||
* Operate second brains and personal knowledge
|
||||
* Organize company docs as context for AI
|
||||
@@ -27,13 +27,25 @@ You can find some Loom walkthroughs below — they are short and to the point:
|
||||
- 🔬 **Open source** — Tolaria is free and open source. I built this for [myself](https://x.com/lucaronin) and for sharing it with others.
|
||||
- 📋 **Standards-based** — Notes are markdown files with YAML frontmatter. No proprietary formats, no locked-in data. Everything works with standard tools if you decide to move away from Tolaria.
|
||||
- 🔍 **Types as lenses, not schemas** — Types in Tolaria are navigation aids, not enforcement mechanisms. There's no required fields, no validation, just helpful categories for finding notes.
|
||||
- 🪄**AI-first but not AI-only** — A vault of files works very well with AI agents, but you are free to use whatever you want. We support Claude Code and Codex CLI (for now), but you can edit the vault with any AI you want. We provide an AGENTS file for your agents to figure out.
|
||||
- 🪄**AI-first but not AI-only** — A vault of files works very well with AI agents, but you are free to use whatever you want. We support Claude Code, Codex CLI, and Gemini CLI setup paths, but you can edit the vault with any AI you want. We provide an AGENTS file for your agents to figure out.
|
||||
- ⌨️ **Keyboard-first** — Tolaria is designed for power-users who want to use keyboard as much as possible. A lot of how we designed the Editor and the Command Palette is based on this.
|
||||
- 💪 **Built from real use** — Tolaria was created for manage my personal vault of 10,000+ notes, and I use it every day. Every feature exists because it solved a real problem.
|
||||
|
||||
## Getting started
|
||||
## Installation
|
||||
|
||||
Download the [latest release here](https://github.com/refactoringhq/tolaria/releases/latest/download/Tolaria.app.tar.gz).
|
||||
### Homebrew
|
||||
|
||||
Install via Homebrew on macOS:
|
||||
|
||||
```batch
|
||||
brew install --cask tolaria
|
||||
```
|
||||
|
||||
### Download from releases
|
||||
|
||||
Download the [latest release here](https://refactoringhq.github.io/tolaria/download/) for macOS, Windows, or Linux.
|
||||
|
||||
## Getting started
|
||||
|
||||
When you open Tolaria for the first time you get the chance of cloning the [getting started vault](https://github.com/refactoringhq/tolaria-getting-started) — which gives you a walkthrough of the whole app.
|
||||
|
||||
|
||||
@@ -49,7 +49,13 @@
|
||||
"laputa-qa-reference.md",
|
||||
"attachments/laputa-reference.png"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "rtl-mixed-direction",
|
||||
"reason": "Arabic and mixed English/Arabic paragraphs keep rich editor and raw editor BiDi QA anchored to the fixture.",
|
||||
"files": [
|
||||
"rtl-mixed-direction-qa.md"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
17
demo-vault-v2/rtl-mixed-direction-qa.md
Normal file
17
demo-vault-v2/rtl-mixed-direction-qa.md
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
type: Note
|
||||
topics:
|
||||
- "[[topic-writing]]"
|
||||
---
|
||||
|
||||
# RTL Mixed Direction QA
|
||||
|
||||
مرحبا بالعالم. هذه فقرة عربية لاختبار اتجاه النص من اليمين إلى اليسار داخل محرر تولاريا.
|
||||
|
||||
English text should keep reading left to right when it appears next to Arabic content.
|
||||
|
||||
English then مرحبا بالعالم keeps both scripts readable on one line.
|
||||
|
||||
مرحبا بالعالم then English keeps the Arabic run anchored correctly while preserving the English words.
|
||||
|
||||
Use this note when checking rich editor and raw Markdown editor behavior for automatic LTR/RTL direction.
|
||||
@@ -47,6 +47,7 @@ _icon: shapes # icon assigned to a type
|
||||
_color: blue # color assigned to a type
|
||||
_order: 10 # sort order in the sidebar
|
||||
_sidebar_label: Projects # override label in sidebar
|
||||
_width: wide # rich-editor width override for this note
|
||||
```
|
||||
|
||||
**This convention is universal** — apply it to all future system-level frontmatter fields. When a new feature needs to store configuration in a note's frontmatter (especially in Type notes), use `_field_name` to keep it hidden from normal user-facing surfaces while still stored on-disk as plain text.
|
||||
@@ -87,6 +88,7 @@ classDiagram
|
||||
+Record~string,string[]~ relationships
|
||||
+String[] outgoingLinks
|
||||
+String? status
|
||||
+String? noteWidth
|
||||
+Number? modifiedAt
|
||||
+Number? createdAt
|
||||
+Number wordCount
|
||||
@@ -135,6 +137,7 @@ interface VaultEntry {
|
||||
relationships: Record<string, string[]> // All frontmatter fields containing wikilinks
|
||||
outgoingLinks: string[] // All [[wikilinks]] found in note body
|
||||
status: string | null // Active, Done, Paused, Archived, Dropped
|
||||
noteWidth?: 'normal' | 'wide' | null // Rich-editor width mode from `_width`
|
||||
modifiedAt: number | null // Unix timestamp (seconds)
|
||||
// Note: owner and cadence are now in the generic `properties` map
|
||||
createdAt: number | null // Unix timestamp (seconds)
|
||||
@@ -157,9 +160,15 @@ interface VaultEntry {
|
||||
|---|---|---|
|
||||
| `markdown` or absent | `.md`, `.markdown` | Full Tolaria note model: frontmatter, BlockNote, raw editor, relationships, title sync |
|
||||
| `text` | UTF-8 editable formats such as `.yml`, `.json`, `.ts`, `.py`, `.sh` | Opens through the raw editor without Markdown note semantics |
|
||||
| `binary` | Images, PDFs, archives, other non-text files | Stays a normal vault file; previewable images open in `FilePreview`, unsupported or broken binaries show an explicit fallback |
|
||||
| `binary` | Images, PDFs, archives, other non-text files | Stays a normal vault file; previewable images and PDFs open in `FilePreview`, unsupported or broken binaries show an explicit fallback |
|
||||
|
||||
Image previewability is inferred in the renderer from the filename extension (`src/utils/filePreview.ts`) rather than stored as a new persisted kind. This keeps the filesystem as source of truth and avoids converting assets into proprietary objects.
|
||||
Asset previewability is inferred in the renderer from the filename extension (`src/utils/filePreview.ts`) rather than stored as a new persisted kind. Supported images render through `<img>` and supported PDFs render through the webview's PDF object renderer, both backed by Tauri asset URLs. Runtime asset access is accumulated only for vault roots Tolaria has loaded in the current app session, because Tauri directory forbids cannot be safely reversed after a vault switch. The "open in default app" action re-enters the active-vault command boundary through `open_vault_file_external` before delegating to the native opener. This keeps the filesystem as source of truth and avoids converting assets into proprietary objects.
|
||||
|
||||
### Note Content Freshness
|
||||
|
||||
The renderer may cache recently opened or preloaded markdown content, but cached content is only a performance hint. `useTabManagement` can reuse cached text immediately when it carries the same `modifiedAt` and `fileSize` identity as the current `VaultEntry`; otherwise it validates the cached string with the `validate_note_content` Tauri command. That command re-enters the same vault path boundary checks as `get_note_content` and compares the cached text against the current on-disk file bytes. A mismatch, missing file, or unreadable file falls back to the normal fresh-read path and existing missing/unreadable recovery.
|
||||
|
||||
`useEditorTabSwap` may reuse BlockNote blocks that were already opened successfully or warmed from prefetched raw content, keyed by vault, path, and exact source content. Background warming is limited to likely next large Markdown notes and defers while the editor is unmounted, raw mode is active, or recent typing/navigation is still inside the foreground idle window. Every async editor swap carries a generation and source-content token so stale conversion results cannot overwrite newer file content or dirty editor state.
|
||||
|
||||
### Entity Types (isA / type)
|
||||
|
||||
@@ -175,17 +184,19 @@ Type is determined **purely** from the `type:` frontmatter field — it is never
|
||||
├── some-topic.md ← type: Topic
|
||||
├── AGENTS.md ← canonical Tolaria AI guidance
|
||||
├── CLAUDE.md ← compatibility shim pointing at AGENTS.md
|
||||
├── GEMINI.md ← optional Gemini CLI shim pointing at AGENTS.md
|
||||
├── project.md ← type: Type (definition document)
|
||||
├── person.md ← type: Type (definition document)
|
||||
├── ...
|
||||
└── type/ ← type definition documents
|
||||
```
|
||||
|
||||
New notes are created at the vault root: `{vault}/{slug}.md`. Changing a note's type only requires updating the `type:` field in frontmatter — the file does not move. Moving a note into a user folder is a separate filesystem concern: the folder path changes, but the note keeps the same filename and `type:` value. The `type/` folder exists solely for type definition documents. Legacy `config/` content is still recognized during migration and repair, but Tolaria's managed AI guidance now lives at the vault root.
|
||||
New notes are created at the vault root: `{vault}/{slug}.md`. Changing a note's type only requires updating the `type:` field in frontmatter — the file does not move. Moving a note into a user folder is a separate filesystem concern: the folder path changes, but the note keeps the same filename and `type:` value. Legacy `type/` and `types/` folders are still scanned like other non-hidden vault folders, so existing type documents in those folders continue to work, but new type documents created by Tolaria are written at the vault root. Legacy `config/` content is still recognized during migration and repair, but Tolaria's managed AI guidance now lives at the vault root.
|
||||
|
||||
A `flatten_vault` migration command is available to move existing notes from type-based subfolders to the vault root.
|
||||
|
||||
### Types as Files
|
||||
|
||||
Each entity type can have a corresponding **type document** in the `type/` folder (e.g., `type/project.md`, `type/person.md`). Type documents:
|
||||
Each entity type can have a corresponding **type document**: any markdown note with `type: Type` in its frontmatter. Tolaria creates new type documents at the vault root (e.g., `project.md`, `person.md`) and still reads existing type documents from subfolders. Type documents:
|
||||
|
||||
- Have `type: Type` in their frontmatter (`Is A: Type` also accepted as legacy alias)
|
||||
- Define type metadata: icon, color, order, sidebar label, template, sort, view, visibility
|
||||
@@ -197,7 +208,7 @@ Each entity type can have a corresponding **type document** in the `type/` folde
|
||||
| Property | Type | Description |
|
||||
|----------|------|-------------|
|
||||
| `icon` | string | Type icon as a Phosphor name (kebab-case, e.g., "cooking-pot") |
|
||||
| `color` | string | Accent color: red, purple, blue, green, yellow, orange |
|
||||
| `color` | string | Accent palette key (`red`, `purple`, `blue`, `green`, `yellow`, `orange`, `teal`, `pink`, `gray`) or a valid CSS color value such as `cyan`, `#22d3ee`, or `rgb(34, 211, 238)` |
|
||||
| `order` | number | Sidebar display order (lower = higher priority) |
|
||||
| `sidebar_label` | string | Custom label overriding auto-pluralization |
|
||||
| `template` | string | Markdown template for new notes of this type |
|
||||
@@ -205,7 +216,7 @@ Each entity type can have a corresponding **type document** in the `type/` folde
|
||||
| `view` | string | Default view mode: "all", "editor-list", "editor-only" |
|
||||
| `visible` | bool | Whether type appears in sidebar (default: true) |
|
||||
|
||||
**Type relationship**: When any entry has an `isA` value (e.g., "Project"), the Rust backend automatically adds a `"Type"` entry to its `relationships` map pointing to `[[type/project]]`. This makes the type navigable from the Inspector panel.
|
||||
**Type relationship**: When any entry has an `isA` value (e.g., "Project"), the Rust backend automatically adds a `"Type"` entry to its `relationships` map pointing to `[[project]]`. This makes the type navigable from the Inspector panel while keeping location as an implementation detail.
|
||||
|
||||
**UI behavior**:
|
||||
- Clicking a section group header pins the type document at the top of the NoteList if it exists
|
||||
@@ -290,19 +301,26 @@ type SidebarFilter = 'all' | 'archived' | 'changes' | 'pulse'
|
||||
type SidebarSelection =
|
||||
| { kind: 'filter'; filter: SidebarFilter }
|
||||
| { kind: 'sectionGroup'; type: string } // e.g. type: 'Project'
|
||||
| { kind: 'folder'; path: string }
|
||||
| { kind: 'folder'; path: string; rootPath?: string }
|
||||
| { kind: 'entity'; entry: VaultEntry } // Neighborhood source note
|
||||
| { kind: 'view'; filename: string }
|
||||
```
|
||||
|
||||
`SidebarSelection.kind === 'folder'` is a first-class navigation target, not just a visual highlight.
|
||||
|
||||
- `FolderTree` keeps the folder interaction surface decomposed into `FolderTreeRow`, `FolderNameInput`, `FolderContextMenu`, and disclosure/context-menu hooks so nested row rendering, inline rename, and right-click actions stay isolated. Non-mutating reveal/copy-path menu items stay callback-driven from `App` so filesystem convenience actions do not leak into folder mutation hooks.
|
||||
- `FolderTree` keeps the folder interaction surface decomposed into `FolderTreeRow`, `FolderNameInput`, `FolderContextMenu`, and disclosure/context-menu hooks so nested row rendering, inline rename, and right-click actions stay isolated. The UI wraps backend folder nodes in a synthetic vault-root row with `path: ""` and `rootPath` set to the opened vault so root-level files can be listed without turning the vault root into a mutable folder. Non-mutating reveal/copy-path menu items stay callback-driven from `App` so filesystem convenience actions do not leak into folder mutation hooks.
|
||||
- `src/components/sidebar/sidebarHooks.ts` owns the shared sidebar interaction primitives for menu positioning/dismissal and inline rename input behavior. Folder, Type, and saved View rows keep their domain-specific actions local, but use those primitives so right-click menus and rename fields have the same outside-click, Escape, focus, blur, and submit semantics.
|
||||
- `useFolderActions()` composes `useFolderRename()` and `useFolderDelete()` to keep folder mutations selection-aware while the rest of `App.tsx` only wires the resulting callbacks into `Sidebar` and the command registry.
|
||||
- `useNoteRetargeting()` is the shared retargeting abstraction for note drops and command-palette actions. It owns the "can drop here?" checks, updates `type:` via frontmatter when a note lands on a type section, and delegates folder moves through the same crash-safe rename pipeline used by the backend rename commands.
|
||||
- A successful folder rename reloads the folder tree plus vault entries, rewrites any affected folder-scoped tabs, and updates `SidebarSelection` to the new relative path when the renamed folder stays selected.
|
||||
- Folder deletion clears pending rename state, confirms destructive intent, drops affected folder-scoped tabs, reloads vault data, and resets folder selection if the deleted subtree owned the current selection.
|
||||
|
||||
### Saved Views
|
||||
|
||||
Saved Views live as YAML files under `views/`. Their definition includes user-visible fields (`name`, `icon`, `color`), note-list preferences (`sort`, `listPropertiesDisplay`), filters, and an optional top-level `order` number. The `order` value is stored directly in the YAML document, not in Markdown frontmatter, and lower values render earlier in every saved-View list. Views without an explicit order sort after ordered views by filename for stable fallback behavior.
|
||||
|
||||
The renderer uses `viewOrdering` helpers to convert drag or command-palette move intent into dense order updates before saving each affected view file through `save_view_cmd`. The sidebar treats saved View rows like Type rows for direct customization: double-click starts inline rename, right-click opens edit/rename/icon-color/delete actions, and keyboard users can open that same menu from the focused row while command-palette actions remain responsible for saved View ordering.
|
||||
|
||||
### Neighborhood Mode
|
||||
|
||||
`SidebarSelection.kind === 'entity'` is Tolaria's Neighborhood mode for note-list browsing.
|
||||
@@ -316,6 +334,12 @@ type SidebarSelection =
|
||||
- Plain click / `Enter` open the focused note without replacing the current Neighborhood.
|
||||
- Cmd/Ctrl-click and Cmd/Ctrl-`Enter` open the note and pivot the note list into that note's Neighborhood.
|
||||
|
||||
## Command Surface
|
||||
|
||||
`src/shared/appCommandManifest.json` is the cross-runtime source for stable app command IDs, menu structure, display labels, accelerators, deterministic shortcut QA metadata, and native menu enablement groups. The renderer imports it through `src/hooks/appCommandCatalog.ts`, which derives `APP_COMMAND_IDS`, shortcut lookup maps, Linux titlebar menu sections, native-menu command membership, and test helpers. Tauri includes the same JSON in `src-tauri/src/menu.rs` and uses it to build custom menu items, emit overridden menu item IDs such as the quick-open alias as their primary command IDs, and toggle state-dependent menu items from manifest groups.
|
||||
|
||||
Domain command builders still own context-sensitive command-palette entries, availability, and execution callbacks. The manifest owns metadata that must stay identical across native menus, renderer shortcuts, deterministic QA bridges, and the Linux fallback menu; OS-native menu items such as Undo, Copy/Paste, Services, Quit, and Window controls remain local to the native menu implementation.
|
||||
|
||||
## File System Integration
|
||||
|
||||
### Vault Scanning (Rust)
|
||||
@@ -335,17 +359,19 @@ type SidebarSelection =
|
||||
5. Sorts by `modified_at` descending
|
||||
6. Skips unparseable files with a warning log
|
||||
|
||||
The folder tree hides only the dedicated `type/` directory, since note types already have their own sidebar section. Default vault folders such as `attachments/` and `views/` remain visible alongside user-created folders.
|
||||
All Notes starts from Markdown notes and excludes Markdown files under `attachments/`. `src/utils/allNotesFileVisibility.ts` resolves the installation-local PDF, image, and unsupported-file toggles from app settings; `noteListHelpers` applies that policy only to All Notes filtering and counts. Folder/root browsing continues to show files from the selected folder independently of those All Notes toggles.
|
||||
|
||||
Command-facing vault content is filtered through `vault::filter_gitignored_entries`, `vault::filter_gitignored_folders`, and `vault::filter_gitignored_paths` when the app setting `hide_gitignored_files` is enabled. The cache still stores the complete scan; `list_vault`, `reload_vault`, `list_vault_folders`, and search apply the visibility filter at the boundary before React consumes entries. The filter batches paths through `git check-ignore --no-index --stdin`, so negated and specific `.gitignore` patterns follow Git semantics as closely as the app can reasonably support.
|
||||
The folder tree hides the legacy `type/` directory, since those type documents already appear through the Types sidebar section. Default vault folders such as `attachments/` and `views/` remain visible alongside user-created folders under the synthetic vault-root row.
|
||||
|
||||
Command-facing vault content is filtered through `vault::filter_gitignored_entries`, `vault::filter_gitignored_folders`, and `vault::filter_gitignored_paths` when the app setting `hide_gitignored_files` is enabled. The cache still stores the complete scan; `list_vault`, `reload_vault`, `list_vault_folders`, and search apply the visibility filter at the boundary before React consumes entries. The filter batches paths through `git check-ignore --no-index --stdin`, drains stdout while stdin is still being written, and short-circuits root `.gitignore` detection before walking for nested ignore files, so large ignored folder sets cannot deadlock the native UI while preserving Git semantics as closely as the app can reasonably support.
|
||||
|
||||
A `vault_health_check` command detects stray files in non-protected subfolders and filename-title mismatches. On vault load, a migration banner offers to flatten stray files to the root via `flatten_vault`.
|
||||
|
||||
Command-layer path access is fenced to the active vault before file operations reach the vault backend. `src-tauri/src/commands/vault/boundary.rs` canonicalizes the configured/requested vault root, rejects `..` escapes and absolute paths outside that root, and validates writable targets through the nearest existing ancestor so note reads, saves, deletes, view-file edits, folder mutations, and image attachment writes cannot step outside the active vault. Image attachment commands refresh the runtime asset scope after saving so files created under a previously missing `attachments/` directory can render immediately.
|
||||
Command-layer path access is fenced to the active vault before file operations reach the vault backend. `src-tauri/src/commands/vault/boundary.rs` canonicalizes the configured/requested vault root, rejects `..` escapes and absolute paths outside that root, and validates writable targets through the nearest existing ancestor so note reads, saves, deletes, view-file edits, folder mutations, and image attachment writes cannot step outside the active vault. If the active root itself cannot be canonicalized, the renderer treats `Active vault is not available` the same as no active vault: it clears stale vault state, drops prefetched note content, and shows the missing-vault recovery screen instead of continuing note/view requests against the disappeared path. Image attachment commands add the current vault root to the runtime asset scope after saving so files created under a previously missing `attachments/` directory can render immediately.
|
||||
|
||||
UI-only file actions operate on paths that are already selected or indexed in React state. Reveal-in-Finder and external-open calls route through the Tauri opener plugin, while copy-path uses the browser clipboard API; none of those actions mutate vault contents or bypass the backend write boundary.
|
||||
UI-only file actions operate on paths that are already selected or indexed in React state. Reveal-in-Finder routes through the Tauri opener plugin, external-open routes through the `open_vault_file_external` command and active-vault boundary before invoking the native opener, and copy-path uses the browser clipboard API. Plain-text paste reads the desktop clipboard through `read_text_from_clipboard` in Tauri so macOS WKWebView clipboard permissions do not block the command; browser/mock mode falls back to the Web Clipboard API or mock handlers. None of those actions mutate vault contents or bypass the backend write boundary.
|
||||
|
||||
The local MCP WebSocket bridge follows the same active-vault boundary. `useVaultSwitcher` calls `sync_mcp_bridge_vault` after the persisted selection loads and after each vault switch; the desktop command starts/restarts the bridge with that vault's canonical path, or stops it when there is no selected vault. MCP Node entrypoints require `VAULT_PATH` and fail clearly instead of falling back to `~/Laputa`.
|
||||
The local MCP WebSocket bridge follows the same active-vault boundary. `useVaultSwitcher` calls `sync_mcp_bridge_vault` after the persisted selection loads and after each vault switch; the desktop command starts/restarts the bridge with that vault's canonical path, or stops it when there is no selected vault. App exit uses the same child cleanup path and waits for the bridge process after killing it. MCP Node entrypoints require `VAULT_PATH` and fail clearly instead of falling back to `~/Laputa`. Manual MCP config export uses the same generated stdio entry as registration, so the copied snippet remains scoped to the active vault without writing third-party config files. Desktop snippet copy goes through the native `copy_text_to_clipboard` command, while browser/mock mode keeps using the Web Clipboard API. External-client stdio MCP processes also exit when stdin closes; their UI-bridge reconnect timers and WebSocket are canceled during shutdown so disconnected clients do not leave extra Node processes behind.
|
||||
|
||||
### Vault Caching
|
||||
|
||||
@@ -379,7 +405,7 @@ The `with_frontmatter()` helper wraps this in a read-transform-write cycle on th
|
||||
|
||||
## Git Integration
|
||||
|
||||
Git operations live in `src-tauri/src/git/`. All operations shell out to the `git` CLI (not libgit2).
|
||||
Git operations live in `src-tauri/src/git/`. All operations shell out to the `git` CLI (not libgit2). Path-producing commands use `core.quotePath=false` so Unicode note filenames stay as UTF-8 paths across status, history, cache invalidation, and rename detection.
|
||||
|
||||
### Data Types
|
||||
|
||||
@@ -442,7 +468,7 @@ interface PulseCommit {
|
||||
- Configurable interval (from app settings: `auto_pull_interval_minutes`)
|
||||
- Pulls on interval, pushes after commits
|
||||
- Awaits the post-pull vault refresh so toasts land after note-list state is fresh
|
||||
- Reopens the clean active tab from disk after a successful pull update so the editor and note list stay aligned
|
||||
- Reopens the clean active tab from disk only when the pull changed that active note, so unrelated updates do not remount the editor
|
||||
- Detects merge conflicts → opens `ConflictResolverModal`
|
||||
- Tracks remote status (branch, ahead/behind via `git_remote_status`)
|
||||
- Handles push rejection (divergence) → sets `pull_required` status
|
||||
@@ -451,7 +477,7 @@ interface PulseCommit {
|
||||
|
||||
### External Vault Refresh
|
||||
|
||||
External vault mutations are any disk writes Tolaria did not just perform through its own save path: Git pulls, AI-agent writes, filesystem watcher events, and edits from another app. These changes must route through `refreshPulledVaultState()` rather than calling `reloadVault()` in isolation. The shared refresh abstraction reloads entries, folders, and saved views together, preserves unsaved active-editor content, reopens a clean active note from disk, and closes the active tab if the file disappeared. `useVaultWatcher` supplies changed filesystem paths to this abstraction after debouncing and after filtering recent app-owned saves.
|
||||
External vault mutations are any disk writes Tolaria did not just perform through its own save path: Git pulls, AI-agent writes, filesystem watcher events, and edits from another app. These changes must route through `refreshPulledVaultState()` rather than calling `reloadVault()` in isolation. The shared refresh abstraction reloads entries, folders, and saved views together, preserves unsaved active-editor content, reopens a clean active note only when the changed-path list includes that note, and closes the active tab if the file disappeared. Unknown or unrelated watcher updates refresh vault-derived state without remounting the active editor. `useVaultWatcher` supplies changed filesystem paths to this abstraction after debouncing and after filtering recent app-owned saves.
|
||||
|
||||
`useGitRemoteStatus` is the commit-time companion to `useAutoSync`:
|
||||
- Re-checks `git_remote_status` when the Commit dialog opens and right before submit
|
||||
@@ -506,8 +532,8 @@ Defined in `src/components/editorSchema.tsx` and styled in `src/components/Edito
|
||||
|
||||
- The schema overrides BlockNote's default `codeBlock` spec with `createCodeBlockSpec({ ...codeBlockOptions, defaultLanguage: "text" })` from `@blocknote/code-block`.
|
||||
- Fenced code blocks now use BlockNote's supported Shiki-backed highlighter path, which renders `.shiki` token spans directly inside the editor DOM.
|
||||
- Tolaria keeps `defaultLanguage: "text"` so unlabeled code blocks do not silently become JavaScript while still supporting the packaged language aliases such as `ts` → `typescript`.
|
||||
- Inline-code chip styling remains scoped to `.bn-inline-content code`, so fenced `pre > code` nodes keep BlockNote's dark shell instead of inheriting the muted inline surface.
|
||||
- Tolaria keeps `defaultLanguage: "text"` so unlabeled code blocks do not silently become JavaScript at creation time. Parsed unlabeled code blocks then run through Tolaria's lightweight language inference, while explicit fence languages and user dropdown choices still win.
|
||||
- Inline-code chip styling remains scoped to `.bn-inline-content code`, so fenced `pre > code` nodes keep the dedicated code-block shell instead of inheriting the muted inline surface.
|
||||
|
||||
### Markdown Math
|
||||
|
||||
@@ -526,6 +552,16 @@ Defined in `src/utils/mermaidMarkdown.ts`, `src/components/MermaidDiagram.tsx`,
|
||||
- Each `mermaidBlock` stores the original fenced Markdown plus the diagram body, so raw-mode entry and saves can restore the canonical source instead of serializing generated SVG.
|
||||
- The rich editor renders diagrams with the `mermaid` package and uses the original source as an inline fallback when rendering fails.
|
||||
- `serializeMermaidAwareBlocks()` wraps the math-aware serializer so math, wikilinks, and diagrams share the same Markdown-first save path.
|
||||
- The `/mermaid` slash command inserts a placeholder rectangle diagram using the same schema-backed Markdown storage path, avoiding an invalid empty diagram state.
|
||||
|
||||
### Tldraw Whiteboards
|
||||
|
||||
Defined in `src/utils/tldrawMarkdown.ts`, `src/components/TldrawWhiteboard.tsx`, `src/components/editorSchema.tsx`, and styled in `src/components/EditorTheme.css`:
|
||||
|
||||
- Fenced `tldraw` blocks become `tldrawBlock` schema nodes before BlockNote sees the Markdown body.
|
||||
- Each `tldrawBlock` stores a stable `boardId` plus the tldraw document snapshot JSON. Session state such as camera, selected tool, and current selection is not persisted into the note.
|
||||
- The rich editor renders the block with the `tldraw` package and saves debounced document snapshot changes back into the block props, so normal Tolaria autosave writes the board into the `.md` file.
|
||||
- The `/whiteboard` slash command inserts an empty tldraw block using the same Markdown-durable storage path. Preview images are intentionally omitted; thumbnails can be added later as derived cache artifacts.
|
||||
|
||||
### Formatting Surface Policy
|
||||
|
||||
@@ -534,9 +570,13 @@ Defined in `src/components/tolariaEditorFormatting.tsx` and `src/components/tola
|
||||
- `SingleEditorView` disables BlockNote's default formatting toolbar, `/` menu, and side menu, then mounts Tolaria-owned controllers so the visible formatting surface matches Tolaria's markdown round-trip guarantees.
|
||||
- The formatting toolbar only exposes inline controls that persist through `blocksToMarkdownLossy()` in Tolaria's save pipeline: bold, italic, strike, nesting, and link creation. Controls that BlockNote can render temporarily but Tolaria cannot faithfully persist, such as underline, color, alignment, and the block-type dropdown, are hidden instead of appearing to work and later disappearing.
|
||||
- Tolaria's formatting-toolbar controller also keeps file/image actions mounted across the tiny hover gap between an image block and the floating toolbar, and while the toolbar itself is hovered, so image controls remain usable instead of collapsing mid-interaction.
|
||||
- The `/` slash menu remains the supported path for markdown-safe block transformations such as headings, quotes, and list blocks. Tolaria filters out BlockNote's toggle-heading and toggle-list variants because those do not map cleanly to the markdown note model.
|
||||
- The block-handle side menu keeps only actions that survive Tolaria's markdown round-trip. Delete and table-header toggles remain available; BlockNote's `Colors` submenu is removed because block colors are not part of Tolaria's supported markdown surface.
|
||||
- `useEditorComposing` tracks `compositionstart` and `compositionend` events that target the BlockNote editor and closes the floating formatting toolbar while IME text is being composed, keeping CJK candidate windows unobstructed without changing normal selection toolbar behavior.
|
||||
- `useImageLightbox` listens for `dblclick` on the rich-editor container and opens `ImageLightbox` only when the event target resolves to a viewable BlockNote image. The target resolver handles media wrappers, ignores image captions/resize controls, missing sources, and tiny tracking-style images, preserving BlockNote's ordinary single-click image selection path.
|
||||
- The `/` slash menu remains the supported path for markdown-safe block transformations such as headings, quotes, list blocks, Mermaid diagrams, and whiteboards. Tolaria filters out BlockNote's toggle-heading and toggle-list variants because those do not map cleanly to the markdown note model.
|
||||
- The block-handle side menu keeps only actions that survive Tolaria's markdown round-trip. Delete and table-header toggles remain available; BlockNote's `Colors` submenu is removed because block colors are not part of Tolaria's supported markdown surface. Tolaria renders the add-block button outside the drag handle so the handle stays next to the block content. The side menu aligns itself to the first rendered text line for the hovered block, so H1/H2 typography, line-height, wrapping, and theme changes do not need per-heading offsets. Block reordering uses a Tolaria-owned pointer gesture and direct BlockNote block moves instead of HTML5 `DataTransfer`, keeping it independent from Tauri's native file-drop system. Block-handle actions re-resolve the current live BlockNote block before mutating or dragging, so note reloads and sync churn cannot leave controls acting on stale block references.
|
||||
- BlockNote's table row/column handles are patched so stale or missing hovered-table state cancels the drag and hides handles instead of throwing. Add/remove row and column actions also validate the table position and cell indexes before resolving a ProseMirror `CellSelection`, so reloads or menu lag cannot turn stale handles into invalid table-selection positions. Checklist checkbox handlers also re-resolve the live block before updating `checked`, making delayed clicks after note reloads a no-op instead of a stale block mutation. Browser and native table regressions should exercise row and column dragging plus add-menu actions because the state is tracked per orientation.
|
||||
- `useNoteWikilinkDrop()` is the shared editor-drop abstraction for dragging note rows into either editor mode. It reads the existing note-retargeting drag payload, resolves the vault-relative stem, and inserts a canonical `[[wikilink]]` without hijacking unrelated plain-text drags.
|
||||
- `plainTextPaste.ts` is the shared plain-text paste target registry. Rich BlockNote and raw CodeMirror surfaces register focused insertion targets, while ordinary focused text controls use DOM selection replacement, so the `Cmd+Shift+V` command can preserve caret/selection behavior without each surface inventing its own clipboard reader.
|
||||
- `useTauriDragDropEvent()` owns the shared Tauri window drag/drop subscription and duplicate-unlisten cleanup used by native drop features.
|
||||
- `useNativePathDrop()` is the shared Tauri file/folder-drop abstraction for text inputs that need filesystem paths instead of attachment import. It consumes native window drag/drop events, gates them to the target element bounds or focused text selection, and lets AI composer / command-palette inputs insert formatted paths at the current cursor.
|
||||
|
||||
@@ -545,18 +585,19 @@ Defined in `src/components/tolariaEditorFormatting.tsx` and `src/components/tola
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["📄 Raw markdown\n(from disk)"] --> B["splitFrontmatter()\n→ yaml + body"]
|
||||
B --> C["preProcessMermaidMarkdown(body)\nmermaid fence → token"]
|
||||
C --> D["preProcessWikilinks(body)\n[[target]] → ‹token›"]
|
||||
D --> E["preProcessMathMarkdown(body)\n$...$ / $$...$$ → tokens"]
|
||||
E --> F["tryParseMarkdownToBlocks()\n→ BlockNote block tree"]
|
||||
F --> G["injectWikilinks + injectMathInBlocks + injectMermaidInBlocks\n tokens → schema nodes"]
|
||||
G --> H["editor.replaceBlocks()\n→ rendered editor"]
|
||||
B --> C["preProcessTldrawMarkdown(body)\ntldraw fence → token"]
|
||||
C --> D["preProcessMermaidMarkdown(body)\nmermaid fence → token"]
|
||||
D --> E["preProcessWikilinks(body)\n[[target]] → ‹token›"]
|
||||
E --> F["preProcessMathMarkdown(body)\n$...$ / $$...$$ → tokens"]
|
||||
F --> G["tryParseMarkdownToBlocks()\n→ BlockNote block tree"]
|
||||
G --> H["injectWikilinks + injectMathInBlocks + injectMermaidInBlocks + injectTldrawInBlocks\n tokens → schema nodes"]
|
||||
H --> I["editor.replaceBlocks()\n→ rendered editor"]
|
||||
|
||||
style A fill:#f8f9fa,stroke:#6c757d,color:#000
|
||||
style H fill:#d4edda,stroke:#28a745,color:#000
|
||||
style I fill:#d4edda,stroke:#28a745,color:#000
|
||||
```
|
||||
|
||||
> Wikilink placeholder tokens use `\u2039` and `\u203A`; math and Mermaid placeholder tokens use ASCII sentinels with URI-encoded payloads.
|
||||
> Wikilink placeholder tokens use `\u2039` and `\u203A`; math, Mermaid, and tldraw placeholder tokens use ASCII sentinels with URI-encoded payloads.
|
||||
|
||||
### BlockNote-to-Markdown Pipeline (Save)
|
||||
|
||||
@@ -571,6 +612,10 @@ flowchart LR
|
||||
style E fill:#d4edda,stroke:#28a745,color:#000
|
||||
```
|
||||
|
||||
Rich-editor change events are coalesced before this serialization runs. `useEditorTabSwap` keeps the latest BlockNote state in the editor, schedules one Markdown serialization for a short idle window, and exposes an explicit flush hook for save, note switch, raw-mode entry, and destructive note actions. This keeps long notes from paying full-document Markdown serialization on every keystroke while preserving the disk-first save path.
|
||||
|
||||
Autosave then waits for a 1.5s idle window before invoking `save_note_content`. If an older save resolves after the user has already typed newer content, the older save is treated as stale and cannot clear the newer pending buffer or repaint tab state over it; the latest pending content remains scheduled for its own save.
|
||||
|
||||
### Wikilink Navigation
|
||||
|
||||
Two navigation mechanisms:
|
||||
@@ -587,6 +632,12 @@ While the user types, `useEditorSaveWithLinks` derives a transient `VaultEntry`
|
||||
|
||||
Current-note find/replace is intentionally backed by raw CodeMirror mode. `Cmd+F`, "Find in Note", and "Replace in Note" switch the active Markdown/text note to raw mode, show the compact find bar above CodeMirror, and operate on the current note only. Plain text matching is case-insensitive by default, `Aa` toggles case sensitivity, `.*` toggles JavaScript-regex matching, and regex replacement supports capture groups through JavaScript replacement syntax.
|
||||
|
||||
### Rich Editor Width Modes
|
||||
|
||||
Rich Markdown editing supports `normal` and `wide` note widths. The effective mode is resolved in `App.tsx` from, in order, the current session's transient note-width cache, `VaultEntry.noteWidth` parsed from `_width`, and the installation-local `settings.note_width_mode` default. The breadcrumb toggle calls the same setter exposed through the command palette.
|
||||
|
||||
Per-note width is persisted as hidden `_width` frontmatter only when the note already has a valid or empty frontmatter block. Notes without frontmatter use the transient cache for the current session, so toggling width never creates frontmatter solely to store UI state. The width class is applied around `SingleEditorView` only; raw CodeMirror mode stays outside `.editor-content-wrapper` and remains full-width.
|
||||
|
||||
### Arrow Ligature Normalization
|
||||
|
||||
Typed ASCII arrow sequences are normalized consistently in both editor modes:
|
||||
@@ -594,6 +645,7 @@ Typed ASCII arrow sequences are normalized consistently in both editor modes:
|
||||
- Rich editor input mounts `createArrowLigaturesExtension()` (`src/components/arrowLigaturesExtension.ts`) into BlockNote and intercepts typed `beforeinput` events before ProseMirror commits the character.
|
||||
- Raw editor input uses the CodeMirror `inputHandler` path in `useCodeMirror` so the same ligature rules apply while editing markdown source directly.
|
||||
- Both paths delegate to the shared `resolveArrowLigatureInput()` helper in `src/utils/arrowLigatures.ts`, which prioritizes `<->` over partial matches, keeps paste literal, and lets escaped forms such as `\\->` and `\\<->` remain ASCII.
|
||||
- The rich-editor extension treats stale, disconnected, or mid-reload ProseMirror views as a no-op. It never blocks the native input path unless it has already built and dispatched a valid ligature transaction.
|
||||
|
||||
## Styling
|
||||
|
||||
@@ -602,6 +654,7 @@ The app uses internal light and dark themes owned by Tolaria (see [ADR-0081](adr
|
||||
1. **Global CSS variables** (`src/index.css`): Semantic app colors, borders, surfaces, and interaction states via `:root` / `[data-theme]`, bridged to Tailwind v4
|
||||
2. **Editor theme** (`src/theme.json`): BlockNote typography, flattened to CSS vars by `useEditorTheme`
|
||||
3. **Runtime theme bridge**: Applies `data-theme` and `.dark` for shadcn/ui, while CodeMirror and editor-specific consumers derive any non-CSS-variable values from the same semantic contract
|
||||
4. **Theme mode commands**: Command-palette actions for light and dark mode call the same `saveSettings` path as the Settings panel and persist only `settings.theme_mode`
|
||||
|
||||
## Localization
|
||||
|
||||
@@ -622,6 +675,7 @@ The Inspector panel (`src/components/Inspector.tsx`) is composed of sub-panels:
|
||||
1. **DynamicPropertiesPanel** (`src/components/DynamicPropertiesPanel.tsx`): Renders frontmatter as editable key-value pairs:
|
||||
- **Editable properties** (top): Type badge, Status pill with dropdown, number fields, boolean toggles, array tag pills, text fields. Click-to-edit interaction.
|
||||
- **Property display modes**: `text`, `number`, `date`, `boolean`, `status`, `url`, `tags`, and `color`. Numeric frontmatter values auto-detect as `number`, and custom scalar keys can be explicitly switched to `Number` through the property-type control.
|
||||
- **Present empty properties**: A top-level frontmatter key with a blank scalar value (for example `start date:`) is treated as present and renders as an editable empty row. Only absent keys are omitted.
|
||||
- **Info section** (bottom, separated by border): Read-only derived metadata — Modified, Created, Words, File Size. Uses muted styling with no interaction.
|
||||
- Keys in `SKIP_KEYS` (`type`, `aliases`, `notion_id`, `workspace`, `is_a`, `Is A`) are hidden from the editable section.
|
||||
|
||||
@@ -669,16 +723,20 @@ No indexing step required — search runs directly against the filesystem.
|
||||
|
||||
Per-vault settings stored locally and scoped by vault path:
|
||||
- Managed by `useVaultConfig` hook and `vaultConfigStore`
|
||||
- Settings: zoom, view mode, editor mode, note layout, tag colors, status colors, property display modes, Inbox/All Notes note-list column overrides, explicit organization workflow toggle
|
||||
- Settings: zoom, view mode, editor mode, tag colors, status colors, property display modes, Inbox/All Notes note-list column overrides, explicit organization workflow toggle, AI agent permission mode (`safe` / `power_user`)
|
||||
- Missing, null, and unknown AI agent permission modes normalize to `safe`; the AI panel can switch modes per vault, preserving the transcript and applying the new mode only to the next agent run
|
||||
- One-time migration from localStorage (`configMigration.ts`)
|
||||
|
||||
Installation-local layout state that should not sync through a vault stays in localStorage. `useLayoutPanels` stores the clamped sidebar, note-list, and inspector widths under `tolaria:layout-panels` so pane sizing survives app relaunches on the same machine.
|
||||
|
||||
### AI Guidance Files
|
||||
|
||||
Tolaria tracks managed vault-level AI guidance separately from normal note content:
|
||||
- `AGENTS.md` is the canonical managed guidance file for Tolaria-aware coding agents
|
||||
- `CLAUDE.md` is a compatibility shim that points Claude Code back to `AGENTS.md`
|
||||
- `GEMINI.md` is an optional Gemini CLI compatibility shim that points Gemini back to `AGENTS.md`
|
||||
- `useVaultAiGuidanceStatus` reads `get_vault_ai_guidance_status` and normalizes the backend state into four UI cases: `managed`, `missing`, `broken`, and `custom`
|
||||
- `restore_vault_ai_guidance` repairs only Tolaria-managed files; user-authored custom `AGENTS.md` / `CLAUDE.md` files are surfaced as custom and left untouched
|
||||
- `restore_vault_ai_guidance` repairs only Tolaria-managed files and creates the optional Gemini shim on explicit request; user-authored custom `AGENTS.md` / `CLAUDE.md` / `GEMINI.md` files are surfaced as custom and left untouched
|
||||
- The status bar AI badge and command palette consume that abstraction to expose restore actions only when the managed guidance is missing or broken
|
||||
|
||||
### Getting Started / Onboarding
|
||||
@@ -697,7 +755,7 @@ Tolaria tracks managed vault-level AI guidance separately from normal note conte
|
||||
`useAiAgentsOnboarding(enabled)` adds a separate first-launch agent step:
|
||||
- Reads a local dismissal flag for the AI agents prompt (with a legacy fallback to the older Claude-only key)
|
||||
- Only shows after vault onboarding has already resolved to a ready state
|
||||
- Uses `get_ai_agents_status`, whose backend treats the app process path, login-shell path, and supported local/toolchain/app install locations, including Windows `.exe` and npm/pnpm/Scoop shim paths, as valid CLI-agent sources
|
||||
- Uses `get_ai_agents_status`, whose backend treats the app process path, login-shell path, and supported local/toolchain/app install locations, including nvm-managed Node installs plus Windows `.exe` and npm/pnpm/Scoop shim paths, as valid CLI-agent sources
|
||||
- Persists dismissal locally once the user continues
|
||||
|
||||
### Remote Git Operations
|
||||
@@ -705,6 +763,7 @@ Tolaria tracks managed vault-level AI guidance separately from normal note conte
|
||||
Tolaria delegates remote auth to the user's system git setup:
|
||||
- `CloneVaultModal` captures a remote URL and local destination
|
||||
- `clone_git_repo` and `create_getting_started_vault` both run system git clone work in blocking Tokio tasks so clone UIs stay responsive
|
||||
- On Linux AppImage launches, every system-git command removes AppImage loader overrides such as `LD_LIBRARY_PATH`, `LD_PRELOAD`, and `GIT_EXEC_PATH` before spawning `git`, so helpers like `git-remote-https` bind against the host git/library stack instead of Tolaria's bundled WebKit/AppImage libraries
|
||||
- `git_add_remote` uses the same system git path and refuses remotes whose history is unrelated or ahead of the local vault
|
||||
- Existing `git_pull` / `git_push` commands keep surfacing raw git errors, and clone commands fail fast when git wants interactive terminal input
|
||||
- No provider-specific token or username is stored in app settings
|
||||
@@ -726,12 +785,18 @@ interface Settings {
|
||||
release_channel: string | null // null = stable default, "alpha" = every-push prerelease feed
|
||||
theme_mode: 'light' | 'dark' | null
|
||||
ui_language: AppLocale | null
|
||||
default_ai_agent: 'claude_code' | 'codex' | 'opencode' | 'pi' | null
|
||||
note_width_mode: 'normal' | 'wide' | null
|
||||
default_ai_agent: 'claude_code' | 'codex' | 'opencode' | 'pi' | 'gemini' | null
|
||||
default_ai_target: string | null // "agent:codex" or "model:<provider>/<model>"
|
||||
ai_model_providers: AiModelProvider[] | null
|
||||
hide_gitignored_files: boolean | null // null = default true
|
||||
all_notes_show_pdfs: boolean | null // null = default false
|
||||
all_notes_show_images: boolean | null // null = default false
|
||||
all_notes_show_unsupported: boolean | null // null = default false
|
||||
}
|
||||
```
|
||||
|
||||
Managed by `useSettings` hook and `SettingsPanel` component. `theme_mode` is installation-local because it controls device comfort rather than vault structure. `ui_language` is also installation-local: `null` follows the supported system language with English fallback, while explicit values pin the UI language for this installation. Stored legacy aliases such as `zh-Hans` are normalized to canonical locale codes before the setting reaches React state. `default_ai_agent` is an installation-local preference that selects which supported CLI agent the AI panel, command palette AI mode, and status bar should target by default. `hide_gitignored_files` is also installation-local and defaults to `true`; changing it reloads entries, search, saved views, and folders without restarting. The AutoGit fields are also installation-local: `useAutoGit` consumes them to schedule automatic checkpoints, while `useCommitFlow` and the status bar quick action reuse the same checkpoint runner and deterministic automatic commit message generation.
|
||||
Managed by `useSettings` hook and `SettingsPanel` component. `theme_mode` is installation-local because it controls device comfort rather than vault structure; the Settings panel and command-palette light/dark actions both update that same value. `ui_language` is also installation-local: `null` follows the supported system language with English fallback, while explicit values pin the UI language for this installation. Stored legacy aliases such as `zh-Hans` are normalized to canonical locale codes before the setting reaches React state. `note_width_mode` is the installation-local default for rich-editor note width; individual notes can override it with `_width` when they already have frontmatter. `default_ai_agent` remains the legacy installation-local CLI fallback. `default_ai_target` is the active AI target used by the AI panel and status bar; it can point at a coding agent or a configured direct model. `ai_model_providers` stores non-secret provider metadata for local/API model targets, while hosted API keys live in Tolaria's local app-data secrets file or user-managed environment variables instead of being persisted in app settings. `hide_gitignored_files` is also installation-local and defaults to `true`; changing it reloads entries, search, saved views, and folders without restarting. The `all_notes_show_pdfs`, `all_notes_show_images`, and `all_notes_show_unsupported` flags are installation-local All Notes category toggles that default off and update the list/counts without changing vault files. The AutoGit fields are also installation-local: `useAutoGit` consumes them to schedule automatic checkpoints, while `useCommitFlow` and the status bar quick action reuse the same checkpoint runner and deterministic automatic commit message generation.
|
||||
|
||||
## Telemetry
|
||||
|
||||
@@ -743,9 +808,16 @@ Managed by `useSettings` hook and `SettingsPanel` component. `theme_mode` is ins
|
||||
- **`useTelemetry(settings, loaded)`** — Reactively initializes/tears down Sentry and PostHog based on settings. Called once in `App`.
|
||||
|
||||
### Libraries
|
||||
- **`src/lib/telemetry.ts`** — `initSentry()`, `teardownSentry()`, `initPostHog()`, `teardownPostHog()`, `trackEvent()`. Path scrubber via `beforeSend` hook. DSN/release/key from `VITE_SENTRY_DSN`, `VITE_SENTRY_RELEASE`, and `VITE_POSTHOG_KEY` env vars.
|
||||
- **`src/lib/telemetry.ts`** — `initSentry()`, `teardownSentry()`, `initPostHog()`, `teardownPostHog()`, `trackEvent()`. Path scrubber via `beforeSend` hook. DSN/key from `VITE_SENTRY_DSN` and `VITE_POSTHOG_KEY`; `VITE_SENTRY_RELEASE` is treated as the build version and only becomes Sentry's `release` for stable calendar builds (`YYYY.M.D`). Alpha/prerelease/internal builds tag `tolaria.build_version` and `tolaria.release_kind` without creating normal Sentry Releases entries.
|
||||
- **`src/main.tsx`** — React root error callbacks (`onCaughtError`, `onUncaughtError`, `onRecoverableError`) forward component-stack context to `Sentry.reactErrorHandler()` for debuggable production React errors.
|
||||
- **`src-tauri/src/telemetry.rs`** — Rust-side Sentry init with `beforeSend` path scrubber. `init_sentry_from_settings()` reads settings and conditionally initializes. `reinit_sentry()` for runtime toggle.
|
||||
- **`src-tauri/src/telemetry.rs`** — Rust-side Sentry init with `beforeSend` path scrubber. `init_sentry_from_settings()` reads settings and conditionally initializes; stable calendar `CARGO_PKG_VERSION` values become Sentry releases, while alpha/prerelease/internal versions are kept as diagnostic tags only. `reinit_sentry()` for runtime toggle.
|
||||
|
||||
### Product Events
|
||||
- **File previews** — `file_preview_opened`, `file_preview_action`, and `file_preview_failed` report only preview/action categories such as `image`, `pdf`, `unsupported`, `open_external`, `copy_path`, and `reveal`.
|
||||
- **Inline image lightbox** — `inline_image_lightbox_opened` records that a rich-editor inline image was opened from double-click, without sending note paths, image URLs, alt text, or file names.
|
||||
- **Code block copy** — `code_block_copied` records that the rich-editor code-block copy action was used, without sending note paths, languages, or code content.
|
||||
- **AI agent sessions** — `ai_agent_message_sent`, `ai_agent_message_blocked`, `ai_agent_response_completed`, `ai_agent_response_failed`, and `ai_agent_permission_mode_changed` use only agent ids, permission modes, counts, and coarse status categories.
|
||||
- **All Notes visibility** — `all_notes_visibility_changed` records only the toggled category and enabled state.
|
||||
|
||||
### Tauri Commands
|
||||
- **`reinit_telemetry`** — Re-reads settings and toggles Rust Sentry on/off. Called from frontend when user changes crash reporting setting.
|
||||
@@ -755,7 +827,7 @@ Managed by `useSettings` hook and `SettingsPanel` component. `theme_mode` is ins
|
||||
## Updates & Feature Flags
|
||||
|
||||
### Hooks
|
||||
- **`useUpdater(releaseChannel)`** — Channel-aware updater state machine. Checks the selected feed, surfaces available/downloading/ready states, and delegates install work to Rust.
|
||||
- **`useUpdater(releaseChannel)`** — Channel-aware updater state machine. Checks the selected feed, surfaces checking/available/downloading/ready states, and delegates install work to Rust.
|
||||
- **`useFeatureFlag(flag)`** — Returns boolean for a named feature flag. Checks `localStorage` override (`ff_<name>`), then falls back to telemetry-backed evaluation. Type-safe via `FeatureFlagName` union.
|
||||
|
||||
### Frontend helpers
|
||||
@@ -771,6 +843,6 @@ Managed by `useSettings` hook and `SettingsPanel` component. `theme_mode` is ins
|
||||
- **`download_and_install_app_update`** — Channel-aware download/install with streamed progress events.
|
||||
|
||||
### CI/CD
|
||||
- **`.github/workflows/release.yml`** — Alpha prereleases from every push to `main` using calendar-semver technical versions (`YYYY.M.D-alpha.N`) and clean `Alpha YYYY.M.D.N` release names. GitHub alpha tags zero-pad the prerelease sequence (`alpha-vYYYY.M.D-alpha.NNNN`) so GitHub release ordering stays chronological while the shipped app version remains `YYYY.M.D-alpha.N`. Publishes `alpha/latest.json` with macOS Apple Silicon/Intel, Linux x64, and Windows x64 updater entries, then refreshes the legacy `latest.json` / `latest-canary.json` aliases to the alpha feed. macOS release assets use `Tolaria_<version>_macOS_Silicon` and `Tolaria_<version>_macOS_Intel` base names. Packaged builds pass the computed version as `VITE_SENTRY_RELEASE`.
|
||||
- **`.github/workflows/release-stable.yml`** — Stable releases from `stable-vYYYY.M.D` tags. Publishes `stable/latest.json`, macOS Apple Silicon and Intel DMG/updater artifacts, Windows x64 installers/updater bundles, and Linux x86_64 `.deb` / AppImage artifacts. Stable macOS DMG/updater assets use the same `Tolaria_<version>_macOS_Silicon` and `Tolaria_<version>_macOS_Intel` base names. Packaged builds pass the computed version as `VITE_SENTRY_RELEASE`.
|
||||
- **`.github/workflows/release.yml`** — Alpha prereleases from every push to `main` using calendar-semver technical versions (`YYYY.M.D-alpha.N`) and clean `Alpha YYYY.M.D.N` release names. GitHub alpha tags zero-pad the prerelease sequence (`alpha-vYYYY.M.D-alpha.NNNN`) so GitHub release ordering stays chronological while the shipped app version remains `YYYY.M.D-alpha.N`. Publishes `alpha/latest.json` with macOS Apple Silicon/Intel, Linux x64, and Windows x64 updater entries, then refreshes the legacy `latest.json` / `latest-canary.json` aliases to the alpha feed. macOS release assets use `Tolaria_<version>_macOS_Silicon` and `Tolaria_<version>_macOS_Intel` base names. Packaged builds pass the computed version as `VITE_SENTRY_RELEASE`, which is retained as a diagnostic build-version tag but not registered as a normal Sentry release for alpha builds.
|
||||
- **`.github/workflows/release-stable.yml`** — Stable releases from `stable-vYYYY.M.D` tags. Publishes `stable/latest.json`, macOS Apple Silicon and Intel DMG/updater artifacts, Windows x64 installers/updater bundles, and Linux x86_64 `.deb` / AppImage artifacts. Stable macOS DMG/updater assets use the same `Tolaria_<version>_macOS_Silicon` and `Tolaria_<version>_macOS_Intel` base names. Packaged builds pass the computed stable version as `VITE_SENTRY_RELEASE`, which is registered as Sentry's release.
|
||||
- **Beta cohorts** are handled in PostHog targeting only. There is no beta updater feed.
|
||||
|
||||
@@ -24,7 +24,9 @@ When deciding where to persist a piece of data, ask: **"Would the user want this
|
||||
| Pinned properties per type | API keys (OpenAI, Google) |
|
||||
| Sidebar label overrides | Auto-sync interval |
|
||||
| Property display order | Window size / position |
|
||||
| Per-note `_width` rich-editor width override | Default rich-editor note width |
|
||||
| Vault-authored `.gitignore` patterns | Whether this installation hides Gitignored files |
|
||||
| Per-vault All Notes note-list column overrides | All Notes PDF/image/unsupported file visibility |
|
||||
| Any user-visible customization of how content is organized or displayed | Any machine-specific or credential-type setting |
|
||||
|
||||
**Rule:** If the information is about *how the content is structured or presented* and the user would expect it to be consistent wherever they open their vault, store it in the vault (frontmatter of the relevant note, using the `_field` underscore convention for system properties). If it's about *this specific installation of the app*, store it in `~/.config/com.tolaria.app/settings.json` or localStorage.
|
||||
@@ -32,8 +34,11 @@ When deciding where to persist a piece of data, ask: **"Would the user want this
|
||||
Examples:
|
||||
- ✅ Vault: `_pinned_properties` in a Type note (every device should show the same pinned properties)
|
||||
- ✅ Vault: `_icon: shapes` in a Type note (icon is part of the type's identity)
|
||||
- ✅ Vault: `_width: wide` in a note that already has frontmatter (per-note reading/editing preference)
|
||||
- ✅ App settings: `zoom: 1.3` (machine-specific preference)
|
||||
- ✅ App settings: `ui_language: "zh-CN"` (installation-specific UI language)
|
||||
- ✅ App settings: `note_width_mode: "wide"` (installation-specific default for notes without an override)
|
||||
- ✅ App settings: `all_notes_show_images: true` (installation-specific All Notes file-category visibility)
|
||||
|
||||
### No hardcoded exceptions
|
||||
|
||||
@@ -83,12 +88,24 @@ flowchart LR
|
||||
3. **No orphan state updates**: Never call `updateEntry()` before the corresponding `handleUpdateFrontmatter()` or `handleDeleteProperty()` has resolved. The three functions in `useEntryActions` (`handleCustomizeType`, `handleRenameSection`, `handleToggleTypeVisibility`) follow this rule — disk write first, then state update.
|
||||
4. **Recovery via reload**: If state ever diverges from disk (crash, external edit, race condition), `Reload Vault` (Cmd+K → "Reload Vault") invalidates the cache and does a full filesystem rescan via the `reload_vault` Tauri command, replacing all React state. The `reload_vault_entry` command can re-read a single file.
|
||||
5. **Cache is disposable**: The `reload_vault` command deletes the cache file before rescanning, guaranteeing fresh data. The cache never contains data that doesn't exist on the filesystem.
|
||||
6. **Visibility filters are command-boundary concerns**: Gitignored-content visibility is applied after scanning/caching, before entries, folders, or search results reach React. The cache remains complete so toggling the setting can show ignored content again without rebuilding a different cache shape.
|
||||
6. **Visibility filters are command-boundary concerns**: Gitignored-content visibility is applied after scanning/caching, before entries, folders, or search results reach React. The cache remains complete so toggling the setting can show ignored content again without rebuilding a different cache shape. Large folder filtering runs on the blocking Tokio pool and drains `git check-ignore` output while feeding stdin so broad ignore matches cannot freeze the native UI thread.
|
||||
|
||||
#### External Change Detection
|
||||
|
||||
The main window starts a native watcher for the active vault through `start_vault_watcher` / `stop_vault_watcher` (`src-tauri/src/vault_watcher.rs`, backed by Rust `notify`). The watcher emits `vault-changed` events for content paths and ignores churn from `.git/`, `node_modules/`, temp files, and `.tolaria-rename-txn`. `useVaultWatcher` batches those events, suppresses recent app-owned saves, and sends the remaining external paths through `refreshPulledVaultState()` so folders, saved views, note-list state, and the clean active editor all refresh under the ADR-0071 unsaved-edit rules. `useVaultLoader.isReloading` drives the status-bar reload spinner for both manual and watcher-triggered reloads.
|
||||
|
||||
#### Progressive Vault Loading
|
||||
|
||||
Vault opening is allowed to render the main app shell while the full entry scan is still in flight. `useVaultLoader` keeps `isLoading` true until entries are ready, but folders and saved views load independently so the sidebar can become useful before the note index completes. The status bar uses the vault activity badge during this initial indexing state, while command-palette and editor-shell interactions remain mounted instead of being hidden behind the full app skeleton. The full skeleton is reserved for app-level capability checks such as the initial Git-state probe.
|
||||
|
||||
Large-vault reproduction and keyboard QA steps live in [LARGE-VAULT-LOADING-QA.md](./LARGE-VAULT-LOADING-QA.md).
|
||||
|
||||
#### Note Opening Fast Path
|
||||
|
||||
Note opening uses bounded in-memory fast paths for raw content and parsed editor blocks. `useTabManagement` owns the markdown/text prefetch cache and treats every cached value as a performance hint only: identity-matched entries (`modifiedAt` + `fileSize`) can be reused immediately, while identity-missing or identity-mismatched cached text is checked with `validate_note_content`, which compares the cached text with the current file bytes inside the validated vault boundary. If validation fails, Tolaria discards the cached entry and reads fresh disk content before swapping the editor.
|
||||
|
||||
The note list opportunistically preloads visible and adjacent markdown/text entries after a short delay. When a large warmed Markdown note resolves, `useEditorTabSwap` may parse it into a bounded parsed-block cache only after foreground editor work has been idle and the rich editor is mounted. Parsed blocks are keyed by vault, path, and exact source content; every async swap carries a generation/source-content token so stale conversion results cannot overwrite newer file content or dirty editor state. The editor never renders a preview surface that later morphs into BlockNote. See [ADR-0105](./adr/0105-editor-correctness-and-responsiveness-contract.md).
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology | Version |
|
||||
@@ -98,6 +115,7 @@ The main window starts a native watcher for the active vault through `start_vaul
|
||||
| Editor | BlockNote | 0.46.2 |
|
||||
| Code block highlighting | @blocknote/code-block | 0.46.2 |
|
||||
| Diagram rendering | Mermaid | 11.14.0 |
|
||||
| Whiteboard rendering | tldraw | 4.5.10 |
|
||||
| Raw editor | CodeMirror 6 | - |
|
||||
| Styling | Tailwind CSS v4 + CSS variables | 4.1.18 |
|
||||
| UI primitives | Radix UI + shadcn/ui | - |
|
||||
@@ -106,7 +124,7 @@ The main window starts a native watcher for the active vault through `start_vaul
|
||||
| Backend language | Rust (edition 2021) | 1.77.2 |
|
||||
| Frontmatter parsing | gray_matter | 0.2 |
|
||||
| Filesystem watcher | notify | 6.1 |
|
||||
| AI (agent panel) | CLI agent adapters (Claude Code + Codex + OpenCode + Pi) | - |
|
||||
| AI (agent panel) | CLI agent adapters (Claude Code + Codex + OpenCode + Pi + Gemini) | - |
|
||||
| Search | Keyword (walkdir-based file scan) | - |
|
||||
| Localization | App-owned runtime + JSON catalogs (`src/lib/i18n.ts`, `src/lib/locales/*.json`, `lara.yaml`) | English fallback + Lara CLI sync |
|
||||
| MCP | @modelcontextprotocol/sdk | 1.0 |
|
||||
@@ -141,11 +159,11 @@ flowchart TD
|
||||
GIT["git/\n(commit, sync, clone)"]
|
||||
SETTINGS["settings.rs"]
|
||||
SEARCH["search.rs"]
|
||||
CLI["ai_agents.rs\n+ claude_cli.rs"]
|
||||
CLI["ai_agents.rs\n+ CLI adapters"]
|
||||
end
|
||||
|
||||
subgraph EXT["External Services"]
|
||||
CCLI["Claude / Codex / OpenCode / Pi CLI\n(agent subprocesses)"]
|
||||
CCLI["Claude / Codex / OpenCode / Pi / Gemini CLI\n(agent subprocesses)"]
|
||||
MCP["MCP Server\n(ws://9710, 9711)"]
|
||||
GCLI["git CLI\n(system executable)"]
|
||||
REMOTE["Git remotes\n(GitHub/GitLab/Gitea/etc.)"]
|
||||
@@ -186,19 +204,21 @@ flowchart TD
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- **Sidebar** (150-400px, resizable): Top-level filters (All Notes, Changes, Pulse), collapsible type-based section groups, and a dedicated folder tree. The folder tree shows user-created folders plus default vault folders such as `attachments/` and `views/`; only the dedicated `type/` directory stays hidden because note types already have their own sidebar section. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete plus filesystem reveal/copy-path actions, and auto-expands ancestor folders when the current selection or rename target is nested. Type sections and folder rows also act as note drop targets: dropping a note on a type updates its `type:` frontmatter, while dropping it on a folder runs the same crash-safe move path as the command palette flow. Each type can have a custom icon, color, sort, and visibility set via its type document in `type/`.
|
||||
- **Note List / Pulse View** (200-500px, resizable): When a section group, filter, or saved view is selected, shows filtered notes with snippets, modified dates, status indicators, and per-context note-list controls. When `selection.kind === 'entity'`, the same pane enters **Neighborhood** mode: the source note is pinned at the top as a normal active row, outgoing relationship groups render first, inverse/backlink groups follow, empty groups stay visible with `0`, and duplicates across groups are allowed when multiple relationships are true. Plain click / `Enter` open the focused note without replacing the current Neighborhood, while Cmd/Ctrl-click and Cmd/Ctrl-`Enter` pivot the pane into the clicked note's Neighborhood. Folder-backed lists also show non-Markdown files: previewable image binaries get an image indicator and open in the editor pane, while unsupported binaries remain muted instead of auto-launching an external app. Saved views reuse the same sort and visible-column controls as the built-in lists, and those changes persist back into the view `.yml` definition (`sort`, `listPropertiesDisplay`). When Pulse filter is active, shows `PulseView` — a chronological git activity feed grouped by day.
|
||||
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with word count and note-layout toggle, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, first-class Mermaid diagram blocks, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide-screen left-aligned note column while preserving the same readable max width. Binary image files render through `FilePreview` as ordinary vault files using Tauri asset URLs, with explicit unsupported/broken fallback states and keyboard focus returning to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
|
||||
- **Sidebar** (220-400px, resizable): Top-level filters (All Notes, Changes, Pulse), saved Views, collapsible type-based section groups, and a dedicated folder tree. The folder tree starts with a vault-root row labeled from the opened vault path, shows root-level files when selected, and nests user-created folders plus default vault folders such as `attachments/` and `views/` underneath it; only the dedicated `type/` directory stays hidden because note types already have their own sidebar section. Saved Views persist a top-level YAML `order` field in each view file and use the same ordered-list mental model as Types: pointer users can drag the existing view row, double-click to rename it, or right-click for edit/rename/appearance/delete actions, while keyboard users can use the row context key for the same menu and command-palette move actions for ordering. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete plus filesystem reveal/copy-path actions on mutable folders, and auto-expands ancestor folders when the current selection or rename target is nested. Type sections and folder rows also act as note drop targets: dropping a note on a type updates its `type:` frontmatter, while dropping it on a folder runs the same crash-safe move path as the command palette flow. Each type can have a custom icon, color, sort, and visibility set via its `type: Type` document; new type documents created by Tolaria are written at the vault root.
|
||||
- **Note List / Pulse View** (220-500px, resizable): When a section group, filter, or saved view is selected, shows filtered notes with snippets, modified dates, status indicators, and per-context note-list controls. When `selection.kind === 'entity'`, the same pane enters **Neighborhood** mode: the source note is pinned at the top as a normal active row, outgoing relationship groups render first, inverse/backlink groups follow, empty groups stay visible with `0`, and duplicates across groups are allowed when multiple relationships are true. Plain click / `Enter` open the focused note without replacing the current Neighborhood, while Cmd/Ctrl-click and Cmd/Ctrl-`Enter` pivot the pane into the clicked note's Neighborhood. Folder-backed lists also show non-Markdown files: previewable image and PDF binaries get file indicators and open in the editor pane, while unsupported binaries remain muted instead of auto-launching an external app. Saved views reuse the same sort and visible-column controls as the built-in lists, and those changes persist back into the view `.yml` definition (`sort`, `listPropertiesDisplay`). When Pulse filter is active, shows `PulseView` — a chronological git activity feed grouped by day.
|
||||
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with word count and rich-editor width toggle, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, first-class Mermaid diagram blocks, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide rich-editor reading surface with preserved side margins; raw CodeMirror remains full-width and unaffected by note width mode. Inline rich-editor images open in a localized shadcn lightbox on double-click while normal single-click BlockNote selection remains untouched, and tiny tracking-style images are ignored. Binary image and PDF files render through `FilePreview` as ordinary vault files using Tauri asset URLs; external-open actions call `open_vault_file_external` so the target is validated against the active vault before the native default app opens it. Unsupported/broken binaries show explicit fallback states and keyboard focus returns to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
|
||||
- **Inspector / AI Agent** (200-500px or 40px collapsed): Toggles between Inspector (frontmatter, relationships, instances, backlinks, git history) and AI Agent panel (the selected CLI agent with tool execution). The Sparkle icon in the breadcrumb bar toggles between them. Per-note `icon` is a suggested Inspector property and the command palette's "Set Note Icon" action opens that field directly. When viewing a Type note, the Inspector shows an **Instances** section listing all notes of that type (sorted by modified_at desc, capped at 50).
|
||||
|
||||
Panels are separated by `ResizeHandle` components that support drag-to-resize.
|
||||
Panels are separated by `ResizeHandle` components that support drag-to-resize. `useLayoutPanels` clamps the sidebar, note-list, and inspector widths before applying them, keeps the side panes from flex-shrinking below their protected widths, and persists the last chosen widths in installation-local localStorage under `tolaria:layout-panels`.
|
||||
|
||||
The main Tauri window derives its minimum width from the visible panes instead of a single fixed floor. `useMainWindowSizeConstraints` treats the editor-only shell as the 480px baseline, adds sidebar / note-list / expanded-inspector allowances on top, and calls the native `update_current_window_min_size` command whenever view mode or inspector visibility changes. That same native command also grows the current window back out when a wider pane combination is restored, while note windows skip this path and keep their dedicated 800×700 initial sizing.
|
||||
The main Tauri window derives its minimum width from the visible panes instead of a single fixed floor. `useMainWindowSizeConstraints` treats the editor-only shell as the 480px baseline, adds the current sidebar / note-list / expanded-inspector widths on top with minimum floors, and calls the native `update_current_window_min_size` command whenever view mode, inspector visibility, or restored pane widths change. That same native command also grows the current window back out when a wider pane combination is restored, while note windows skip this path and keep their dedicated 800×700 initial sizing.
|
||||
|
||||
The main Tauri window also persists its last normal size and screen position in the app config directory as `window-state.json`. The state stores logical window points, while `window_state.rs` migrates older physical-pixel state on read so Retina and non-Retina launches restore the same user-facing bounds. On startup, the restored frame applies only to the main window and clamps to the currently available monitor work areas, so stale coordinates from a disconnected display fall back to a visible placement. Maximized, fullscreen, minimized, and detached note-window frames are not written as the restore baseline.
|
||||
|
||||
Linux uses custom React-rendered window chrome instead of the native Tauri menu bar. `setup_linux_window_chrome()` drops server-side decorations on the main window, `openNoteInNewWindow()` does the same for detached note windows, and `LinuxTitlebar`/`LinuxMenuButton` route both window controls and menu actions back through the same shared command pipeline that macOS uses for native menu clicks.
|
||||
When Tolaria is launched from a Linux AppImage, `run()` also injects `WEBKIT_DISABLE_DMABUF_RENDERER=1` unless the user already set that variable. This keeps the workaround scoped to bundled WebKitGTK launches that are prone to Fedora/Wayland DMA-BUF crashes without changing native package installs.
|
||||
Tauri setup keeps launch-time filesystem and subprocess work off the window creation critical path. Legacy `~/Laputa` housekeeping and the initial persisted-vault MCP bridge sync run on named background threads, so large legacy vaults, stale active-vault paths, or slow process startup cannot beachball the macOS app before React mounts. React still resyncs the bridge from `useVaultSwitcher` after the persisted selection loads, and no selected vault stops the bridge. The HTML bootstrap also installs a Tauri-only one-shot watchdog: React reports readiness from an effect after the root commits, and if that readiness signal never arrives the WebView reloads once instead of leaving macOS users in an inert rendered shell.
|
||||
|
||||
Linux uses custom React-rendered window chrome instead of the native Tauri menu bar. `setup_linux_window_chrome()` drops server-side decorations on the main window, `openNoteInNewWindow()` does the same for detached note windows, and `LinuxTitlebar`/`LinuxMenuButton` route both window controls and menu actions back through the same shared command pipeline that the desktop native menus use. The native app menu keeps macOS-only Services/Hide entries off Windows and Linux, while cross-platform custom items such as Check for Updates emit Tolaria command IDs and show visible updater feedback.
|
||||
When Tolaria is launched from a Linux AppImage, `run()` also applies AppImage-only WebKitGTK startup safeguards without changing native package installs. It injects `WEBKIT_DISABLE_DMABUF_RENDERER=1` and `WEBKIT_DISABLE_COMPOSITING_MODE=1` independently unless the user already set either variable, and on Wayland sessions it re-execs once with the first architecture-matching system `libwayland-client.so` in `LD_PRELOAD` when the user has not provided their own preload. The candidate order prefers Fedora-style `lib64` and Debian-style `x86_64-linux-gnu` paths before generic `/usr/lib`, and the ELF header is checked so a 64-bit Tolaria process does not retry with a 32-bit Wayland client library. The same AppImage path checks whether `fc-match` resolves the default emoji font to `Noto-COLRv1.ttf`; when the user has not provided `FONTCONFIG_FILE` or `FONTCONFIG_PATH`, Tolaria writes a cache-local fontconfig file that rejects only that matched font file and exports it before WebKit starts. The rendering overrides keep AppImage WebViews from blanking after accelerated compositing/DMA-BUF failures, the re-exec addresses AppImage library-order failures that can surface as `Could not create default EGL display: EGL_BAD_PARAMETER`, and the fontconfig guard avoids known WebKit crashes in COLRv1 emoji font rendering while leaving other emoji fonts available.
|
||||
|
||||
## Multi-Window (Note Windows)
|
||||
|
||||
@@ -214,7 +234,7 @@ Notes can be opened in separate Tauri windows for focused editing. Secondary win
|
||||
- `openNoteInNewWindow()` (`src/utils/openNoteWindow.ts`) creates a new `WebviewWindow` via the Tauri v2 JS API with URL query params (`?window=note&path=...&vault=...&title=...`)
|
||||
- `main.tsx` checks `isNoteWindow()` at boot to route between `App` (main window) and `NoteWindow` (secondary window)
|
||||
- `NoteWindow` (`src/NoteWindow.tsx`) is a minimal shell that loads vault entries, fetches note content, applies the theme, and renders a single `Editor` instance
|
||||
- Each window has its own auto-save via `useEditorSaveWithLinks` (same 500ms debounce, same Rust `save_note_content` command), and raw-editor typing also derives frontmatter-backed `VaultEntry` state in the renderer so Inspector and note-list surfaces react immediately without waiting for a full reload
|
||||
- Each window has its own auto-save via `useEditorSaveWithLinks` (same 1.5s low-end-safe idle debounce, same Rust `save_note_content` command), and raw-editor typing also derives frontmatter-backed `VaultEntry` state in the renderer so Inspector and note-list surfaces react immediately without waiting for a full reload
|
||||
- Secondary windows are sized 800×700; macOS keeps the overlay title bar, while Linux mounts the shared React titlebar on undecorated windows
|
||||
- Capabilities config (`src-tauri/capabilities/default.json`) grants permissions to both `main` and `note-*` window labels
|
||||
|
||||
@@ -224,12 +244,13 @@ Notes can be opened in separate Tauri windows for focused editing. Secondary win
|
||||
|
||||
Full agent mode — spawns the selected local CLI agent as a subprocess with tool access and MCP vault integration.
|
||||
|
||||
1. **Frontend** (`AiPanel` + `useCliAiAgent` + `aiAgentSession.ts` + `aiAgents.ts`) — one normalized session lifecycle for message state, reasoning blocks, tool action cards, response display, onboarding, and default-agent selection
|
||||
2. **Backend** (`ai_agents.rs`) — normalizes agent availability and streaming, dispatching to per-agent adapters
|
||||
3. **Agent adapters** — Claude Code still uses `claude_cli.rs` with `acceptEdits`, strict Tolaria MCP config, a file/search-only built-in tool list, hidden Windows subprocess launches, and closed stdin for print-mode subprocesses so Windows launches receive EOF; Codex runs through `codex --sandbox workspace-write --ask-for-approval never exec --json`; OpenCode runs through `opencode run --format json`; Pi runs through `pi --mode json --no-session` with `npm:pi-mcp-adapter`. OpenCode and Pi both launch from the active vault cwd with closed stdin and transient MCP config. All app-launched paths use hidden Windows launches and avoid dangerous permission-bypass flags.
|
||||
4. **MCP Integration** — Claude receives the generated MCP config file path, Codex receives the same Tolaria MCP server via transient `-c mcp_servers.tolaria.*` config overrides, OpenCode receives it through `OPENCODE_CONFIG_CONTENT`, and Pi receives it through a temporary `PI_CODING_AGENT_DIR/mcp.json` consumed by `pi-mcp-adapter`
|
||||
1. **Frontend** (`AiPanel` + `useCliAiAgent` + `aiAgentSession.ts` + `aiAgents.ts` + `aiTargets.ts`) — one normalized session lifecycle for message state, reasoning blocks, tool action cards, response display, onboarding, default-target selection, and the per-vault Safe / Power User permission mode shown in the panel header for coding agents
|
||||
2. **Backend orchestration** (`ai_agents.rs`) — normalizes agent availability, streaming, and the request permission mode before dispatching to per-agent adapters
|
||||
3. **Shared runtime scaffold** (`cli_agent_runtime.rs`) — owns the common request shape, prompt wrapping, JSON-line subprocess lifecycle, normalized error/done handling, version probing, and Tolaria MCP server path resolution used by app-managed CLI agents
|
||||
4. **Agent adapters** — Shared prompts are mode-aware on every turn, including turns with note context snapshots: Vault Safe tells agents not to use or advertise shell, while Power User tells shell-capable agents to keep local commands scoped to the active vault. Claude Code still uses `claude_cli.rs` with `acceptEdits`, strict Tolaria MCP config, and a scoped tool list: Safe enables file/search/edit tools only, while Power User adds Bash to the available tools and pre-approves Bash with `--allowedTools` without using dangerous bypass flags. Codex runtime specifics live in `codex_cli.rs`; Safe runs `codex --sandbox read-only --ask-for-approval untrusted exec --json`, while Power User runs `codex --sandbox workspace-write --ask-for-approval never exec --json` so shell execution stays enabled across repeated turns. OpenCode runs through `opencode run --format json` with transient permissions: Safe denies bash and external directories, while Power User allows bash but still denies external directories. Pi runs through `pi --mode json --no-session` with `npm:pi-mcp-adapter`; both modes currently share the same transient MCP config and the prompt does not promise shell for Pi Power User. Gemini runs through `gemini --output-format stream-json --prompt` so assistant message chunks, tool calls, and final errors are mapped from the CLI event stream instead of relying on a buffered `response` field. Gemini Safe uses `auto_edit` plus `tools.exclude=["run_shell_command"]`; Power User intentionally uses `yolo` against a trusted transient Tolaria MCP entry. Codex, OpenCode, Pi, and Gemini all launch from the active vault cwd with closed stdin and transient MCP config. All app-launched paths use hidden Windows launches and avoid dangerous permission-bypass flags.
|
||||
5. **MCP Integration** — Claude receives the generated MCP config file path, Codex receives the same Tolaria MCP server via transient `-c mcp_servers.tolaria.*` config overrides using Tolaria's resolved Node path plus `VAULT_PATH` and `WS_UI_PORT`, OpenCode receives it through `OPENCODE_CONFIG_CONTENT`, Pi receives it through a temporary `PI_CODING_AGENT_DIR/mcp.json` consumed by `pi-mcp-adapter`, and Gemini receives it through a temporary settings file pointed at by `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
|
||||
|
||||
CLI-agent availability intentionally does not depend only on the desktop app's inherited `PATH`. The detectors check the current process path, the user's login shell, and supported local/toolchain install locations such as native `~/.local/bin`, local `~/.claude/local`, Mise/asdf shims, npm-global, Homebrew, Windows `%APPDATA%\npm`/pnpm/Scoop shims, Windows `.exe` launchers, and the macOS Codex app resource path so first-run onboarding works on fresh macOS and Windows installs.
|
||||
CLI-agent availability intentionally does not depend only on the desktop app's inherited `PATH`. The detectors check the current process path, the user's login shell, and supported local/toolchain install locations such as native `~/.local/bin`, local `~/.claude/local`, Mise/asdf shims, nvm-managed Node installs, npm-global, Homebrew, Windows `%APPDATA%\npm`/pnpm/Scoop shims, Windows `.exe` launchers, and the macOS Codex app resource path so first-run onboarding works on fresh macOS and Windows installs. App-managed CLI spawns also expand the active vault path before using it as the subprocess working directory, then extend the child process `PATH` with the resolved binary directory plus those common toolchain directories, which lets GUI-launched macOS sessions run Homebrew/npm shims and their `node`-backed MCP subprocesses even when Finder/Dock did not inherit a terminal shell path.
|
||||
|
||||
#### Agent Event Flow
|
||||
|
||||
@@ -243,12 +264,12 @@ sequenceDiagram
|
||||
|
||||
U->>FE: sendMessage(text, references)
|
||||
FE->>FE: buildContextSnapshot(activeNote, linkedNotes, openTabs)
|
||||
FE->>R: invoke('stream_ai_agent', {agent, message, systemPrompt, vaultPath})
|
||||
FE->>R: invoke('stream_ai_agent', {agent, message, systemPrompt, vaultPath, permissionMode})
|
||||
R->>R: pick adapter for claude_code, codex, opencode, or pi
|
||||
R->>C: spawn agent with MCP-enabled config
|
||||
|
||||
loop Normalized stream
|
||||
C-->>R: Claude NDJSON, Codex JSONL, OpenCode JSON, or Pi JSON events
|
||||
C-->>R: Claude NDJSON, Codex JSONL, OpenCode JSON, Pi JSON, or Gemini JSONL events
|
||||
R-->>FE: emit("ai-agent-stream", event)
|
||||
alt TextDelta
|
||||
FE->>FE: accumulate response (revealed on Done)
|
||||
@@ -278,23 +299,29 @@ The agent panel (`ai-context.ts`) builds a structured JSON snapshot from the act
|
||||
|
||||
```json
|
||||
{
|
||||
"activeNote": { "path", "title", "type", "frontmatter", "content" },
|
||||
"linkedNotes": [{ "path", "title", "content" }],
|
||||
"openTabs": [{ "title", "snippet" }],
|
||||
"vaultMetadata": { "noteTypes", "stats", "filter" },
|
||||
"references": [{ "title", "path", "type" }]
|
||||
"activeNote": { "path", "title", "type", "frontmatter", "body", "wordCount", "bodyTruncated?" },
|
||||
"openTabs": [{ "path", "title", "type", "frontmatter" }],
|
||||
"noteList": [{ "path", "title", "type" }],
|
||||
"vault": { "types", "totalNotes" },
|
||||
"referencedNotes": [{ "title", "path", "type" }]
|
||||
}
|
||||
```
|
||||
|
||||
Token budget: 60% of 180k context limit (~108k tokens max). Active note gets priority, then linked notes, then truncation.
|
||||
Large active notes are compacted into a head/tail body snapshot before they enter the CLI prompt. The snapshot records `bodyTruncated` metadata and instructs agents to call `get_note(path)` before content-sensitive edits or summaries, keeping lower-context OpenCode providers from failing on oversized active-note context while preserving access to the full note through MCP.
|
||||
|
||||
### Direct Model Targets
|
||||
|
||||
Tolaria also supports direct model targets for local servers and API providers. These targets are stored as app-level provider metadata and can be selected in Settings or the status bar alongside coding agents. Direct model targets run in Chat mode: they receive the same note-context snapshot and conversation history, but they do not receive vault-write tools or shell access. The backend `stream_ai_model` command supports OpenAI-compatible chat completions and Anthropic Messages-compatible calls, including Ollama, LM Studio, OpenRouter, OpenAI, Anthropic, Gemini, and custom compatible endpoints.
|
||||
|
||||
Provider secrets are not written to `settings.json`. Hosted API targets can use Tolaria's local app-data secrets file (`ai-provider-secrets.json`, outside vaults/worktrees and owner-only on Unix) or reference an environment variable name. Local endpoints can omit authentication.
|
||||
|
||||
### Authentication
|
||||
|
||||
Each CLI agent authenticates itself outside Tolaria. Claude Code uses its existing CLI login; Codex surfaces a friendly prompt to run `codex login` when needed; OpenCode surfaces a friendly prompt to run `opencode auth login` or configure a provider when needed; Pi surfaces a friendly prompt to run `pi /login` or configure a provider API key when needed. Tolaria does not store model-provider API keys in app settings.
|
||||
Each CLI agent authenticates itself outside Tolaria. Claude Code uses its existing CLI login; Codex surfaces a friendly prompt to run `codex login` when needed; OpenCode surfaces a friendly prompt to run `opencode auth login` or configure a provider when needed; Pi surfaces a friendly prompt to run `pi /login` or configure a provider API key when needed. Tolaria does not store model-provider API keys in app settings; direct provider secrets stay in local app data or user-managed environment variables.
|
||||
|
||||
## MCP Server
|
||||
|
||||
The MCP server (`mcp-server/`) exposes vault operations as tools for AI assistants (Claude Code, Cursor, or any MCP-compatible client).
|
||||
The MCP server (`mcp-server/`) exposes vault operations as tools for AI assistants (Claude Code, Gemini CLI, Cursor, or any MCP-compatible client).
|
||||
|
||||
### Tool Surface (14 tools)
|
||||
|
||||
@@ -326,10 +353,11 @@ The MCP server (`mcp-server/`) exposes vault operations as tools for AI assistan
|
||||
|
||||
Tolaria can register itself as an MCP server in:
|
||||
- `~/.claude.json` and `~/.claude/mcp.json` (Claude Code compatibility across current CLI and legacy MCP-file setups)
|
||||
- `~/.gemini/settings.json` (Gemini CLI)
|
||||
- `~/.cursor/mcp.json` (Cursor)
|
||||
- `~/.config/mcp/mcp.json` (generic MCP-compatible clients)
|
||||
|
||||
That setup is user-initiated through the status bar / command palette flow, not a startup side effect. Registration is non-destructive (additive, preserves other servers), uses `upsert` semantics, and can be reversed by removing Tolaria's entry again. Tolaria verifies Node.js is available before writing config, writes an explicit `type: "stdio"` entry, pins `VAULT_PATH` to the active vault, and sets `WS_UI_PORT=9711` so UI actions route back to the desktop app. Packaged builds resolve `mcp-server/` from the installed resource directory next to the executable before falling back to macOS `Resources`, Linux bundle paths, and AppImage paths. The `useMcpStatus` hook tracks whether the active vault is explicitly connected (`checking | installed | not_installed`). The desktop WebSocket bridge is started only when a persisted active vault exists and is resynced from React state on vault changes; no selected vault stops the bridge instead of falling back to `~/Laputa`.
|
||||
That setup is user-initiated through the status bar / command palette flow, not a startup side effect. Registration is non-destructive (additive, preserves other servers and Gemini settings), uses `upsert` semantics, and can be reversed by removing Tolaria's entry again. Tolaria verifies Node.js is available before writing config, writes an explicit `type: "stdio"` entry, pins `VAULT_PATH` to the active vault, and sets `WS_UI_PORT=9711` so UI actions route back to the desktop app. The same generated entry is exposed as a manual JSON snippet in the MCP setup dialog and through the AI panel copy action, giving users a transparent fallback for MCP-compatible tools Tolaria does not auto-configure. In the desktop app, `useMcpStatus` copies that snippet through the native `copy_text_to_clipboard` command instead of the Web Clipboard API so macOS WKWebView permission policy cannot block setup. Packaged builds resolve `mcp-server/` from the installed resource directory next to the executable before falling back to macOS `Resources`, Linux package roots such as `/usr/local/Tolaria`, `/usr/lib/tolaria`, and `/usr/lib/tolaria/resources`, and AppImage paths. The `useMcpStatus` hook tracks whether the active vault is explicitly connected (`checking | installed | not_installed`) and owns connect, disconnect, exact-snippet load, and copy-to-clipboard actions. Gemini CLI still owns its own install and sign-in; Tolaria writes the durable external MCP entry only on explicit setup, while app-managed Gemini sessions use transient settings and optional vault guidance. The desktop WebSocket bridge is started only when a persisted active vault exists and is resynced from React state on vault changes; no selected vault stops the bridge instead of falling back to `~/Laputa`. Stdio MCP server processes are owned by the external client that launched them: when that client closes stdin, Tolaria cancels UI-bridge reconnect timers, closes any UI WebSocket, and exits the Node process instead of keeping it alive in the background.
|
||||
|
||||
### Architecture
|
||||
|
||||
@@ -376,11 +404,12 @@ flowchart LR
|
||||
|----------|---------|
|
||||
| `spawn_ws_bridge(vault_path)` | Spawns `ws-bridge.js` as child process with VAULT_PATH env |
|
||||
| `sync_mcp_bridge_vault(vault_path?)` | Starts, restarts, or stops the desktop WebSocket bridge as the selected vault changes |
|
||||
| `register_mcp(vault_path)` | Verifies Node.js, resolves the packaged `mcp-server/`, and writes Tolaria's explicit stdio entry to Claude Code, Cursor, and generic MCP configs on user request |
|
||||
| `remove_mcp()` | Removes Tolaria's MCP entry from Claude Code, Cursor, and generic MCP configs |
|
||||
| `register_mcp(vault_path)` | Verifies Node.js, resolves the packaged `mcp-server/`, and writes Tolaria's explicit stdio entry to Claude Code, Gemini CLI, Cursor, and generic MCP configs on user request |
|
||||
| `mcp_config_snippet(vault_path)` | Builds the exact `mcpServers.tolaria` JSON users can copy into any compatible client without writing third-party config files |
|
||||
| `remove_mcp()` | Removes Tolaria's MCP entry from Claude Code, Gemini CLI, Cursor, and generic MCP configs |
|
||||
| `upsert_mcp_config(path, entry)` | Atomic config file update (create/merge, preserves others) |
|
||||
|
||||
The `WsBridgeChild` state wrapper in `lib.rs` ensures the bridge process is replaced on vault switches, stopped when no active vault is selected, and killed on app exit via the `RunEvent::Exit` handler. The same desktop layer now keeps the Tauri asset protocol scoped to the active vault instead of every filesystem path.
|
||||
The `WsBridgeChild` state wrapper in `lib.rs` ensures the bridge process is replaced on vault switches, stopped when no active vault is selected, and killed plus waited on app exit via the `RunEvent::Exit` handler. The same desktop layer keeps Tauri asset protocol access limited to vault roots loaded during the current app session; command calls remain active-vault scoped for reads, writes, and external opens.
|
||||
|
||||
## Search
|
||||
|
||||
@@ -425,7 +454,7 @@ The app uses internal app-owned light and dark themes (see [ADR-0081](adr/0081-i
|
||||
|
||||
1. **Global CSS variables** (`src/index.css`): Semantic app colors, borders, surfaces, and interaction states. Bridged to Tailwind v4 via `@theme inline`.
|
||||
2. **Editor theme** (`src/theme.json`): BlockNote-specific typography. Flattened to CSS vars by `useEditorTheme`; editor colors resolve through the same semantic app variables.
|
||||
3. **Theme runtime**: Applies `data-theme` and the shadcn-compatible `.dark` class before React consumers render, with a localStorage mirror to avoid startup flash when dark mode is selected.
|
||||
3. **Theme runtime**: Applies `data-theme` and the shadcn-compatible `.dark` class before React consumers render, with a localStorage mirror to avoid startup flash when dark mode is selected. Settings and command-palette theme actions both write the same installation-local `settings.theme_mode` value.
|
||||
|
||||
## Localization
|
||||
|
||||
@@ -468,15 +497,17 @@ On first launch, `useOnboarding` checks if the default vault exists. If not, it
|
||||
- **Open an existing folder** → system file picker; plain Markdown folders without `.git` open immediately in supported non-git mode
|
||||
- **Get started with a template** → pick a parent folder, then call `create_getting_started_vault()` with the derived `.../Getting Started` child path so the cloned vault opens into the populated repo root immediately
|
||||
|
||||
If the selected vault disappears after startup, `useVaultLoader` re-checks `check_vault_exists` when reloads or vault-derived surfaces fail. A confirmed missing path clears cached entries, folders, views, modified-file state, and prefetched note content, then `App` reuses the `vault-missing` `WelcomeScreen` state so note and view actions cannot keep targeting the stale active vault.
|
||||
|
||||
When an opened folder is not yet a git repo, Tolaria shows a dismissible Git setup dialog and a persistent `Git disabled` status-bar warning. Markdown scanning, note browsing, note editing, and search continue normally. Git-dependent surfaces (history, changes, commit, sync, conflict resolution, remotes, AutoGit, and auto-sync) stay unavailable until the user explicitly initializes Git from the dialog, the status-bar warning, or the `Initialize Git for Current Vault` command-palette action.
|
||||
|
||||
When the user enables Git later, `init_git_repo` runs `git init`, ensures Tolaria's default `.gitignore`, stages the vault, and writes the initial `Initial vault setup` commit. Before app-managed setup and remote-connection commits, Tolaria ensures the vault has local `user.name` / `user.email` values, falling back to `Tolaria <vault@tolaria.md>` when the vault has no local Git identity yet. That app-managed setup commit explicitly disables commit signing for the single command so inherited global or local `commit.gpgsign` preferences cannot strand onboarding when GPG is missing or misconfigured. Later `git_commit` calls honor the user's signing configuration first, then retry the same app-managed commit once with `commit.gpgsign=false` only when Git reports a signing-helper failure, so working GPG/SSH signing setups continue to sign while broken GPG setups do not create repeated opaque commit failures.
|
||||
|
||||
Once a vault is ready, `useAiAgentsOnboarding` can show a one-time `AiAgentsOnboardingPrompt`. That prompt reads `useAiAgentsStatus` so first launch surfaces whether Claude Code, Codex, OpenCode, and Pi are installed, offers per-agent install links when they are missing, and stores local dismissal so the prompt does not repeat on every launch.
|
||||
Once a vault is ready, `useAiAgentsOnboarding` can show a one-time `AiAgentsOnboardingPrompt`. That prompt reads `useAiAgentsStatus` so first launch surfaces whether Claude Code, Codex, OpenCode, Pi, and Gemini CLI are installed, offers per-agent install links when they are missing, and stores local dismissal so the prompt does not repeat on every launch.
|
||||
|
||||
`useGettingStartedClone` reuses the same parent-folder semantics for the status-bar / command-palette clone action, and `Toast` is rendered through the AI-agents onboarding gate so the resolved destination path stays visible right after a successful clone.
|
||||
|
||||
The starter content no longer lives in the app repo. `src-tauri/src/vault/getting_started.rs` holds the public starter repo URL (`refactoringhq/tolaria-getting-started`), delegates the clone to the git backend, then normalizes Tolaria-managed root guidance and type scaffolding (`AGENTS.md`, `CLAUDE.md`, `type.md`, `note.md`) so fresh starter vaults pick up the current defaults even when the remote starter repo still carries a legacy copy or an older pre-`type:` `is_a`-era template. `AGENTS.md` stays the canonical vault guidance file; `CLAUDE.md` is a compatibility shim that imports it for Claude Code without duplicating the instructions, and Tolaria seeds it as an organized `Note` so it stays out of the way in a fresh vault. The clone helper still accepts the legacy `LAPUTA_GETTING_STARTED_REPO_URL` environment override so older automation can continue to redirect the starter source during the transition.
|
||||
The starter content no longer lives in the app repo. `src-tauri/src/vault/getting_started.rs` holds the public starter repo URL (`refactoringhq/tolaria-getting-started`), delegates the clone to the git backend, then normalizes Tolaria-managed root guidance and type scaffolding (`AGENTS.md`, `CLAUDE.md`, `type.md`, `note.md`) so fresh starter vaults pick up the current defaults even when the remote starter repo still carries a legacy copy or an older pre-`type:` `is_a`-era template. `AGENTS.md` stays the canonical vault guidance file; `CLAUDE.md` is a compatibility shim that imports it for Claude Code without duplicating the instructions, and Tolaria seeds it as an organized `Note` so it stays out of the way in a fresh vault. Optional `GEMINI.md` guidance is created only by the explicit AI guidance restore action. The clone helper still accepts the legacy `LAPUTA_GETTING_STARTED_REPO_URL` environment override so older automation can continue to redirect the starter source during the transition.
|
||||
|
||||
After the clone completes, Tolaria removes every configured git remote from the new starter vault. Getting Started vaults therefore open as local-only by default, and users opt into a remote later with the explicit Add Remote flow.
|
||||
|
||||
@@ -488,8 +519,9 @@ Tolaria no longer implements provider-specific OAuth or remote-repository APIs.
|
||||
1. User opens `CloneVaultModal` from onboarding or the vault menu
|
||||
2. User pastes any git URL and chooses a local destination
|
||||
3. The `clone_git_repo()` Tauri command runs `git clone` inside a blocking Tokio task so the Tauri window stays responsive during slow or failing clones
|
||||
4. `git_push()` / `git_pull()` continue to use the same system git path
|
||||
5. Clone commands disable interactive terminal / askpass prompts and surface the git failure back to the UI instead of freezing the app waiting for input
|
||||
4. Linux AppImage builds strip AppImage loader variables from system-git subprocesses before spawning `git`, keeping `git-remote-https` on the host git/library stack
|
||||
5. `git_push()` / `git_pull()` continue to use the same system git path
|
||||
6. Clone commands disable interactive terminal / askpass prompts and surface the git failure back to the UI instead of freezing the app waiting for input
|
||||
|
||||
**Auth model:**
|
||||
- SSH keys, Git Credential Manager, macOS Keychain helpers, `gh auth`, and other git helpers all work without app-specific setup
|
||||
@@ -520,9 +552,9 @@ sequenceDiagram
|
||||
participant MCP as MCP Server
|
||||
participant U as User
|
||||
|
||||
T->>T: apply Linux AppImage WebKit env override<br/>(AppImage only)
|
||||
T->>T: run_startup_tasks()<br/>(migrate + seed only)
|
||||
T->>MCP: spawn_ws_bridge() — ports 9710 + 9711
|
||||
T->>T: apply Linux AppImage WebKit env/preload safeguards<br/>(AppImage only)
|
||||
T->>T: start background legacy vault housekeeping<br/>(does not block setup)
|
||||
T->>MCP: start background initial ws-bridge sync<br/>(if active vault exists)
|
||||
T->>A: App mounts
|
||||
|
||||
A->>A: useOnboarding — vault exists?
|
||||
@@ -530,10 +562,16 @@ sequenceDiagram
|
||||
A-->>U: WelcomeScreen
|
||||
else Vault found
|
||||
A->>VL: useVaultLoader fires
|
||||
VL->>T: invoke('reload_vault') → sync active vault asset scope + scan_vault_cached()
|
||||
VL->>T: invoke('reload_vault') → allow requested vault roots in asset scope + scan_vault_cached()
|
||||
T-->>VL: VaultEntry[]
|
||||
VL->>T: invoke('get_modified_files')
|
||||
alt Runtime vault path disappears
|
||||
VL->>T: invoke('check_vault_exists')
|
||||
VL-->>A: unavailable vault path + cleared stale state
|
||||
A-->>U: WelcomeScreen (vault missing)
|
||||
end
|
||||
A->>T: useMcpStatus — check explicit MCP setup state
|
||||
A->>T: sync_mcp_bridge_vault(selected path)
|
||||
VL-->>A: entries ready
|
||||
end
|
||||
|
||||
@@ -620,12 +658,12 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
| `parsing.rs` | Text processing: snippet extraction, markdown stripping, ISO date parsing, `extract_title` (H1 → legacy frontmatter → filename), `slug_to_title` |
|
||||
| `title_sync.rs` | Legacy filename → `title` frontmatter sync helper; no longer used by the normal note-open flow |
|
||||
| `cache.rs` | Git-based incremental vault caching (`scan_vault_cached`), git helpers |
|
||||
| `ignored.rs` | Gitignored-content visibility filtering via batched `git check-ignore` |
|
||||
| `ignored.rs` | Gitignored-content visibility filtering via batched, pipe-safe `git check-ignore` |
|
||||
| `filename_rules.rs` | Cross-platform validation for note filenames, folder names, and custom view filenames |
|
||||
| `rename.rs` | `rename_note` / `rename_note_filename` / `move_note_to_folder` — stage crash-safe file moves, update `title` frontmatter when needed, recover unfinished rename transactions, and report backlink rewrite failures |
|
||||
| `image.rs` | `save_image` / `copy_image_to_vault` — save editor image attachments with sanitized filenames |
|
||||
| `migration.rs` | `flatten_vault`, `vault_health_check`, `migrate_is_a_to_type` |
|
||||
| `config_seed.rs` | Maintains vault AI guidance (`AGENTS.md` + `CLAUDE.md` shim), migrates legacy `config/agents.md`, and repairs missing root type scaffolding such as `type.md` and `note.md` |
|
||||
| `config_seed.rs` | Maintains vault AI guidance (`AGENTS.md`, `CLAUDE.md`, and optional `GEMINI.md` shims), migrates legacy `config/agents.md`, and repairs missing root type scaffolding such as `type.md` and `note.md` |
|
||||
| `getting_started.rs` | Clones and normalizes the public Getting Started starter vault |
|
||||
|
||||
## Rust Backend Modules
|
||||
@@ -636,8 +674,9 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
| `frontmatter/` | YAML frontmatter read/write (`mod.rs`, `yaml.rs`, `ops.rs`) |
|
||||
| `git/` | Git operations (`commit.rs`, `status.rs`, `history.rs`, `conflict.rs`, `remote.rs`, `pulse.rs`, `clone.rs`, `connect.rs`) |
|
||||
| `search.rs` | Keyword search — walkdir-based vault file scan with Gitignored-content visibility filtering |
|
||||
| `ai_agents.rs` | Shared CLI-agent detection, stream normalization, and adapter dispatch |
|
||||
| `claude_cli.rs` | Claude Code subprocess spawning + NDJSON stream parsing |
|
||||
| `ai_agents.rs` | CLI-agent request normalization and adapter dispatch |
|
||||
| `cli_agent_runtime.rs` | Shared CLI-agent request, prompt, subprocess, version, and MCP path helpers |
|
||||
| `claude_cli.rs`, `codex_cli.rs`, `opencode_cli.rs`, `pi_cli.rs`, `gemini_cli.rs` | CLI-agent command/config/event adapters |
|
||||
| `pi_cli.rs`, `pi_config.rs`, `pi_discovery.rs`, `pi_events.rs` | Pi subprocess launch, transient MCP adapter config, discovery, and JSON stream parsing |
|
||||
| `mcp.rs` | MCP server spawning + explicit config registration/removal |
|
||||
| `commands/` | Tauri command handlers (split into submodules) |
|
||||
@@ -659,18 +698,20 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
| `rename_note` | Crash-safe note rename + `title` frontmatter update + cross-vault wikilinks + failed backlink counts |
|
||||
| `move_note_to_folder` | Crash-safe folder move that preserves the filename, reloads the moved note, and rewrites path-based wikilinks |
|
||||
| `create_vault_folder` | Create a folder relative to the active vault root |
|
||||
| `list_vault_folders` | Build the folder tree on the blocking Tokio pool, then apply Gitignored-content visibility → `Vec<FolderNode>` |
|
||||
| `rename_vault_folder` | Rename a folder relative to the active vault root and return old/new relative paths |
|
||||
| `delete_vault_folder` | Permanently delete a folder subtree relative to the active vault root |
|
||||
| `sync_note_title` | Legacy helper: rewrite `title` frontmatter from filename → `bool` (modified); not used by the normal note-open flow |
|
||||
| `batch_archive_notes` | Archive multiple notes |
|
||||
| `batch_delete_notes` | Permanently delete notes from disk |
|
||||
| `reload_vault` | Sync the active vault asset scope, invalidate cache, full rescan from filesystem, then apply Gitignored-content visibility → `Vec<VaultEntry>` |
|
||||
| `reload_vault` | Allow the requested vault roots in the runtime asset scope, invalidate cache, full rescan from filesystem, then apply Gitignored-content visibility → `Vec<VaultEntry>` |
|
||||
| `reload_vault_entry` | Re-read a single file from disk → `VaultEntry` |
|
||||
| `open_vault_file_external` | Validate an existing file against the active vault boundary, then open it with the system default app |
|
||||
| `start_vault_watcher` / `stop_vault_watcher` | Start or stop native active-vault filesystem change events |
|
||||
| `check_vault_exists` | Check if vault path exists |
|
||||
| `create_empty_vault` | Create a git-backed vault, then seed root `AGENTS.md`, `CLAUDE.md`, `type.md`, and `note.md` defaults |
|
||||
| `create_getting_started_vault` | Clone the public Getting Started vault, refresh Tolaria-managed guidance/config defaults, and keep the cloned repo clean |
|
||||
| `get_vault_ai_guidance_status` | Report whether `AGENTS.md` and the `CLAUDE.md` shim are managed, missing, broken, or custom |
|
||||
| `get_vault_ai_guidance_status` | Report whether `AGENTS.md`, `CLAUDE.md`, and optional `GEMINI.md` guidance are managed, missing, broken, or custom |
|
||||
| `restore_vault_ai_guidance` | Restore any missing/broken Tolaria-managed guidance files without overwriting custom ones |
|
||||
|
||||
### Frontmatter
|
||||
@@ -722,11 +763,14 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
|---------|-------------|
|
||||
| `stream_claude_chat` | Claude CLI chat mode (streaming) |
|
||||
| `check_claude_cli` | Check if Claude CLI is available |
|
||||
| `get_ai_agents_status` | Check Claude Code + Codex + OpenCode + Pi availability |
|
||||
| `stream_ai_agent` | Stream Claude Code, Codex, OpenCode, or Pi through the normalized agent event layer |
|
||||
| `register_mcp_tools` | Register MCP in Claude/Cursor/generic config for the active vault |
|
||||
| `remove_mcp_tools` | Remove Tolaria's MCP entry from Claude/Cursor/generic config |
|
||||
| `check_mcp_status` | Check whether the active vault is explicitly registered in Claude/Cursor/generic config |
|
||||
| `get_ai_agents_status` | Check Claude Code + Codex + OpenCode + Pi + Gemini availability |
|
||||
| `stream_ai_agent` | Stream Claude Code, Codex, OpenCode, Pi, or Gemini through the normalized agent event layer |
|
||||
| `register_mcp_tools` | Register MCP in Claude/Gemini/Cursor/generic config for the active vault |
|
||||
| `remove_mcp_tools` | Remove Tolaria's MCP entry from Claude/Gemini/Cursor/generic config |
|
||||
| `check_mcp_status` | Check whether the active vault is explicitly registered in Claude/Gemini/Cursor/generic config |
|
||||
| `get_mcp_config_snippet` | Return the exact manual MCP JSON snippet for the active vault |
|
||||
| `copy_text_to_clipboard` | Copy setup snippets through the native desktop clipboard command path |
|
||||
| `read_text_from_clipboard` | Read current desktop clipboard text for command-driven plain-text paste |
|
||||
| `sync_mcp_bridge_vault` | Sync the desktop WebSocket bridge process to the selected vault, or stop it when no vault is selected |
|
||||
|
||||
The desktop MCP WebSocket bridge is intentionally local-only. `mcp-server/ws-bridge.js` binds both bridge ports to loopback, rejects non-loopback clients, accepts browser/Tauri origins only on the UI bridge, and rejects browser-origin requests on the tool bridge so remote pages cannot drive vault tools directly.
|
||||
@@ -743,8 +787,8 @@ The desktop MCP WebSocket bridge is intentionally local-only. `mcp-server/ws-bri
|
||||
| `save_vault_config` | Save per-vault UI config |
|
||||
| `get_default_vault_path` | Get default vault path |
|
||||
| `get_build_number` | Get app build number |
|
||||
| `save_image` | Save base64 image to `attachments/` and refresh the active vault asset scope |
|
||||
| `copy_image_to_vault` | Copy image file to `attachments/` and refresh the active vault asset scope |
|
||||
| `save_image` | Save base64 image to `attachments/` and ensure the vault root is in the runtime asset scope |
|
||||
| `copy_image_to_vault` | Copy image file to `attachments/` and ensure the vault root is in the runtime asset scope |
|
||||
| `update_menu_state` | Update native menu checkmarks and enabled/disabled state for selection-dependent actions |
|
||||
| `trigger_menu_command` | Emit a native menu command ID for deterministic shortcut QA |
|
||||
| `update_current_window_min_size` | Update the active Tauri window's minimum size and optionally grow it to fit restored panes |
|
||||
@@ -785,15 +829,15 @@ No Redux or global context. State lives in the root `App.tsx` and custom hooks:
|
||||
| `useTabManagement` | Navigation history, note switching | Note navigation lifecycle |
|
||||
| `useVaultSwitcher` | `vaultPath`, `extraVaults` | Vault switching |
|
||||
| `useTheme` | Editor theme CSS vars and theme-mode bridge | Editor typography and app theme runtime |
|
||||
| `useCliAiAgent` | `messages`, `status`, tool actions | Selected AI agent conversation backed by the shared session pipeline |
|
||||
| `useCliAiAgent` | `messages`, `status`, tool actions | Selected AI agent conversation backed by the shared session pipeline and vault permission mode |
|
||||
| `useAutoSync` | Sync interval, pull/push state | Git auto-sync |
|
||||
| `useAutoGit` | Last activity timestamp, idle/inactive checkpoint triggers | Automatic commit/push checkpoints |
|
||||
| `useCommitFlow` | Commit dialog state, shared manual/automatic checkpoint runner | Git commit/push orchestration |
|
||||
| `useGitRemoteStatus` | `remoteStatus`, `refreshRemoteStatus()` | On-demand remote detection for commit UI |
|
||||
| `useUnifiedSearch` | Query, results, loading state | Keyword search |
|
||||
| `useSettings` | App settings (telemetry, release channel, theme mode, UI language, auto-sync interval, AutoGit thresholds, default AI agent, Gitignored-content visibility) | Persistent settings |
|
||||
| `useVaultConfig` | Per-vault UI preferences | Vault-specific config |
|
||||
| `appCommandDispatcher` | Canonical shortcut/menu command IDs | Shared execution path for renderer and native menu commands |
|
||||
| `useSettings` | App settings (telemetry, release channel, theme mode, UI language, auto-sync interval, AutoGit thresholds, default AI agent, Gitignored-content visibility, All Notes file visibility) | Persistent settings |
|
||||
| `useVaultConfig` | Per-vault UI preferences, AI permission mode | Vault-specific config |
|
||||
| `appCommandDispatcher` | Manifest-backed shortcut/menu command IDs | Shared execution path for renderer and native menu commands |
|
||||
|
||||
Data flows unidirectionally: `App` passes data and callbacks as props to child components. No child-to-child communication — everything goes through `App`.
|
||||
|
||||
@@ -807,6 +851,7 @@ Data flows unidirectionally: `App` passes data and callbacks as props to child c
|
||||
| Cmd+S | Save current note |
|
||||
| Cmd+F | Find in current note when the editor is focused; otherwise note-list search can claim it |
|
||||
| Cmd+Shift+F | Find in vault |
|
||||
| Cmd+Shift+V | Paste without Formatting into the active supported editing surface |
|
||||
| Cmd+[ / Cmd+] | Navigate back / forward (replaces tabs) |
|
||||
| Cmd+Z / Cmd+Shift+Z | Undo / Redo |
|
||||
| Cmd+1–9 | Switch to tab N |
|
||||
@@ -817,12 +862,14 @@ Selection-dependent actions are wired through the command palette and the native
|
||||
|
||||
Shortcut routing is explicit:
|
||||
|
||||
- `appCommandCatalog.ts` is the shared shortcut manifest for command IDs, modifier rules, and deterministic QA metadata
|
||||
- `src/shared/appCommandManifest.json` is the shared command/menu metadata source for command IDs, menu labels, accelerators, native-menu enablement groups, and deterministic QA flags
|
||||
- `appCommandCatalog.ts` derives renderer command IDs, shortcut lookup maps, Linux menu sections, and QA metadata from that manifest
|
||||
- `formatShortcutDisplay()` derives platform-accurate visible shortcut labels (`⌘` on macOS, `Ctrl` on Windows/Linux) from that same manifest so menus, tooltips, and command-palette copy stay aligned with real accelerators
|
||||
- `useAppKeyboard` is the primary execution path for real shortcut keypresses, including Tauri runs
|
||||
- macOS browser-reserved chords such as `Cmd+O`, `Cmd+F`, and `Cmd+Shift+L` are unblocked at webview init via `tauri-plugin-prevent-default`, then continue through the same renderer-first command path
|
||||
- `Cmd+Shift+V` uses the same command path for "Paste without Formatting"; `plainTextPaste.ts` reads text through the native clipboard command in Tauri and inserts it through the active rich/raw editor target or the focused browser text control
|
||||
- `Cmd+F` is surface-aware: editor focus opens current-note find/replace in raw CodeMirror, note-list focus preserves note-list search, and native menu enablement follows focus availability events so only one `Cmd+F` menu item is active
|
||||
- `menu.rs`, `useMenuEvents`, and Linux's `LinuxMenuButton` emit the same command IDs for native menu clicks, accelerators, and custom titlebar menu actions
|
||||
- `menu.rs`, `useMenuEvents`, and Linux's `LinuxMenuButton` emit the same manifest-derived command IDs for native menu clicks, accelerators, and custom titlebar menu actions
|
||||
- `appCommandDispatcher.ts` suppresses the paired native-menu/renderer echo from a single shortcut so the command runs once
|
||||
- Deterministic QA uses two explicit proof paths from the shared manifest:
|
||||
- renderer shortcut-event proof through `window.__laputaTest.triggerShortcutCommand()`
|
||||
@@ -938,11 +985,12 @@ sequenceDiagram
|
||||
- `anonymous_id` is a locally-generated UUID, never tied to identity
|
||||
- `send_default_pii: false` on both SDKs
|
||||
- PostHog: `autocapture: false`, `persistence: 'memory'`, no cookies
|
||||
- Product events use categorical metadata only: file preview kind/action, AI agent id/permission mode/counts/status, and All Notes visibility category/enabled state.
|
||||
|
||||
**Architecture:**
|
||||
- **Rust:** `sentry` crate initialized in `lib.rs::setup()` via `telemetry::init_sentry_from_settings()`
|
||||
- **JS:** `@sentry/react` + `posthog-js` initialized lazily by `useTelemetry` hook; the React root also wires `onCaughtError`, `onUncaughtError`, and `onRecoverableError` through `Sentry.reactErrorHandler()` so production React invariants include component stack context when crash reporting is enabled.
|
||||
- **Release grouping:** packaged release workflows pass `VITE_SENTRY_RELEASE` from the computed build version so frontend Sentry events group by the shipped alpha or stable version.
|
||||
- **Release grouping:** packaged release workflows pass `VITE_SENTRY_RELEASE` from the computed build version, but the app only assigns Sentry's `release` field for stable calendar builds (`YYYY.M.D`). Alpha/prerelease/internal builds omit `release` so they do not create normal Sentry Releases entries, while both frontend and Rust Sentry scopes tag `tolaria.build_version` and `tolaria.release_kind` for diagnostics.
|
||||
- **Settings:** `telemetry_consent`, `crash_reporting_enabled`, `analytics_enabled`, `anonymous_id` in `Settings` struct
|
||||
- **Consent:** `TelemetryConsentDialog` shown when `telemetry_consent === null`
|
||||
|
||||
@@ -997,7 +1045,7 @@ Desktop-only modules gated at the crate level:
|
||||
Desktop-only features gated at the function level in `commands/`:
|
||||
- Git operations (commit, pull, push, status, history, diff, conflicts)
|
||||
- Clone-by-URL via system git (`clone_repo`)
|
||||
- CLI AI agent streaming (Claude, Codex, OpenCode, Pi)
|
||||
- CLI AI agent streaming (Claude, Codex, OpenCode, Pi, Gemini)
|
||||
- MCP registration and status
|
||||
- Menu state updates
|
||||
|
||||
|
||||
@@ -29,6 +29,22 @@ If you run the desktop app on Linux, install Tauri's WebKit2GTK 4.1 dependencies
|
||||
libappindicator-gtk3-devel librsvg2-devel
|
||||
```
|
||||
|
||||
### Linux AppImage Wayland troubleshooting
|
||||
|
||||
On some Wayland systems, the Linux AppImage may fail to launch with:
|
||||
|
||||
```text
|
||||
Could not create default EGL display: EGL_BAD_PARAMETER. Aborting...
|
||||
```
|
||||
|
||||
Recent Tolaria AppImages automatically disable unstable WebKitGTK AppImage rendering paths and retry startup with an architecture-matching system Wayland client library when they detect this class of AppImage + Wayland environment. If you are running an older build, use this workaround:
|
||||
|
||||
```bash
|
||||
WEBKIT_DISABLE_COMPOSITING_MODE=1 WEBKIT_DISABLE_DMABUF_RENDERER=1 LD_PRELOAD=/usr/lib64/libwayland-client.so.0 ./Tolaria*.AppImage
|
||||
```
|
||||
|
||||
If your distribution stores the 64-bit library elsewhere, use that path instead, for example `/usr/lib/x86_64-linux-gnu/libwayland-client.so.0`. On 64-bit Fedora, avoid `/usr/lib/libwayland-client.so.0`; that path can point at a 32-bit library and be ignored by the loader with a wrong ELF class warning.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
@@ -53,6 +69,8 @@ pnpm playwright:regression # Full Playwright regression suite
|
||||
|
||||
`create_getting_started_vault` clones the public starter repo and then removes every git remote from the new local copy. That means Getting Started vaults open local-only by default. Users connect a compatible remote later through the bottom-bar `No remote` chip or the command palette, both of which feed the same `AddRemoteModal` and `git_add_remote` backend flow.
|
||||
|
||||
Linux AppImage builds still use the user's system `git`. Before Tolaria spawns that `git` process, it removes AppImage loader overrides such as `LD_LIBRARY_PATH`, `LD_PRELOAD`, and `GIT_EXEC_PATH` so HTTPS clone helpers use the host git libraries instead of bundled AppImage libraries.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
@@ -79,7 +97,7 @@ tolaria/
|
||||
│ │ ├── RawEditorView.tsx # CodeMirror raw editor
|
||||
│ │ ├── Inspector.tsx # Fourth panel: metadata + relationships
|
||||
│ │ ├── DynamicPropertiesPanel.tsx # Editable frontmatter properties
|
||||
│ │ ├── AiPanel.tsx # AI agent panel (selected CLI agent)
|
||||
│ │ ├── AiPanel.tsx # AI agent panel (selected CLI agent + per-vault permission mode)
|
||||
│ │ ├── AiMessage.tsx # Agent message display
|
||||
│ │ ├── AiActionCard.tsx # Agent tool action cards
|
||||
│ │ ├── AiAgentsOnboardingPrompt.tsx # First-launch AI agent installer prompt
|
||||
@@ -114,7 +132,8 @@ tolaria/
|
||||
│ │ ├── useNoteCreation.ts # Note/type creation
|
||||
│ │ ├── useNoteRename.ts # Note renaming + wikilink updates
|
||||
│ │ ├── useCliAiAgent.ts # Selected AI agent state + normalized session pipeline
|
||||
│ │ ├── useAiAgentsStatus.ts # Claude/Codex/OpenCode/Pi availability polling
|
||||
│ │ ├── aiAgentPermissionMode.ts # Safe/Power User mode normalization + labels
|
||||
│ │ ├── useAiAgentsStatus.ts # Claude/Codex/OpenCode/Pi/Gemini availability polling
|
||||
│ │ ├── useAiAgentPreferences.ts # Default-agent persistence + cycling
|
||||
│ │ ├── useAiActivity.ts # MCP UI bridge listener
|
||||
│ │ ├── useAutoSync.ts # Auto git pull/push
|
||||
@@ -140,6 +159,7 @@ tolaria/
|
||||
│ ├── utils/ # Pure utility functions (~48 files)
|
||||
│ │ ├── wikilinks.ts # Wikilink preprocessing pipeline
|
||||
│ │ ├── frontmatter.ts # TypeScript YAML parser
|
||||
│ │ ├── plainTextPaste.ts # Shared Paste without Formatting command target registry
|
||||
│ │ ├── platform.ts # Runtime platform + Linux chrome gating helpers
|
||||
│ │ ├── ai-agent.ts # Agent stream utilities
|
||||
│ │ ├── ai-chat.ts # Token estimation utilities
|
||||
@@ -188,9 +208,11 @@ tolaria/
|
||||
│ │ │ ├── conflict.rs, remote.rs, pulse.rs
|
||||
│ │ ├── telemetry.rs # Sentry init + path scrubber
|
||||
│ │ ├── search.rs # Keyword search (walkdir-based)
|
||||
│ │ ├── ai_agents.rs # Shared CLI-agent detection + stream adapters
|
||||
│ │ ├── claude_cli.rs # Claude CLI subprocess management
|
||||
│ │ ├── pi_cli.rs # Pi CLI subprocess management
|
||||
│ │ ├── ai_agents.rs # CLI-agent request normalization + adapter dispatch
|
||||
│ │ ├── cli_agent_runtime.rs # Shared CLI-agent runtime process/prompt/MCP helpers
|
||||
│ │ ├── claude_cli.rs # Claude CLI adapter
|
||||
│ │ ├── codex_cli.rs # Codex CLI adapter
|
||||
│ │ ├── pi_cli.rs # Pi CLI adapter
|
||||
│ │ ├── mcp.rs # MCP server lifecycle + explicit config registration/removal
|
||||
│ │ ├── app_updater.rs # Alpha/stable updater endpoint selection
|
||||
│ │ ├── settings.rs # App settings persistence
|
||||
@@ -261,9 +283,9 @@ tolaria/
|
||||
| `src-tauri/src/frontmatter/ops.rs` | YAML manipulation — how properties are updated/deleted in files. |
|
||||
| `src-tauri/src/git/` | All git operations (clone, commit, pull, push, conflicts, pulse, add-remote). |
|
||||
| `src-tauri/src/search.rs` | Keyword search — scans vault files with walkdir. |
|
||||
| `src-tauri/src/ai_agents.rs` | Shared CLI-agent availability checks, adapter dispatch, and stream normalization. |
|
||||
| `src-tauri/src/claude_cli.rs` | Claude CLI subprocess spawning + NDJSON stream parsing. |
|
||||
| `src-tauri/src/pi_cli.rs` | Pi subprocess spawning through JSON mode and transient MCP adapter config. |
|
||||
| `src-tauri/src/ai_agents.rs` | CLI-agent request normalization, availability aggregation, adapter dispatch, and Claude event mapping. |
|
||||
| `src-tauri/src/cli_agent_runtime.rs` | Shared CLI-agent request shape, prompt wrapping, JSON subprocess lifecycle, version probing, and MCP path helpers. |
|
||||
| `src-tauri/src/claude_cli.rs`, `src-tauri/src/codex_cli.rs`, `src-tauri/src/opencode_cli.rs`, `src-tauri/src/pi_cli.rs`, `src-tauri/src/gemini_cli.rs` | Per-agent command, config, discovery, and JSON event adapters. |
|
||||
| `src-tauri/src/app_updater.rs` | Desktop updater bridge — selects alpha/stable manifests and streams install progress. |
|
||||
|
||||
### Editor
|
||||
@@ -282,9 +304,10 @@ tolaria/
|
||||
|
||||
| File | Why it matters |
|
||||
|------|---------------|
|
||||
| `src/components/AiPanel.tsx` | AI agent panel — selected CLI agent with tool execution, reasoning, and actions. |
|
||||
| `src/components/AiPanel.tsx` | AI agent panel — selected CLI agent with tool execution, reasoning, actions, and per-vault permission mode. |
|
||||
| `src/hooks/useCliAiAgent.ts` | Thin React owner for the selected CLI agent session state. |
|
||||
| `src/lib/aiAgentSession.ts` | Single message/session lifecycle for prompt normalization, history, streaming, and reset behavior. |
|
||||
| `src/lib/aiAgentPermissionMode.ts` | Safe/Power User mode normalization, display labels, and local transcript marker text. |
|
||||
| `src/lib/aiAgentFileOperations.ts` | Detects agent-created or modified vault files from normalized tool inputs. |
|
||||
| `src/lib/aiAgents.ts` | Supported agent definitions, status normalization, and default-agent helpers. |
|
||||
| `src/utils/ai-context.ts` | Context snapshot builder for AI conversations. |
|
||||
@@ -304,7 +327,7 @@ tolaria/
|
||||
| `src/lib/releaseChannel.ts` | Normalizes persisted updater-channel values (`stable` default, optional `alpha`). |
|
||||
| `src/lib/appUpdater.ts` | Frontend wrapper for channel-aware updater commands. |
|
||||
| `src/hooks/useMainWindowSizeConstraints.ts` | Derives the main-window minimum width from the visible panes and asks Tauri to grow back to fit wider layouts. |
|
||||
| `src/hooks/useVaultConfig.ts` | Per-vault local UI preferences (zoom, view mode, colors, Inbox columns, explicit organization workflow). |
|
||||
| `src/hooks/useVaultConfig.ts` | Per-vault local UI preferences (zoom, view mode, colors, Inbox columns, explicit organization workflow, AI permission mode). |
|
||||
| `src/components/SettingsPanel.tsx` | Settings UI for telemetry, release channel, sync interval, UI language, default AI agent, and the vault-level explicit organization toggle. |
|
||||
| `src/hooks/useUpdater.ts` | In-app updates using the selected alpha/stable feed. |
|
||||
|
||||
@@ -341,7 +364,7 @@ type SidebarSelection =
|
||||
|
||||
### Command Registry
|
||||
|
||||
`useCommandRegistry` + `useAppCommands` build a centralized command registry. Commands are registered with labels, shortcuts, and handlers. The `CommandPalette` (Cmd+K) fuzzy-searches this registry. Shortcut combos live in `appCommandCatalog.ts`; real keypresses always flow through `useAppKeyboard`, native menu clicks emit the same command IDs through `useMenuEvents`, and `appCommandDispatcher.ts` suppresses the duplicate native/renderer echo from a single shortcut. On macOS, any browser-reserved chord that WKWebView swallows before that path must also be added to the narrow `tauri-plugin-prevent-default` registration in `src-tauri/src/lib.rs`. On Linux, `LinuxTitlebar.tsx` and `LinuxMenuButton.tsx` reuse the same command IDs through `trigger_menu_command` because the native GTK menu bar is intentionally not mounted. The same shortcut manifest also declares the deterministic QA mode for each shortcut-capable command.
|
||||
`useCommandRegistry` + `useAppCommands` build a centralized command registry. Commands are registered with labels, shortcuts, and handlers. The `CommandPalette` (Cmd+K) fuzzy-searches this registry. Settings commands can update installation-local preferences directly when they reuse an existing settings path, such as the light/dark theme-mode actions writing `settings.theme_mode`. Shortcut combos live in `appCommandCatalog.ts`; real keypresses always flow through `useAppKeyboard`, native menu clicks emit the same command IDs through `useMenuEvents`, and `appCommandDispatcher.ts` suppresses the duplicate native/renderer echo from a single shortcut. Plain-text paste follows this same path: the command owns `Cmd+Shift+V`, the menu and palette expose the same action, and `plainTextPaste.ts` resolves the active rich/raw editor target or focused text control before reading clipboard text. On macOS, any browser-reserved chord that WKWebView swallows before that path must also be added to the narrow `tauri-plugin-prevent-default` registration in `src-tauri/src/lib.rs`. On Linux, `LinuxTitlebar.tsx` and `LinuxMenuButton.tsx` reuse the same command IDs through `trigger_menu_command` because the native GTK menu bar is intentionally not mounted. The same shortcut manifest also declares the deterministic QA mode for each shortcut-capable command.
|
||||
|
||||
Commands whose availability depends on the current note or Git state must also flow through `update_menu_state` so the native menu stays in sync with the command palette. The deleted-note restore action in Changes view is the reference example: the row opens a deleted diff preview, the command palette exposes "Restore Deleted Note", and the Note menu enables the same action only while that preview is active.
|
||||
|
||||
@@ -386,7 +409,7 @@ BASE_URL="http://localhost:5173" npx playwright test tests/smoke/<slug>.spec.ts
|
||||
1. Write the Rust function in the appropriate module (`vault/`, `git/`, etc.)
|
||||
2. Add a command handler in `commands/`
|
||||
3. Register it in the `generate_handler![]` macro in `lib.rs`
|
||||
4. Call it from the frontend via `invoke()` in the appropriate hook
|
||||
4. Call it from the frontend via `invoke()` in the appropriate hook or utility, keeping native-only permission work behind the Tauri command boundary
|
||||
5. Add a mock handler in `mock-tauri.ts`
|
||||
|
||||
### Add a new component
|
||||
@@ -398,7 +421,7 @@ BASE_URL="http://localhost:5173" npx playwright test tests/smoke/<slug>.spec.ts
|
||||
|
||||
### Add a new entity type
|
||||
|
||||
1. Create a type document: `type/mytype.md` with `type: Type` frontmatter (icon, color, order, etc.)
|
||||
1. Create a type document at the vault root: `mytype.md` with `type: Type` frontmatter (icon, color, order, etc.)
|
||||
2. The sidebar section groups are auto-generated from type documents — no code change needed if `visible: true`
|
||||
3. Update `CreateNoteDialog.tsx` type options if users should be able to create it from the dialog
|
||||
4. Notes of this type are created at the vault root with `type: MyType` in frontmatter — no dedicated folder needed
|
||||
@@ -420,11 +443,14 @@ BASE_URL="http://localhost:5173" npx playwright test tests/smoke/<slug>.spec.ts
|
||||
1. **Agent system prompt**: Edit `src/utils/ai-agent.ts` (inline system prompt string)
|
||||
2. **Context building**: Edit `src/utils/ai-context.ts` for what data is sent to the agent
|
||||
3. **Tool action display**: Edit `src/components/AiActionCard.tsx`
|
||||
4. **Claude CLI arguments**: Edit `src-tauri/src/claude_cli.rs` (`run_agent_stream()`; keep app-managed launches on strict Tolaria MCP config, `acceptEdits`, and the scoped file/search tool list)
|
||||
5. **Shared agent adapters / Codex/Pi args**: Edit `src-tauri/src/ai_agents.rs` plus the per-agent adapter modules (keep Codex sandboxed with active-vault `workspace-write`, keep Pi on transient MCP config, and do not use dangerous permission bypasses unless an ADR explicitly designs a new mode)
|
||||
4. **Permission-mode UI and request plumbing**: Edit `src/lib/aiAgentPermissionMode.ts`, `src/components/AiPanel*.tsx`, `src/hooks/useCliAiAgent.ts`, and `src/utils/streamAiAgent.ts`
|
||||
5. **Shared CLI runtime behavior**: Edit `src-tauri/src/cli_agent_runtime.rs` for process lifecycle, prompt wrapping, version probing, and common Tolaria MCP path handling.
|
||||
6. **Agent-specific arguments/events**: Edit the per-agent adapter modules (`claude_cli.rs`, `codex_cli.rs`, `opencode_*`, `pi_*`, `gemini_*`). Keep Codex Safe on `read-only` + `untrusted` and Codex Power User on active-vault `workspace-write` + `never`, keep Pi and Gemini on transient MCP config, and do not use dangerous permission bypasses unless an ADR explicitly designs a new mode. Gemini Power User intentionally uses Gemini's `yolo` mode per ADR-0103.
|
||||
|
||||
### Work with external MCP setup
|
||||
|
||||
1. **Backend registration/status**: Edit `src-tauri/src/mcp.rs`; registration must verify Node.js first, resolve the packaged `mcp-server/` for macOS, Windows, Linux, and AppImage installs, and write an explicit stdio entry with `VAULT_PATH` plus `WS_UI_PORT=9711`
|
||||
2. **Setup dialog copy/actions**: Edit `src/components/McpSetupDialog.tsx`; users should see the Node.js prerequisite and the manual config shape before Tolaria writes third-party config files
|
||||
1. **Backend registration/status/snippets**: Edit `src-tauri/src/mcp.rs`; registration and manual config generation must verify Node.js first, resolve the packaged `mcp-server/` for macOS, Windows, Linux package roots (`/usr/local/Tolaria`, `/usr/local/lib/tolaria`, `/usr/lib/tolaria`, `/usr/lib/tolaria/resources`), and AppImage installs, and use an explicit stdio entry with `VAULT_PATH` plus `WS_UI_PORT=9711`
|
||||
2. **Setup dialog copy/actions**: Edit `src/components/McpSetupDialog.tsx` and `src/hooks/useMcpStatus.ts`; users should see the Node.js prerequisite, the exact generated manual config, and a copy action before Tolaria writes third-party config files
|
||||
3. **Status hook/toasts**: Edit `src/hooks/useMcpStatus.ts` when setup, reconnect, disconnect, or failure messaging changes
|
||||
4. **Gemini CLI compatibility**: Keep `~/.gemini/settings.json` in the registration path list and keep optional `GEMINI.md` generation behind `restore_vault_ai_guidance`; app-managed Gemini sessions still require the user to install and sign in to Gemini CLI, but Tolaria supplies transient MCP settings when Gemini is selected as the default AI agent
|
||||
5. **Process lifecycle**: Stdio MCP servers in `mcp-server/index.js` must exit when their external client closes stdin, and the desktop-owned `ws-bridge.js` child must be stopped on vault deselection, vault switch, and app exit
|
||||
|
||||
53
docs/LARGE-VAULT-LOADING-QA.md
Normal file
53
docs/LARGE-VAULT-LOADING-QA.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Large Vault Loading QA
|
||||
|
||||
Use this when validating startup responsiveness for large vaults. The goal is to make the bottleneck reproducible without using a real user vault.
|
||||
|
||||
## Synthetic Vault
|
||||
|
||||
Create a disposable vault with many markdown files:
|
||||
|
||||
```bash
|
||||
VAULT="$(mktemp -d /tmp/tolaria-large-vault.XXXXXX)"
|
||||
mkdir -p "$VAULT/type" "$VAULT/archive" "$VAULT/assets"
|
||||
cat > "$VAULT/type/project.md" <<'EOF'
|
||||
---
|
||||
is_a: Type
|
||||
---
|
||||
# Project
|
||||
EOF
|
||||
|
||||
for i in $(seq -w 1 20000); do
|
||||
cat > "$VAULT/project-$i.md" <<EOF
|
||||
---
|
||||
is_a: Project
|
||||
status: Active
|
||||
related_to:
|
||||
- "[[project-00001]]"
|
||||
---
|
||||
# Project $i
|
||||
|
||||
Synthetic body $i with enough text to exercise parsing and snippets.
|
||||
EOF
|
||||
done
|
||||
|
||||
git -C "$VAULT" init
|
||||
git -C "$VAULT" config user.email qa@example.invalid
|
||||
git -C "$VAULT" config user.name "Tolaria QA"
|
||||
git -C "$VAULT" add .
|
||||
git -C "$VAULT" commit -m "seed large vault"
|
||||
echo "$VAULT"
|
||||
```
|
||||
|
||||
## Manual QA
|
||||
|
||||
1. Start Tolaria with `pnpm tauri dev`.
|
||||
2. Open the synthetic vault path printed above.
|
||||
3. Verify the main shell renders before the full note list finishes indexing.
|
||||
4. Confirm the status bar shows vault activity while indexing is still in progress.
|
||||
5. Use keyboard-only flows while indexing continues:
|
||||
- Cmd+K opens the command palette.
|
||||
- Cmd+P opens quick open; results may be partial or empty until indexing finishes.
|
||||
- Create a new note with Cmd+N and type in the editor.
|
||||
6. Wait for indexing to finish and verify the note list/search state is consistent.
|
||||
|
||||
The synthetic vault lives under `/tmp`; remove it after QA if it is no longer needed.
|
||||
35
docs/adr/0091-gemini-cli-external-ai-setup.md
Normal file
35
docs/adr/0091-gemini-cli-external-ai-setup.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0091"
|
||||
title: "Gemini CLI external AI setup"
|
||||
status: active
|
||||
date: 2026-04-28
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria already supports explicit MCP setup for external desktop AI tools. Users asked for Gemini CLI support so the same active-vault MCP server can be registered where Gemini reads tool configuration, with optional Gemini-specific vault guidance.
|
||||
|
||||
Gemini CLI reads MCP server definitions from `~/.gemini/settings.json` and can load project guidance from `GEMINI.md`. Tolaria must support those conventions without silently rewriting global user settings or overwriting user-authored vault instructions.
|
||||
|
||||
## Decision
|
||||
|
||||
Tolaria adds `~/.gemini/settings.json` to the explicit external AI setup path list. The existing MCP entry shape is reused: `mcpServers.tolaria` runs the packaged stdio server through Node.js, pins `VAULT_PATH` to the selected vault, and sets `WS_UI_PORT=9711`.
|
||||
|
||||
Vault guidance keeps `AGENTS.md` as the canonical shared source. `restore_vault_ai_guidance` can create or repair a managed `GEMINI.md` shim that imports `AGENTS.md`, while bootstrap and repair flows continue to seed only required Tolaria guidance (`AGENTS.md` and `CLAUDE.md`) plus type scaffolding. Custom `GEMINI.md` files are classified as custom and are not overwritten.
|
||||
|
||||
The setup dialog documents that Gemini CLI still needs its own install and sign-in. Tolaria does not store Gemini credentials or model-provider API keys.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **Add Gemini to explicit MCP setup and optional guidance restore** (chosen): matches the existing consent boundary, preserves user settings, and gives Gemini the shared vault context.
|
||||
- **Generate `GEMINI.md` automatically for every vault**: simpler discovery, but turns an optional third-party compatibility file into startup side effect and dirties vaults for users who do not use Gemini.
|
||||
- **Document manual Gemini setup only**: avoids code changes, but leaves users to transpose paths and loses the active-vault safety already available for other MCP clients.
|
||||
- **Create a Gemini-specific MCP entry shape**: unnecessary because Gemini accepts the same `mcpServers` entry structure used by the existing Tolaria MCP server.
|
||||
|
||||
## Consequences
|
||||
|
||||
- External AI setup now writes/removes Tolaria's MCP entry in Claude, Gemini, Cursor, and generic MCP config files.
|
||||
- Gemini users can create a managed `GEMINI.md` shim without duplicating the canonical `AGENTS.md` guidance.
|
||||
- Existing vault bootstrap and repair remain non-invasive for users who do not use Gemini.
|
||||
- Native QA requires a local Gemini CLI install and authentication for an end-to-end Gemini prompt; otherwise the app can still verify the generated config and documentation paths.
|
||||
39
docs/adr/0092-vault-ai-agent-permission-modes.md
Normal file
39
docs/adr/0092-vault-ai-agent-permission-modes.md
Normal file
@@ -0,0 +1,39 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0092"
|
||||
title: "Vault-scoped AI agent permission modes"
|
||||
status: active
|
||||
date: 2026-04-28
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0074 established explicit setup and least-privilege defaults for desktop AI tools. The in-app AI panel now supports multiple local CLI agents, and users need a clear per-vault way to choose whether an agent should stay in the narrow vault-safe profile or use broader local-work tools for that vault.
|
||||
|
||||
The mode must be visible at the point of use, must not mutate global CLI settings, and must not silently restore dangerous bypass flags. Existing transcripts should remain intact when the mode changes because a change applies to the next agent run, not to a process that is already streaming.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria stores an `ai_agent_permission_mode` per vault with values `safe` and `power_user`, defaulting missing or null values to `safe`, and passes that normalized mode through the AI panel stream request into each CLI adapter.**
|
||||
|
||||
The AI panel header displays the current mode and offers a compact Vault Safe / Power User control that is disabled while an agent run is active. Changing the mode preserves the transcript and inserts a local transcript marker.
|
||||
|
||||
Adapter mappings remain conservative:
|
||||
- Claude Code Safe keeps `acceptEdits`, strict Tolaria MCP config, and file/search/edit tools only; Power User adds Bash to the allowed tool list without using `--dangerously-skip-permissions`.
|
||||
- Codex keeps the active-vault `workspace-write` sandbox and `--ask-for-approval never` in both modes.
|
||||
- OpenCode uses transient `OPENCODE_CONFIG_CONTENT`; Safe denies bash and external directories, while Power User allows bash but still denies external directories.
|
||||
- Pi receives the mode on the adapter request path; both modes currently use the same transient MCP adapter config.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **Per-vault Safe / Power User modes** (chosen): makes the permission surface explicit where the agent is used and preserves least-privilege defaults for each vault.
|
||||
- **Global app setting**: simpler storage, but a single toggle can over-apply a power-user profile to unrelated vaults.
|
||||
- **Dangerous bypass mode**: maximizes CLI freedom, but violates ADR-0074's least-privilege boundary and needs a separate explicit security decision.
|
||||
- **Adapter-specific UI switches**: exposes too much implementation detail and makes cross-agent behavior harder to reason about.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Vault config normalization owns the safe default for old vaults and malformed values.
|
||||
- Agent requests now carry a permission mode through frontend and Rust boundaries, so new adapters must choose an explicit mapping.
|
||||
- Power User is intentionally not equivalent across agents; where an adapter lacks a safe broader local-work switch, both modes may map to the same conservative behavior and must document that with tests.
|
||||
- Any future dangerous mode requires a new ADR and separate UI language.
|
||||
35
docs/adr/0093-shared-cli-agent-runtime-adapters.md
Normal file
35
docs/adr/0093-shared-cli-agent-runtime-adapters.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0093"
|
||||
title: "Shared CLI agent runtime adapters"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria supports Claude Code, Codex, OpenCode, and Pi as local CLI agents in the AI panel. Each agent has different command-line arguments, configuration shape, and JSON event schema, but the Rust backend had grown repeated runtime plumbing around those differences: request shapes, prompt wrapping, subprocess launch, stdout JSON reading, stderr capture, exit handling, done events, version probing, and Tolaria MCP server path resolution.
|
||||
|
||||
That duplication made small runtime fixes expensive because they had to be repeated across several adapter files. It also kept Codex-specific command and event mapping inside `ai_agents.rs`, making the top-level module both an orchestrator and a bespoke adapter.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria uses `cli_agent_runtime.rs` as the shared runtime scaffold for app-managed CLI agents, while `ai_agents.rs` only normalizes and dispatches requests to per-agent adapter modules.**
|
||||
|
||||
The shared scaffold owns the common agent request shape, system/user prompt wrapping, JSON-line process lifecycle, normalized error/done handling for `AiAgentStreamEvent` adapters, version probing, and Tolaria MCP server path resolution. Per-agent modules keep the provider-specific pieces: binary discovery candidates, command arguments, transient config shape, authentication error wording, and JSON event mapping.
|
||||
|
||||
Codex now lives in `codex_cli.rs`, matching the Claude, OpenCode, and Pi adapter boundary. `ai_agents.rs` remains the Tauri-facing orchestrator that chooses an adapter and maps Claude's legacy event enum into the normalized event stream.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **Shared runtime scaffold with thin adapters** (chosen): reduces repeated process lifecycle code without hiding provider-specific command/config/event behavior.
|
||||
- **One trait object per agent**: more uniform on paper, but adds indirection without removing much current complexity.
|
||||
- **Leave each adapter self-contained**: keeps local readability for a single file, but new process, prompt, and MCP fixes continue to land in parallel.
|
||||
- **Fully generic event mapping**: over-abstracts the JSON schemas and makes provider-specific edge cases harder to test.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Runtime lifecycle fixes should usually start in `cli_agent_runtime.rs`.
|
||||
- New agent adapters should use the shared request/prompt/process helpers and keep only command, config, discovery, and event mapping local.
|
||||
- `ai_agents.rs` should not grow provider-specific runtime code again; it should normalize the frontend request, dispatch to an adapter, and map any legacy event shape.
|
||||
- The shared scaffold deliberately does not erase provider differences. Authentication messages, permission semantics, and transient config formats remain adapter-owned and must stay covered by adapter tests.
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0094"
|
||||
title: "Gitignored content visibility as a command-boundary filter"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria's vault scanner now indexes more of the real filesystem so Folder views, search, and reload flows can reflect what is actually in the vault. In Git-backed vaults, that includes generated, local-only, or machine-specific content that users intentionally hide through `.gitignore`.
|
||||
|
||||
Always showing Gitignored files makes Folder lists and search noisy, especially in vaults that contain exports, build artifacts, or personal local scratch files. But removing those files during scanning would make visibility dependent on cache shape, complicate toggling, and blur the distinction between "what exists in the vault" and "what this installation chooses to surface."
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria keeps the vault scan and cache complete, then applies Gitignored-content visibility at the command boundary before entries, folders, or search results reach React.**
|
||||
|
||||
- `hide_gitignored_files` is an installation-local app setting and defaults to `true`.
|
||||
- Visibility checks use batched `git check-ignore --no-index --stdin` so Tolaria follows normal Git ignore and negation semantics as closely as practical.
|
||||
- `list_vault`, `reload_vault`, `list_vault_folders`, and keyword search all apply the same filter when the setting is enabled.
|
||||
- Toggling the setting reloads the current vault surfaces instead of rebuilding a different cache format.
|
||||
- If a vault has no `.gitignore`, or Gitignored visibility is turned off, Tolaria shows the full scanned result.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Complete scan/cache + boundary filter** (chosen): keeps the filesystem model authoritative, makes toggling cheap and consistent, and avoids cache divergence.
|
||||
- **Skip Gitignored content during scan/cache**: reduces later filtering work, but makes visibility part of the persisted cache shape and complicates instant toggling.
|
||||
- **Always show Gitignored content**: simplest implementation, but too noisy for real Git-backed vaults and undermines users' existing ignore rules.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Gitignored visibility is a per-installation comfort preference, not vault-authored shared metadata.
|
||||
- Search, folder lists, and note reloads stay aligned because they all consult the same boundary filter.
|
||||
- The cache can still support future visibility changes without a data migration.
|
||||
- Users can reveal ignored content again immediately by disabling the setting.
|
||||
- Future features that expose vault file lists should apply the same boundary filter unless they intentionally need raw filesystem output.
|
||||
35
docs/adr/0095-saved-view-order-field.md
Normal file
35
docs/adr/0095-saved-view-order-field.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0095"
|
||||
title: "Saved views use an explicit YAML order field"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Saved Views already persist as user-editable YAML files in the vault and sync through Git. Filename ordering was stable, but it forced users to rename files just to change sidebar order and gave Tolaria no durable way to support drag reordering, move actions, or keyboard-first ordering controls.
|
||||
|
||||
The ordering choice also needs to travel with the view definition itself. Saved Views are part of the vault's shared information architecture, not a machine-local preference.
|
||||
|
||||
## Decision
|
||||
|
||||
**Each Saved View may store an optional top-level `order` number in its YAML definition, and Tolaria sorts views by that value before falling back to filename.**
|
||||
|
||||
- Lower `order` values render earlier in the sidebar and other Saved View lists.
|
||||
- Views without `order` sort after ordered views and then fall back to filename ordering for stability.
|
||||
- Reordering actions rewrite affected view files with a dense sequence of order values instead of encoding position in filenames.
|
||||
- The same persisted order supports drag handles, explicit move buttons, and command-palette ordering actions.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Explicit `order` field in the view YAML** (chosen): portable, Git-syncable, easy to inspect by hand, and consistent with the existing file-first view model.
|
||||
- **Filename-based ordering only**: no schema change, but makes reordering clumsy and couples user-visible structure to file naming.
|
||||
- **App-local ordering state**: easy to prototype, but breaks cross-device consistency and separates ordering from the view artifact users already version.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Saved View ordering becomes part of the vault and syncs naturally through Git.
|
||||
- Existing views remain valid; unordered files keep a stable fallback sort until reordered.
|
||||
- Reordering can touch multiple view files in one action because Tolaria normalizes the sequence.
|
||||
- Future Saved View features should treat `order` as part of the shared YAML schema rather than introducing a parallel ordering store.
|
||||
37
docs/adr/0096-root-created-type-documents.md
Normal file
37
docs/adr/0096-root-created-type-documents.md
Normal file
@@ -0,0 +1,37 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0096"
|
||||
title: "Root-created type documents"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria identifies type definitions by markdown frontmatter (`type: Type`), not by filesystem location. Older documentation and UI creation flows still treated `type/` as the canonical destination for new type documents, with a compatibility fallback for vaults that already used `types/`.
|
||||
|
||||
That folder-based creation policy conflicted with the broader vault model: notes are scanned from all non-hidden folders, type identity comes from metadata, and root `type.md` / `note.md` definitions are already used by repair and bootstrap flows.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria creates new type documents at the vault root.**
|
||||
|
||||
- A type document is any markdown note with `type: Type` in frontmatter.
|
||||
- New UI-created type documents use `{vault}/{slug}.md`.
|
||||
- Existing type documents in `type/`, `types/`, or other scanned folders remain valid and continue to drive templates, icons, colors, visibility, sorting, and sidebar grouping.
|
||||
- Creation does not silently migrate or move existing type documents.
|
||||
- Root filename collisions are handled as file collisions; Tolaria must not overwrite an existing note when creating a type document.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Root-created type documents** (chosen): matches the metadata-first model, removes special casing from creation, and aligns new types with root-managed default type scaffolding.
|
||||
- **Canonical `type/` folder**: avoids root filename collisions, but makes path special even though type identity is already defined by frontmatter.
|
||||
- **Preserve existing folder convention dynamically**: minimizes change for plural `types/` vaults, but creates inconsistent behavior across vaults and leaves `types/` only partially supported.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Users can inspect and edit type documents as ordinary root notes by default.
|
||||
- Existing vaults with `type/` or `types/` type documents remain readable because vault scanning already includes non-hidden subdirectories.
|
||||
- If a root note with the same slug already exists, type creation fails with a collision message instead of writing into a fallback folder.
|
||||
- Legacy `type/` may remain hidden from the folder tree so old type documents do not duplicate the Types sidebar section.
|
||||
- Re-evaluate if users need a guided migration from folder-based type documents to root type documents.
|
||||
42
docs/adr/0097-gemini-cli-agent-adapter.md
Normal file
42
docs/adr/0097-gemini-cli-agent-adapter.md
Normal file
@@ -0,0 +1,42 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0097"
|
||||
title: "Gemini CLI agent adapter"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0091 added Gemini CLI to explicit external MCP setup, but Gemini was still absent from Tolaria's selectable app-managed AI agents. That left the AI panel able to generate Gemini-compatible MCP configuration while the actual agent picker, availability checks, install links, and streaming dispatch did not treat Gemini like Claude Code, Codex, OpenCode, or Pi.
|
||||
|
||||
Gemini CLI supports headless `--prompt` execution with JSON output, configurable approval modes, tool exclusion, and settings-file overrides through `GEMINI_CLI_SYSTEM_SETTINGS_PATH`. Those features are enough to launch Gemini from Tolaria without mutating the user's durable `~/.gemini/settings.json` during app-managed sessions.
|
||||
|
||||
## Decision
|
||||
|
||||
Tolaria adds Gemini CLI as a first-class `AiAgentId`. The frontend agent definitions, onboarding prompt, install links, default-agent normalization, status badge, command registry, settings persistence, and mock Tauri status payloads include `gemini`.
|
||||
|
||||
The desktop backend adds a Gemini adapter that:
|
||||
|
||||
- discovers `gemini` through the process path, login shell, and common local/toolchain install locations
|
||||
- runs `gemini --output-format json --approval-mode <mode> --prompt <prompt>` from the active vault
|
||||
- supplies Tolaria MCP through a temporary settings file referenced by `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
|
||||
- uses Safe mode with `auto_edit`, an untrusted MCP entry, and `tools.exclude=["run_shell_command"]`
|
||||
- uses Power User mode with `yolo` and a trusted Tolaria MCP entry
|
||||
- maps Gemini JSON responses into Tolaria's existing AI panel stream events
|
||||
|
||||
The existing external MCP setup remains explicit and durable. The app-managed Gemini adapter uses transient settings so selecting Gemini in Tolaria does not rewrite the user's global Gemini config.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **Add Gemini as a first-class app-managed agent** (chosen): matches the existing agent picker and onboarding UI, uses Gemini's headless JSON mode, and keeps MCP setup vault-scoped.
|
||||
- **Keep Gemini as external MCP setup only**: avoids another adapter, but keeps the interface inconsistent and requires users to leave Tolaria for a flow that other agents support in-panel.
|
||||
- **Write app-managed Gemini config into `~/.gemini/settings.json`**: reuses the external setup path, but would blur the consent boundary and risk overwriting user preferences during normal AI panel usage.
|
||||
- **Use interactive Gemini sessions**: could preserve richer CLI state, but does not fit Tolaria's current one-request stream lifecycle and would make cleanup/auth/error handling harder.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Gemini appears anywhere users can choose, install, or switch local AI agents.
|
||||
- End-to-end native Gemini QA requires the Gemini CLI to be installed and authenticated, but missing/auth failures now produce agent-specific guidance.
|
||||
- Safe and Power User behavior is limited by Gemini's own approval/tool semantics; if Gemini changes those names, the adapter tests and docs need updating.
|
||||
- The durable MCP setup path and optional `GEMINI.md` shim continue to serve external Gemini usage outside Tolaria's AI panel.
|
||||
29
docs/adr/0098-in-app-image-and-pdf-file-previews.md
Normal file
29
docs/adr/0098-in-app-image-and-pdf-file-previews.md
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0098"
|
||||
title: "In-app image and PDF previews for binary vault files"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
supersedes: "0086"
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0086 introduced the `FilePreview` path for image binaries while keeping binary files as ordinary `VaultEntry` records. The same file-first model should now cover PDFs, because asset-heavy vaults often mix screenshots, diagrams, and document exports that users need to inspect without leaving Tolaria.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria previews supported image and PDF files in the editor pane while keeping them as ordinary binary vault files.**
|
||||
|
||||
- The scanner keeps the coarse `fileKind: "binary"` representation. Previewability stays a renderer concern inferred from the file extension in `src/utils/filePreview.ts`.
|
||||
- Supported images render with `<img>` and supported PDFs render with the webview PDF object renderer, both using Tauri asset URLs from `convertFileSrc`.
|
||||
- The Tauri CSP permits scoped asset URLs in `object-src` so PDF objects can load vault-backed files without broadening script, connect, or image policy.
|
||||
- PDF preview fallback content lives inside the PDF object so unsupported or failed renderers still expose an explicit "Open in default app" escape hatch.
|
||||
- Note-list rows for previewable images and PDFs remain clickable and carry file-specific indicators; unsupported binary rows stay muted and non-clickable.
|
||||
- `Escape` on the preview surface returns keyboard focus to the note list, matching the existing image-preview keyboard behavior.
|
||||
|
||||
## Consequences
|
||||
|
||||
- PDFs do not become notes and do not get Markdown editor semantics.
|
||||
- The asset preview surface can keep growing to additional safe binary formats without changing the vault scanner or persisted cache shape.
|
||||
- Broken PDFs may rely on the webview's own renderer failure state, but the surrounding Tolaria preview chrome still provides reveal, copy path, and default-app actions.
|
||||
37
docs/adr/0099-cumulative-vault-asset-scope.md
Normal file
37
docs/adr/0099-cumulative-vault-asset-scope.md
Normal file
@@ -0,0 +1,37 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0099"
|
||||
title: "Cumulative vault asset scope for previews"
|
||||
status: active
|
||||
date: 2026-04-29
|
||||
supersedes: "0074 asset-protocol runtime scoping"
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0074 moved the desktop asset protocol away from broad filesystem access and toward runtime vault scoping. The implementation tried to keep only the active vault in scope by calling Tauri's `forbid_directory` for vault roots that were no longer active.
|
||||
|
||||
Tauri's filesystem scope treats forbidden paths as permanent precedence rules: a forbidden path is denied even if it is later allowed again. After a user switched away from a vault and back, image and PDF previews could keep producing `403 Forbidden` responses for valid vault files until the app restarted.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria accumulates Tauri asset protocol access for vault roots loaded during the current app session and never forbids a previously loaded vault root at runtime.**
|
||||
|
||||
- `sync_vault_asset_scope` adds the canonical vault root and requested vault root when they are missing from the runtime asset scope.
|
||||
- The runtime asset scope remains narrower than global filesystem access because only vault roots that Tolaria has loaded are added.
|
||||
- Command paths still enforce the active vault boundary through the Rust command layer before reads, writes, external opens, and attachment imports.
|
||||
- Asset scope revocation is deferred to process exit, because Tauri does not expose a safe runtime unallow operation for directories.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Cumulative runtime vault scope** (chosen): keeps previews reliable after vault switches while preserving vault-only access in the current process.
|
||||
- **Continue forbidding previous vaults**: appears stricter, but Tauri forbids are not reversible and valid previews fail after switching back.
|
||||
- **Allow all filesystem paths**: avoids preview failures but returns to the broad asset protocol access that ADR-0074 intentionally removed.
|
||||
- **Replace `convertFileSrc` with a custom protocol**: could support exact active-vault revocation, but it would be a larger cross-cutting migration for editor images, file previews, and PDF rendering.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Images and PDFs from any vault loaded in the current session can keep rendering after vault switches.
|
||||
- The app process, not each vault switch, is the revocation boundary for asset URL access.
|
||||
- Active-vault command validation remains the primary guard for mutations and default-app opens.
|
||||
- Re-evaluate this if Tauri adds a public runtime unallow operation for asset protocol directories.
|
||||
35
docs/adr/0100-synthetic-vault-root-folder-row.md
Normal file
35
docs/adr/0100-synthetic-vault-root-folder-row.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0100"
|
||||
title: "Synthetic vault-root row in folder navigation"
|
||||
status: active
|
||||
date: 2026-04-30
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0033 introduced subfolder scanning and a collapsible folder tree backed by `list_vault_folders`, but the sidebar still had no first-class way to select the vault root itself. That left root-level files outside the folder-navigation model and pushed the UI toward one-off handling for the opened vault path.
|
||||
|
||||
The new sidebar behavior needs to show root-level files when the user clicks the vault name, while preserving the existing folder rename/delete model for real folders only.
|
||||
|
||||
## Decision
|
||||
|
||||
**Represent the vault root in the sidebar as a synthetic frontend-owned folder row rather than as a mutable backend folder.**
|
||||
|
||||
- `FolderTree` wraps backend folder nodes in a root row with `path: ""` and `rootPath` set to the opened vault path.
|
||||
- `SidebarSelection` keeps using `kind: 'folder'`, but root selection is encoded as the empty folder path plus `rootPath` metadata.
|
||||
- Root-level file filtering is handled in note-list helpers as a dedicated root case instead of pretending the vault root is an ordinary folder.
|
||||
- Rename/delete remain available only for real folders; the vault root row is navigable, not mutable.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Option A** (chosen): Synthetic vault-root row in the renderer — keeps `list_vault_folders` focused on real folders, avoids backend schema churn, and reuses the existing folder-selection mental model.
|
||||
- **Option B**: Add a pseudo-folder to backend folder results — would couple presentation-only root behavior to command data and blur the distinction between the vault itself and mutable folders.
|
||||
- **Option C**: Keep root files outside folder navigation entirely — simpler, but leaves the sidebar with an incomplete navigation model and special cases elsewhere in the UI.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Folder navigation now has a single model for root and nested folder browsing.
|
||||
- Backend folder APIs stay unchanged: they describe actual folders, not UI-only rows.
|
||||
- Selection handling must treat `path: ""` as the vault-root case and use `rootPath` when computing direct-root file membership.
|
||||
- Re-evaluate if folder actions ever need to operate on the vault root itself, because that would likely require a separate command model instead of extending the synthetic row.
|
||||
35
docs/adr/0101-categorical-product-analytics-events.md
Normal file
35
docs/adr/0101-categorical-product-analytics-events.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0101"
|
||||
title: "Categorical product analytics events"
|
||||
status: active
|
||||
date: 2026-04-30
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0016 established opt-in PostHog analytics and Sentry crash reporting, but new feature telemetry now spans file previews, inline image lightbox opens, AI agent session lifecycle events, and All Notes visibility toggles. Instrumenting those flows ad hoc would make it easy to leak vault-specific data such as note paths, filenames, prompt text, or image URLs.
|
||||
|
||||
Tolaria needs richer product telemetry for feature behavior while preserving the privacy bar expected from a local-first notes app.
|
||||
|
||||
## Decision
|
||||
|
||||
**Route product analytics through dedicated helper functions that emit only coarse categorical metadata.**
|
||||
|
||||
- Product events live behind `src/lib/productAnalytics.ts` instead of scattering raw `trackEvent()` payloads across feature code.
|
||||
- Allowed payloads are constrained to categories and counts such as preview kind, action kind, AI agent id, permission mode, response/tool counts, status, and All Notes visibility category/enabled state.
|
||||
- Product events must not include vault content, note titles, file paths, filenames, image URLs, prompt text, or other user-authored data.
|
||||
- When a feature needs telemetry, it should add or extend a typed helper rather than sending free-form payloads inline.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Option A** (chosen): Typed categorical wrappers for product events — preserves useful product signals while keeping privacy constraints explicit and reviewable in one place.
|
||||
- **Option B**: Let each feature call `trackEvent()` directly with whatever fields seem useful — faster short term, but inconsistent and too easy to let sensitive data leak into analytics.
|
||||
- **Option C**: Avoid new product events entirely — safest from a privacy standpoint, but leaves the team blind to whether preview, AI, and list-visibility features are actually being used or failing.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Telemetry reviews become easier because the allowed product-event surface is centralized.
|
||||
- Future product analytics work should start by defining categorical event helpers, not by attaching raw note/file context.
|
||||
- Some debugging detail is intentionally sacrificed; deep diagnosis should rely on consented crash reporting and local reproduction rather than richer analytics payloads.
|
||||
- Re-evaluate if Tolaria ever needs a broader telemetry taxonomy or stronger compile-time guarantees around event schemas.
|
||||
29
docs/adr/0102-low-end-safe-autosave-idle-window.md
Normal file
29
docs/adr/0102-low-end-safe-autosave-idle-window.md
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0102"
|
||||
title: "Low-end-safe autosave idle window"
|
||||
status: active
|
||||
date: 2026-04-30
|
||||
supersedes: "0015"
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0015 chose a 500ms autosave debounce so normal edits would persist quickly without writing on every keystroke. GitHub issue #443 showed that this window is too aggressive on very weak Windows CPUs: if typing intervals exceed 500ms or a save takes long enough to overlap continued typing, Tolaria can start disk and derived-state work while the user is still entering text.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria autosaves after a 1.5s idle window and treats stale in-flight autosaves as obsolete when newer content arrives before they resolve.** Manual saves, note switches, raw-mode entry, and destructive actions still flush pending editor content immediately.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **Option A — 1.5s idle window plus stale-save protection** (chosen): reduces mid-typing saves on slow CPUs while keeping ordinary autosave behavior fast enough for reliability. It also prevents an older slow save from clearing or repainting over newer pending text.
|
||||
- **Option B — Keep 500ms and only fix stale saves**: preserves the previous timing but still triggers repeated saves for slower typists and weaker machines.
|
||||
- **Option C — Save only on blur or navigation**: minimizes background work but increases crash-loss risk during longer writing sessions.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Autosave is less likely to compete with active typing on low-end Windows hardware.
|
||||
- The unsaved window grows from roughly 500ms to roughly 1.5s after Tolaria receives the latest content change.
|
||||
- Explicit flush paths remain immediate, so navigation, manual save, raw-mode transitions, and destructive actions still preserve pending edits before proceeding.
|
||||
- Future changes to autosave timing should keep weak-CPU responsiveness and stale in-flight save behavior in the same test surface.
|
||||
32
docs/adr/0103-adapter-specific-ai-permission-semantics.md
Normal file
32
docs/adr/0103-adapter-specific-ai-permission-semantics.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0103"
|
||||
title: "Adapter-specific AI permission semantics"
|
||||
status: active
|
||||
date: 2026-04-30
|
||||
supersedes: "0092"
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0092 introduced per-vault Vault Safe / Power User modes, but the first implementation left too much room for adapter drift. Some agents can directly deny or allow Bash, some expose only a sandbox/approval profile, and Pi currently has no narrower app-managed switch beyond Tolaria's transient MCP configuration. The shared UI still needs a consistent product contract: Vault Safe must not encourage shell execution, while Power User should keep shell execution available across repeated agent turns where the selected adapter supports it.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria treats the permission mode as a product contract first and maps it conservatively per adapter.**
|
||||
|
||||
- Shared AI system prompts are mode-aware on every turn, including turns with note context snapshots.
|
||||
- Vault Safe tells agents not to use or advertise shell, terminal, Bash, script execution, git, or command-line tools.
|
||||
- Power User tells shell-capable agents that local shell commands are available for the active vault and should remain scoped to that vault.
|
||||
- Claude Code Safe excludes Bash; Power User includes and pre-approves Bash without dangerous bypass flags.
|
||||
- Codex Safe uses the CLI's read-only sandbox plus untrusted approval policy; Power User uses workspace-write plus never-ask approval so shell-capable Codex turns remain low-friction across the session.
|
||||
- OpenCode Safe denies bash and external directories; Power User allows bash while still denying external directories.
|
||||
- Pi keeps the same conservative transient MCP config in both modes until the Pi CLI exposes a reliable app-managed shell permission switch. The prompt must not promise shell for Pi Power User.
|
||||
- Gemini Safe excludes `run_shell_command`; Gemini Power User intentionally uses `yolo` with trusted transient Tolaria MCP settings.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Mode behavior is no longer described solely by generic UI copy; adapter docs and tests define the exact mapping.
|
||||
- Codex Vault Safe remains a best-effort safe profile rather than a true built-in-tools-off mode, because Codex CLI currently exposes sandbox and approval controls but not a dedicated switch to remove shell tooling while preserving MCP.
|
||||
- Future adapters must either implement both modes explicitly or document that Power User maps to the same conservative behavior.
|
||||
- If Tolaria adds a stronger warning or dangerous mode later, it needs a separate ADR and UI language.
|
||||
48
docs/adr/0104-tauri-frontend-readiness-watchdog.md
Normal file
48
docs/adr/0104-tauri-frontend-readiness-watchdog.md
Normal file
@@ -0,0 +1,48 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0104"
|
||||
title: "Tauri frontend readiness watchdog"
|
||||
status: active
|
||||
date: 2026-05-01
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria already keeps heavy filesystem and subprocess work off the Tauri window-creation path, but that alone does not protect against a different startup failure mode: the desktop WebView can render the static HTML shell while the React app never becomes interactive.
|
||||
|
||||
On macOS this showed up as an inert window that looked launched but never finished mounting the real app. The failure boundary is cross-layer:
|
||||
|
||||
- `index.html` can paint before React commits
|
||||
- React root errors can happen before the app reports itself ready
|
||||
- a plain reload is acceptable as a one-time recovery, but an automatic reload loop is not
|
||||
- browser/mock runs should not inherit desktop-only recovery behavior
|
||||
|
||||
Tolaria needs a startup contract that distinguishes “HTML painted” from “frontend actually became interactive”, and a bounded recovery path when that contract is not satisfied.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria uses a Tauri-only frontend-readiness watchdog that reloads the WebView at most once if React never reports startup readiness.**
|
||||
|
||||
Concretely:
|
||||
|
||||
- `index.html` installs a Tauri-only startup timer before React loads
|
||||
- React dispatches a readiness signal from a mounted effect after the app shell commits
|
||||
- if readiness never arrives before the timeout, the WebView reloads once
|
||||
- the same one-shot reload path is available to React root error handling before readiness is marked
|
||||
- `sessionStorage` tracks whether the startup reload was already attempted so Tolaria does not loop forever
|
||||
- browser/mock environments keep using ordinary browser clipboard/storage behavior and do not enable this desktop startup recovery path
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Tauri-only readiness watchdog with one-shot reload** (chosen): directly addresses the inert-startup failure mode, keeps recovery local to the frontend, and avoids permanent reload loops. Cost: startup now depends on a small cross-layer contract between HTML bootstrap and React.
|
||||
- **Do nothing and rely on manual relaunch**: simplest implementation, but leaves users stranded in a broken-looking app state with no automatic recovery.
|
||||
- **Reload on any React root error without a readiness gate**: more aggressive, but too noisy; post-startup runtime errors should not trigger surprise reloads.
|
||||
- **Move recovery entirely into native Rust window/bootstrap logic**: possible, but the failure signal lives in the frontend lifecycle, so native code would still need a readiness handshake.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Tolaria now distinguishes successful frontend startup from merely rendering the HTML shell.
|
||||
- Desktop startup recovery is bounded to a single retry per session, reducing the chance of trapping users in reload loops.
|
||||
- `index.html`, `src/main.tsx`, and `src/utils/frontendReady.ts` form a shared startup contract that future bootstrap refactors must preserve.
|
||||
- Any future change that delays app-shell mount beyond the watchdog timeout must re-evaluate the timeout and readiness trigger.
|
||||
- If a startup failure persists after one retry, Tolaria still surfaces the broken state instead of hiding a deeper bug behind repeated reloads.
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0105"
|
||||
title: "Editor correctness and responsiveness contract"
|
||||
status: active
|
||||
date: 2026-05-01
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria notes are durable Markdown files on disk, but the rich editor renders them through BlockNote blocks. Large notes exposed a tempting optimization: show a fast Markdown preview first, then hydrate BlockNote later. In practice, that creates two renderers for the same document, visible flicker, delayed click-time lag, and more places for stale async work to race with the currently selected note.
|
||||
|
||||
The editor must optimize for the product priorities in this order:
|
||||
|
||||
1. no crashes
|
||||
2. no stale content, race-condition overwrites, or lost edits
|
||||
3. responsive typing and cursor movement
|
||||
4. fast note-list-to-editor loading
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria keeps a single direct editor surface for Markdown notes and treats editor content swaps as generation-checked, source-content-checked operations.** Fast loading may use raw file-content prefetching and a bounded parsed-block cache, but it must not show a separate preview that later swaps into the editor. Parsed BlockNote blocks are reusable only when their source Markdown exactly matches the content being opened, and background parsing must run only after recent typing/navigation has gone idle.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Single direct editor surface with guarded swaps plus bounded caches** (chosen): preserves one visual representation of the document, rejects stale async parse results, validates or identity-checks cached disk content before opening, and keeps typing work debounced. Cons: very large notes can still wait on BlockNote conversion when they were not warmed.
|
||||
- **Fast Markdown preview followed by hidden BlockNote hydration**: improves first paint but creates flicker, delayed edit-time stalls, and duplicated rendering semantics.
|
||||
- **Unbounded or eager background BlockNote parsing for likely next notes**: can make some opens faster, but competes with typing/navigation and introduces stale parse-result hazards unless heavily scheduled, bounded, and invalidated.
|
||||
- **Always raw mode for large notes**: strongest responsiveness for huge files, but changes the editing experience abruptly and should be an explicit fallback rather than the default.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Async editor work must prove it still matches both the latest swap generation and the latest tab source content before touching BlockNote.
|
||||
- Cached raw note content must be validated against disk before it is shown unless it carries the same `modifiedAt` and `fileSize` identity as the current `VaultEntry`, or the content was just authored by Tolaria in the current process.
|
||||
- Cached parsed BlockNote blocks must be keyed by vault, path, and exact source content, cloned on read/write, and bounded by entry count plus source byte budget.
|
||||
- Background parsed-block warming is allowed only for likely next large Markdown notes after a foreground idle window; active typing, raw mode, and editor mount state must defer it.
|
||||
- Dirty local editor content remains authoritative. External filesystem refreshes may replace clean notes, but must not overwrite unsaved local edits.
|
||||
- Per-keystroke editor work must stay minimal. Serialization, metadata derivation, autosave, and cache updates should be debounced, coalesced, or scheduled away from active typing.
|
||||
- Future large-note optimizations should target true progressive/chunked conversion or explicit raw/read-only fallback states, not a visually different preview that morphs into BlockNote.
|
||||
31
docs/adr/0106-shared-app-command-manifest.md
Normal file
31
docs/adr/0106-shared-app-command-manifest.md
Normal file
@@ -0,0 +1,31 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0106"
|
||||
title: "Shared app command manifest"
|
||||
status: active
|
||||
date: 2026-05-02
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria command metadata was split across several runtime surfaces: TypeScript owned shortcut lookup and command-palette shortcut display, Rust owned native menu IDs, labels, accelerators, aliases, and enablement groups, and the Linux titlebar fallback menu duplicated another command list. Adding or changing a command required carefully editing multiple files that could drift while still compiling.
|
||||
|
||||
The existing renderer-first shortcut model and native-menu dedupe remain correct, but they need a single source for metadata that must be identical across those surfaces.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria stores cross-runtime app command metadata in `src/shared/appCommandManifest.json`, and both the renderer and Tauri native menu derive their command/menu IDs, accelerators, menu labels, menu aliases, enablement groups, and deterministic QA metadata from it.** Context-sensitive command-palette builders still own availability and execution callbacks, and OS-native menu entries remain local to the native menu implementation.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Shared JSON manifest included by TypeScript and Rust** (chosen): works in both runtimes without code generation, keeps menu metadata reviewable, and lets tests validate drift directly.
|
||||
- **Generate TypeScript and Rust constants from a schema**: gives stronger compile-time types but adds a build step and a generated-file maintenance burden for a small manifest.
|
||||
- **Keep duplicated constants with more tests**: reduces immediate refactor scope, but still forces every command change through parallel manual edits.
|
||||
|
||||
## Consequences
|
||||
|
||||
- New app commands that appear in native menus or shortcut QA must be added to `src/shared/appCommandManifest.json`.
|
||||
- `appCommandCatalog.ts` is responsible for turning the manifest into typed renderer helpers such as `APP_COMMAND_IDS`, shortcut lookup maps, Linux menu sections, and deterministic QA definitions.
|
||||
- `src-tauri/src/menu.rs` includes the same manifest JSON, builds custom menu items from it, maps overridden menu item IDs such as `file-quick-open-alias` back to their primary command IDs, and resolves state-dependent enablement groups from manifest entries.
|
||||
- Platform-native menu items such as Undo, Redo, Copy, Paste, Select All, Services, Quit, and Window controls stay in Rust because they are OS affordances, not Tolaria app commands.
|
||||
- Command-palette builders continue to own dynamic labels, filtering, enabled state, and callbacks where those depend on current app state.
|
||||
43
docs/adr/0107-markdown-durable-tldraw-whiteboards.md
Normal file
43
docs/adr/0107-markdown-durable-tldraw-whiteboards.md
Normal file
@@ -0,0 +1,43 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0107"
|
||||
title: "Markdown-durable tldraw whiteboards in notes"
|
||||
status: active
|
||||
date: 2026-05-03
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria notes are durable Markdown files, while whiteboard editing needs an interactive canvas with structured shape data. tldraw provides a mature React whiteboard runtime and exposes snapshot APIs that can persist the document without using browser-local `persistenceKey` storage.
|
||||
|
||||
The storage decision needs to preserve Tolaria's filesystem source-of-truth rule: deleting local caches must not lose a board, raw mode must expose the canonical source, and Git should track the board together with the surrounding note.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria will support whiteboards as Markdown-durable fenced `tldraw` blocks backed by tldraw document snapshots.**
|
||||
|
||||
The implementation:
|
||||
|
||||
- Converts fenced `tldraw` blocks into temporary placeholders before BlockNote parses Markdown.
|
||||
- Replaces those placeholders with `tldrawBlock` schema blocks that store a stable board id and tldraw document snapshot JSON.
|
||||
- Renders each block with the `tldraw` package inside the rich editor.
|
||||
- Debounces tldraw document changes into BlockNote block props so Tolaria's normal autosave writes the snapshot into the `.md` file.
|
||||
- Serializes `tldrawBlock` nodes back to fenced Markdown before save, raw-mode entry, and editor-position snapshots.
|
||||
- Adds a `/whiteboard` slash command that inserts the same block format.
|
||||
|
||||
Session state such as camera position, selected shapes, and selected tools is not persisted into the note. Preview images are intentionally omitted from the initial design; they may be introduced later as derived cache artifacts for note lists, search results, or graph cards.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Markdown fenced block with tldraw document snapshot** (chosen): keeps the board in the note file, matches Tolaria's Mermaid/math round-trip model, and works for both full whiteboard notes and embedded boards inside larger notes.
|
||||
- **tldraw `persistenceKey` / IndexedDB**: simplest app integration, but violates the vault-as-source-of-truth rule and would lose boards when browser storage is cleared.
|
||||
- **Separate `.tldr` files embedded from Markdown**: keeps JSON out of prose notes, but fragments note ownership, makes embedded boards harder to move with their parent note, and complicates Git history for small board edits.
|
||||
- **Preview-image-first storage**: useful for thumbnails, but not editable source. It would make the PNG an attractive but stale source of truth.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `src/utils/tldrawMarkdown.ts` is the canonical parser/serializer bridge for whiteboard blocks.
|
||||
- `src/components/TldrawWhiteboard.tsx` owns the tldraw runtime integration and only persists document snapshots.
|
||||
- Raw mode remains a direct source editor for the fenced JSON.
|
||||
- Embedded whiteboards and future full-note whiteboard templates share the same storage format.
|
||||
- Asset support is deferred; when added, asset bytes should live in vault-relative attachment paths referenced from the tldraw asset records.
|
||||
32
docs/adr/0107-pointer-owned-editor-block-reordering.md
Normal file
32
docs/adr/0107-pointer-owned-editor-block-reordering.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0107"
|
||||
title: "Pointer-owned editor block reordering"
|
||||
status: active
|
||||
date: 2026-05-02
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria uses BlockNote for rich Markdown editing, Tauri for native desktop file drops, and custom editor drop handlers for images and wikilinks. BlockNote's default block drag path depends on HTML5 drag events and `DataTransfer`. On macOS inside the Tauri webview, that makes block reordering fragile because the same browser-level drag system also carries native file/image drops into the editor.
|
||||
|
||||
Regressions tended to oscillate: fixes that restored block dragging could break image drops, and fixes that protected native drops could make block reordering fail or lose visual feedback. The drag handle also needs editor-specific affordances: a moving block preview, an insertion separator, stale-block protection, and typography-aware positioning for the side-menu controls.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria owns editor block reordering as a pointer gesture that directly moves BlockNote blocks, and leaves HTML5/native drag data paths for file, image, and external drops.** The drag side menu is responsible for resolving live BlockNote blocks, computing pointer hit targets, rendering drag affordances, and aligning the hover controls to the rendered text range of the hovered block.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Pointer-owned block reordering** (chosen): separates internal block moves from native drop payloads, works without `DataTransfer`, gives Tolaria deterministic visual affordances, and can be tested with Playwright pointer/mouse actions. Cons: Tolaria now owns a small amount of hit-testing, block-move, and affordance code around BlockNote.
|
||||
- **Continue using BlockNote's HTML5 drag handler**: keeps less local code, but ties internal block moves to the same unstable drag channel used by native file drops in Tauri.
|
||||
- **Patch native file drops around BlockNote drag events**: might repair individual regressions, but preserves the root coupling between editor-internal reordering and external drag payload handling.
|
||||
- **Disable block dragging on macOS/Tauri**: avoids the conflict, but removes an important editing workflow.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Internal block reordering must not depend on `DataTransfer` or `draggable=true`.
|
||||
- File/image/wikilink drop behavior remains owned by the existing editor drop abstractions and native Tauri file-drop bridge.
|
||||
- Block reordering tests should use pointer or mouse movement in Playwright, and should assert the moving preview and insertion separator while the drag is in progress.
|
||||
- The side menu should align to measured rendered content rather than heading-specific pixel offsets, so future theme font-size and line-height changes do not need drag-control retuning.
|
||||
- Changes to BlockNote DOM structure around `.bn-block-content`, `.bn-inline-content`, `.bn-side-menu`, or block container IDs require rechecking the pointer hit-testing and side-menu alignment tests.
|
||||
30
docs/adr/0108-direct-model-ai-targets.md
Normal file
30
docs/adr/0108-direct-model-ai-targets.md
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0108"
|
||||
title: "Direct model AI targets alongside coding agents"
|
||||
status: active
|
||||
date: 2026-05-03
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria's AI panel originally targeted desktop coding-agent CLIs only. That works well for tool-capable vault editing, but it excludes users who run local model servers, users who prefer OpenAI or Anthropic APIs, and future mobile builds where desktop subprocesses cannot run.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria models AI selection as an AI target.** Targets can be desktop coding agents or direct model endpoints. Coding agents keep the existing Safe / Power User permission modes and tool access. Direct model targets run in Chat mode: they receive note context and conversation history, but they do not get vault-write tools or shell access.
|
||||
|
||||
Direct model provider metadata is stored in app settings. Provider API secrets are not stored in settings; hosted providers can either save a key in Tolaria's local app-data secrets file or read a key from a named environment variable. The local secrets file is outside the vault, outside project worktrees, and written with owner-only file permissions on Unix platforms. Local providers such as Ollama and LM Studio can run without a key.
|
||||
|
||||
## Options Considered
|
||||
|
||||
- **AI target abstraction** (chosen): supports agents, local models, hosted APIs, and mobile-compatible model runtimes without pretending all AI backends have the same capabilities.
|
||||
- **Treat custom providers as OpenCode configuration only**: lower implementation cost on desktop, but does not help mobile and keeps API users dependent on a coding-agent install.
|
||||
- **Direct API runtime with write tools immediately**: powerful, but would require Tolaria-owned tool loops, confirmations, retries, and safety semantics before the basic chat value is proven.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Settings owns durable provider setup and default target selection.
|
||||
- The status bar becomes a quick target switcher across agents and configured model targets.
|
||||
- The AI panel explains capability differences: agents show Safe / Power User; direct model targets show Chat mode.
|
||||
- Future work can migrate local secrets to OS keychain storage and add read/write tool loops without changing the top-level target model.
|
||||
25
docs/adr/0108-sanitized-rendered-markup-and-safe-regex.md
Normal file
25
docs/adr/0108-sanitized-rendered-markup-and-safe-regex.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# 0108. Sanitized Rendered Markup and Safe User Regex
|
||||
|
||||
Date: 2026-05-03
|
||||
|
||||
## Status
|
||||
|
||||
Accepted
|
||||
|
||||
## Context
|
||||
|
||||
Tolaria renders generated SVG/HTML from trusted libraries such as Mermaid and KaTeX, and it allows users to opt into regex matching in filters and editor find/replace. Codacy SRM flagged the raw markup insertion and direct regex construction as Critical XSS/DoS risks.
|
||||
|
||||
## Decision
|
||||
|
||||
Add direct runtime dependencies on `dompurify` and `safe-regex2`.
|
||||
|
||||
Rendered Mermaid SVG and KaTeX HTML must be sanitized before insertion and mounted through DOM nodes rather than React `dangerouslySetInnerHTML`. User-provided regex sources must be length-bounded and checked with `safe-regex2` before compilation.
|
||||
|
||||
SCA-reported vulnerable transitive dependencies are pinned through package-manager overrides so Codacy resolves patched floors until upstream dependencies adopt them naturally. This includes `protobufjs`, the MCP SDK web-server stack, and Vite's parser/build transitive stack. Rust lockfile-only updates keep OpenSSL, rustls-webpki, and tar on patched versions without changing public Tauri APIs.
|
||||
|
||||
## Consequences
|
||||
|
||||
Markup rendering now has an explicit sanitizer boundary that is shared by Mermaid and math rendering. User regex features remain available, but unsafe or overly large expressions fail validation instead of running in the UI thread.
|
||||
|
||||
The overrides should be removed once the dependency graph no longer pulls the vulnerable versions.
|
||||
@@ -70,7 +70,7 @@ proposed → active → superseded
|
||||
| [0012](0012-claude-cli-for-ai-agent.md) | Claude CLI subprocess for AI agent | active |
|
||||
| [0013](0013-remove-theming-system.md) | Remove vault-based theming system | superseded -> [0081](0081-internal-light-dark-theme-runtime.md) |
|
||||
| [0014](0014-git-based-vault-cache.md) | Git-based incremental vault cache | active |
|
||||
| [0015](0015-auto-save-with-debounce.md) | Auto-save with 500ms debounce | active |
|
||||
| [0015](0015-auto-save-with-debounce.md) | Auto-save with 500ms debounce | superseded → [0102](0102-low-end-safe-autosave-idle-window.md) |
|
||||
| [0016](0016-sentry-posthog-telemetry.md) | Sentry + PostHog telemetry with consent | active |
|
||||
| [0017](canary-release-channel-and-local-feature-flags.md) | Canary release channel and feature flags | superseded → [0057](0057-alpha-stable-release-channels-and-beta-cohorts.md) |
|
||||
| [0018](0018-codescene-code-health-gates.md) | CodeScene code health gates in CI | superseded → [0064](0064-ratcheted-codescene-thresholds.md) |
|
||||
@@ -142,3 +142,23 @@ proposed → active → superseded
|
||||
| [0085](0085-non-git-vault-support.md) | Non-git vaults open with explicit later Git initialization | active |
|
||||
| [0088](0088-markdown-durable-mermaid-diagrams.md) | Markdown-durable Mermaid diagrams in notes | active |
|
||||
| [0089](0089-active-vault-filesystem-watcher.md) | Active vault filesystem watcher | active |
|
||||
| [0090](0090-pi-cli-agent-adapter.md) | Pi CLI agent adapter | active |
|
||||
| [0091](0091-gemini-cli-external-ai-setup.md) | Gemini CLI external AI setup | active |
|
||||
| [0092](0092-vault-ai-agent-permission-modes.md) | Vault-scoped AI agent permission modes | superseded -> [0103](0103-adapter-specific-ai-permission-semantics.md) |
|
||||
| [0093](0093-shared-cli-agent-runtime-adapters.md) | Shared CLI agent runtime adapters | active |
|
||||
| [0094](0094-gitignored-content-visibility-boundary-filter.md) | Gitignored content visibility as a command-boundary filter | active |
|
||||
| [0095](0095-saved-view-order-field.md) | Saved views use an explicit YAML order field | active |
|
||||
| [0096](0096-root-created-type-documents.md) | Root-created type documents | active |
|
||||
| [0097](0097-gemini-cli-agent-adapter.md) | Gemini CLI agent adapter | active |
|
||||
| [0098](0098-in-app-image-and-pdf-file-previews.md) | In-app image and PDF previews for binary vault files | active |
|
||||
| [0099](0099-cumulative-vault-asset-scope.md) | Cumulative vault asset scope for previews | active |
|
||||
| [0100](0100-synthetic-vault-root-folder-row.md) | Synthetic vault-root row in folder navigation | active |
|
||||
| [0101](0101-categorical-product-analytics-events.md) | Categorical product analytics events | active |
|
||||
| [0102](0102-low-end-safe-autosave-idle-window.md) | Low-end-safe autosave idle window | active |
|
||||
| [0103](0103-adapter-specific-ai-permission-semantics.md) | Adapter-specific AI permission semantics | active |
|
||||
| [0104](0104-tauri-frontend-readiness-watchdog.md) | Tauri frontend readiness watchdog | active |
|
||||
| [0105](0105-editor-correctness-and-responsiveness-contract.md) | Editor correctness and responsiveness contract | active |
|
||||
| [0106](0106-shared-app-command-manifest.md) | Shared app command manifest | active |
|
||||
| [0107](0107-markdown-durable-tldraw-whiteboards.md) | Markdown-durable tldraw whiteboards in notes | active |
|
||||
| [0107](0107-pointer-owned-editor-block-reordering.md) | Pointer-owned editor block reordering | active |
|
||||
| [0108](0108-sanitized-rendered-markup-and-safe-regex.md) | Sanitized rendered markup and safe user regex | active |
|
||||
|
||||
44
index.html
44
index.html
@@ -50,6 +50,50 @@
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
var readyEventName = 'tolaria:frontend-ready';
|
||||
var reloadAttemptKey = 'tolaria:startup-reload-attempted';
|
||||
var startupTimeoutMs = 10000;
|
||||
var isTauri = '__TAURI__' in window || '__TAURI_INTERNALS__' in window;
|
||||
|
||||
if (!isTauri) return;
|
||||
|
||||
function hasReloadAttempted() {
|
||||
try {
|
||||
return sessionStorage.getItem(reloadAttemptKey) === '1';
|
||||
} catch (err) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function markReloadAttempted() {
|
||||
try {
|
||||
sessionStorage.setItem(reloadAttemptKey, '1');
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function clearReloadAttempt() {
|
||||
try {
|
||||
sessionStorage.removeItem(reloadAttemptKey);
|
||||
} catch (err) {
|
||||
// Storage can be unavailable in hardened WebView/privacy modes.
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener(readyEventName, clearReloadAttempt, { once: true });
|
||||
window.setTimeout(function () {
|
||||
if (window.__tolariaFrontendReady === true) return;
|
||||
if (hasReloadAttempted()) return;
|
||||
if (!markReloadAttempted()) return;
|
||||
|
||||
window.location.reload();
|
||||
}, startupTimeoutMs);
|
||||
})();
|
||||
</script>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
192
lara.lock
192
lara.lock
@@ -11,9 +11,10 @@ files:
|
||||
command.openSettings: 638c05f4f159a403e04aebe94b46a2a8
|
||||
command.openSettings.keywords: ab6b5e03395f4db955ed9cbfd4de33b7
|
||||
command.openLanguageSettings: e5a425aa6222fab3df66c0e1e0ca4183
|
||||
command.openLanguageSettings.keywords: 68efcb7e847b1a9d472baa609824be80
|
||||
command.openLanguageSettings.keywords: 6a910000cbf23eac3c7078e518cae66a
|
||||
command.useSystemLanguage: b7f0315c47d4a59faa2a49571fcf1fca
|
||||
command.openH1Setting: 05b4f6edc0e98b29670e8ee902cdb9bf
|
||||
command.toggleGitignoredFilesVisibility: 0a2d3ea4e8ff8b00a801183caeb97a03
|
||||
command.contribute: 9887a4451812854f0f1b6f669a874307
|
||||
command.checkUpdates: f77f38f684c8b974dd4a56bb321cfd5f
|
||||
command.group.navigation: 846495f9ceed11accf8879f555936a7d
|
||||
@@ -38,6 +39,7 @@ files:
|
||||
command.note.newType: adce5108f18945cc502a06c02445e32d
|
||||
command.note.newTypedNote: 1493eda772c2179cb6247169d00723b2
|
||||
command.note.saveNote: 2a309cda46e95b00d2a5a8afb3cc0047
|
||||
command.note.pastePlainText: 09e8075dbd91e11878f8f4a138df760c
|
||||
command.note.findInNote: f72f8f93d8e6119d5d08b60eb3a7b3bc
|
||||
command.note.replaceInNote: b008e2e20c5e4cd202f4386271d6bed1
|
||||
command.note.deleteNote: 56f727a2ee11d15159f1aa6373314cb6
|
||||
@@ -65,11 +67,19 @@ files:
|
||||
command.view.toggleProperties: 54f12756a363401243d82cbd0466117e
|
||||
command.view.toggleDiff: 148a10ef6f04f897e73289f529ecae86
|
||||
command.view.toggleRaw: 9b622257cd6345ceaf58e42b1410899b
|
||||
command.view.noteWidthNormal: d29ab88a55ae178bf4b5257201e51801
|
||||
command.view.noteWidthWide: 403f3913ad71451a90787c235f1684de
|
||||
command.view.defaultNoteWidthNormal: b045349e37329df23317db98cccd3263
|
||||
command.view.defaultNoteWidthWide: 41f326763e3e3954912dfd45d04bd87c
|
||||
command.view.leftLayout: 5046a7166675e2d0175b9da3befdcaca
|
||||
command.view.centerLayout: 3bc6759c005178aae519aa3dd227cb74
|
||||
command.view.toggleAiPanel: 4279cbf31767465f25feff6e7bdd336e
|
||||
command.view.newAiChat: 1b0a886d6e77f628ec96c2d71cdb0a9b
|
||||
command.view.toggleBacklinks: b3c4be2d2c07bb8df181355a2c3658a7
|
||||
command.view.moveViewUp: 76f92d3250e028609349d825c672f13e
|
||||
command.view.moveViewDown: 9deea30162b8d3234f8d52795ad7393f
|
||||
command.view.moveNamedViewUp: b4ac634d13a09eacb680ef12c69dd1f7
|
||||
command.view.moveNamedViewDown: 15302c02df26fe52def77636e9141711
|
||||
command.view.zoomIn: ae4a8e406b707636392b6673fca0e6a6
|
||||
command.view.zoomOut: 97326f8cd9df886a6b19af180fb7dcc9
|
||||
command.view.resetZoom: 193ee8c32391fc5cc303a51617cfd046
|
||||
@@ -81,6 +91,9 @@ files:
|
||||
command.settings.setupExternalAi: 24eea679eb699763daa2e3f2a67fcf9a
|
||||
command.settings.reloadVault: f6e506dad6b6cf2be24d9438d458ae54
|
||||
command.settings.repairVault: cee560b1fd5ad9d1ff1c19a0a2afe77a
|
||||
command.settings.useLightMode: a76d5b1c076983bc113d247f0520c166
|
||||
command.settings.useDarkMode: ba7873c42ae00542ba71db9be3b6761f
|
||||
command.settings.toggleGitignoredFilesVisibility: 0a2d3ea4e8ff8b00a801183caeb97a03
|
||||
command.ai.openAgents: 612abe804edd0f5ae228a534f77f3d23
|
||||
command.ai.restoreGuidance: 23331fecc692d11d85cf24838ed273f2
|
||||
command.ai.switchToAgent: 5bb02187e653b360ab7ed661403271f2
|
||||
@@ -91,7 +104,9 @@ files:
|
||||
settings.sync.title: 36f62a237420dcdc7096ad3a9018c4d9
|
||||
settings.sync.description: 06a6957c40867be2c28783183dc1bf5f
|
||||
settings.pullInterval: 4f95ca677398604bca241427261ed07b
|
||||
settings.pullIntervalDescription: 4a75c15f44d59dc8cb100ec2d0693048
|
||||
settings.releaseChannel: 2da37055e15a217f18bd403922085c3f
|
||||
settings.releaseChannelDescription: c5ae9b7f25376df383d36603366ac1fa
|
||||
settings.releaseStable: fa3aff3c185c6dc7754235f397c2099a
|
||||
settings.releaseAlpha: 6132295fcf5570fb8b0a944ef322a598
|
||||
settings.appearance.title: a1c58e94227389415de133efdf78ea6e
|
||||
@@ -110,25 +125,88 @@ files:
|
||||
settings.autogit.enable: 9b205a4ae0e3ad4e6708155880ce9c75
|
||||
settings.autogit.enableDescription: a7424a8f90c0b7f290a8144d12374554
|
||||
settings.autogit.idleThreshold: 28016cc6fccd951a904ee3020cd733b6
|
||||
settings.autogit.idleThresholdDescription: 521140491e8c9d5a1d7b7739bc333358
|
||||
settings.autogit.inactiveThreshold: d28cb60d1e70e020ae8d1294e32dd474
|
||||
settings.autogit.inactiveThresholdDescription: f9e43c90bd10bae937c2cfa5c2767f1c
|
||||
settings.titles.title: 761443f70a5067ecf015c6fb3fae9cef
|
||||
settings.titles.description: b94aeeca78dd376cc19b9aa019e53f6c
|
||||
settings.titles.autoRename: 5383db8e790ebf5f956d9c59cb4c4f67
|
||||
settings.titles.autoRenameDescription: cc28c28d8817736e658082a2261d9a6e
|
||||
settings.vaultContent.title: 78b883ce9acb9c25e611158a518d9185
|
||||
settings.vaultContent.description: a53487bf1c7898a1459dc1510e216f7d
|
||||
settings.vaultContent.hideGitignored: 2c07ee6c8bfe746d356f44275d42f90e
|
||||
settings.vaultContent.hideGitignoredDescription: e8b1ddfa416610f9d6eb299fa123a1d6
|
||||
settings.allNotesVisibility.title: 0e07c3d48b91e1a4c42c1ff3e5751ec3
|
||||
settings.allNotesVisibility.description: bc9caa48296281401aad694fed65a2d9
|
||||
settings.allNotesVisibility.pdfs: 27ce5e1e1761ff362dbf75c76c6b4941
|
||||
settings.allNotesVisibility.pdfsDescription: 8191ed4a095cdd60ef856ce0ff213a48
|
||||
settings.allNotesVisibility.images: ea15460e63b6e8e92f8c03a79eeb6e4e
|
||||
settings.allNotesVisibility.imagesDescription: 1704e10d5e5cdc17d2d2a5fb7b8969bf
|
||||
settings.allNotesVisibility.unsupported: 257fe04419c9f6543a43e58b1edf9eb5
|
||||
settings.allNotesVisibility.unsupportedDescription: a3b8aa66900c742f001cd4533b3df44a
|
||||
settings.aiAgents.title: 27f08387b26e1ceeb1b60bd9c97e7a47
|
||||
settings.aiAgents.description: a13222e67eb121676ff6dfc7b085f02d
|
||||
settings.aiAgents.description: 042a8037f1a4f90c76ce31a49fdff59c
|
||||
settings.aiAgents.default: 6af573559fd05d8c35bc57b41cc78e24
|
||||
settings.aiAgents.defaultTarget: 5acfc74fd97a6dd2d67d15c66de5eed5
|
||||
settings.aiAgents.agentGroup: 965530cbbec45b1754ed3ece120399f7
|
||||
settings.aiAgents.localGroup: d34f4b997ce78da5aa57d657a5d6fcb5
|
||||
settings.aiAgents.apiGroup: 589a257cbd265eaa7de93de8b4084dff
|
||||
settings.aiAgents.installed: 73329564760013a7824ff9d5d1af91ff
|
||||
settings.aiAgents.missing: ea21841da70e6405af19fabc4ff8bdd9
|
||||
settings.aiAgents.ready: 909a648c713be25fcd050725d0a41e37
|
||||
settings.aiAgents.notInstalled: 0ac3f76ef78bfdbab6331731ee56ba22
|
||||
settings.aiAgents.apiReady: e5b06f6ef4ef5f4bc2848d46195e3f48
|
||||
settings.aiAgents.apiLocalKey: 119de2f31867b273a134f05bc56b9e57
|
||||
settings.aiAgents.apiEnv: e011db3dff54ed3deae37a9615e31ebf
|
||||
settings.aiAgents.apiNoKey: 5bbccbfcd09b28902bbf5319dd6e6053
|
||||
settings.aiAgents.installedTitle: 5cb9b5ae5ebc66652814dff4584705cc
|
||||
settings.aiAgents.installedDescription: fb9ba9667725fb40fa1e5d58a2c02692
|
||||
settings.aiAgents.noVersion: 89831adb7114946e916b9c31d57a1e33
|
||||
settings.aiProviders.title: 63eb84d8510f9f086d282ec7d47adaa1
|
||||
settings.aiProviders.description: 6c86c013eb6fb198b51e29ec47d66464
|
||||
settings.aiProviders.localTitle: c7c20443d8aaf04271df9d713f5c02ce
|
||||
settings.aiProviders.localDescription: 7abed40ef2e46741c64ff47e423cca39
|
||||
settings.aiProviders.apiTitle: 66537b9e5200ebbbfbd091144d8afbcc
|
||||
settings.aiProviders.apiDescription: 6ec773352e05a805af3abcebeff4e756
|
||||
settings.aiProviders.kind: 27703c8f150ac4bb0a3a83a7857353af
|
||||
settings.aiProviders.kind.ollama: c23e8db458397f37c8e8d98e94e55a18
|
||||
settings.aiProviders.kind.lmStudio: 7b9b319662715e90583e823a6c3cfdbe
|
||||
settings.aiProviders.kind.openAi: 0523b13262b12c215d8009938f5c14f1
|
||||
settings.aiProviders.kind.anthropic: f431db65cea024a5f19eab835afefee2
|
||||
settings.aiProviders.kind.gemini: 766cc4dd4d5005652e8514e3513683f8
|
||||
settings.aiProviders.kind.openRouter: a0607683815b6585fb80e7cac72ac59a
|
||||
settings.aiProviders.kind.compatible: 1a4dc90a183c26d9026c6ac7727aa4cd
|
||||
settings.aiProviders.name: 49ee3087348e8d44e1feda1917443987
|
||||
settings.aiProviders.baseUrl: ade86bc4899761ad46c52e381b6228bb
|
||||
settings.aiProviders.model: 6bd36c36869288188863bd53a9bc5ed1
|
||||
settings.aiProviders.key: 656a6828d7ef1bb791e42087c4b5ee6e
|
||||
settings.aiProviders.keyPlaceholder: 57dbf3720af3f156018bfff7f5a99b23
|
||||
settings.aiProviders.keyStorage: 3e5b8cfbc66d3a33dad3fda058bf5851
|
||||
settings.aiProviders.keyStorage.local: 7c6189f734f3c66d162a3f06529af1d9
|
||||
settings.aiProviders.keyStorage.env: a71b071971d7c54e9af381c9bea093d9
|
||||
settings.aiProviders.keyStorage.none: 94c841331ccd5179a283487f96285c90
|
||||
settings.aiProviders.keyEnv: cb72671bd5cf65512d4c94e8ad6182ef
|
||||
settings.aiProviders.keySafety: 0d59d7e4def35e51c4bb785d74180afc
|
||||
settings.aiProviders.keySafetyLocal: 8ef2ba0192ac725fa1a3e737e852387c
|
||||
settings.aiProviders.localSafety: 60fb65e4e0d35cec3135584d8219e8fd
|
||||
settings.aiProviders.add: a9f8e8b4ca3cbc4fc3bff5d59d6a5419
|
||||
settings.aiProviders.addLocal: 681985f2e412f22fcd55a0553f6e4bee
|
||||
settings.aiProviders.addApi: 767b46f2a51aa9dd050cb226cd86e192
|
||||
settings.aiProviders.test: 602009d5aea1c1ef06fd777968f7e80e
|
||||
settings.aiProviders.testing: 9d770c909c2c69b09eae2372c4cf405d
|
||||
settings.aiProviders.testSuccess: 51677ed54231e41a4fe40850d90b64b2
|
||||
settings.aiProviders.empty: 9378027dec7f93fcc5011c5e528bdf82
|
||||
settings.aiProviders.defaultEndpoint: 666b355c305dd4c7b4649d3d7b4c5d11
|
||||
settings.aiProviders.keyLocalSaved: f4a102d6a67212e21f0f31f0758aea81
|
||||
settings.aiProviders.keyEnvSaved: bfed2d745dd76dbea9341d27e06c39f2
|
||||
settings.aiProviders.noKey: 1ab089f80ef4dc6c1ce3e173f5b405a0
|
||||
settings.workflow.title: 24f47cdbe9ddba774a7cc53e51d9032e
|
||||
settings.workflow.description: aa9a07539b87cf407c3edc8a22732d45
|
||||
settings.workflow.explicit: 54a5b5c27937d25271c3127d093e8361
|
||||
settings.workflow.explicitDescription: ce523427b5dd0f9895f63d1fbb90ad24
|
||||
settings.workflow.autoAdvance: 9ed337f5bc61603d19a1ef35f3a3a243
|
||||
settings.workflow.autoAdvanceDescription: ae58ad8abf03df7cbdae8c3a725258f7
|
||||
settings.privacy.title: 0dd6c14e00cc9f45a68c1bca88d1317d
|
||||
settings.privacy.title: aa96a21412def0d916f43b639424f8e4
|
||||
settings.privacy.description: 33d53059be620b58e38b8e5c5ab26b27
|
||||
settings.privacy.crashReporting: b4efc5b61526566d431e99242f5c21b4
|
||||
settings.privacy.crashReportingDescription: e9d7c7efce44adc08d0460be1aad5c42
|
||||
@@ -138,6 +216,90 @@ files:
|
||||
settings.cancel: ea4788705e6873b424c65e91c2846b19
|
||||
settings.save: c9cc8cce247e49bae79f15173ce97354
|
||||
common.cancel: ea4788705e6873b424c65e91c2846b19
|
||||
common.create: 686e697538050e4664636337cc3b834f
|
||||
common.save: c9cc8cce247e49bae79f15173ce97354
|
||||
common.remove: 1063e38cb53d94d386f21227fcd84717
|
||||
customize.color: cb5feb1b7314637725a2e73bdc9f7295
|
||||
customize.icon: 817434295a673aed431435658b65d9a7
|
||||
customize.searchIcons: 0688a8098567785a05cb4cf937cbb880
|
||||
customize.noIconsFound: 89c25bea716a589b11599f2bbcf34054
|
||||
customize.template: 278c491bdd8a53618c149c4ac790da34
|
||||
customize.templatePlaceholder: 44482755791f96f37118f3a3bc66f668
|
||||
customize.done: f92965e2c8a7afb3c1b9a5c09a263636
|
||||
viewDialog.title.create: 01e53f288ebe0b7bdda19c8151aa7710
|
||||
viewDialog.title.edit: 6369f1c063cb2c22efa584a19e98d97f
|
||||
viewDialog.description.create: a9600940be61edfcad2b47fb72965406
|
||||
viewDialog.description.edit: d4e6333950d5031c5f4ae766a1f1d886
|
||||
viewDialog.nameLabel: 49ee3087348e8d44e1feda1917443987
|
||||
viewDialog.namePlaceholder: dbb077d36957a33c4147eb24919192e1
|
||||
viewDialog.filtersLabel: f3f43e30c8c7d78c6ac0173515e57a00
|
||||
viewDialog.saveError: 80fe81f3ca09ea03af03fdb9ae809eda
|
||||
viewDialog.selectedIcon: 5f98b507ccec0bbc51ca7e8a5b270250
|
||||
viewDialog.selectedColor: 192ec1a9973f328c3620cd3fa670c745
|
||||
ai.permission.safe.short: c6eea0560cd6f377e78dff2c85cc9122
|
||||
ai.permission.safe.control: 386cc66605d50e5bf1fb726f97e55b55
|
||||
ai.permission.safe.tooltip: 3bd635e2b2223da302994d77bfd7edfd
|
||||
ai.permission.powerUser.short: d4a47db271fc1ef3cd17f7396326b057
|
||||
ai.permission.powerUser.control: d4a47db271fc1ef3cd17f7396326b057
|
||||
ai.permission.powerUser.tooltip: 2585ecdb79ca02a3ee779bb61552de03
|
||||
ai.permission.modeAria: 3ff6346566a4c44fd5c7395907125d3e
|
||||
ai.permission.changed: b5d06ad47e6053fe5a73f4571a40e00c
|
||||
ai.panel.title: 4412225fe5b326643b8c2e1d9b7b10ae
|
||||
ai.panel.status.checking: 118740af1c4521b917e29791d661db82
|
||||
ai.panel.status.missing: fe07f8eac233c229d81cbe9aa25668a0
|
||||
ai.panel.status.ready: 296a0ac791eab2df130789f55fdc109b
|
||||
ai.panel.mode.chat: 55dcdf017b51fc96f7b5f9d63013b95d
|
||||
ai.panel.mode.chatDescription: d7744ae39e7920a8eac7b21b58fce348
|
||||
ai.panel.copyMcpConfig: 6a8c9fe401557c870e3a90bbfab01b25
|
||||
ai.panel.mcpConfig: 53bac93d0314941c8d2c1163026f3ad9
|
||||
ai.panel.newChat: 1b0a886d6e77f628ec96c2d71cdb0a9b
|
||||
ai.panel.close: d00ba22b83762f5a6e66db0be9e916d7
|
||||
ai.panel.linkedCount: 5292fda189a357c9597b1cb0e1b0900b
|
||||
ai.panel.empty.checkingTitle: 0dde2076cb53fe497d05d231296d50bb
|
||||
ai.panel.empty.checkingDescription: 31e41510d851c366860377ba0c956f0b
|
||||
ai.panel.empty.missingTitle: a2b764da52cb43b191bb4ecfd8ea4d26
|
||||
ai.panel.empty.missingDescription: 91825c7d86b1d588d44a33e1d94af950
|
||||
ai.panel.empty.withContextTitle: 66f02985937083e4ef62b98cc9f25aee
|
||||
ai.panel.empty.noContextTitle: e919aeb0a49b58e494e43e5f6f6597c9
|
||||
ai.panel.empty.withContextDescription: dd8faefcc8160a2db800a41d6628facb
|
||||
ai.panel.empty.noContextDescription: 6a6e610835808016d1f2790c3f991a54
|
||||
ai.panel.placeholder.checking: 08fec77719c37d3d6279b2641b37b4d3
|
||||
ai.panel.placeholder.missing: 547c492026d115608067988b7cfbb9a9
|
||||
ai.panel.placeholder.ready: 31f5265c2e0432a7ca10d08e5c6f3114
|
||||
ai.panel.send: 747c6a3564774149c989884e0c581d53
|
||||
mcp.setup.manageTitle: d786c7b9ab9b2406258648931bca0e01
|
||||
mcp.setup.setupTitle: b4b373f690c8a0008885b31e78e93a5c
|
||||
mcp.setup.connectedDescription: a2a3be70c0ac9fa7ef112df5252249fa
|
||||
mcp.setup.setupDescription: 8bf199ffbcf303a99abac078c0c5e094
|
||||
mcp.setup.reconnect: 813ba447b5e64c17ff9b68c693358ca3
|
||||
mcp.setup.connect: fb95777dbc9f7b22014dc360a2957652
|
||||
mcp.setup.disconnect: 42ae25231906c83927831e0ef7c317ac
|
||||
mcp.setup.connecting: 182e7eda4e721ad00737460b88701dee
|
||||
mcp.setup.disconnecting: 11de134aefe51cb4a5c545b5a057a871
|
||||
mcp.setup.nodeRequirement: ac58a35cf21d2204fed548c227f77594
|
||||
mcp.setup.writeEntryDescription: 370aa4403d2ffc37f574503bc3cd00e6
|
||||
mcp.setup.clientPathsDescription: 94565852412051c799e78d2f4525ff53
|
||||
mcp.setup.geminiGuidanceDescription: 182cf5b84b2f56cb1cf41dcdb5e093d8
|
||||
mcp.setup.manual.title: 2188ca52346158cbd103ca7ce7c12dd9
|
||||
mcp.setup.manual.copy: 6a8c9fe401557c870e3a90bbfab01b25
|
||||
mcp.setup.manual.loading: 11ee201c121c8e2015c065952474a3ea
|
||||
mcp.setup.manual.unavailable: 8b4330b839c41bad378c86c91ee0b5cd
|
||||
mcp.toast.connected: 7716c0f9dad41a7fdbef592074459239
|
||||
mcp.toast.refreshed: 227d8721ebec3077792b1223c1f30e54
|
||||
mcp.toast.disconnected: 9b5254079561087d679e35aa10c80638
|
||||
mcp.toast.alreadyDisconnected: 645bec2e33bd9de2b334b704d9fa84cf
|
||||
mcp.toast.configCopied: 458b50444b9a1cb069b00475c0951b8a
|
||||
mcp.toast.configCopyFailed: b451cfb95f87458d142d026a8aca74cf
|
||||
mcp.toast.setupFailed: 51f290962c08d8ba76bfc6c19552eaed
|
||||
mcp.toast.disconnectFailed: ddc3387ab6e996ce15bc4950a3548e1e
|
||||
mcp.error.clipboardUnavailable: 3b9ed3fe7dba627edb74e1cdaa02b2ee
|
||||
save.toast.saved: 248336101b461380a4b2391a7625493d
|
||||
save.toast.nothingToSave: 86ae8cef7371e639f3c007449a2f7d1f
|
||||
save.toast.missingActiveVault: 49cf5064a7dce757f895950d8beeed68
|
||||
save.error.failed: b55b9fefe93fabae3c277e4e7956a534
|
||||
save.error.autoFailed: 09b2b131f07baddb5ba8f5a3ee6234c5
|
||||
save.error.invalidPath: c96fb669715e86508f4c5e73da9f6995
|
||||
savedViews.reordered: 531081a566b826eed2e714ce70a0de08
|
||||
locale.en: 78463a384a5aa4fad5fa73e2f506ecfc
|
||||
sidebar.nav.inbox: 3882d32c66e7e768145ecd8f104b0c08
|
||||
sidebar.nav.allNotes: cd76cf851b08a9d2feafaf255bc1f4d5
|
||||
@@ -148,10 +310,16 @@ files:
|
||||
sidebar.group.folders: d86e2756f698bea5aac3e2276639f042
|
||||
sidebar.action.createView: ba019414ea8c7fcdb4a83a70ec1bb639
|
||||
sidebar.action.editView: acdf34bd08b0692b906d446e590b1eb9
|
||||
sidebar.action.renameView: 429b903fddf39bb21887282d188c4b62
|
||||
sidebar.action.deleteView: c8f4f9cd8ff820f955474e5c9f70ff39
|
||||
sidebar.action.reorderView: ca2f42548fd57160d22fd0809bf8ed6e
|
||||
sidebar.action.moveViewUp: e601b7f0901f12efb71f7821c0fdb79e
|
||||
sidebar.action.moveViewDown: 6f86951085367864e3e4eb13f5c8688e
|
||||
sidebar.action.customizeSections: 050a134cad1e9c6f04abe5d635592703
|
||||
sidebar.action.renameSection: 8936914051df04e7550d0eeb4a31e0e0
|
||||
sidebar.action.renameType: 327d51d97d4b0e3ddcb7afa39c4bf5fa
|
||||
sidebar.action.customizeIconColor: 9a2f685c74d261ab483ef00dee5314fe
|
||||
sidebar.action.deleteType: c52e15c44f6372c6ddb2758254a041ef
|
||||
sidebar.action.createType: 6cfb8b8aa3fdce38e675819691b48f5c
|
||||
sidebar.action.collapse: 00873bdddd457791609bff1243c40a6b
|
||||
sidebar.action.expand: 8f98e9696f6eed958573012f52710faa
|
||||
@@ -162,6 +330,7 @@ files:
|
||||
sidebar.action.copyFolderPathMenu: 1779ec6018a385912c1a5499a1bbf2b2
|
||||
sidebar.action.renameFolderMenu: deb1d8fa030292e7eda2c244b313aca2
|
||||
sidebar.action.deleteFolderMenu: c78c889ac7396dc148fc859c9221e545
|
||||
sidebar.view.name: 67b904f75d1872abba088a3442caff40
|
||||
sidebar.folder.name: 710417c4e57a6a01500fe4c0c448ce3d
|
||||
sidebar.folder.newName: e0ad5b2db20359a85de80c1231323bea
|
||||
sidebar.folder.expand: b7545cb143816942ff096d890090fb6f
|
||||
@@ -239,6 +408,8 @@ files:
|
||||
editor.find.replaceAll: b1c94ca2fbc3e78fc30069c8d0f01680
|
||||
editor.toolbar.rawReturn: 5ddcf5e0dc8b933b344bb6ca3d8e131d
|
||||
editor.toolbar.rawOpen: 89ad60735a649b60dacd2301cda0c4ec
|
||||
editor.toolbar.noteWidthNormal: 9bb55413ec536c4a8fa41c4c4464ab44
|
||||
editor.toolbar.noteWidthWide: 1a744f406c9150f76739bd167c3e47ec
|
||||
editor.toolbar.centerLayout: 3fabf7e9b285eeec90704d271f1049b7
|
||||
editor.toolbar.leftLayout: acab6c8612816e012ff9f4220a42e485
|
||||
editor.toolbar.removeFavorite: 7188286e36fc6c1892dd53aaa54237fb
|
||||
@@ -255,7 +426,10 @@ files:
|
||||
editor.toolbar.delete: f48134a07b016a1de05d4ba6d2fbfb41
|
||||
editor.toolbar.revealFile: 76f4ed52da9937ae432dcf5a108fabb4
|
||||
editor.toolbar.copyFilePath: 64c6cec5ca57efbb8c9c93ae5fbccd27
|
||||
editor.toolbar.moreActions: 89e19353176b94068dec4c768c25e70b
|
||||
editor.toolbar.openProperties: 948b90b60b8ce827f179e8c5b85b112e
|
||||
editor.codeBlock.copy: 8e477020fb3f7ab844b91ff1d7de8347
|
||||
editor.imageLightbox.title: 2c5a15c875bcdc2478c4a5cad044e10c
|
||||
editor.filename.rename: c31c2b468229232ad6287e734fe67d96
|
||||
editor.filename.renameToTitle: bff34a6a2dd1eb87c59403946679237f
|
||||
editor.filename.trigger: 4e9739c2f937c828bbf5d1f935fe7fb9
|
||||
@@ -269,6 +443,8 @@ files:
|
||||
inspector.title.properties: 9fc2d28c05ed9eb1d75ba4465abf15a9
|
||||
inspector.title.propertiesShortcut: 427d1cbdc813cf54c5fac2508d38d407
|
||||
inspector.title.closePropertiesShortcut: 97b953e45042d4143dd19624dc345d29
|
||||
inspector.title.collidingProperties: bf71358d0af34696e88bea278eac046a
|
||||
inspector.title.collidingPropertiesAria: ce5c3569f304cd69b0f33a6fc185f49b
|
||||
inspector.empty.noNoteSelected: 046d95682b747a30ed8a7b0b1d581629
|
||||
inspector.empty.noProperties: 6864166e0f65d81b1eb474e41fde8822
|
||||
inspector.empty.initializeProperties: edf249d214b68f5afe8634c577b709c4
|
||||
@@ -297,6 +473,7 @@ files:
|
||||
inspector.info.words: 6f15b8d4b7287d60a8ea3d1c5cbadc84
|
||||
inspector.info.size: 6f6cb72d544962fa333e2e34ce64f719
|
||||
update.available: 992477975168b876be8e77ce2975e390
|
||||
update.checking: a07813cc05571f23ce8dd7039583d7da
|
||||
update.releaseNotes: 5dd03e8d039863e563e049be198c3fd3
|
||||
update.updateNow: 99b1054c0f320be9f109c877a5efd0b2
|
||||
update.dismiss: c8a59e7135a20b362f9c768b09454fdb
|
||||
@@ -318,6 +495,8 @@ files:
|
||||
status.vault.cloneGit: a7d0aef7c6237a36e54fd5a26e9c23fe
|
||||
status.vault.cloneGettingStarted: 9953a11a477b441976a626a9acf5d7df
|
||||
status.vault.notFound: 3119b7fa94c96209bca571b7c7ed0b7e
|
||||
status.vault.reloading: 893da50ef3a9e01d8a99ff5d3ceb55e9
|
||||
status.vault.reloadingTooltip: 4a884bd7d113797ad16f905f70742da8
|
||||
status.vault.remove: 7f3b4f76df23626170940dbc55c70728
|
||||
status.remote.noneConfigured: 18a4edd4e8d862ccb343937f45585fb1
|
||||
status.remote.inSync: a56f571b4df55d88fb06e61e343b3c91
|
||||
@@ -368,6 +547,7 @@ files:
|
||||
status.ai.noAgentsTooltip: 1bdc02ec2dd7f9701b4371ffd5770318
|
||||
status.ai.selectedMissing: a37f3dbc73725219e90d709fe0d3ad97
|
||||
status.ai.defaultAgent: 79650d57d1678e56c75dbbcba6ea87f7
|
||||
status.ai.defaultTarget: 65ea5bdb609833c4baffd2cbd0e86542
|
||||
status.ai.restoreDetails: 47a913b58ce40add6521bc93e807476f
|
||||
status.ai.withGuidance: 1eafd34810db6bba54dac7aa549b5182
|
||||
status.ai.active: 059e3a3167c2ab00f4ca872e82a48d98
|
||||
@@ -377,6 +557,9 @@ files:
|
||||
status.ai.vaultGuidance: 7bb4644efe6ae7cec9993c8bd85f1519
|
||||
status.ai.restoreGuidance: 23331fecc692d11d85cf24838ed273f2
|
||||
status.ai.openOptions: d387b1ab67586c7a2d83db8900a4dd8e
|
||||
status.ai.modelTargets: 8f3ceb96e088f8bdaecc236778401ac9
|
||||
status.ai.localChat: 215a24e3d38fb8b68deea6dad0142326
|
||||
status.ai.apiChat: 6dffd5b9997885efe701631cea5c470d
|
||||
pulse.title: 16d2b386b2034b9488996466aaae0b57
|
||||
pulse.today: 1dd1c5fb7f25cd41b291d43a89e3aefd
|
||||
pulse.yesterday: ebfe9ce86e6e9fb953aa7a25b59c1956
|
||||
@@ -402,5 +585,8 @@ files:
|
||||
locale.ptPT: 71bfc0d79772120b52c1c0782450ff84
|
||||
locale.es419: edbf64ac382b82a54795fb409beb54be
|
||||
locale.zhCN: 1e81fc32fea0e9f3a978661e4b5e484d
|
||||
locale.zhTW: d0bb8c23f6e4f8c8037b6774ba912036
|
||||
locale.jaJP: f32ced6a9ba164c4b3c047fd1d7c882e
|
||||
locale.koKR: d0bdb3cde477d82e766da05ebda50ccb
|
||||
locale.vi: 7b80fae85640c16cdb0261bef0c27636
|
||||
locale.plPL: c730389bc8d99e59c867766babdd48b5
|
||||
|
||||
@@ -18,8 +18,11 @@ locales:
|
||||
- pt-PT
|
||||
- es-419
|
||||
- zh-CN
|
||||
- zh-TW
|
||||
- ja-JP
|
||||
- ko-KR
|
||||
- vi
|
||||
- pl-PL
|
||||
|
||||
files:
|
||||
json:
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
/**
|
||||
* Tolaria MCP Server — lightweight vault tools for AI agents.
|
||||
*
|
||||
* The agent has full shell access (bash, read, write, edit).
|
||||
* These MCP tools provide Tolaria-specific capabilities that
|
||||
* native tools cannot replace:
|
||||
* These MCP tools provide Tolaria-specific capabilities alongside each
|
||||
* app-managed agent's own Safe / Power User permission profile:
|
||||
*
|
||||
* - search_notes: full-text search across vault notes
|
||||
* - get_vault_context: vault structure overview (types, note count, folders)
|
||||
@@ -30,27 +29,69 @@ const WS_UI_URL = `ws://localhost:${WS_UI_PORT}`
|
||||
// Connect as a WebSocket CLIENT to the UI bridge (run by ws-bridge.js).
|
||||
// The bridge relays messages to all other clients (the React frontend).
|
||||
let uiSocket = null
|
||||
let reconnectTimer = null
|
||||
let shutdownStarted = false
|
||||
const RECONNECT_INTERVAL_MS = 3000
|
||||
|
||||
function connectUiBridge() {
|
||||
if (shutdownStarted) return
|
||||
|
||||
try {
|
||||
const ws = new WebSocket(WS_UI_URL)
|
||||
uiSocket = ws
|
||||
ws.on('open', () => {
|
||||
uiSocket = ws
|
||||
if (shutdownStarted) {
|
||||
closeUiSocket()
|
||||
return
|
||||
}
|
||||
console.error(`[mcp] Connected to UI bridge at ${WS_UI_URL}`)
|
||||
})
|
||||
ws.on('close', () => {
|
||||
uiSocket = null
|
||||
setTimeout(connectUiBridge, RECONNECT_INTERVAL_MS)
|
||||
if (uiSocket === ws) uiSocket = null
|
||||
scheduleUiReconnect()
|
||||
})
|
||||
ws.on('error', () => {
|
||||
// Silent — bridge may not be running yet, will retry
|
||||
})
|
||||
} catch {
|
||||
setTimeout(connectUiBridge, RECONNECT_INTERVAL_MS)
|
||||
scheduleUiReconnect()
|
||||
}
|
||||
}
|
||||
connectUiBridge()
|
||||
|
||||
function scheduleUiReconnect() {
|
||||
if (shutdownStarted) return
|
||||
|
||||
clearUiReconnectTimer()
|
||||
reconnectTimer = setTimeout(connectUiBridge, RECONNECT_INTERVAL_MS)
|
||||
reconnectTimer.unref?.()
|
||||
}
|
||||
|
||||
function clearUiReconnectTimer() {
|
||||
if (!reconnectTimer) return
|
||||
|
||||
clearTimeout(reconnectTimer)
|
||||
reconnectTimer = null
|
||||
}
|
||||
|
||||
function closeUiSocket() {
|
||||
const socket = uiSocket
|
||||
uiSocket = null
|
||||
if (!socket) return
|
||||
|
||||
socket.removeAllListeners()
|
||||
socket.on('error', () => {})
|
||||
if (socket.readyState === WebSocket.CONNECTING) {
|
||||
socket.terminate?.()
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
socket.close()
|
||||
} catch {
|
||||
// Ignore close races during process teardown.
|
||||
}
|
||||
socket.terminate?.()
|
||||
}
|
||||
|
||||
function broadcastUiAction(action, payload) {
|
||||
if (!uiSocket || uiSocket.readyState !== WebSocket.OPEN) return
|
||||
@@ -121,15 +162,6 @@ const TOOLS = [
|
||||
},
|
||||
]
|
||||
|
||||
const TOOL_HANDLERS = {
|
||||
search_notes: handleSearchNotes,
|
||||
get_vault_context: handleVaultContext,
|
||||
get_note: handleGetNote,
|
||||
open_note: handleOpenNote,
|
||||
highlight_editor: handleHighlightEditor,
|
||||
refresh_vault: handleRefreshVault,
|
||||
}
|
||||
|
||||
async function handleSearchNotes(args) {
|
||||
const results = await searchNotes(VAULT_PATH, args.query, args.limit)
|
||||
const text = results.length === 0
|
||||
@@ -166,6 +198,25 @@ function handleRefreshVault(args) {
|
||||
return { content: [{ type: 'text', text: 'Vault refresh triggered' }] }
|
||||
}
|
||||
|
||||
function callToolHandler(name, args) {
|
||||
switch (name) {
|
||||
case 'search_notes':
|
||||
return handleSearchNotes(args)
|
||||
case 'get_vault_context':
|
||||
return handleVaultContext()
|
||||
case 'get_note':
|
||||
return handleGetNote(args)
|
||||
case 'open_note':
|
||||
return handleOpenNote(args)
|
||||
case 'highlight_editor':
|
||||
return handleHighlightEditor(args)
|
||||
case 'refresh_vault':
|
||||
return handleRefreshVault(args)
|
||||
default:
|
||||
throw new Error(`Unknown tool: ${name}`)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Server setup ---
|
||||
|
||||
const server = new Server(
|
||||
@@ -179,12 +230,8 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params
|
||||
const handler = TOOL_HANDLERS[name]
|
||||
if (!handler) {
|
||||
throw new Error(`Unknown tool: ${name}`)
|
||||
}
|
||||
try {
|
||||
return await handler(args)
|
||||
return await callToolHandler(name, args)
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Error: ${error.message}` }],
|
||||
@@ -193,10 +240,47 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
}
|
||||
})
|
||||
|
||||
async function shutdown(exitCode = 0) {
|
||||
if (shutdownStarted) return
|
||||
|
||||
shutdownStarted = true
|
||||
clearUiReconnectTimer()
|
||||
closeUiSocket()
|
||||
|
||||
try {
|
||||
await server.close()
|
||||
} catch (error) {
|
||||
console.error(`[mcp] Error while closing server: ${error.message}`)
|
||||
}
|
||||
|
||||
process.exitCode = exitCode
|
||||
setImmediate(() => process.exit(exitCode))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const transport = new StdioServerTransport()
|
||||
server.onclose = () => {
|
||||
void shutdown(0)
|
||||
}
|
||||
process.stdin.once('end', () => {
|
||||
void shutdown(0)
|
||||
})
|
||||
process.stdin.once('close', () => {
|
||||
void shutdown(0)
|
||||
})
|
||||
process.once('SIGINT', () => {
|
||||
void shutdown(0)
|
||||
})
|
||||
process.once('SIGTERM', () => {
|
||||
void shutdown(0)
|
||||
})
|
||||
|
||||
connectUiBridge()
|
||||
await server.connect(transport)
|
||||
console.error(`Tolaria MCP server running (vault: ${VAULT_PATH})`)
|
||||
}
|
||||
|
||||
main().catch(console.error)
|
||||
main().catch((error) => {
|
||||
console.error(error)
|
||||
void shutdown(1)
|
||||
})
|
||||
|
||||
32
mcp-server/package-lock.json
generated
32
mcp-server/package-lock.json
generated
@@ -14,9 +14,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "1.19.9",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz",
|
||||
"integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==",
|
||||
"version": "1.19.13",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.13.tgz",
|
||||
"integrity": "sha512-TsQLe4i2gvoTtrHje625ngThGBySOgSK3Xo2XRYOdqGN1teR8+I7vchQC46uLJi8OF62YTYA3AhSpumtkhsaKQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.14.1"
|
||||
@@ -431,12 +431,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/express-rate-limit": {
|
||||
"version": "8.2.1",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz",
|
||||
"integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==",
|
||||
"version": "8.2.2",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.2.tgz",
|
||||
"integrity": "sha512-Ybv7bqtOgA914MLwaHWVFXMpMYeR1MQu/D+z2MaLYteqBsTIp9sY3AU7mGNLMJv8eLg8uQMpE20I+L2Lv49nSg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ip-address": "10.0.1"
|
||||
"ip-address": "10.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
@@ -619,9 +619,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.12.0",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.0.tgz",
|
||||
"integrity": "sha512-NekXntS5M94pUfiVZ8oXXK/kkri+5WpX2/Ik+LVsl+uvw+soj4roXIsPqO+XsWrAw20mOzaXOZf3Q7PfB9A/IA==",
|
||||
"version": "4.12.14",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz",
|
||||
"integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
@@ -670,9 +670,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz",
|
||||
"integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==",
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
|
||||
"integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
@@ -882,9 +882,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
|
||||
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
|
||||
"version": "8.4.0",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.0.tgz",
|
||||
"integrity": "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
|
||||
@@ -12,5 +12,11 @@
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"gray-matter": "^4.0.3",
|
||||
"ws": "^8.19.0"
|
||||
},
|
||||
"overrides": {
|
||||
"@hono/node-server": "1.19.13",
|
||||
"express-rate-limit": "8.2.2",
|
||||
"hono": "4.12.14",
|
||||
"path-to-regexp": "8.4.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { describe, it, before, after } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs/promises'
|
||||
import { spawn } from 'node:child_process'
|
||||
import {
|
||||
mkdtemp, mkdir, open, rm,
|
||||
} from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
findMarkdownFiles, getNote, searchNotes, vaultContext,
|
||||
} from './vault.js'
|
||||
@@ -11,14 +15,15 @@ import { evaluateBridgeRequest } from './ws-bridge.js'
|
||||
|
||||
let tmpDir
|
||||
const ACTIVE_VAULT_ERROR = 'Note path must stay inside the active vault'
|
||||
const MCP_SERVER_DIR = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
before(async () => {
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'laputa-mcp-test-'))
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'laputa-mcp-test-'))
|
||||
|
||||
await fs.mkdir(path.join(tmpDir, 'project'), { recursive: true })
|
||||
await fs.mkdir(path.join(tmpDir, 'note'), { recursive: true })
|
||||
await mkdir(path.join(tmpDir, 'project'), { recursive: true })
|
||||
await mkdir(path.join(tmpDir, 'note'), { recursive: true })
|
||||
|
||||
await fs.writeFile(path.join(tmpDir, 'project', 'test-project.md'), `---
|
||||
await writeTextFile(path.join(tmpDir, 'project', 'test-project.md'), `---
|
||||
title: Test Project
|
||||
is_a: Project
|
||||
status: Active
|
||||
@@ -29,7 +34,7 @@ status: Active
|
||||
This is a test project for the MCP server.
|
||||
`)
|
||||
|
||||
await fs.writeFile(path.join(tmpDir, 'note', 'daily-log.md'), `---
|
||||
await writeTextFile(path.join(tmpDir, 'note', 'daily-log.md'), `---
|
||||
title: Daily Log
|
||||
is_a: Note
|
||||
---
|
||||
@@ -39,7 +44,7 @@ is_a: Note
|
||||
Today I worked on the MCP server implementation.
|
||||
`)
|
||||
|
||||
await fs.writeFile(path.join(tmpDir, 'project', 'second-project.md'), `---
|
||||
await writeTextFile(path.join(tmpDir, 'project', 'second-project.md'), `---
|
||||
title: Second Project
|
||||
type: Project
|
||||
status: Draft
|
||||
@@ -54,7 +59,7 @@ Another project for testing list and context.
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true })
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('findMarkdownFiles', () => {
|
||||
@@ -208,17 +213,79 @@ describe('requireVaultPath', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('stdio process lifecycle', () => {
|
||||
it('exits when the MCP client closes stdin', async () => {
|
||||
const child = spawn(process.execPath, ['index.js'], {
|
||||
cwd: MCP_SERVER_DIR,
|
||||
env: { ...process.env, VAULT_PATH: tmpDir, WS_UI_PORT: '65534' },
|
||||
stdio: ['pipe', 'ignore', 'pipe'],
|
||||
})
|
||||
let stderr = ''
|
||||
child.stderr.setEncoding('utf8')
|
||||
child.stderr.on('data', chunk => {
|
||||
stderr += chunk
|
||||
})
|
||||
|
||||
await sleep(200)
|
||||
child.stdin.end()
|
||||
|
||||
const exit = await waitForExit(child, 1_500)
|
||||
if (!exit) {
|
||||
child.kill()
|
||||
await waitForExit(child, 1_000)
|
||||
assert.fail(`MCP server stayed alive after stdin closed.\n${stderr}`)
|
||||
}
|
||||
|
||||
assert.equal(exit.signal, null)
|
||||
assert.equal(exit.code, 0, stderr)
|
||||
})
|
||||
})
|
||||
|
||||
async function assertRejectsOutsideVault(prefix, resolveNotePath) {
|
||||
const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), prefix))
|
||||
const outsideDir = await mkdtemp(path.join(os.tmpdir(), prefix))
|
||||
const outsideNote = path.join(outsideDir, 'outside.md')
|
||||
|
||||
try {
|
||||
await fs.writeFile(outsideNote, '# Outside\n')
|
||||
await writeTextFile(outsideNote, '# Outside\n')
|
||||
await assert.rejects(
|
||||
() => getNote(tmpDir, resolveNotePath(outsideNote)),
|
||||
{ message: ACTIVE_VAULT_ERROR },
|
||||
)
|
||||
} finally {
|
||||
await fs.rm(outsideDir, { recursive: true, force: true })
|
||||
await rm(outsideDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function writeTextFile(filePath, content) {
|
||||
const handle = await open(filePath, 'w')
|
||||
try {
|
||||
await handle.writeFile(content, 'utf-8')
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function waitForExit(child, timeoutMs) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup()
|
||||
resolve(null)
|
||||
}, timeoutMs)
|
||||
|
||||
child.once('exit', onExit)
|
||||
|
||||
function onExit(code, signal) {
|
||||
cleanup()
|
||||
resolve({ code, signal })
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
clearTimeout(timer)
|
||||
child.off('exit', onExit)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* Vault operations — read-only helpers for Laputa markdown vault.
|
||||
* Write operations are handled by the agent's native bash/write/edit tools.
|
||||
* Vault operations — read-only helpers for Tolaria markdown vault.
|
||||
* Write operations are handled by the app-managed agent's active permission
|
||||
* profile and native file-edit tools when available.
|
||||
*/
|
||||
import fs from 'node:fs/promises'
|
||||
import { open, opendir, realpath } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import matter from 'gray-matter'
|
||||
|
||||
@@ -15,17 +16,17 @@ const ACTIVE_VAULT_ERROR = 'Note path must stay inside the active vault'
|
||||
*/
|
||||
export async function findMarkdownFiles(dir) {
|
||||
const results = []
|
||||
const items = await fs.readdir(dir, { withFileTypes: true })
|
||||
for (const item of items) {
|
||||
const items = await opendir(dir)
|
||||
for await (const item of items) {
|
||||
await collectMarkdownFile(results, dir, item)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
async function resolveVaultNotePath(vaultPath, notePath) {
|
||||
const vaultRoot = await fs.realpath(vaultPath)
|
||||
const vaultRoot = await realpath(vaultPath)
|
||||
const requestedPath = resolveRequestedNotePath(vaultRoot, notePath)
|
||||
const noteRealPath = await fs.realpath(requestedPath)
|
||||
const noteRealPath = await realpath(requestedPath)
|
||||
const relativePath = path.relative(vaultRoot, noteRealPath)
|
||||
|
||||
if (!isVaultRelativePath(relativePath)) {
|
||||
@@ -50,7 +51,7 @@ export async function getNote(vaultPath, notePath) {
|
||||
noteRealPath,
|
||||
relativePath,
|
||||
} = await resolveVaultNotePath(vaultPath, notePath)
|
||||
const raw = await fs.readFile(noteRealPath, 'utf-8')
|
||||
const raw = await readUtf8File(noteRealPath)
|
||||
const parsed = matter(raw)
|
||||
return {
|
||||
path: relativePath,
|
||||
@@ -73,7 +74,7 @@ export async function searchNotes(vaultPath, query, limit = 10) {
|
||||
|
||||
for (const filePath of files) {
|
||||
if (results.length >= limit) break
|
||||
const content = await fs.readFile(filePath, 'utf-8')
|
||||
const content = await readUtf8File(filePath)
|
||||
const filename = path.basename(filePath, '.md')
|
||||
const titleMatch = extractTitle(content, filename)
|
||||
if (!matchesSearchQuery(titleMatch, content, q)) continue
|
||||
@@ -125,7 +126,8 @@ export async function vaultContext(vaultPath) {
|
||||
async function collectMarkdownFile(results, dir, item) {
|
||||
if (item.name.startsWith('.')) return
|
||||
|
||||
const full = path.join(dir, item.name)
|
||||
const full = resolveInside(dir, item.name)
|
||||
if (!full) return
|
||||
if (item.isDirectory()) {
|
||||
results.push(...await findMarkdownFiles(full))
|
||||
return
|
||||
@@ -138,7 +140,16 @@ async function collectMarkdownFile(results, dir, item) {
|
||||
|
||||
function resolveRequestedNotePath(vaultRoot, notePath) {
|
||||
if (path.isAbsolute(notePath)) return notePath
|
||||
return path.resolve(vaultRoot, notePath)
|
||||
const resolved = resolveInside(vaultRoot, notePath)
|
||||
if (!resolved) throw new Error(ACTIVE_VAULT_ERROR)
|
||||
return resolved
|
||||
}
|
||||
|
||||
function resolveInside(root, target) {
|
||||
const resolved = path.resolve(root, target)
|
||||
const relative = path.relative(root, resolved)
|
||||
if (isVaultRelativePath(relative)) return resolved
|
||||
return null
|
||||
}
|
||||
|
||||
function isVaultRelativePath(relativePath) {
|
||||
@@ -150,11 +161,11 @@ function matchesSearchQuery(title, content, query) {
|
||||
}
|
||||
|
||||
async function readVaultContextNote(vaultPath, filePath) {
|
||||
const raw = await fs.readFile(filePath, 'utf-8')
|
||||
const raw = await readUtf8File(filePath)
|
||||
const parsed = matter(raw)
|
||||
const rel = path.relative(vaultPath, filePath)
|
||||
const topFolder = extractTopFolder(rel)
|
||||
const stat = await fs.stat(filePath)
|
||||
const stat = await statFile(filePath)
|
||||
const type = parsed.data.type || parsed.data.is_a || null
|
||||
|
||||
return {
|
||||
@@ -178,8 +189,8 @@ async function readConfigFiles(vaultPath) {
|
||||
const configFiles = {}
|
||||
|
||||
try {
|
||||
const agentsPath = path.join(vaultPath, 'config', 'agents.md')
|
||||
configFiles.agents = await fs.readFile(agentsPath, 'utf-8')
|
||||
const agentsPath = resolveInside(vaultPath, 'config/agents.md')
|
||||
if (agentsPath) configFiles.agents = await readUtf8File(agentsPath)
|
||||
} catch {
|
||||
// config/agents.md may not exist yet
|
||||
}
|
||||
@@ -187,6 +198,24 @@ async function readConfigFiles(vaultPath) {
|
||||
return configFiles
|
||||
}
|
||||
|
||||
async function readUtf8File(filePath) {
|
||||
const handle = await open(filePath, 'r')
|
||||
try {
|
||||
return await handle.readFile('utf-8')
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function statFile(filePath) {
|
||||
const handle = await open(filePath, 'r')
|
||||
try {
|
||||
return await handle.stat()
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract title from markdown content (first H1 or frontmatter title).
|
||||
* @param {string} content
|
||||
|
||||
@@ -38,6 +38,7 @@ const TRUSTED_UI_ORIGINS = new Set([
|
||||
/** @type {WebSocketServer | null} */
|
||||
let uiBridge = null
|
||||
let vaultPath = null
|
||||
const UNKNOWN_TOOL = Symbol('unknown tool')
|
||||
|
||||
function activeVaultPath() {
|
||||
vaultPath ??= requireVaultPath()
|
||||
@@ -53,30 +54,65 @@ function broadcastUiAction(action, payload) {
|
||||
}
|
||||
|
||||
|
||||
const TOOL_HANDLERS = {
|
||||
open_note: (args) => getNote(activeVaultPath(), args.path).then(note => ({ content: note.content, frontmatter: note.frontmatter })),
|
||||
read_note: (args) => getNote(activeVaultPath(), args.path).then(note => ({ content: note.content, frontmatter: note.frontmatter })),
|
||||
search_notes: (args) => searchNotes(activeVaultPath(), args.query, args.limit),
|
||||
vault_context: () => vaultContext(activeVaultPath()),
|
||||
ui_open_note: (args) => { broadcastUiAction('vault_changed', { path: args.path }); broadcastUiAction('open_note', { path: args.path }); return { ok: true } },
|
||||
ui_open_tab: (args) => { broadcastUiAction('vault_changed', { path: args.path }); broadcastUiAction('open_tab', { path: args.path }); return { ok: true } },
|
||||
ui_highlight: (args) => { broadcastUiAction('highlight', { element: args.element, path: args.path }); return { ok: true } },
|
||||
ui_set_filter: (args) => { broadcastUiAction('set_filter', { filterType: args.type }); return { ok: true } },
|
||||
highlight_editor: (args) => { broadcastUiAction('highlight', { element: args.element, path: args.path }); return { ok: true } },
|
||||
refresh_vault: (args) => { broadcastUiAction('vault_changed', { path: args?.path }); return { ok: true } },
|
||||
async function readNoteTool(args) {
|
||||
const note = await getNote(activeVaultPath(), args.path)
|
||||
return { content: note.content, frontmatter: note.frontmatter }
|
||||
}
|
||||
|
||||
function uiOpenNoteTool(args) {
|
||||
broadcastUiAction('vault_changed', { path: args.path })
|
||||
broadcastUiAction('open_note', { path: args.path })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
function uiOpenTabTool(args) {
|
||||
broadcastUiAction('vault_changed', { path: args.path })
|
||||
broadcastUiAction('open_tab', { path: args.path })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
function highlightTool(args) {
|
||||
broadcastUiAction('highlight', { element: args.element, path: args.path })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
function uiSetFilterTool(args) {
|
||||
broadcastUiAction('set_filter', { filterType: args.type })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
function refreshVaultTool(args) {
|
||||
broadcastUiAction('vault_changed', { path: args?.path })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
const TOOL_EXECUTORS = [
|
||||
['open_note', readNoteTool],
|
||||
['read_note', readNoteTool],
|
||||
['search_notes', (args) => searchNotes(activeVaultPath(), args.query, args.limit)],
|
||||
['vault_context', () => vaultContext(activeVaultPath())],
|
||||
['ui_open_note', uiOpenNoteTool],
|
||||
['ui_open_tab', uiOpenTabTool],
|
||||
['ui_highlight', highlightTool],
|
||||
['highlight_editor', highlightTool],
|
||||
['ui_set_filter', uiSetFilterTool],
|
||||
['refresh_vault', refreshVaultTool],
|
||||
]
|
||||
|
||||
function callToolHandler(tool, args) {
|
||||
const executor = TOOL_EXECUTORS.find(([name]) => name === tool)?.[1]
|
||||
return executor ? executor(args) : UNKNOWN_TOOL
|
||||
}
|
||||
|
||||
async function handleMessage(data) {
|
||||
const msg = JSON.parse(data)
|
||||
const { id, tool, args } = msg
|
||||
|
||||
const handler = TOOL_HANDLERS[tool]
|
||||
if (!handler) {
|
||||
return { id, error: `Unknown tool: ${tool}` }
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await handler(args || {})
|
||||
const result = await callToolHandler(tool, args || {})
|
||||
if (result === UNKNOWN_TOOL) {
|
||||
return { id, error: `Unknown tool: ${tool}` }
|
||||
}
|
||||
return { id, result }
|
||||
} catch (err) {
|
||||
return { id, error: err.message }
|
||||
|
||||
19
package.json
19
package.json
@@ -17,7 +17,7 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"playwright:smoke": "playwright test --config playwright.smoke.config.ts tests/smoke/delete-note-nonblocking.spec.ts tests/smoke/example.spec.ts tests/smoke/fix-ai-chat-empty-body-v3.spec.ts tests/smoke/fix-crash-create-note.spec.ts tests/smoke/fresh-start-telemetry-onboarding.spec.ts tests/smoke/getting-started-template.spec.ts tests/smoke/h1-title-decoupled.spec.ts tests/smoke/h1-untitled-auto-rename.spec.ts tests/smoke/keyboard-command-routing.spec.ts tests/smoke/linkify-init-warnings.spec.ts tests/smoke/multi-selection-shortcuts.spec.ts tests/smoke/wikilink-path-fix.spec.ts",
|
||||
"playwright:smoke": "playwright test --config playwright.smoke.config.ts tests/smoke/autosave-low-end-typing.spec.ts tests/smoke/create-note-backing-file.spec.ts tests/smoke/delete-note-nonblocking.spec.ts tests/smoke/example.spec.ts tests/smoke/fix-ai-chat-empty-body-v3.spec.ts tests/smoke/fix-crash-create-note.spec.ts tests/smoke/fresh-start-telemetry-onboarding.spec.ts tests/smoke/frontmatter-date-picker.spec.ts tests/smoke/getting-started-template.spec.ts tests/smoke/h1-title-decoupled.spec.ts tests/smoke/h1-untitled-auto-rename.spec.ts tests/smoke/keyboard-command-routing.spec.ts tests/smoke/linkify-init-warnings.spec.ts tests/smoke/missing-active-vault-recovery.spec.ts tests/smoke/missing-string-metadata-open-note.spec.ts tests/smoke/multibyte-search-snippet.spec.ts tests/smoke/multi-selection-shortcuts.spec.ts tests/smoke/pull-refresh-open-note.spec.ts tests/smoke/vault-loading-skeleton.spec.ts tests/smoke/wikilink-path-fix.spec.ts",
|
||||
"playwright:regression": "playwright test tests/smoke/",
|
||||
"playwright:integration": "playwright test --config playwright.integration.config.ts",
|
||||
"test:coverage": "node scripts/run-vitest-coverage.mjs",
|
||||
@@ -58,6 +58,7 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "3.4.2",
|
||||
"katex": "^0.16.28",
|
||||
"lucide-react": "^0.564.0",
|
||||
"mermaid": "^11.14.0",
|
||||
@@ -70,8 +71,10 @@
|
||||
"react-virtuoso": "^4.18.1",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"safe-regex2": "5.1.1",
|
||||
"tailwind-merge": "^3.4.1",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"tldraw": "^4.5.10",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"unicode-emoji-json": "^0.8.0"
|
||||
},
|
||||
@@ -98,8 +101,20 @@
|
||||
"jsdom": "^28.0.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"vite": "^7.3.1",
|
||||
"vite": "^7.3.2",
|
||||
"vitest": "^4.0.18",
|
||||
"ws": "^8.19.0"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"@hono/node-server": "1.19.13",
|
||||
"express-rate-limit": "8.2.2",
|
||||
"hono": "4.12.14",
|
||||
"path-to-regexp": "8.4.0",
|
||||
"picomatch": "4.0.4",
|
||||
"postcss": "8.5.10",
|
||||
"protobufjs": "7.5.6",
|
||||
"rollup": "4.59.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,9 +2,21 @@ diff --git a/dist/blocknote-react.js b/dist/blocknote-react.js
|
||||
index 6271d12d2cd5152e924c5bfe78f3b8904844dbfe..12bb96bb36d445a77d51a18d0de446a3f9f0ea59 100644
|
||||
--- a/dist/blocknote-react.js
|
||||
+++ b/dist/blocknote-react.js
|
||||
@@ -157,6 +157,16 @@ function so(e) {
|
||||
const n = "getBoundingClientRect" in e ? () => e.getBoundingClientRect() : () => e.element.getBoundingClientRect();
|
||||
return () => "element" in e && (e.cacheMountedBoundingClientRect ?? !0) ? (e.element.isConnected && (t = n()), t) : n();
|
||||
@@ -155,8 +155,26 @@ var Rt = (e) => {
|
||||
function so(e) {
|
||||
let t = new DOMRect();
|
||||
- const n = "getBoundingClientRect" in e ? () => e.getBoundingClientRect() : () => e.element.getBoundingClientRect();
|
||||
- return () => "element" in e && (e.cacheMountedBoundingClientRect ?? !0) ? (e.element.isConnected && (t = n()), t) : n();
|
||||
+ const n = () => "getBoundingClientRect" in e ? e.getBoundingClientRect() : e.element instanceof Element ? e.element.getBoundingClientRect() : t;
|
||||
+ return () => {
|
||||
+ if (!("element" in e) || !(e.cacheMountedBoundingClientRect ?? !0))
|
||||
+ return n();
|
||||
+ if (!(e.element instanceof Element))
|
||||
+ return n();
|
||||
+ if (e.element.isConnected)
|
||||
+ t = n();
|
||||
+ return t;
|
||||
+ };
|
||||
}
|
||||
+function __bnSafeDomAtPos(e, t) {
|
||||
+ const n = e.prosemirrorView;
|
||||
@@ -19,7 +31,7 @@ index 6271d12d2cd5152e924c5bfe78f3b8904844dbfe..12bb96bb36d445a77d51a18d0de446a3
|
||||
const z = (e) => {
|
||||
var h, b, p;
|
||||
const { refs: t, floatingStyles: n, context: o } = Ze({
|
||||
@@ -216,9 +226,7 @@ const Lt = (e) => {
|
||||
@@ -216,9 +234,7 @@ const Lt = (e) => {
|
||||
const s = Ue(t, c.doc);
|
||||
if (!s)
|
||||
return;
|
||||
@@ -30,7 +42,7 @@ index 6271d12d2cd5152e924c5bfe78f3b8904844dbfe..12bb96bb36d445a77d51a18d0de446a3
|
||||
if (a instanceof Element)
|
||||
return {
|
||||
element: a
|
||||
@@ -3306,14 +3314,15 @@ const pi = (e) => {
|
||||
@@ -3306,14 +3322,15 @@ const pi = (e) => {
|
||||
);
|
||||
if (!m)
|
||||
return {};
|
||||
@@ -49,7 +61,7 @@ index 6271d12d2cd5152e924c5bfe78f3b8904844dbfe..12bb96bb36d445a77d51a18d0de446a3
|
||||
return p instanceof Element ? (d.cellReference = { element: p }, d.rowReference = {
|
||||
element: f,
|
||||
getBoundingClientRect: () => {
|
||||
@@ -4371,7 +4380,7 @@ const El = (e) => {
|
||||
@@ -4371,7 +4388,7 @@ const El = (e) => {
|
||||
const a = Ue(t, c.prosemirrorState.doc);
|
||||
if (!a)
|
||||
return;
|
||||
|
||||
912
pnpm-lock.yaml
generated
912
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,9 @@ const forwardedArgs = process.argv.slice(2)
|
||||
const hasFileParallelismOverride = forwardedArgs.some((arg) =>
|
||||
arg === '--fileParallelism' || arg === '--no-file-parallelism'
|
||||
)
|
||||
const hasMaxWorkersOverride = forwardedArgs.some((arg) =>
|
||||
arg === '--maxWorkers' || arg.startsWith('--maxWorkers=')
|
||||
)
|
||||
const maxAttempts = 2
|
||||
|
||||
const packageManagerExec = process.env.npm_execpath
|
||||
@@ -46,10 +49,11 @@ async function runCoverageAttempt(attempt) {
|
||||
|
||||
const commandArgs = [
|
||||
...baseCommandArgs,
|
||||
// Vitest 4.0.18 occasionally crashes during coverage worker teardown
|
||||
// after all files pass, so serialize file execution unless a caller
|
||||
// explicitly opts into a different file-parallelism mode.
|
||||
...(hasFileParallelismOverride ? [] : ['--no-file-parallelism']),
|
||||
// Keep coverage fast enough for CI while avoiding the unbounded worker
|
||||
// contention that makes a few DOM-heavy suites time out under full
|
||||
// file parallelism. Callers can still opt into serial or wider runs.
|
||||
...(hasFileParallelismOverride ? [] : ['--fileParallelism']),
|
||||
...(hasMaxWorkersOverride ? [] : ['--maxWorkers=4']),
|
||||
`--coverage.reportsDirectory=${runCoverageDir}`,
|
||||
...forwardedArgs,
|
||||
]
|
||||
|
||||
@@ -5,7 +5,14 @@
|
||||
*/
|
||||
|
||||
import http from 'http'
|
||||
import fs from 'fs'
|
||||
import {
|
||||
closeSync,
|
||||
createReadStream,
|
||||
fstatSync,
|
||||
openSync,
|
||||
opendirSync,
|
||||
readFileSync,
|
||||
} from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import matter from 'gray-matter'
|
||||
@@ -16,8 +23,71 @@ const REPO_DIR = path.resolve(__dirname, '..')
|
||||
const PORT = 5173
|
||||
|
||||
function isAllowedPath(p) {
|
||||
const resolved = path.resolve(p)
|
||||
return resolved.startsWith(REPO_DIR)
|
||||
return isInsideRelativePath(path.relative(REPO_DIR, p))
|
||||
}
|
||||
|
||||
function isInsideRelativePath(relative) {
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function resolveInside(root, target) {
|
||||
const normalizedTarget = path.normalize(target)
|
||||
if (path.isAbsolute(normalizedTarget)) return null
|
||||
const candidate = path.normalize(`${root}${path.sep}${normalizedTarget}`)
|
||||
return isInsideRelativePath(path.relative(root, candidate)) ? candidate : null
|
||||
}
|
||||
|
||||
function readUtf8File(filePath) {
|
||||
const fd = openSync(filePath, 'r')
|
||||
try {
|
||||
return readFileSync(fd, 'utf-8')
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
|
||||
function pathStats(filePath) {
|
||||
const fd = openSync(filePath, 'r')
|
||||
try {
|
||||
return fstatSync(fd)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
|
||||
function pathExists(filePath) {
|
||||
try {
|
||||
pathStats(filePath)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function directoryEntries(dir) {
|
||||
const directory = opendirSync(dir)
|
||||
try {
|
||||
const entries = []
|
||||
let entry = directory.readSync()
|
||||
while (entry) {
|
||||
entries.push(entry)
|
||||
entry = directory.readSync()
|
||||
}
|
||||
return entries
|
||||
} finally {
|
||||
directory.closeSync()
|
||||
}
|
||||
}
|
||||
|
||||
function streamFile(filePath) {
|
||||
const fd = openSync(filePath, 'r')
|
||||
return createReadStream(null, { fd, autoClose: true })
|
||||
}
|
||||
|
||||
function staticAssetPath(url) {
|
||||
const pathname = new URL(url, 'http://localhost').pathname
|
||||
const requested = pathname === '/' ? 'index.html' : decodeURIComponent(pathname).replace(/^\/+/, '')
|
||||
return resolveInside(DIST_DIR, requested) ?? path.normalize(`${DIST_DIR}${path.sep}index.html`)
|
||||
}
|
||||
|
||||
const MIME = {
|
||||
@@ -34,8 +104,9 @@ const MIME = {
|
||||
function findMarkdownFiles(dir) {
|
||||
const results = []
|
||||
try {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
for (const entry of directoryEntries(dir)) {
|
||||
const full = resolveInside(dir, entry.name)
|
||||
if (!full) continue
|
||||
if (entry.isDirectory()) results.push(...findMarkdownFiles(full))
|
||||
else if (entry.name.endsWith('.md')) results.push(full)
|
||||
}
|
||||
@@ -51,9 +122,9 @@ function extractWikiLinks(value) {
|
||||
|
||||
function parseMarkdownFile(filePath) {
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf-8')
|
||||
const raw = readUtf8File(filePath)
|
||||
const { data: fm, content } = matter(raw)
|
||||
const stat = fs.statSync(filePath)
|
||||
const stat = pathStats(filePath)
|
||||
|
||||
const DEDICATED = new Set(['aliases','Is A','Belongs to','Related to','Status','Owner','Cadence','Created at'])
|
||||
const relationships = {}
|
||||
@@ -98,7 +169,7 @@ function serveVaultApi(url, res) {
|
||||
|
||||
if (params.pathname === '/api/vault/list') {
|
||||
const dir = params.searchParams.get('path')
|
||||
if (!dir || !isAllowedPath(dir) || !fs.existsSync(dir)) {
|
||||
if (!dir || !isAllowedPath(dir) || !pathExists(dir)) {
|
||||
res.writeHead(400); res.end(JSON.stringify({ error: 'bad path' })); return true
|
||||
}
|
||||
const entries = findMarkdownFiles(dir).map(parseMarkdownFile).filter(Boolean)
|
||||
@@ -109,22 +180,22 @@ function serveVaultApi(url, res) {
|
||||
|
||||
if (params.pathname === '/api/vault/content') {
|
||||
const file = params.searchParams.get('path')
|
||||
if (!file || !isAllowedPath(file) || !fs.existsSync(file)) {
|
||||
if (!file || !isAllowedPath(file) || !pathExists(file)) {
|
||||
res.writeHead(400); res.end(JSON.stringify({ error: 'bad path' })); return true
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify({ content: fs.readFileSync(file, 'utf-8') }))
|
||||
res.end(JSON.stringify({ content: readUtf8File(file) }))
|
||||
return true
|
||||
}
|
||||
|
||||
if (params.pathname === '/api/vault/all-content') {
|
||||
const dir = params.searchParams.get('path')
|
||||
if (!dir || !isAllowedPath(dir) || !fs.existsSync(dir)) {
|
||||
if (!dir || !isAllowedPath(dir) || !pathExists(dir)) {
|
||||
res.writeHead(400); res.end(JSON.stringify({ error: 'bad path' })); return true
|
||||
}
|
||||
const map = {}
|
||||
for (const f of findMarkdownFiles(dir)) {
|
||||
try { map[f] = fs.readFileSync(f, 'utf-8') } catch {}
|
||||
try { map[f] = readUtf8File(f) } catch {}
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify(map))
|
||||
@@ -146,13 +217,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
// Static files
|
||||
let filePath = path.join(DIST_DIR, url === '/' ? 'index.html' : url)
|
||||
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
|
||||
filePath = path.join(DIST_DIR, 'index.html') // SPA fallback
|
||||
let filePath = staticAssetPath(url)
|
||||
if (!pathExists(filePath) || pathStats(filePath).isDirectory()) {
|
||||
filePath = path.normalize(`${DIST_DIR}${path.sep}index.html`) // SPA fallback
|
||||
}
|
||||
const ext = path.extname(filePath)
|
||||
res.writeHead(200, { 'Content-Type': MIME[ext] ?? 'application/octet-stream' })
|
||||
fs.createReadStream(filePath).pipe(res)
|
||||
streamFile(filePath).pipe(res)
|
||||
})
|
||||
|
||||
server.listen(PORT, '0.0.0.0', () => {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import fs from 'node:fs'
|
||||
import {
|
||||
closeSync, fstatSync, openSync, opendirSync, readFileSync,
|
||||
} from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
@@ -7,7 +9,42 @@ const localesDir = path.join(root, 'src/lib/locales')
|
||||
const sourcePath = path.join(localesDir, 'en.json')
|
||||
|
||||
function readCatalog(filePath) {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
return JSON.parse(readUtf8File(filePath))
|
||||
}
|
||||
|
||||
function readUtf8File(filePath) {
|
||||
const fd = openSync(filePath, 'r')
|
||||
try {
|
||||
return readFileSync(fd, 'utf8')
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
|
||||
function directoryFiles(dirPath) {
|
||||
const dir = opendirSync(dirPath)
|
||||
try {
|
||||
const files = []
|
||||
let entry = dir.readSync()
|
||||
while (entry) {
|
||||
if (entry.isFile()) files.push(entry.name)
|
||||
entry = dir.readSync()
|
||||
}
|
||||
return files
|
||||
} finally {
|
||||
dir.closeSync()
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDirectory(dirPath) {
|
||||
const fd = openSync(dirPath, 'r')
|
||||
try {
|
||||
if (!fstatSync(fd).isDirectory()) {
|
||||
throw new Error(`${dirPath} is not a directory`)
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
|
||||
function isFlatObject(value) {
|
||||
@@ -74,7 +111,8 @@ const sourceCatalog = readCatalog(sourcePath)
|
||||
assertFlatStringCatalog('en', sourceCatalog)
|
||||
|
||||
const sourceKeys = Object.keys(sourceCatalog).sort()
|
||||
const localeFiles = fs.readdirSync(localesDir).filter((file) => file.endsWith('.json'))
|
||||
ensureDirectory(localesDir)
|
||||
const localeFiles = directoryFiles(localesDir).filter((file) => file.endsWith('.json'))
|
||||
const issues = []
|
||||
|
||||
for (const file of localeFiles) {
|
||||
|
||||
155
src-tauri/Cargo.lock
generated
155
src-tauri/Cargo.lock
generated
@@ -892,7 +892,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users 0.5.2",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1079,7 +1079,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1486,8 +1486,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi 0.11.1+wasi-snapshot-preview1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1497,9 +1499,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasip2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1857,6 +1861,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2361,6 +2366,12 @@ dependencies = [
|
||||
"value-bag",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "mac"
|
||||
version = "0.1.1"
|
||||
@@ -2897,9 +2908,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.75"
|
||||
version = "0.10.78"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"
|
||||
checksum = "f38c4372413cdaaf3cc79dd92d29d7d9f5ab09b51b10dded508fb90bb70b9222"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"cfg-if",
|
||||
@@ -2929,9 +2940,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.111"
|
||||
version = "0.9.114"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
|
||||
checksum = "13ce1245cd07fcc4cfdb438f7507b0c7e4f3849a69fd84d52374c66d83741bb6"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -3391,6 +3402,61 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.3.4",
|
||||
"lru-slab",
|
||||
"rand 0.9.4",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.44"
|
||||
@@ -3437,6 +3503,16 @@ dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
|
||||
dependencies = [
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.2.2"
|
||||
@@ -3457,6 +3533,16 @@ dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.5.1"
|
||||
@@ -3475,6 +3561,15 @@ dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_hc"
|
||||
version = "0.2.0"
|
||||
@@ -3612,6 +3707,7 @@ dependencies = [
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-tls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
@@ -3619,6 +3715,8 @@ dependencies = [
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3626,6 +3724,7 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
@@ -3633,6 +3732,7 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3763,6 +3863,12 @@ version = "0.1.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -3782,7 +3888,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3817,6 +3923,7 @@ version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -3838,7 +3945,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3849,9 +3956,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.9"
|
||||
version = "0.103.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||
checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
@@ -4603,9 +4710,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.44"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
|
||||
checksum = "22692a6476a21fa75fdfc11d452fda482af402c008cdbaf3476414e122040973"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
@@ -5002,7 +5109,7 @@ dependencies = [
|
||||
"getrandom 0.4.1",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5185,6 +5292,7 @@ dependencies = [
|
||||
"log",
|
||||
"notify",
|
||||
"regex",
|
||||
"reqwest 0.12.28",
|
||||
"sentry",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5808,6 +5916,16 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-time"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webkit2gtk"
|
||||
version = "2.0.2"
|
||||
@@ -5861,6 +5979,15 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.38.2"
|
||||
@@ -5919,7 +6046,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -39,5 +39,6 @@ tauri-plugin-prevent-default = "4.0.4"
|
||||
sentry = "0.37"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
tempfile = "3"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
"core:default",
|
||||
"core:window:allow-create",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-start-resize-dragging",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-set-title",
|
||||
"core:webview:allow-create-webview-window",
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::BufRead;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -10,6 +7,15 @@ pub enum AiAgentId {
|
||||
Codex,
|
||||
Opencode,
|
||||
Pi,
|
||||
Gemini,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AiAgentPermissionMode {
|
||||
#[default]
|
||||
Safe,
|
||||
PowerUser,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -24,6 +30,7 @@ pub struct AiAgentsStatus {
|
||||
pub codex: AiAgentAvailability,
|
||||
pub opencode: AiAgentAvailability,
|
||||
pub pi: AiAgentAvailability,
|
||||
pub gemini: AiAgentAvailability,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -61,14 +68,22 @@ pub struct AiAgentStreamRequest {
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub vault_path: String,
|
||||
pub permission_mode: Option<AiAgentPermissionMode>,
|
||||
}
|
||||
|
||||
impl AiAgentStreamRequest {
|
||||
fn permission_mode(&self) -> AiAgentPermissionMode {
|
||||
self.permission_mode.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_ai_agents_status() -> AiAgentsStatus {
|
||||
AiAgentsStatus {
|
||||
claude_code: availability_from_claude(),
|
||||
codex: availability_from_codex(),
|
||||
opencode: availability_from_opencode(),
|
||||
pi: availability_from_pi(),
|
||||
codex: crate::codex_cli::check_cli(),
|
||||
opencode: crate::opencode_cli::check_cli(),
|
||||
pi: crate::pi_cli::check_cli(),
|
||||
gemini: crate::gemini_cli::check_cli(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,12 +91,14 @@ pub fn run_ai_agent_stream<F>(request: AiAgentStreamRequest, mut emit: F) -> Res
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let permission_mode = request.permission_mode();
|
||||
match request.agent {
|
||||
AiAgentId::ClaudeCode => {
|
||||
let mapped = crate::claude_cli::AgentStreamRequest {
|
||||
message: request.message,
|
||||
system_prompt: request.system_prompt,
|
||||
vault_path: request.vault_path,
|
||||
permission_mode,
|
||||
};
|
||||
crate::claude_cli::run_agent_stream(mapped, |event| {
|
||||
if let Some(mapped_event) = map_claude_event(event) {
|
||||
@@ -89,12 +106,21 @@ where
|
||||
}
|
||||
})
|
||||
}
|
||||
AiAgentId::Codex => run_codex_agent_stream(request, emit),
|
||||
AiAgentId::Codex => {
|
||||
let mapped = crate::codex_cli::AgentStreamRequest {
|
||||
message: request.message,
|
||||
system_prompt: request.system_prompt,
|
||||
vault_path: request.vault_path,
|
||||
permission_mode,
|
||||
};
|
||||
crate::codex_cli::run_agent_stream(mapped, emit)
|
||||
}
|
||||
AiAgentId::Opencode => {
|
||||
let mapped = crate::opencode_cli::AgentStreamRequest {
|
||||
message: request.message,
|
||||
system_prompt: request.system_prompt,
|
||||
vault_path: request.vault_path,
|
||||
permission_mode,
|
||||
};
|
||||
crate::opencode_cli::run_agent_stream(mapped, emit)
|
||||
}
|
||||
@@ -103,9 +129,19 @@ where
|
||||
message: request.message,
|
||||
system_prompt: request.system_prompt,
|
||||
vault_path: request.vault_path,
|
||||
permission_mode,
|
||||
};
|
||||
crate::pi_cli::run_agent_stream(mapped, emit)
|
||||
}
|
||||
AiAgentId::Gemini => {
|
||||
let mapped = crate::gemini_cli::AgentStreamRequest {
|
||||
message: request.message,
|
||||
system_prompt: request.system_prompt,
|
||||
vault_path: request.vault_path,
|
||||
permission_mode,
|
||||
};
|
||||
crate::gemini_cli::run_agent_stream(mapped, emit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,351 +153,6 @@ fn availability_from_claude() -> AiAgentAvailability {
|
||||
}
|
||||
}
|
||||
|
||||
fn availability_from_codex() -> AiAgentAvailability {
|
||||
let binary = match find_codex_binary() {
|
||||
Ok(binary) => binary,
|
||||
Err(_) => {
|
||||
return AiAgentAvailability {
|
||||
installed: false,
|
||||
version: None,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
AiAgentAvailability {
|
||||
installed: true,
|
||||
version: version_for_binary(&binary),
|
||||
}
|
||||
}
|
||||
|
||||
fn availability_from_opencode() -> AiAgentAvailability {
|
||||
crate::opencode_cli::check_cli()
|
||||
}
|
||||
|
||||
fn availability_from_pi() -> AiAgentAvailability {
|
||||
crate::pi_cli::check_cli()
|
||||
}
|
||||
|
||||
fn version_for_binary(binary: &PathBuf) -> Option<String> {
|
||||
crate::hidden_command(binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn find_codex_binary() -> Result<PathBuf, String> {
|
||||
if let Some(binary) = find_codex_binary_on_path() {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
if let Some(binary) = find_codex_binary_in_user_shell() {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
if let Some(binary) = find_existing_binary(codex_binary_candidates()) {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
Err("Codex CLI not found. Install it: https://developers.openai.com/codex/cli".into())
|
||||
}
|
||||
|
||||
fn find_codex_binary_on_path() -> Option<PathBuf> {
|
||||
crate::hidden_command("which")
|
||||
.arg("codex")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn find_codex_binary_in_user_shell() -> Option<PathBuf> {
|
||||
user_shell_candidates()
|
||||
.into_iter()
|
||||
.filter(|shell| shell.exists())
|
||||
.find_map(|shell| command_path_from_shell(&shell, "codex"))
|
||||
}
|
||||
|
||||
fn user_shell_candidates() -> Vec<PathBuf> {
|
||||
let mut shells = Vec::new();
|
||||
if let Some(shell) = std::env::var_os("SHELL") {
|
||||
if !shell.is_empty() {
|
||||
shells.push(PathBuf::from(shell));
|
||||
}
|
||||
}
|
||||
shells.push(PathBuf::from("/bin/zsh"));
|
||||
shells.push(PathBuf::from("/bin/bash"));
|
||||
shells
|
||||
}
|
||||
|
||||
fn command_path_from_shell(shell: &Path, command: &str) -> Option<PathBuf> {
|
||||
crate::hidden_command(shell)
|
||||
.arg("-lc")
|
||||
.arg(format!("command -v {command}"))
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_from_successful_output(output: &std::process::Output) -> Option<PathBuf> {
|
||||
if output.status.success() {
|
||||
first_existing_path(&String::from_utf8_lossy(&output.stdout))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn first_existing_path(stdout: &str) -> Option<PathBuf> {
|
||||
stdout.lines().find_map(|line| {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let candidate = PathBuf::from(trimmed);
|
||||
candidate.exists().then_some(candidate)
|
||||
})
|
||||
}
|
||||
|
||||
fn codex_binary_candidates() -> Vec<PathBuf> {
|
||||
dirs::home_dir()
|
||||
.map(|home| codex_binary_candidates_for_home(&home))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn codex_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
home.join(".local/bin/codex"),
|
||||
home.join(".codex/bin/codex"),
|
||||
home.join(".local/share/mise/shims/codex"),
|
||||
home.join(".asdf/shims/codex"),
|
||||
home.join(".npm-global/bin/codex"),
|
||||
home.join(".npm/bin/codex"),
|
||||
home.join(".bun/bin/codex"),
|
||||
PathBuf::from("/usr/local/bin/codex"),
|
||||
PathBuf::from("/opt/homebrew/bin/codex"),
|
||||
PathBuf::from("/Applications/Codex.app/Contents/Resources/codex"),
|
||||
]
|
||||
}
|
||||
|
||||
fn find_existing_binary(candidates: Vec<PathBuf>) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|candidate| candidate.exists())
|
||||
}
|
||||
|
||||
fn run_codex_agent_stream<F>(request: AiAgentStreamRequest, mut emit: F) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let binary = find_codex_binary()?;
|
||||
let args = build_codex_args(&request)?;
|
||||
let prompt = build_codex_prompt(&request);
|
||||
|
||||
let mut command = build_codex_command(&binary, args, prompt, &request.vault_path);
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Failed to spawn codex: {error}"))?;
|
||||
|
||||
let stdout = child.stdout.take().ok_or("No stdout handle")?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
|
||||
let mut thread_id = String::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(error) => {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: format!("Read error: {error}"),
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let json = match serde_json::from_str::<serde_json::Value>(&line) {
|
||||
Ok(json) => json,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if let Some(id) = json["thread_id"].as_str() {
|
||||
thread_id = id.to_string();
|
||||
}
|
||||
|
||||
dispatch_codex_event(&json, &mut emit);
|
||||
}
|
||||
|
||||
let stderr_output = child
|
||||
.stderr
|
||||
.take()
|
||||
.and_then(|stderr| std::io::read_to_string(stderr).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|error| format!("Wait failed: {error}"))?;
|
||||
if !status.success() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: format_codex_error(stderr_output, status.to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
emit(AiAgentStreamEvent::Done);
|
||||
|
||||
Ok(thread_id)
|
||||
}
|
||||
|
||||
fn build_codex_command(
|
||||
binary: &Path,
|
||||
args: Vec<String>,
|
||||
prompt: String,
|
||||
vault_path: &str,
|
||||
) -> std::process::Command {
|
||||
let mut command = crate::hidden_command(binary);
|
||||
command
|
||||
.args(args)
|
||||
.arg(prompt)
|
||||
.current_dir(vault_path)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
command
|
||||
}
|
||||
|
||||
fn build_codex_args(request: &AiAgentStreamRequest) -> Result<Vec<String>, String> {
|
||||
let mcp_server = crate::mcp::mcp_server_dir()?.join("index.js");
|
||||
let mcp_server_path = mcp_server
|
||||
.to_str()
|
||||
.ok_or("Invalid MCP server path")?
|
||||
.to_string();
|
||||
|
||||
Ok(vec![
|
||||
"--sandbox".into(),
|
||||
"workspace-write".into(),
|
||||
"--ask-for-approval".into(),
|
||||
"never".into(),
|
||||
"exec".into(),
|
||||
"--json".into(),
|
||||
"-C".into(),
|
||||
request.vault_path.clone(),
|
||||
"-c".into(),
|
||||
r#"mcp_servers.tolaria.command="node""#.into(),
|
||||
"-c".into(),
|
||||
format!(r#"mcp_servers.tolaria.args=["{}"]"#, mcp_server_path),
|
||||
"-c".into(),
|
||||
format!(
|
||||
r#"mcp_servers.tolaria.env={{VAULT_PATH="{}"}}"#,
|
||||
request.vault_path
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn build_codex_prompt(request: &AiAgentStreamRequest) -> String {
|
||||
match request
|
||||
.system_prompt
|
||||
.as_ref()
|
||||
.map(|prompt| prompt.trim())
|
||||
.filter(|prompt| !prompt.is_empty())
|
||||
{
|
||||
Some(system_prompt) => format!(
|
||||
"System instructions:\n{system_prompt}\n\nUser request:\n{}",
|
||||
request.message
|
||||
),
|
||||
None => request.message.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_codex_event<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
match json["type"].as_str().unwrap_or_default() {
|
||||
"thread.started" => {
|
||||
if let Some(thread_id) = json["thread_id"].as_str() {
|
||||
emit(AiAgentStreamEvent::Init {
|
||||
session_id: thread_id.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
"item.started" => emit_codex_item_event(json, false, emit),
|
||||
"item.completed" => emit_codex_item_event(json, true, emit),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_codex_item_event<F>(json: &serde_json::Value, completed: bool, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let item = &json["item"];
|
||||
let item_type = item["type"].as_str().unwrap_or_default();
|
||||
let item_id = item["id"].as_str().unwrap_or_default();
|
||||
|
||||
match item_type {
|
||||
"command_execution" => {
|
||||
if completed {
|
||||
emit(AiAgentStreamEvent::ToolDone {
|
||||
tool_id: item_id.to_string(),
|
||||
output: item["aggregated_output"]
|
||||
.as_str()
|
||||
.map(|output| output.to_string()),
|
||||
});
|
||||
} else {
|
||||
emit(AiAgentStreamEvent::ToolStart {
|
||||
tool_name: "Bash".into(),
|
||||
tool_id: item_id.to_string(),
|
||||
input: item["command"]
|
||||
.as_str()
|
||||
.map(|command| serde_json::json!({ "command": command }).to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
"agent_message" if completed => {
|
||||
if let Some(text) = item["text"].as_str() {
|
||||
emit(AiAgentStreamEvent::TextDelta {
|
||||
text: text.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_codex_error(stderr_output: String, status: String) -> String {
|
||||
let lower = stderr_output.to_ascii_lowercase();
|
||||
if is_codex_auth_error(&lower) {
|
||||
return "Codex CLI is not authenticated. Run `codex login` or launch `codex` in your terminal.".into();
|
||||
}
|
||||
|
||||
if is_codex_write_permission_error(&lower) {
|
||||
return "Codex could not write to the active vault. Tolaria starts Codex with a workspace-write sandbox, so verify the selected vault folder is writable and retry; writes outside the active vault remain blocked.".into();
|
||||
}
|
||||
|
||||
if stderr_output.trim().is_empty() {
|
||||
format!("codex exited with status {status}")
|
||||
} else {
|
||||
stderr_output.lines().take(3).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
fn is_codex_auth_error(lower: &str) -> bool {
|
||||
["auth", "login", "sign in"]
|
||||
.iter()
|
||||
.any(|pattern| lower.contains(pattern))
|
||||
}
|
||||
|
||||
fn is_codex_write_permission_error(lower: &str) -> bool {
|
||||
[
|
||||
"read-only sandbox",
|
||||
"writing is blocked",
|
||||
"rejected by user approval",
|
||||
"rejected by the environment",
|
||||
]
|
||||
.iter()
|
||||
.any(|pattern| lower.contains(pattern))
|
||||
}
|
||||
|
||||
fn map_claude_event(event: crate::claude_cli::ClaudeStreamEvent) -> Option<AiAgentStreamEvent> {
|
||||
match event {
|
||||
crate::claude_cli::ClaudeStreamEvent::Init { session_id } => {
|
||||
@@ -499,193 +190,45 @@ fn map_claude_event(event: crate::claude_cli::ClaudeStreamEvent) -> Option<AiAge
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
fn request_with_permission(
|
||||
permission_mode: Option<AiAgentPermissionMode>,
|
||||
) -> AiAgentStreamRequest {
|
||||
AiAgentStreamRequest {
|
||||
agent: AiAgentId::Codex,
|
||||
message: "Summarize this vault".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_request_uses_default_or_explicit_permission_mode() {
|
||||
assert_eq!(
|
||||
request_with_permission(None).permission_mode(),
|
||||
AiAgentPermissionMode::Safe
|
||||
);
|
||||
assert_eq!(
|
||||
request_with_permission(Some(AiAgentPermissionMode::PowerUser)).permission_mode(),
|
||||
AiAgentPermissionMode::PowerUser
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_status_contains_all_agents() {
|
||||
let status = get_ai_agents_status();
|
||||
assert!(matches!(status.claude_code.installed, true | false));
|
||||
assert!(matches!(status.codex.installed, true | false));
|
||||
assert!(matches!(status.opencode.installed, true | false));
|
||||
assert!(matches!(status.pi.installed, true | false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_codex_prompt_keeps_system_prompt_first() {
|
||||
let prompt = build_codex_prompt(&AiAgentStreamRequest {
|
||||
agent: AiAgentId::Codex,
|
||||
message: "Rename the note".into(),
|
||||
system_prompt: Some("Be concise".into()),
|
||||
vault_path: "/tmp/vault".into(),
|
||||
});
|
||||
|
||||
assert!(prompt.starts_with("System instructions:\nBe concise"));
|
||||
assert!(prompt.contains("User request:\nRename the note"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_codex_args_uses_safe_default_permissions() {
|
||||
if let Ok(args) = build_codex_args(&AiAgentStreamRequest {
|
||||
agent: AiAgentId::Codex,
|
||||
message: "Rename the note".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
}) {
|
||||
assert_eq!(args[0], "--sandbox");
|
||||
assert_eq!(args[1], "workspace-write");
|
||||
assert_eq!(args[2], "--ask-for-approval");
|
||||
assert_eq!(args[3], "never");
|
||||
assert_eq!(args[4], "exec");
|
||||
assert!(!args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
|
||||
assert!(!args.contains(&"danger-full-access".to_string()));
|
||||
assert!(args.contains(&"--json".to_string()));
|
||||
assert!(args.contains(&"-C".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_codex_command_keeps_agent_process_contract() {
|
||||
let binary = PathBuf::from("codex");
|
||||
let args = vec!["exec".to_string(), "--json".to_string()];
|
||||
let command = build_codex_command(&binary, args, "Summarize".into(), "/tmp/vault");
|
||||
let actual_args: Vec<&OsStr> = command.get_args().collect();
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("codex"));
|
||||
assert_eq!(
|
||||
actual_args,
|
||||
vec![
|
||||
OsStr::new("exec"),
|
||||
OsStr::new("--json"),
|
||||
OsStr::new("Summarize")
|
||||
]
|
||||
);
|
||||
assert_eq!(command.get_current_dir(), Some(Path::new("/tmp/vault")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_binary_candidates_include_supported_macos_installs() {
|
||||
let home = PathBuf::from("/Users/alex");
|
||||
let candidates = codex_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".local/bin/codex"),
|
||||
home.join(".codex/bin/codex"),
|
||||
home.join(".local/share/mise/shims/codex"),
|
||||
home.join(".asdf/shims/codex"),
|
||||
home.join(".npm-global/bin/codex"),
|
||||
home.join(".bun/bin/codex"),
|
||||
PathBuf::from("/Applications/Codex.app/Contents/Resources/codex"),
|
||||
let install_flags = [
|
||||
status.claude_code.installed,
|
||||
status.codex.installed,
|
||||
status.opencode.installed,
|
||||
status.pi.installed,
|
||||
status.gemini.installed,
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_existing_path_skips_empty_and_missing_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let missing = dir.path().join("missing-codex");
|
||||
let codex = dir.path().join("codex");
|
||||
std::fs::write(&codex, "#!/bin/sh\n").unwrap();
|
||||
|
||||
let stdout = format!("\n{}\n{}\n", missing.display(), codex.display());
|
||||
|
||||
assert_eq!(first_existing_path(&stdout), Some(codex));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn command_path_from_shell_finds_codex_from_login_shell() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let codex = dir.path().join("codex");
|
||||
std::fs::write(&codex, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&codex, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let shell = dir.path().join("shell");
|
||||
std::fs::write(
|
||||
&shell,
|
||||
format!(
|
||||
"#!/bin/sh\nif [ \"$1\" = \"-lc\" ]; then echo '{}'; fi\n",
|
||||
codex.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert_eq!(command_path_from_shell(&shell, "codex"), Some(codex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_codex_command_events_maps_to_bash_events() {
|
||||
let mut events = Vec::new();
|
||||
let started = serde_json::json!({
|
||||
"type": "item.started",
|
||||
"item": {
|
||||
"id": "item_1",
|
||||
"type": "command_execution",
|
||||
"command": "/bin/zsh -lc pwd"
|
||||
}
|
||||
});
|
||||
let completed = serde_json::json!({
|
||||
"type": "item.completed",
|
||||
"item": {
|
||||
"id": "item_1",
|
||||
"type": "command_execution",
|
||||
"aggregated_output": "/private/tmp\n"
|
||||
}
|
||||
});
|
||||
|
||||
dispatch_codex_event(&started, &mut |event| events.push(event));
|
||||
dispatch_codex_event(&completed, &mut |event| events.push(event));
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::ToolStart { tool_name, tool_id, .. }
|
||||
if tool_name == "Bash" && tool_id == "item_1"
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::ToolDone { tool_id, output }
|
||||
if tool_id == "item_1" && output.as_deref() == Some("/private/tmp\n")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_codex_agent_message_maps_to_text_delta() {
|
||||
let mut events = Vec::new();
|
||||
let completed = serde_json::json!({
|
||||
"type": "item.completed",
|
||||
"item": {
|
||||
"id": "item_2",
|
||||
"type": "agent_message",
|
||||
"text": "All set"
|
||||
}
|
||||
});
|
||||
|
||||
dispatch_codex_event(&completed, &mut |event| events.push(event));
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "All set"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_codex_error_explains_vault_write_permission_failures() {
|
||||
let message = format_codex_error(
|
||||
"The patch was rejected by the environment: writing is blocked by read-only sandbox; rejected by user approval settings".into(),
|
||||
"exit status: 1".into(),
|
||||
);
|
||||
|
||||
assert!(message.contains("active vault"));
|
||||
assert!(message.contains("writable"));
|
||||
assert!(message.contains("outside"));
|
||||
assert!(install_flags
|
||||
.iter()
|
||||
.all(|installed| matches!(installed, true | false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -695,6 +238,66 @@ mod tests {
|
||||
assert!(matches!(mapped, Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_claude_text_events_preserve_stream_data() {
|
||||
assert!(matches!(
|
||||
map_claude_event(crate::claude_cli::ClaudeStreamEvent::Init {
|
||||
session_id: "session-1".into(),
|
||||
}),
|
||||
Some(AiAgentStreamEvent::Init { session_id }) if session_id == "session-1"
|
||||
));
|
||||
assert!(matches!(
|
||||
map_claude_event(crate::claude_cli::ClaudeStreamEvent::TextDelta {
|
||||
text: "visible output".into(),
|
||||
}),
|
||||
Some(AiAgentStreamEvent::TextDelta { text }) if text == "visible output"
|
||||
));
|
||||
assert!(matches!(
|
||||
map_claude_event(crate::claude_cli::ClaudeStreamEvent::ThinkingDelta {
|
||||
text: "thinking".into(),
|
||||
}),
|
||||
Some(AiAgentStreamEvent::ThinkingDelta { text }) if text == "thinking"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_claude_tool_events_preserve_stream_data() {
|
||||
let started = map_claude_event(crate::claude_cli::ClaudeStreamEvent::ToolStart {
|
||||
tool_name: "Read".into(),
|
||||
tool_id: "tool-1".into(),
|
||||
input: Some("{\"file\":\"note.md\"}".into()),
|
||||
});
|
||||
let finished = map_claude_event(crate::claude_cli::ClaudeStreamEvent::ToolDone {
|
||||
tool_id: "tool-1".into(),
|
||||
output: Some("done".into()),
|
||||
});
|
||||
|
||||
assert!(matches!(
|
||||
started,
|
||||
Some(AiAgentStreamEvent::ToolStart { tool_name, tool_id, input })
|
||||
if tool_name == "Read"
|
||||
&& tool_id == "tool-1"
|
||||
&& input.as_deref() == Some("{\"file\":\"note.md\"}")
|
||||
));
|
||||
assert!(matches!(
|
||||
finished,
|
||||
Some(AiAgentStreamEvent::ToolDone { tool_id, output })
|
||||
if tool_id == "tool-1" && output.as_deref() == Some("done")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_claude_error_event_preserves_message() {
|
||||
let mapped = map_claude_event(crate::claude_cli::ClaudeStreamEvent::Error {
|
||||
message: "missing auth".into(),
|
||||
});
|
||||
|
||||
assert!(matches!(
|
||||
mapped,
|
||||
Some(AiAgentStreamEvent::Error { message }) if message == "missing auth"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_claude_result_event_preserves_final_text() {
|
||||
let mapped = map_claude_event(crate::claude_cli::ClaudeStreamEvent::Result {
|
||||
@@ -707,4 +310,14 @@ mod tests {
|
||||
Some(AiAgentStreamEvent::TextDelta { text }) if text == "Final answer from Claude"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_claude_empty_result_event_is_ignored() {
|
||||
let mapped = map_claude_event(crate::claude_cli::ClaudeStreamEvent::Result {
|
||||
text: String::new(),
|
||||
session_id: "session-1".into(),
|
||||
});
|
||||
|
||||
assert!(mapped.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
668
src-tauri/src/ai_models.rs
Normal file
668
src-tauri/src/ai_models.rs
Normal file
@@ -0,0 +1,668 @@
|
||||
use crate::ai_agents::AiAgentStreamEvent;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AiModelProviderKind {
|
||||
OpenAi,
|
||||
Anthropic,
|
||||
OpenAiCompatible,
|
||||
Ollama,
|
||||
LmStudio,
|
||||
OpenRouter,
|
||||
Gemini,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AiModelApiKeyStorage {
|
||||
None,
|
||||
Env,
|
||||
LocalFile,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct AiModelCapabilities {
|
||||
pub streaming: bool,
|
||||
pub tools: bool,
|
||||
pub vision: bool,
|
||||
pub json_mode: bool,
|
||||
pub reasoning: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct AiModelDefinition {
|
||||
pub id: String,
|
||||
pub display_name: Option<String>,
|
||||
pub context_window: Option<u32>,
|
||||
pub max_output_tokens: Option<u32>,
|
||||
pub capabilities: AiModelCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct AiModelProvider {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: AiModelProviderKind,
|
||||
pub base_url: Option<String>,
|
||||
pub api_key_storage: Option<AiModelApiKeyStorage>,
|
||||
pub api_key_env_var: Option<String>,
|
||||
pub headers: Option<BTreeMap<String, String>>,
|
||||
pub models: Vec<AiModelDefinition>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AiModelStreamRequest {
|
||||
pub provider: AiModelProvider,
|
||||
pub model_id: String,
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub api_key_override: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AiModelProviderTestRequest {
|
||||
pub provider: AiModelProvider,
|
||||
pub model_id: String,
|
||||
pub api_key_override: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
struct AiProviderSecrets {
|
||||
provider_api_keys: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
pub fn normalize_ai_model_providers(
|
||||
providers: Option<Vec<AiModelProvider>>,
|
||||
) -> Option<Vec<AiModelProvider>> {
|
||||
let normalized = providers?
|
||||
.into_iter()
|
||||
.filter_map(normalize_ai_model_provider)
|
||||
.collect::<Vec<_>>();
|
||||
if normalized.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(normalized)
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_ai_model_provider(mut provider: AiModelProvider) -> Option<AiModelProvider> {
|
||||
provider.id = provider.id.trim().to_ascii_lowercase();
|
||||
provider.name = provider.name.trim().to_string();
|
||||
provider.base_url = normalize_optional_string(provider.base_url);
|
||||
provider.api_key_env_var = normalize_optional_string(provider.api_key_env_var);
|
||||
provider.api_key_storage = normalize_api_key_storage(&provider);
|
||||
provider.models = normalized_models(provider.models);
|
||||
|
||||
is_valid_provider(&provider).then_some(provider)
|
||||
}
|
||||
|
||||
fn normalize_api_key_storage(provider: &AiModelProvider) -> Option<AiModelApiKeyStorage> {
|
||||
match provider.api_key_storage {
|
||||
Some(AiModelApiKeyStorage::LocalFile) => Some(AiModelApiKeyStorage::LocalFile),
|
||||
Some(AiModelApiKeyStorage::Env) | None if provider.api_key_env_var.is_some() => {
|
||||
Some(AiModelApiKeyStorage::Env)
|
||||
}
|
||||
_ => Some(AiModelApiKeyStorage::None),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_models(models: Vec<AiModelDefinition>) -> Vec<AiModelDefinition> {
|
||||
models
|
||||
.into_iter()
|
||||
.filter_map(|mut model| {
|
||||
model.id = model.id.trim().to_string();
|
||||
model.display_name = normalize_optional_string(model.display_name);
|
||||
(!model.id.is_empty()).then_some(model)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_valid_provider(provider: &AiModelProvider) -> bool {
|
||||
!provider.id.is_empty() && !provider.name.is_empty() && !provider.models.is_empty()
|
||||
}
|
||||
|
||||
fn normalize_optional_string(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|candidate| candidate.trim().to_string())
|
||||
.filter(|candidate| !candidate.is_empty())
|
||||
}
|
||||
|
||||
pub fn run_ai_model_stream<F>(request: AiModelStreamRequest, mut emit: F) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
emit(AiAgentStreamEvent::Init {
|
||||
session_id: format!("api-{}", uuid::Uuid::new_v4()),
|
||||
});
|
||||
|
||||
let text = send_model_message(&request)?;
|
||||
|
||||
emit(AiAgentStreamEvent::TextDelta { text });
|
||||
emit(AiAgentStreamEvent::Done);
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
pub fn test_ai_model_provider(request: AiModelProviderTestRequest) -> Result<String, String> {
|
||||
let request = AiModelStreamRequest {
|
||||
provider: request.provider,
|
||||
model_id: request.model_id,
|
||||
message: "Reply with exactly OK.".into(),
|
||||
system_prompt: Some(
|
||||
"You are testing whether this model endpoint is reachable. Reply with exactly OK."
|
||||
.into(),
|
||||
),
|
||||
api_key_override: normalize_optional_string(request.api_key_override),
|
||||
};
|
||||
send_model_message(&request)
|
||||
}
|
||||
|
||||
fn send_model_message(request: &AiModelStreamRequest) -> Result<String, String> {
|
||||
match request.provider.kind {
|
||||
AiModelProviderKind::Anthropic => send_anthropic_message(request),
|
||||
_ => send_openai_compatible_message(request),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_openai_compatible_message(request: &AiModelStreamRequest) -> Result<String, String> {
|
||||
let endpoint = format!("{}/chat/completions", normalized_base_url(request)?);
|
||||
let mut messages = Vec::new();
|
||||
if let Some(system_prompt) = non_empty_option(request.system_prompt.as_deref()) {
|
||||
messages.push(serde_json::json!({ "role": "system", "content": system_prompt }));
|
||||
}
|
||||
messages.push(serde_json::json!({ "role": "user", "content": request.message }));
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"model": request.model_id,
|
||||
"messages": messages,
|
||||
"stream": false
|
||||
});
|
||||
let json = send_json_request(request, endpoint, payload)?;
|
||||
extract_openai_text(&json)
|
||||
}
|
||||
|
||||
fn send_anthropic_message(request: &AiModelStreamRequest) -> Result<String, String> {
|
||||
let endpoint = format!("{}/messages", normalized_base_url(request)?);
|
||||
let mut payload = serde_json::json!({
|
||||
"model": request.model_id,
|
||||
"max_tokens": selected_max_tokens(request),
|
||||
"messages": [{ "role": "user", "content": request.message }]
|
||||
});
|
||||
|
||||
if let Some(system_prompt) = non_empty_option(request.system_prompt.as_deref()) {
|
||||
payload["system"] = serde_json::Value::String(system_prompt.to_string());
|
||||
}
|
||||
|
||||
let json = send_json_request(request, endpoint, payload)?;
|
||||
extract_anthropic_text(&json)
|
||||
}
|
||||
|
||||
fn selected_max_tokens(request: &AiModelStreamRequest) -> u32 {
|
||||
request
|
||||
.provider
|
||||
.models
|
||||
.iter()
|
||||
.find(|model| model.id == request.model_id)
|
||||
.and_then(|model| model.max_output_tokens)
|
||||
.unwrap_or(4096)
|
||||
}
|
||||
|
||||
fn normalized_base_url(request: &AiModelStreamRequest) -> Result<String, String> {
|
||||
let fallback = match request.provider.kind {
|
||||
AiModelProviderKind::OpenAi => "https://api.openai.com/v1",
|
||||
AiModelProviderKind::Anthropic => "https://api.anthropic.com/v1",
|
||||
AiModelProviderKind::OpenRouter => "https://openrouter.ai/api/v1",
|
||||
AiModelProviderKind::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai",
|
||||
AiModelProviderKind::Ollama => "http://localhost:11434/v1",
|
||||
AiModelProviderKind::LmStudio => "http://127.0.0.1:1234/v1",
|
||||
AiModelProviderKind::OpenAiCompatible => "",
|
||||
};
|
||||
let base = request
|
||||
.provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.and_then(non_empty_str)
|
||||
.unwrap_or(fallback)
|
||||
.trim_end_matches('/');
|
||||
if base.is_empty() {
|
||||
return Err("Custom API providers need a base URL.".into());
|
||||
}
|
||||
Ok(base.to_string())
|
||||
}
|
||||
|
||||
fn send_json_request(
|
||||
request: &AiModelStreamRequest,
|
||||
endpoint: String,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.build()
|
||||
.map_err(|error| format!("Failed to create HTTP client: {error}"))?;
|
||||
let builder = client.post(endpoint).json(&payload);
|
||||
let builder = apply_auth_headers(builder, request)?;
|
||||
let builder = apply_provider_headers(builder, request);
|
||||
let response = send_provider_request(builder)?;
|
||||
let status = response.status();
|
||||
let text = response
|
||||
.text()
|
||||
.map_err(|error| format!("Failed to read AI provider response: {error}"))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!(
|
||||
"AI provider returned {status}: {}",
|
||||
truncate_error(&text)
|
||||
));
|
||||
}
|
||||
serde_json::from_str(&text)
|
||||
.map_err(|error| format!("Failed to parse AI provider response: {error}"))
|
||||
}
|
||||
|
||||
fn apply_auth_headers(
|
||||
builder: reqwest::blocking::RequestBuilder,
|
||||
request: &AiModelStreamRequest,
|
||||
) -> Result<reqwest::blocking::RequestBuilder, String> {
|
||||
let Some(api_key) = api_key_from_provider(request)? else {
|
||||
return Ok(builder);
|
||||
};
|
||||
|
||||
Ok(match request.provider.kind {
|
||||
AiModelProviderKind::Anthropic => builder.header("x-api-key", api_key),
|
||||
_ => builder.bearer_auth(api_key),
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_provider_headers(
|
||||
mut builder: reqwest::blocking::RequestBuilder,
|
||||
request: &AiModelStreamRequest,
|
||||
) -> reqwest::blocking::RequestBuilder {
|
||||
if matches!(request.provider.kind, AiModelProviderKind::Anthropic) {
|
||||
builder = builder.header("anthropic-version", "2023-06-01");
|
||||
}
|
||||
for (key, value) in safe_custom_headers(request) {
|
||||
builder = builder.header(key, value);
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
fn safe_custom_headers(request: &AiModelStreamRequest) -> Vec<(&String, &String)> {
|
||||
request
|
||||
.provider
|
||||
.headers
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|headers| headers.iter())
|
||||
.filter(|(key, value)| {
|
||||
!key.eq_ignore_ascii_case("authorization") && non_empty_option(Some(value)).is_some()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn send_provider_request(
|
||||
builder: reqwest::blocking::RequestBuilder,
|
||||
) -> Result<reqwest::blocking::Response, String> {
|
||||
builder
|
||||
.send()
|
||||
.map_err(|error| format!("AI provider request failed: {error}"))
|
||||
}
|
||||
|
||||
pub fn save_provider_api_key(provider_id: String, api_key: String) -> Result<(), String> {
|
||||
let provider_id = normalize_secret_provider_id(&provider_id)?;
|
||||
let api_key = api_key.trim().to_string();
|
||||
if api_key.is_empty() {
|
||||
return Err("API key cannot be empty.".into());
|
||||
}
|
||||
let path = secrets_path()?;
|
||||
let mut secrets = read_secrets_at(&path)?;
|
||||
secrets.provider_api_keys.insert(provider_id, api_key);
|
||||
write_secrets_at(&path, &secrets)
|
||||
}
|
||||
|
||||
pub fn delete_provider_api_key(provider_id: String) -> Result<(), String> {
|
||||
let provider_id = normalize_secret_provider_id(&provider_id)?;
|
||||
let path = secrets_path()?;
|
||||
let mut secrets = read_secrets_at(&path)?;
|
||||
secrets.provider_api_keys.remove(&provider_id);
|
||||
write_secrets_at(&path, &secrets)
|
||||
}
|
||||
|
||||
fn normalize_secret_provider_id(provider_id: &str) -> Result<String, String> {
|
||||
let provider_id = provider_id.trim().to_ascii_lowercase();
|
||||
if provider_id.is_empty() {
|
||||
Err("Provider ID cannot be empty.".into())
|
||||
} else {
|
||||
Ok(provider_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn secrets_path() -> Result<std::path::PathBuf, String> {
|
||||
crate::settings::preferred_app_config_path("ai-provider-secrets.json")
|
||||
}
|
||||
|
||||
fn read_secrets_at(path: &Path) -> Result<AiProviderSecrets, String> {
|
||||
if !path.exists() {
|
||||
return Ok(AiProviderSecrets::default());
|
||||
}
|
||||
let content = fs::read_to_string(path)
|
||||
.map_err(|error| format!("Failed to read AI provider secrets: {error}"))?;
|
||||
serde_json::from_str(&content)
|
||||
.map_err(|error| format!("Failed to parse AI provider secrets: {error}"))
|
||||
}
|
||||
|
||||
fn write_secrets_at(path: &Path, secrets: &AiProviderSecrets) -> Result<(), String> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|error| format!("Failed to create AI provider secrets directory: {error}"))?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(secrets)
|
||||
.map_err(|error| format!("Failed to serialize AI provider secrets: {error}"))?;
|
||||
write_secret_file(path, json)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_secret_file(path: &Path, content: String) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.map_err(|error| format!("Failed to open AI provider secrets file: {error}"))?;
|
||||
file.write_all(content.as_bytes())
|
||||
.map_err(|error| format!("Failed to write AI provider secrets: {error}"))?;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))
|
||||
.map_err(|error| format!("Failed to secure AI provider secrets file: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn write_secret_file(path: &Path, content: String) -> Result<(), String> {
|
||||
fs::write(path, content)
|
||||
.map_err(|error| format!("Failed to write AI provider secrets: {error}"))
|
||||
}
|
||||
|
||||
fn api_key_from_local_file(request: &AiModelStreamRequest) -> Result<Option<String>, String> {
|
||||
let secrets = read_secrets_at(&secrets_path()?)?;
|
||||
let api_key = secrets
|
||||
.provider_api_keys
|
||||
.get(&request.provider.id)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty());
|
||||
if api_key.is_none() {
|
||||
return Err(format!(
|
||||
"No local API key is saved for {}.",
|
||||
request.provider.name
|
||||
));
|
||||
}
|
||||
Ok(api_key)
|
||||
}
|
||||
|
||||
fn api_key_from_env(request: &AiModelStreamRequest) -> Result<Option<String>, String> {
|
||||
let Some(name) = request
|
||||
.provider
|
||||
.api_key_env_var
|
||||
.as_deref()
|
||||
.and_then(non_empty_str)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
std::env::var(name)
|
||||
.map(Some)
|
||||
.map_err(|_| format!("Environment variable {name} is not set for this AI provider."))
|
||||
}
|
||||
|
||||
fn api_key_from_provider(request: &AiModelStreamRequest) -> Result<Option<String>, String> {
|
||||
if let Some(api_key) = request
|
||||
.api_key_override
|
||||
.as_deref()
|
||||
.and_then(non_empty_str)
|
||||
.map(str::to_string)
|
||||
{
|
||||
return Ok(Some(api_key));
|
||||
}
|
||||
|
||||
match request.provider.api_key_storage {
|
||||
Some(AiModelApiKeyStorage::LocalFile) => api_key_from_local_file(request),
|
||||
Some(AiModelApiKeyStorage::Env) => api_key_from_env(request),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_openai_text(json: &serde_json::Value) -> Result<String, String> {
|
||||
json["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.map(str::to_string)
|
||||
.filter(|text| !text.trim().is_empty())
|
||||
.ok_or_else(|| "AI provider response did not include assistant text.".to_string())
|
||||
}
|
||||
|
||||
fn extract_anthropic_text(json: &serde_json::Value) -> Result<String, String> {
|
||||
let text = json["content"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|block| block["text"].as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
if text.trim().is_empty() {
|
||||
Err("Anthropic response did not include assistant text.".into())
|
||||
} else {
|
||||
Ok(text)
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_option(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn non_empty_str(value: &str) -> Option<&str> {
|
||||
non_empty_option(Some(value))
|
||||
}
|
||||
|
||||
fn truncate_error(value: &str) -> String {
|
||||
const MAX_ERROR_LENGTH: usize = 600;
|
||||
if value.len() <= MAX_ERROR_LENGTH {
|
||||
return value.to_string();
|
||||
}
|
||||
format!("{}...", &value[..MAX_ERROR_LENGTH])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn capabilities() -> AiModelCapabilities {
|
||||
AiModelCapabilities {
|
||||
streaming: true,
|
||||
tools: false,
|
||||
vision: false,
|
||||
json_mode: true,
|
||||
reasoning: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn model(id: &str) -> AiModelDefinition {
|
||||
AiModelDefinition {
|
||||
id: id.into(),
|
||||
display_name: Some(" Demo Model ".into()),
|
||||
context_window: Some(128_000),
|
||||
max_output_tokens: Some(8192),
|
||||
capabilities: capabilities(),
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(kind: AiModelProviderKind) -> AiModelProvider {
|
||||
AiModelProvider {
|
||||
id: " Demo ".into(),
|
||||
name: " Demo Provider ".into(),
|
||||
kind,
|
||||
base_url: Some(" https://example.com/v1/ ".into()),
|
||||
api_key_storage: None,
|
||||
api_key_env_var: Some(" DEMO_API_KEY ".into()),
|
||||
headers: None,
|
||||
models: vec![model(" demo-model "), model(" ")],
|
||||
}
|
||||
}
|
||||
|
||||
fn request(provider: AiModelProvider) -> AiModelStreamRequest {
|
||||
AiModelStreamRequest {
|
||||
provider,
|
||||
model_id: "demo-model".into(),
|
||||
message: "Hello".into(),
|
||||
system_prompt: Some(" Be concise. ".into()),
|
||||
api_key_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_providers_trims_values_and_filters_invalid_entries() {
|
||||
let invalid = AiModelProvider {
|
||||
id: " ".into(),
|
||||
name: "Missing".into(),
|
||||
kind: AiModelProviderKind::OpenAiCompatible,
|
||||
base_url: None,
|
||||
api_key_storage: None,
|
||||
api_key_env_var: None,
|
||||
headers: None,
|
||||
models: vec![model("ignored")],
|
||||
};
|
||||
|
||||
let providers = normalize_ai_model_providers(Some(vec![
|
||||
invalid,
|
||||
provider(AiModelProviderKind::OpenAiCompatible),
|
||||
]))
|
||||
.expect("valid provider should remain");
|
||||
|
||||
assert_eq!(providers.len(), 1);
|
||||
let normalized = &providers[0];
|
||||
assert_eq!(normalized.id, "demo");
|
||||
assert_eq!(normalized.name, "Demo Provider");
|
||||
assert_eq!(
|
||||
normalized.base_url.as_deref(),
|
||||
Some("https://example.com/v1/")
|
||||
);
|
||||
assert_eq!(normalized.api_key_env_var.as_deref(), Some("DEMO_API_KEY"));
|
||||
assert_eq!(normalized.api_key_storage, Some(AiModelApiKeyStorage::Env));
|
||||
assert_eq!(normalized.models.len(), 1);
|
||||
assert_eq!(normalized.models[0].id, "demo-model");
|
||||
assert_eq!(
|
||||
normalized.models[0].display_name.as_deref(),
|
||||
Some("Demo Model")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_providers_returns_none_for_missing_or_empty_sets() {
|
||||
assert_eq!(normalize_ai_model_providers(None), None);
|
||||
assert_eq!(normalize_ai_model_providers(Some(Vec::new())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_request_helpers_resolve_defaults_and_safe_headers() {
|
||||
let mut provider = provider(AiModelProviderKind::Anthropic);
|
||||
provider.base_url = None;
|
||||
provider.headers = Some(BTreeMap::from([
|
||||
("Authorization".into(), "ignored".into()),
|
||||
("X-Demo".into(), "demo".into()),
|
||||
("X-Blank".into(), " ".into()),
|
||||
]));
|
||||
provider.models = vec![model("demo-model")];
|
||||
let request = request(provider);
|
||||
let headers = safe_custom_headers(&request)
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.as_str(), value.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
normalized_base_url(&request).unwrap(),
|
||||
"https://api.anthropic.com/v1"
|
||||
);
|
||||
assert_eq!(selected_max_tokens(&request), 8192);
|
||||
assert_eq!(headers, vec![("X-Demo", "demo")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_requires_base_url() {
|
||||
let mut provider = provider(AiModelProviderKind::OpenAiCompatible);
|
||||
provider.base_url = Some(" ".into());
|
||||
|
||||
assert_eq!(
|
||||
normalized_base_url(&request(provider)).unwrap_err(),
|
||||
"Custom API providers need a base URL.",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_provider_text_payloads_and_reports_empty_responses() {
|
||||
let openai = json!({
|
||||
"choices": [{ "message": { "content": "Hello from OpenAI" } }]
|
||||
});
|
||||
let anthropic = json!({
|
||||
"content": [
|
||||
{ "text": "Hello " },
|
||||
{ "text": "from Anthropic" }
|
||||
]
|
||||
});
|
||||
|
||||
assert_eq!(extract_openai_text(&openai).unwrap(), "Hello from OpenAI");
|
||||
assert_eq!(
|
||||
extract_anthropic_text(&anthropic).unwrap(),
|
||||
"Hello from Anthropic"
|
||||
);
|
||||
assert_eq!(
|
||||
extract_openai_text(&json!({ "choices": [] })).unwrap_err(),
|
||||
"AI provider response did not include assistant text.",
|
||||
);
|
||||
assert_eq!(
|
||||
extract_anthropic_text(&json!({ "content": [{ "type": "thinking" }] })).unwrap_err(),
|
||||
"Anthropic response did not include assistant text.",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saves_reads_and_validates_local_provider_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested/secrets.json");
|
||||
let secrets = AiProviderSecrets {
|
||||
provider_api_keys: BTreeMap::from([("demo".into(), "secret".into())]),
|
||||
};
|
||||
|
||||
write_secrets_at(&path, &secrets).unwrap();
|
||||
|
||||
assert_eq!(read_secrets_at(&path).unwrap(), secrets);
|
||||
assert_eq!(
|
||||
read_secrets_at(&dir.path().join("missing.json")).unwrap(),
|
||||
AiProviderSecrets::default()
|
||||
);
|
||||
assert_eq!(normalize_secret_provider_id(" Demo ").unwrap(), "demo");
|
||||
assert_eq!(
|
||||
normalize_secret_provider_id(" ").unwrap_err(),
|
||||
"Provider ID cannot be empty.",
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncates_long_provider_errors_without_touching_short_errors() {
|
||||
let short = "provider unavailable";
|
||||
let long = "x".repeat(605);
|
||||
|
||||
assert_eq!(truncate_error(short), short);
|
||||
assert_eq!(truncate_error(&long).len(), 603);
|
||||
assert!(truncate_error(&long).ends_with("..."));
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,8 @@ pub async fn download_and_install_app_update<R: Runtime>(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ReleaseChannel;
|
||||
use super::{AppUpdateDownloadEvent, AppUpdateMetadata, ReleaseChannel};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn release_channel_defaults_to_stable() {
|
||||
@@ -176,4 +177,54 @@ mod tests {
|
||||
"https://refactoringhq.github.io/tolaria/stable/latest.json"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_metadata_serializes_for_frontend_consumers() {
|
||||
let metadata = AppUpdateMetadata {
|
||||
current_version: "2026.4.1".into(),
|
||||
version: "2026.4.2".into(),
|
||||
date: Some("2026-04-30T12:00:00Z".into()),
|
||||
body: Some("Bug fixes".into()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(metadata).unwrap(),
|
||||
json!({
|
||||
"currentVersion": "2026.4.1",
|
||||
"version": "2026.4.2",
|
||||
"date": "2026-04-30T12:00:00Z",
|
||||
"body": "Bug fixes"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_events_serialize_as_tagged_frontend_events() {
|
||||
let events = [
|
||||
(
|
||||
AppUpdateDownloadEvent::Started {
|
||||
content_length: Some(4096),
|
||||
},
|
||||
json!({
|
||||
"event": "Started",
|
||||
"data": { "contentLength": 4096 }
|
||||
}),
|
||||
),
|
||||
(
|
||||
AppUpdateDownloadEvent::Progress { chunk_length: 512 },
|
||||
json!({
|
||||
"event": "Progress",
|
||||
"data": { "chunkLength": 512 }
|
||||
}),
|
||||
),
|
||||
(
|
||||
AppUpdateDownloadEvent::Finished,
|
||||
json!({ "event": "Finished" }),
|
||||
),
|
||||
];
|
||||
|
||||
for (event, expected) in events {
|
||||
assert_eq!(serde_json::to_value(event).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
pub use crate::cli_agent_runtime::AgentStreamRequest;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::io::BufRead;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
|
||||
@@ -50,14 +51,6 @@ pub struct ChatStreamRequest {
|
||||
pub session_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Parameters accepted by Claude Code agent streams.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AgentStreamRequest {
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub vault_path: String,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Finding the `claude` binary
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -71,7 +64,10 @@ pub(crate) fn find_claude_binary() -> Result<PathBuf, String> {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
if let Some(binary) = find_existing_binary(claude_binary_candidates()) {
|
||||
if let Some(binary) = crate::cli_agent_runtime::find_executable_binary_candidate(
|
||||
claude_binary_candidates(),
|
||||
"Claude CLI",
|
||||
)? {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
@@ -148,7 +144,7 @@ fn claude_binary_candidates() -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
fn claude_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
let mut candidates = vec![
|
||||
home.join(".local/bin/claude"),
|
||||
home.join(".local/bin/claude.exe"),
|
||||
home.join(".claude/local/claude"),
|
||||
@@ -163,18 +159,33 @@ fn claude_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
home.join(".npm/bin/claude"),
|
||||
home.join(".npm/bin/claude.cmd"),
|
||||
home.join(".npm/bin/claude.exe"),
|
||||
home.join(".linuxbrew/bin/claude"),
|
||||
home.join("AppData/Roaming/npm/claude.cmd"),
|
||||
home.join("AppData/Roaming/npm/claude.exe"),
|
||||
home.join("AppData/Local/pnpm/claude.cmd"),
|
||||
home.join("AppData/Local/pnpm/claude.exe"),
|
||||
home.join("scoop/shims/claude.exe"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/claude"),
|
||||
PathBuf::from("/opt/homebrew/bin/claude"),
|
||||
PathBuf::from("/usr/local/bin/claude"),
|
||||
]
|
||||
];
|
||||
candidates.extend(nvm_node_binary_candidates_for_home(home, "claude"));
|
||||
candidates
|
||||
}
|
||||
|
||||
fn find_existing_binary(candidates: Vec<PathBuf>) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|candidate| candidate.exists())
|
||||
fn nvm_node_binary_candidates_for_home(home: &Path, binary_name: &str) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut candidates = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.is_dir())
|
||||
.map(|path| path.join("bin").join(binary_name))
|
||||
.collect::<Vec<_>>();
|
||||
candidates.sort();
|
||||
candidates
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -193,16 +204,9 @@ pub fn check_cli() -> ClaudeCliStatus {
|
||||
}
|
||||
};
|
||||
|
||||
let version = crate::hidden_command(&bin)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
|
||||
|
||||
ClaudeCliStatus {
|
||||
installed: true,
|
||||
version,
|
||||
version: crate::cli_agent_runtime::version_for_binary(&bin),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,10 +277,15 @@ fn build_agent_args(req: &AgentStreamRequest) -> Result<Vec<String>, String> {
|
||||
"--permission-mode".into(),
|
||||
"acceptEdits".into(),
|
||||
"--tools".into(),
|
||||
"Read,Edit,MultiEdit,Write,Glob,Grep,LS".into(),
|
||||
agent_tools(req.permission_mode).into(),
|
||||
"--no-session-persistence".into(),
|
||||
];
|
||||
|
||||
if let Some(allowed_tools) = preapproved_agent_tools(req.permission_mode) {
|
||||
args.push("--allowedTools".into());
|
||||
args.push(allowed_tools.into());
|
||||
}
|
||||
|
||||
if let Some(ref sp) = req.system_prompt {
|
||||
if !sp.is_empty() {
|
||||
args.push("--append-system-prompt".into());
|
||||
@@ -287,19 +296,32 @@ fn build_agent_args(req: &AgentStreamRequest) -> Result<Vec<String>, String> {
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
fn agent_tools(permission_mode: AiAgentPermissionMode) -> &'static str {
|
||||
match permission_mode {
|
||||
AiAgentPermissionMode::Safe => "Read,Edit,MultiEdit,Write,Glob,Grep,LS",
|
||||
AiAgentPermissionMode::PowerUser => "Read,Edit,MultiEdit,Write,Glob,Grep,LS,Bash",
|
||||
}
|
||||
}
|
||||
|
||||
fn preapproved_agent_tools(permission_mode: AiAgentPermissionMode) -> Option<&'static str> {
|
||||
match permission_mode {
|
||||
AiAgentPermissionMode::Safe => None,
|
||||
AiAgentPermissionMode::PowerUser => Some("Bash"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Build a temporary MCP config JSON string pointing to the vault MCP server.
|
||||
fn build_mcp_config(vault_path: &str) -> Result<String, String> {
|
||||
let server_dir = crate::mcp::mcp_server_dir()?;
|
||||
let index_js = server_dir.join("index.js");
|
||||
let mcp_server_path = crate::cli_agent_runtime::mcp_server_path_string()?;
|
||||
let config = serde_json::json!({
|
||||
"mcpServers": {
|
||||
"tolaria": {
|
||||
"command": "node",
|
||||
"args": [index_js.to_string_lossy()],
|
||||
"args": [mcp_server_path],
|
||||
"env": { "VAULT_PATH": vault_path }
|
||||
}
|
||||
}
|
||||
@@ -314,6 +336,8 @@ struct StreamState {
|
||||
tool_inputs: HashMap<String, String>,
|
||||
/// The tool_use id of the block currently being streamed.
|
||||
current_tool_id: Option<String>,
|
||||
/// Tracks whether response text has already been emitted for this run.
|
||||
emitted_text: bool,
|
||||
}
|
||||
|
||||
/// Core subprocess runner shared by chat and agent modes.
|
||||
@@ -327,55 +351,28 @@ fn run_claude_subprocess<F>(
|
||||
where
|
||||
F: FnMut(ClaudeStreamEvent),
|
||||
{
|
||||
let mut cmd = build_claude_command(bin, args, cwd);
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to spawn claude: {e}"))?;
|
||||
|
||||
let stdout = child.stdout.take().ok_or("No stdout handle")?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
|
||||
let mut state = StreamState {
|
||||
session_id: String::new(),
|
||||
tool_inputs: HashMap::new(),
|
||||
current_tool_id: None,
|
||||
emitted_text: false,
|
||||
};
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
emit(ClaudeStreamEvent::Error {
|
||||
message: format!("Read error: {e}"),
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
let cmd = build_claude_command(bin, args, cwd);
|
||||
let run = crate::cli_agent_runtime::run_json_line_process(
|
||||
cmd,
|
||||
"claude",
|
||||
emit,
|
||||
|message| ClaudeStreamEvent::Error { message },
|
||||
|json, emit, session_id| {
|
||||
dispatch_event(json, &mut state, emit);
|
||||
*session_id = state.session_id.clone();
|
||||
},
|
||||
)?;
|
||||
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue, // skip non-JSON lines
|
||||
};
|
||||
|
||||
dispatch_event(&json, &mut state, emit);
|
||||
}
|
||||
|
||||
// Read stderr for potential error messages.
|
||||
let stderr_output = child
|
||||
.stderr
|
||||
.take()
|
||||
.and_then(|s| std::io::read_to_string(s).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
let status = child.wait().map_err(|e| format!("Wait failed: {e}"))?;
|
||||
|
||||
if !status.success() && state.session_id.is_empty() {
|
||||
if !run.status.success() && state.session_id.is_empty() {
|
||||
emit(ClaudeStreamEvent::Error {
|
||||
message: format_failed_claude_exit(&stderr_output, status),
|
||||
message: format_failed_claude_exit(&run.stderr_output, run.status),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -390,6 +387,7 @@ fn build_claude_command(
|
||||
cwd: Option<&str>,
|
||||
) -> std::process::Command {
|
||||
let mut cmd = crate::hidden_command(bin);
|
||||
crate::cli_agent_runtime::configure_agent_command_environment(&mut cmd, bin);
|
||||
cmd.args(args)
|
||||
.env_remove("CLAUDECODE") // prevent "nested session" guard
|
||||
.stdin(Stdio::null())
|
||||
@@ -473,7 +471,15 @@ where
|
||||
if !sid.is_empty() {
|
||||
state.session_id = sid.clone();
|
||||
}
|
||||
let text = json["result"].as_str().unwrap_or("").to_string();
|
||||
let text = if state.emitted_text {
|
||||
String::new()
|
||||
} else {
|
||||
let text = json["result"].as_str().unwrap_or("").to_string();
|
||||
if !text.is_empty() {
|
||||
state.emitted_text = true;
|
||||
}
|
||||
text
|
||||
};
|
||||
emit(ClaudeStreamEvent::Result {
|
||||
text,
|
||||
session_id: sid,
|
||||
@@ -483,19 +489,9 @@ where
|
||||
// --- Complete assistant message (fallback for text when no partials) ---
|
||||
"assistant" => {
|
||||
if let Some(content) = json["message"]["content"].as_array() {
|
||||
let emit_text = !state.emitted_text;
|
||||
for block in content {
|
||||
if block["type"].as_str() == Some("tool_use") {
|
||||
if let (Some(id), Some(name)) =
|
||||
(block["id"].as_str(), block["name"].as_str())
|
||||
{
|
||||
let input = format_tool_input(&block["input"], state, id);
|
||||
emit(ClaudeStreamEvent::ToolStart {
|
||||
tool_name: name.to_string(),
|
||||
tool_id: id.to_string(),
|
||||
input,
|
||||
});
|
||||
}
|
||||
}
|
||||
dispatch_assistant_content_block(block, emit_text, state, emit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -518,9 +514,7 @@ where
|
||||
match delta["type"].as_str() {
|
||||
Some("text_delta") => {
|
||||
if let Some(text) = delta["text"].as_str() {
|
||||
emit(ClaudeStreamEvent::TextDelta {
|
||||
text: text.to_string(),
|
||||
});
|
||||
emit_text_delta(text, state, emit);
|
||||
}
|
||||
}
|
||||
Some("thinking_delta") => {
|
||||
@@ -565,6 +559,46 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_assistant_content_block<F>(
|
||||
block: &serde_json::Value,
|
||||
emit_text: bool,
|
||||
state: &mut StreamState,
|
||||
emit: &mut F,
|
||||
) where
|
||||
F: FnMut(ClaudeStreamEvent),
|
||||
{
|
||||
match block["type"].as_str() {
|
||||
Some("text") if emit_text => {
|
||||
if let Some(text) = block["text"].as_str() {
|
||||
emit_text_delta(text, state, emit);
|
||||
}
|
||||
}
|
||||
Some("tool_use") => {
|
||||
if let (Some(id), Some(name)) = (block["id"].as_str(), block["name"].as_str()) {
|
||||
let input = format_tool_input(&block["input"], state, id);
|
||||
emit(ClaudeStreamEvent::ToolStart {
|
||||
tool_name: name.to_string(),
|
||||
tool_id: id.to_string(),
|
||||
input,
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_text_delta<F>(text: &str, state: &mut StreamState, emit: &mut F)
|
||||
where
|
||||
F: FnMut(ClaudeStreamEvent),
|
||||
{
|
||||
if !text.is_empty() {
|
||||
state.emitted_text = true;
|
||||
}
|
||||
emit(ClaudeStreamEvent::TextDelta {
|
||||
text: text.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Build the tool input string, preferring accumulated delta chunks over the
|
||||
/// block's `input` field (which may be empty at stream start).
|
||||
fn format_tool_input(
|
||||
@@ -607,6 +641,87 @@ mod tests {
|
||||
use std::ffi::OsString;
|
||||
use std::process::Command;
|
||||
|
||||
macro_rules! chat_request {
|
||||
($message:expr, None, None $(,)?) => {
|
||||
ChatStreamRequest {
|
||||
message: $message.into(),
|
||||
system_prompt: None,
|
||||
session_id: None,
|
||||
}
|
||||
};
|
||||
($message:expr, Some($system_prompt:expr), None $(,)?) => {
|
||||
ChatStreamRequest {
|
||||
message: $message.into(),
|
||||
system_prompt: Some($system_prompt.to_string()),
|
||||
session_id: None,
|
||||
}
|
||||
};
|
||||
($message:expr, None, Some($session_id:expr) $(,)?) => {
|
||||
ChatStreamRequest {
|
||||
message: $message.into(),
|
||||
system_prompt: None,
|
||||
session_id: Some($session_id.to_string()),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! agent_request {
|
||||
($message:expr, None, $permission_mode:expr $(,)?) => {
|
||||
AgentStreamRequest {
|
||||
message: $message.into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode: $permission_mode,
|
||||
}
|
||||
};
|
||||
($message:expr, Some($system_prompt:expr), $permission_mode:expr $(,)?) => {
|
||||
AgentStreamRequest {
|
||||
message: $message.into(),
|
||||
system_prompt: Some($system_prompt.to_string()),
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode: $permission_mode,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_args_contain {
|
||||
($args:expr, [$($value:expr),+ $(,)?] $(,)?) => {
|
||||
$(
|
||||
assert!($args.contains(&$value.to_string()), "missing {}", $value);
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_args_lack {
|
||||
($args:expr, [$($value:expr),+ $(,)?] $(,)?) => {
|
||||
$(
|
||||
assert!(!$args.contains(&$value.to_string()), "unexpected {}", $value);
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_no_arg_contains {
|
||||
($args:expr, $fragment:expr $(,)?) => {
|
||||
assert!(!$args.iter().any(|arg| arg.contains($fragment)));
|
||||
};
|
||||
}
|
||||
|
||||
fn arg_value_after<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
let index = args.iter().position(|arg| arg == name)?;
|
||||
args.get(index + 1).map(String::as_str)
|
||||
}
|
||||
|
||||
fn assert_binary_candidates_include(home: &Path, expected: &[PathBuf]) {
|
||||
let candidates = claude_binary_candidates_for_home(home);
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_cli_returns_status() {
|
||||
let status = check_cli();
|
||||
@@ -617,6 +732,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_binary_candidates_include_nvm_managed_node_installs() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let claude = home.path().join(".nvm/versions/node/v22.12.0/bin/claude");
|
||||
std::fs::create_dir_all(claude.parent().unwrap()).unwrap();
|
||||
std::fs::write(&claude, "#!/bin/sh\n").unwrap();
|
||||
|
||||
let candidates = claude_binary_candidates_for_home(home.path());
|
||||
|
||||
assert!(candidates.contains(&claude), "missing {}", claude.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_args_use_safe_mode_without_bash_by_default() {
|
||||
let args = build_agent_args(&agent_request!(
|
||||
"Rename the note",
|
||||
None,
|
||||
AiAgentPermissionMode::Safe,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_args_contain!(
|
||||
args,
|
||||
["--strict-mcp-config", "--permission-mode", "acceptEdits"]
|
||||
);
|
||||
assert_args_contain!(args, ["Read,Edit,MultiEdit,Write,Glob,Grep,LS"]);
|
||||
assert_no_arg_contains!(args, "Bash");
|
||||
assert_args_lack!(args, ["--allowedTools"]);
|
||||
assert_args_lack!(args, ["--dangerously-skip-permissions"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_args_allow_bash_in_power_user_mode_without_dangerous_bypass() {
|
||||
let args = build_agent_args(&agent_request!(
|
||||
"Rename the note",
|
||||
None,
|
||||
AiAgentPermissionMode::PowerUser,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_args_contain!(args, ["--strict-mcp-config"]);
|
||||
assert_args_contain!(args, ["Read,Edit,MultiEdit,Write,Glob,Grep,LS,Bash"]);
|
||||
assert_args_lack!(args, ["--dangerously-skip-permissions"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_args_preapprove_bash_for_power_user_runs() {
|
||||
let args = build_agent_args(&agent_request!(
|
||||
"Run a local script",
|
||||
None,
|
||||
AiAgentPermissionMode::PowerUser,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(arg_value_after(&args, "--allowedTools"), Some("Bash"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_mcp_config_is_valid_json() {
|
||||
if let Ok(config_str) = build_mcp_config("/tmp/test-vault") {
|
||||
@@ -636,6 +808,7 @@ mod tests {
|
||||
session_id: String::new(),
|
||||
tool_inputs: HashMap::new(),
|
||||
current_tool_id: None,
|
||||
emitted_text: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -765,10 +938,35 @@ mod tests {
|
||||
{ "type": "tool_use", "id": "tu_1", "name": "search_notes", "input": {} }
|
||||
] }
|
||||
}));
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events.len(), 2);
|
||||
assert!(
|
||||
matches!(&events[0], ClaudeStreamEvent::ToolStart { tool_name, tool_id, .. } if tool_name == "search_notes" && tool_id == "tu_1")
|
||||
matches!(&events[0], ClaudeStreamEvent::TextDelta { text } if text == "Let me search.")
|
||||
);
|
||||
assert!(
|
||||
matches!(&events[1], ClaudeStreamEvent::ToolStart { tool_name, tool_id, .. } if tool_name == "search_notes" && tool_id == "tu_1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_event_result_after_text_delta_does_not_duplicate_response_text() {
|
||||
let (state, events) = run_dispatch_sequence(vec![
|
||||
serde_json::json!({
|
||||
"type": "stream_event",
|
||||
"event": { "type": "content_block_delta", "delta": { "type": "text_delta", "text": "Visible reply" } }
|
||||
}),
|
||||
serde_json::json!({
|
||||
"type": "result",
|
||||
"session_id": "session-1",
|
||||
"result": "Visible reply"
|
||||
}),
|
||||
]);
|
||||
|
||||
assert_eq!(state.session_id, "session-1");
|
||||
assert!(matches!(&events[..],
|
||||
[
|
||||
ClaudeStreamEvent::TextDelta { text },
|
||||
ClaudeStreamEvent::Result { text: result_text, session_id },
|
||||
] if text == "Visible reply" && result_text.is_empty() && session_id == "session-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1142,52 +1340,31 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn build_chat_args_basic() {
|
||||
let req = ChatStreamRequest {
|
||||
message: "hello".into(),
|
||||
system_prompt: None,
|
||||
session_id: None,
|
||||
};
|
||||
let args = build_chat_args(&req);
|
||||
assert!(args.contains(&"-p".to_string()));
|
||||
assert!(args.contains(&"hello".to_string()));
|
||||
assert!(args.contains(&"stream-json".to_string()));
|
||||
assert!(!args.contains(&"--system-prompt".to_string()));
|
||||
assert!(!args.contains(&"--resume".to_string()));
|
||||
let args = build_chat_args(&chat_request!("hello", None, None));
|
||||
|
||||
assert_args_contain!(args, ["-p", "hello", "stream-json"]);
|
||||
assert_args_lack!(args, ["--system-prompt", "--resume"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_chat_args_with_system_prompt() {
|
||||
let req = ChatStreamRequest {
|
||||
message: "hi".into(),
|
||||
system_prompt: Some("You are helpful.".into()),
|
||||
session_id: None,
|
||||
};
|
||||
let args = build_chat_args(&req);
|
||||
assert!(args.contains(&"--system-prompt".to_string()));
|
||||
assert!(args.contains(&"You are helpful.".to_string()));
|
||||
let args = build_chat_args(&chat_request!("hi", Some("You are helpful."), None));
|
||||
|
||||
assert_args_contain!(args, ["--system-prompt", "You are helpful."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_chat_args_empty_system_prompt_is_skipped() {
|
||||
let req = ChatStreamRequest {
|
||||
message: "hi".into(),
|
||||
system_prompt: Some(String::new()),
|
||||
session_id: None,
|
||||
};
|
||||
let args = build_chat_args(&req);
|
||||
let args = build_chat_args(&chat_request!("hi", Some(""), None));
|
||||
|
||||
assert!(!args.contains(&"--system-prompt".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_chat_args_with_session_id() {
|
||||
let req = ChatStreamRequest {
|
||||
message: "continue".into(),
|
||||
system_prompt: None,
|
||||
session_id: Some("sess-abc".into()),
|
||||
};
|
||||
let args = build_chat_args(&req);
|
||||
assert!(args.contains(&"--resume".to_string()));
|
||||
assert!(args.contains(&"sess-abc".to_string()));
|
||||
let args = build_chat_args(&chat_request!("continue", None, Some("sess-abc")));
|
||||
|
||||
assert_args_contain!(args, ["--resume", "sess-abc"]);
|
||||
}
|
||||
|
||||
// --- build_agent_args ---
|
||||
@@ -1195,46 +1372,44 @@ mod tests {
|
||||
#[test]
|
||||
fn build_agent_args_basic() {
|
||||
// build_agent_args calls build_mcp_config which needs mcp_server_dir
|
||||
if let Ok(args) = build_agent_args(&AgentStreamRequest {
|
||||
message: "create note".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
}) {
|
||||
assert!(args.contains(&"-p".to_string()));
|
||||
assert!(args.contains(&"create note".to_string()));
|
||||
assert!(args.contains(&"--mcp-config".to_string()));
|
||||
assert!(args.contains(&"--strict-mcp-config".to_string()));
|
||||
assert!(args.contains(&"--permission-mode".to_string()));
|
||||
assert!(args.contains(&"acceptEdits".to_string()));
|
||||
assert!(args.contains(&"--tools".to_string()));
|
||||
assert!(args.contains(&"Read,Edit,MultiEdit,Write,Glob,Grep,LS".to_string()));
|
||||
assert!(!args.contains(&"--dangerously-skip-permissions".to_string()));
|
||||
assert!(!args.contains(&"bypassPermissions".to_string()));
|
||||
assert!(!args.contains(&"Bash".to_string()));
|
||||
assert!(args.contains(&"--no-session-persistence".to_string()));
|
||||
assert!(!args.contains(&"--append-system-prompt".to_string()));
|
||||
if let Ok(args) = build_agent_args(&agent_request!(
|
||||
"create note",
|
||||
None,
|
||||
AiAgentPermissionMode::Safe,
|
||||
)) {
|
||||
assert_args_contain!(args, ["-p", "create note", "--mcp-config"]);
|
||||
assert_args_contain!(args, ["--strict-mcp-config", "--permission-mode"]);
|
||||
assert_args_contain!(args, ["acceptEdits", "--tools"]);
|
||||
assert_args_contain!(args, ["Read,Edit,MultiEdit,Write,Glob,Grep,LS"]);
|
||||
assert_args_contain!(args, ["--no-session-persistence"]);
|
||||
assert_args_lack!(
|
||||
args,
|
||||
[
|
||||
"--dangerously-skip-permissions",
|
||||
"bypassPermissions",
|
||||
"--append-system-prompt",
|
||||
],
|
||||
);
|
||||
assert_no_arg_contains!(args, "Bash");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_agent_args_with_system_prompt() {
|
||||
if let Ok(args) = build_agent_args(&AgentStreamRequest {
|
||||
message: "do it".into(),
|
||||
system_prompt: Some("Act as expert.".into()),
|
||||
vault_path: "/tmp/v".into(),
|
||||
}) {
|
||||
assert!(args.contains(&"--append-system-prompt".to_string()));
|
||||
assert!(args.contains(&"Act as expert.".to_string()));
|
||||
if let Ok(args) = build_agent_args(&agent_request!(
|
||||
"do it",
|
||||
Some("Act as expert."),
|
||||
AiAgentPermissionMode::Safe,
|
||||
)) {
|
||||
assert_args_contain!(args, ["--append-system-prompt", "Act as expert."]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_agent_args_empty_system_prompt_is_skipped() {
|
||||
if let Ok(args) = build_agent_args(&AgentStreamRequest {
|
||||
message: "x".into(),
|
||||
system_prompt: Some(String::new()),
|
||||
vault_path: "/tmp/v".into(),
|
||||
}) {
|
||||
if let Ok(args) =
|
||||
build_agent_args(&agent_request!("x", Some(""), AiAgentPermissionMode::Safe))
|
||||
{
|
||||
assert!(!args.contains(&"--append-system-prompt".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -1244,7 +1419,6 @@ mod tests {
|
||||
#[test]
|
||||
fn claude_binary_candidates_include_supported_local_and_toolchain_installs() {
|
||||
let home = PathBuf::from("/Users/alex");
|
||||
let candidates = claude_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".local/bin/claude"),
|
||||
home.join(".claude/local/claude"),
|
||||
@@ -1252,32 +1426,30 @@ mod tests {
|
||||
home.join(".npm-global/bin/claude"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
assert_binary_candidates_include(&home, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_binary_candidates_include_linuxbrew_installs() {
|
||||
let home = PathBuf::from("/home/alex");
|
||||
let expected = [
|
||||
home.join(".linuxbrew/bin/claude"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/claude"),
|
||||
];
|
||||
|
||||
assert_binary_candidates_include(&home, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_binary_candidates_include_windows_exe_installs() {
|
||||
let home = PathBuf::from(r"C:\Users\alex");
|
||||
let candidates = claude_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".local/bin/claude.exe"),
|
||||
home.join(".claude/local/claude.exe"),
|
||||
home.join("AppData/Roaming/npm/claude.cmd"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
assert_binary_candidates_include(&home, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1293,9 +1465,19 @@ mod tests {
|
||||
let claude = dir.path().join(".local/bin/claude.exe");
|
||||
std::fs::create_dir_all(claude.parent().unwrap()).unwrap();
|
||||
std::fs::write(&claude, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
find_existing_binary(claude_binary_candidates_for_home(dir.path())),
|
||||
crate::cli_agent_runtime::find_executable_binary_candidate(
|
||||
claude_binary_candidates_for_home(dir.path()),
|
||||
"Claude CLI",
|
||||
)
|
||||
.unwrap(),
|
||||
Some(claude)
|
||||
);
|
||||
}
|
||||
@@ -1333,6 +1515,7 @@ mod tests {
|
||||
message: "test".into(),
|
||||
system_prompt: Some("sys".into()),
|
||||
vault_path: "/tmp/nonexistent".into(),
|
||||
permission_mode: AiAgentPermissionMode::Safe,
|
||||
};
|
||||
let mut events = vec![];
|
||||
let result = run_agent_stream(req, |e| events.push(e));
|
||||
@@ -1345,7 +1528,7 @@ mod tests {
|
||||
let mut events = vec![];
|
||||
let result = run_claude_subprocess(&fake_bin, &[], None, &mut |e| events.push(e));
|
||||
assert!(result.is_err());
|
||||
assert!(result.unwrap_err().contains("Failed to spawn"));
|
||||
assert!(result.unwrap_err().contains("Failed to start claude"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
369
src-tauri/src/cli_agent_runtime.rs
Normal file
369
src-tauri/src/cli_agent_runtime.rs
Normal file
@@ -0,0 +1,369 @@
|
||||
use crate::ai_agents::{AiAgentPermissionMode, AiAgentStreamEvent};
|
||||
use serde::Deserialize;
|
||||
use std::ffi::OsString;
|
||||
use std::io::BufRead;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AgentStreamRequest {
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub vault_path: String,
|
||||
pub permission_mode: AiAgentPermissionMode,
|
||||
}
|
||||
|
||||
pub(crate) struct JsonLineRun {
|
||||
pub session_id: String,
|
||||
pub stderr_output: String,
|
||||
pub status: ExitStatus,
|
||||
}
|
||||
|
||||
pub(crate) fn build_prompt(message: &str, system_prompt: Option<&str>) -> String {
|
||||
match system_prompt
|
||||
.map(str::trim)
|
||||
.filter(|prompt| !prompt.is_empty())
|
||||
{
|
||||
Some(system_prompt) => {
|
||||
format!("System instructions:\n{system_prompt}\n\nUser request:\n{message}")
|
||||
}
|
||||
None => message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_server_path_string() -> Result<String, String> {
|
||||
Ok(crate::mcp::mcp_server_dir()?
|
||||
.join("index.js")
|
||||
.to_str()
|
||||
.ok_or("Invalid MCP server path")?
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn version_for_binary(binary: &PathBuf) -> Option<String> {
|
||||
let mut command = crate::hidden_command(binary);
|
||||
configure_agent_command_environment(&mut command, binary);
|
||||
command
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn configure_agent_command_environment(command: &mut Command, binary: &Path) {
|
||||
if let Some(path) = expanded_agent_path(binary) {
|
||||
command.env("PATH", path);
|
||||
}
|
||||
}
|
||||
|
||||
fn expanded_agent_path(binary: &Path) -> Option<OsString> {
|
||||
let mut paths = std::env::var_os("PATH")
|
||||
.map(|path| std::env::split_paths(&path).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
|
||||
for candidate in agent_path_candidates(binary) {
|
||||
push_unique_path(&mut paths, candidate);
|
||||
}
|
||||
|
||||
std::env::join_paths(paths).ok()
|
||||
}
|
||||
|
||||
fn agent_path_candidates(binary: &Path) -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
|
||||
if let Some(parent) = binary
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
{
|
||||
candidates.push(parent.to_path_buf());
|
||||
}
|
||||
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
candidates.extend([
|
||||
home.join(".local/bin"),
|
||||
home.join(".local/share/mise/shims"),
|
||||
home.join(".asdf/shims"),
|
||||
home.join(".npm-global/bin"),
|
||||
home.join(".npm/bin"),
|
||||
home.join(".bun/bin"),
|
||||
home.join(".linuxbrew/bin"),
|
||||
home.join("AppData/Roaming/npm"),
|
||||
home.join("AppData/Local/pnpm"),
|
||||
home.join("scoop/shims"),
|
||||
]);
|
||||
}
|
||||
|
||||
candidates.extend([
|
||||
PathBuf::from("/opt/homebrew/bin"),
|
||||
PathBuf::from("/usr/local/bin"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin"),
|
||||
]);
|
||||
|
||||
candidates
|
||||
}
|
||||
|
||||
fn push_unique_path(paths: &mut Vec<PathBuf>, candidate: PathBuf) {
|
||||
if candidate.as_os_str().is_empty() {
|
||||
return;
|
||||
}
|
||||
if paths.iter().any(|path| path == &candidate) {
|
||||
return;
|
||||
}
|
||||
paths.push(candidate);
|
||||
}
|
||||
|
||||
pub(crate) fn find_executable_binary_candidate(
|
||||
candidates: Vec<PathBuf>,
|
||||
agent_label: &str,
|
||||
) -> Result<Option<PathBuf>, String> {
|
||||
let mut first_unusable_candidate = None;
|
||||
|
||||
for candidate in candidates {
|
||||
if !candidate.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_executable_file(&candidate) {
|
||||
return Ok(Some(candidate));
|
||||
}
|
||||
|
||||
if first_unusable_candidate.is_none() {
|
||||
first_unusable_candidate = Some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
match first_unusable_candidate {
|
||||
Some(candidate) => Err(format!(
|
||||
"{agent_label} binary found at {} but it is not executable. Fix the file permissions or reinstall the CLI.",
|
||||
candidate.display()
|
||||
)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_executable_file(path: &Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
std::fs::metadata(path)
|
||||
.map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
path.is_file()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_json_line(
|
||||
line: Result<String, std::io::Error>,
|
||||
) -> Result<Option<serde_json::Value>, String> {
|
||||
let line = line.map_err(|error| format!("Read error: {error}"))?;
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(serde_json::from_str::<serde_json::Value>(trimmed).ok())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_ai_agent_json_line<F>(
|
||||
line: Result<String, std::io::Error>,
|
||||
emit: &mut F,
|
||||
) -> Option<serde_json::Value>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
match parse_json_line(line) {
|
||||
Ok(json) => json,
|
||||
Err(message) => {
|
||||
emit(AiAgentStreamEvent::Error { message });
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_json_line_process<Event, F, H>(
|
||||
mut command: Command,
|
||||
process_name: &'static str,
|
||||
emit: &mut F,
|
||||
error_event: impl Fn(String) -> Event,
|
||||
mut handle_json: H,
|
||||
) -> Result<JsonLineRun, String>
|
||||
where
|
||||
F: FnMut(Event),
|
||||
H: FnMut(&serde_json::Value, &mut F, &mut String),
|
||||
{
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format_spawn_error(process_name, &error))?;
|
||||
let stdout = child.stdout.take().ok_or("No stdout handle")?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
let mut session_id = String::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
match parse_json_line(line) {
|
||||
Ok(Some(json)) => handle_json(&json, emit, &mut session_id),
|
||||
Ok(None) => {}
|
||||
Err(message) => {
|
||||
emit(error_event(message));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let stderr_output = child
|
||||
.stderr
|
||||
.take()
|
||||
.and_then(|stderr| std::io::read_to_string(stderr).ok())
|
||||
.unwrap_or_default();
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|error| format!("Wait failed: {error}"))?;
|
||||
|
||||
Ok(JsonLineRun {
|
||||
session_id,
|
||||
stderr_output,
|
||||
status,
|
||||
})
|
||||
}
|
||||
|
||||
fn format_spawn_error(process_name: &str, error: &std::io::Error) -> String {
|
||||
if error.kind() == std::io::ErrorKind::NotFound {
|
||||
return format!(
|
||||
"Failed to start {process_name}: the CLI or one of its runtime dependencies was not found. If it was installed with Homebrew, make sure /opt/homebrew/bin or /usr/local/bin contains the CLI and Node.js, then restart Tolaria. Details: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
format!("Failed to spawn {process_name}: {error}")
|
||||
}
|
||||
|
||||
pub(crate) fn run_ai_agent_json_stream<F>(
|
||||
command: Command,
|
||||
process_name: &'static str,
|
||||
mut emit: F,
|
||||
session_id: impl Fn(&serde_json::Value) -> Option<&str>,
|
||||
dispatch_event: impl Fn(&serde_json::Value, &mut F),
|
||||
format_error: impl Fn(String, String) -> String,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let run = run_json_line_process(
|
||||
command,
|
||||
process_name,
|
||||
&mut emit,
|
||||
|message| AiAgentStreamEvent::Error { message },
|
||||
|json, emit, active_session_id| {
|
||||
if let Some(id) = session_id(json) {
|
||||
*active_session_id = id.to_string();
|
||||
}
|
||||
dispatch_event(json, emit);
|
||||
},
|
||||
)?;
|
||||
|
||||
if !run.status.success() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: format_error(run.stderr_output, run.status.to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
emit(AiAgentStreamEvent::Done);
|
||||
Ok(run.session_id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn build_prompt_keeps_system_prompt_first() {
|
||||
let prompt = build_prompt("Rename the note", Some("Be concise"));
|
||||
|
||||
assert!(prompt.starts_with("System instructions:\nBe concise"));
|
||||
assert!(prompt.contains("User request:\nRename the note"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_prompt_skips_blank_system_prompt() {
|
||||
assert_eq!(
|
||||
build_prompt("Rename the note", Some(" ")),
|
||||
"Rename the note"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_json_line_reports_read_errors_and_skips_blank_or_invalid_lines() {
|
||||
assert!(parse_json_line(Ok(" ".into())).unwrap().is_none());
|
||||
assert!(parse_json_line(Ok("not json".into())).unwrap().is_none());
|
||||
|
||||
let error = parse_json_line(Err(std::io::Error::other("broken pipe"))).unwrap_err();
|
||||
assert!(error.contains("broken pipe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_command_environment_keeps_homebrew_shims_available() {
|
||||
let mut command = Command::new("/opt/homebrew/bin/codex");
|
||||
configure_agent_command_environment(&mut command, Path::new("/opt/homebrew/bin/codex"));
|
||||
let path = command
|
||||
.get_envs()
|
||||
.find(|(key, _)| *key == std::ffi::OsStr::new("PATH"))
|
||||
.and_then(|(_, value)| value)
|
||||
.expect("PATH should be set");
|
||||
let paths = std::env::split_paths(path).collect::<Vec<_>>();
|
||||
|
||||
assert!(paths.contains(&PathBuf::from("/opt/homebrew/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/usr/local/bin")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_not_found_errors_explain_gui_path_runtime_dependencies() {
|
||||
let error = std::io::Error::new(std::io::ErrorKind::NotFound, "No such file or directory");
|
||||
let message = format_spawn_error("codex", &error);
|
||||
|
||||
assert!(message.contains("Failed to start codex"));
|
||||
assert!(message.contains("/opt/homebrew/bin"));
|
||||
assert!(message.contains("Node.js"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn executable_binary_candidate_skips_unusable_file_when_later_candidate_works() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let unusable = dir.path().join("codex-unusable");
|
||||
let executable = dir.path().join("codex");
|
||||
std::fs::write(&unusable, "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(&executable, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&unusable, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let found =
|
||||
find_executable_binary_candidate(vec![unusable, executable.clone()], "Codex CLI")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(found, Some(executable));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn executable_binary_candidate_reports_unusable_file_when_no_candidate_works() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let unusable = dir.path().join("opencode");
|
||||
std::fs::write(&unusable, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&unusable, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
|
||||
let error =
|
||||
find_executable_binary_candidate(vec![unusable.clone()], "OpenCode CLI").unwrap_err();
|
||||
|
||||
assert!(error.contains("OpenCode CLI binary found"));
|
||||
assert!(error.contains(&unusable.display().to_string()));
|
||||
assert!(error.contains("not executable"));
|
||||
}
|
||||
}
|
||||
1063
src-tauri/src/codex_cli.rs
Normal file
1063
src-tauri/src/codex_cli.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,7 @@
|
||||
#[cfg(desktop)]
|
||||
use crate::ai_agents::{AiAgentStreamRequest, AiAgentsStatus};
|
||||
#[cfg(desktop)]
|
||||
use crate::ai_models::{AiModelProviderTestRequest, AiModelStreamRequest};
|
||||
use crate::claude_cli::{ChatStreamRequest, ClaudeCliStatus};
|
||||
use crate::vault::VaultAiGuidanceStatus;
|
||||
|
||||
@@ -81,14 +83,54 @@ define_desktop_stream_command!(
|
||||
crate::claude_cli::run_chat_stream
|
||||
);
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn normalize_agent_request(mut request: AiAgentStreamRequest) -> AiAgentStreamRequest {
|
||||
request.vault_path = expand_tilde(&request.vault_path).into_owned();
|
||||
request
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn run_normalized_ai_agent_stream(
|
||||
request: AiAgentStreamRequest,
|
||||
emitter: StreamEmitter<crate::ai_agents::AiAgentStreamEvent>,
|
||||
) -> Result<String, String> {
|
||||
crate::ai_agents::run_ai_agent_stream(normalize_agent_request(request), emitter)
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
define_desktop_stream_command!(
|
||||
stream_ai_agent,
|
||||
AiAgentStreamRequest,
|
||||
"ai-agent-stream",
|
||||
crate::ai_agents::run_ai_agent_stream
|
||||
run_normalized_ai_agent_stream
|
||||
);
|
||||
|
||||
#[cfg(desktop)]
|
||||
define_desktop_stream_command!(
|
||||
stream_ai_model,
|
||||
AiModelStreamRequest,
|
||||
"ai-model-stream",
|
||||
crate::ai_models::run_ai_model_stream
|
||||
);
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub fn save_ai_model_provider_api_key(provider_id: String, api_key: String) -> Result<(), String> {
|
||||
crate::ai_models::save_provider_api_key(provider_id, api_key)
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub fn delete_ai_model_provider_api_key(provider_id: String) -> Result<(), String> {
|
||||
crate::ai_models::delete_provider_api_key(provider_id)
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub fn test_ai_model_provider(request: AiModelProviderTestRequest) -> Result<String, String> {
|
||||
crate::ai_models::test_ai_model_provider(request)
|
||||
}
|
||||
|
||||
// ── Claude CLI (mobile stubs) ───────────────────────────────────────────────
|
||||
|
||||
#[cfg(mobile)]
|
||||
@@ -120,6 +162,10 @@ pub fn get_ai_agents_status() -> AiAgentsStatus {
|
||||
installed: false,
|
||||
version: None,
|
||||
},
|
||||
gemini: crate::ai_agents::AiAgentAvailability {
|
||||
installed: false,
|
||||
version: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,11 +187,84 @@ pub async fn stream_ai_agent(
|
||||
Err("CLI AI agents are not available on mobile".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub async fn stream_ai_model(
|
||||
_app_handle: tauri::AppHandle,
|
||||
_request: crate::ai_models::AiModelStreamRequest,
|
||||
) -> Result<String, String> {
|
||||
Err("Direct AI model chat is not available in this mobile build yet.".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub fn save_ai_model_provider_api_key(
|
||||
_provider_id: String,
|
||||
_api_key: String,
|
||||
) -> Result<(), String> {
|
||||
Err("Local AI provider secret storage is only available in the desktop app.".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub fn delete_ai_model_provider_api_key(_provider_id: String) -> Result<(), String> {
|
||||
Err("Local AI provider secret storage is only available in the desktop app.".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub fn test_ai_model_provider(
|
||||
_request: crate::ai_models::AiModelProviderTestRequest,
|
||||
) -> Result<String, String> {
|
||||
Err("Direct AI model tests are not available in this mobile build yet.".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vault::AiGuidanceFileState;
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn normalize_agent_request_expands_tilde_in_vault_path() {
|
||||
use crate::ai_agents::AiAgentId;
|
||||
|
||||
let home = dirs::home_dir().unwrap();
|
||||
let request = AiAgentStreamRequest {
|
||||
agent: AiAgentId::ClaudeCode,
|
||||
message: "hi".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "~/Vaults/content".into(),
|
||||
permission_mode: None,
|
||||
};
|
||||
|
||||
let normalized = normalize_agent_request(request);
|
||||
|
||||
assert_eq!(
|
||||
normalized.vault_path,
|
||||
format!("{}/Vaults/content", home.display()),
|
||||
"vault_path must be tilde-expanded so spawned agents can chdir into it",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn normalize_agent_request_leaves_absolute_vault_path_untouched() {
|
||||
use crate::ai_agents::AiAgentId;
|
||||
|
||||
let request = AiAgentStreamRequest {
|
||||
agent: AiAgentId::Codex,
|
||||
message: "hi".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/Users/example/vault".into(),
|
||||
permission_mode: None,
|
||||
};
|
||||
|
||||
let normalized = normalize_agent_request(request);
|
||||
|
||||
assert_eq!(normalized.vault_path, "/Users/example/vault");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guidance_commands_report_and_restore_vault_guidance_files() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
@@ -154,14 +273,17 @@ mod tests {
|
||||
let initial = get_vault_ai_guidance_status(vault_path.clone()).unwrap();
|
||||
assert_eq!(initial.agents_state, AiGuidanceFileState::Missing);
|
||||
assert_eq!(initial.claude_state, AiGuidanceFileState::Missing);
|
||||
assert_eq!(initial.gemini_state, AiGuidanceFileState::Missing);
|
||||
assert!(initial.can_restore);
|
||||
|
||||
let restored = restore_vault_ai_guidance(vault_path.clone()).unwrap();
|
||||
assert_eq!(restored.agents_state, AiGuidanceFileState::Managed);
|
||||
assert_eq!(restored.claude_state, AiGuidanceFileState::Managed);
|
||||
assert_eq!(restored.gemini_state, AiGuidanceFileState::Managed);
|
||||
assert!(!restored.can_restore);
|
||||
|
||||
assert!(dir.path().join("AGENTS.md").exists());
|
||||
assert!(dir.path().join("CLAUDE.md").exists());
|
||||
assert!(dir.path().join("GEMINI.md").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,7 +214,7 @@ fn has_tolaria_vault_marker(path: &std::path::Path) -> bool {
|
||||
pub fn init_git_repo(vault_path: VaultPathArg) -> Result<(), String> {
|
||||
let vault_path = expand_tilde(&vault_path);
|
||||
validate_git_init_target(&vault_path)?;
|
||||
crate::git::init_repo(&vault_path)
|
||||
crate::git::init_repo(std::path::Path::new(vault_path.as_ref()))
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
|
||||
167
src-tauri/src/commands/memory.rs
Normal file
167
src-tauri/src/commands/memory.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
use serde::Serialize;
|
||||
use std::process::Command;
|
||||
|
||||
const WEBKIT_AUX_PID_WINDOW: u32 = 512;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProcessMemoryEntry {
|
||||
pub pid: u32,
|
||||
pub parent_pid: u32,
|
||||
pub rss_bytes: u64,
|
||||
pub role: String,
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProcessMemorySnapshot {
|
||||
pub current_pid: u32,
|
||||
pub total_rss_bytes: u64,
|
||||
pub entries: Vec<ProcessMemoryEntry>,
|
||||
}
|
||||
|
||||
struct ProcessRow {
|
||||
pid: u32,
|
||||
parent_pid: u32,
|
||||
rss_kib: u64,
|
||||
command: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_process_memory_snapshot() -> Result<ProcessMemorySnapshot, String> {
|
||||
let current_pid = std::process::id();
|
||||
let entries = collect_related_process_memory(current_pid)?;
|
||||
let total_rss_bytes = entries.iter().map(|entry| entry.rss_bytes).sum();
|
||||
|
||||
Ok(ProcessMemorySnapshot {
|
||||
current_pid,
|
||||
total_rss_bytes,
|
||||
entries,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_related_process_memory(current_pid: u32) -> Result<Vec<ProcessMemoryEntry>, String> {
|
||||
let rows = read_process_rows()?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter_map(|row| related_process_entry(row, current_pid))
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn related_process_entry(row: ProcessRow, current_pid: u32) -> Option<ProcessMemoryEntry> {
|
||||
let role = classify_related_process(&row, current_pid)?;
|
||||
Some(ProcessMemoryEntry {
|
||||
pid: row.pid,
|
||||
parent_pid: row.parent_pid,
|
||||
rss_bytes: row.rss_kib.saturating_mul(1024),
|
||||
role,
|
||||
command: row.command,
|
||||
})
|
||||
}
|
||||
|
||||
fn classify_related_process(row: &ProcessRow, current_pid: u32) -> Option<String> {
|
||||
if row.pid == current_pid {
|
||||
return Some("app".to_string());
|
||||
}
|
||||
if !is_nearby_webkit_auxiliary(row, current_pid) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if row.command.contains("WebKit.WebContent") {
|
||||
return Some("webkit-webcontent".to_string());
|
||||
}
|
||||
if row.command.contains("WebKit.GPU") {
|
||||
return Some("webkit-gpu".to_string());
|
||||
}
|
||||
if row.command.contains("WebKit.Networking") {
|
||||
return Some("webkit-networking".to_string());
|
||||
}
|
||||
Some("webkit".to_string())
|
||||
}
|
||||
|
||||
fn is_nearby_webkit_auxiliary(row: &ProcessRow, current_pid: u32) -> bool {
|
||||
row.pid > current_pid
|
||||
&& row.pid.saturating_sub(current_pid) <= WEBKIT_AUX_PID_WINDOW
|
||||
&& row.command.contains("com.apple.WebKit.")
|
||||
}
|
||||
|
||||
fn parse_process_row(line: &str) -> Option<ProcessRow> {
|
||||
let mut fields = line.split_whitespace();
|
||||
let pid = fields.next()?.parse().ok()?;
|
||||
let parent_pid = fields.next()?.parse().ok()?;
|
||||
let rss_kib = fields.next()?.parse().ok()?;
|
||||
let command = fields.collect::<Vec<_>>().join(" ");
|
||||
if command.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(ProcessRow {
|
||||
pid,
|
||||
parent_pid,
|
||||
rss_kib,
|
||||
command,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn read_process_rows() -> Result<Vec<ProcessRow>, String> {
|
||||
let output = Command::new("ps")
|
||||
.args(["-axo", "pid=,ppid=,rss=,command="])
|
||||
.output()
|
||||
.map_err(|error| format!("Failed to sample process memory: {error}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err("Failed to sample process memory with ps".to_string());
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
Ok(stdout.lines().filter_map(parse_process_row).collect())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn read_process_rows() -> Result<Vec<ProcessRow>, String> {
|
||||
Err("Process memory snapshots are only implemented on Unix platforms".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_ps_rows_with_spaced_commands() {
|
||||
let row = parse_process_row(" 42 1 1024 /System/WebKit WebContent").unwrap();
|
||||
|
||||
assert_eq!(row.pid, 42);
|
||||
assert_eq!(row.parent_pid, 1);
|
||||
assert_eq!(row.rss_kib, 1024);
|
||||
assert_eq!(row.command, "/System/WebKit WebContent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_nearby_webkit_auxiliaries() {
|
||||
let row = ProcessRow {
|
||||
pid: 120,
|
||||
parent_pid: 1,
|
||||
rss_kib: 10,
|
||||
command: "/System/com.apple.WebKit.WebContent.xpc".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
classify_related_process(&row, 100),
|
||||
Some("webkit-webcontent".to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unrelated_webkit_auxiliaries() {
|
||||
let row = ProcessRow {
|
||||
pid: 900,
|
||||
parent_pid: 1,
|
||||
rss_kib: 10,
|
||||
command: "/System/com.apple.WebKit.WebContent.xpc".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(classify_related_process(&row, 100), None);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod folders;
|
||||
mod git;
|
||||
pub mod git_clone;
|
||||
mod git_connect;
|
||||
mod memory;
|
||||
mod system;
|
||||
mod vault;
|
||||
mod version;
|
||||
@@ -15,6 +16,7 @@ pub use delete::*;
|
||||
pub use folders::*;
|
||||
pub use git::*;
|
||||
pub use git_connect::*;
|
||||
pub use memory::*;
|
||||
pub use system::*;
|
||||
pub use vault::*;
|
||||
pub use version::*;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#[cfg(desktop)]
|
||||
use std::process::Command;
|
||||
use std::io::Write;
|
||||
#[cfg(desktop)]
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[cfg(desktop)]
|
||||
use crate::menu;
|
||||
@@ -131,6 +133,122 @@ pub async fn check_mcp_status(vault_path: String) -> Result<crate::mcp::McpStatu
|
||||
.map_err(|e| format!("MCP status check failed: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub async fn get_mcp_config_snippet(vault_path: String) -> Result<String, String> {
|
||||
let vault_path = super::expand_tilde(&vault_path).into_owned();
|
||||
tokio::task::spawn_blocking(move || crate::mcp::mcp_config_snippet(&vault_path))
|
||||
.await
|
||||
.map_err(|e| format!("MCP config task failed: {e}"))?
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn clipboard_command() -> Command {
|
||||
crate::hidden_command("pbcopy")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn clipboard_read_command() -> Command {
|
||||
crate::hidden_command("pbpaste")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn clipboard_command() -> Command {
|
||||
crate::hidden_command("clip.exe")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn clipboard_read_command() -> Command {
|
||||
let mut command = crate::hidden_command("powershell.exe");
|
||||
command.args(["-NoProfile", "-Command", "Get-Clipboard -Raw"]);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, not(any(target_os = "macos", target_os = "windows"))))]
|
||||
fn clipboard_command() -> Command {
|
||||
let mut command = crate::hidden_command("sh");
|
||||
command.args([
|
||||
"-c",
|
||||
"if command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; elif command -v xsel >/dev/null 2>&1; then xsel --clipboard --input; else exit 127; fi",
|
||||
]);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, not(any(target_os = "macos", target_os = "windows"))))]
|
||||
fn clipboard_read_command() -> Command {
|
||||
let mut command = crate::hidden_command("sh");
|
||||
command.args([
|
||||
"-c",
|
||||
"if command -v wl-paste >/dev/null 2>&1; then wl-paste; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard -out; elif command -v xsel >/dev/null 2>&1; then xsel --clipboard --output; else exit 127; fi",
|
||||
]);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn clipboard_failure_message(stderr: &[u8]) -> String {
|
||||
let message = String::from_utf8_lossy(stderr).trim().to_string();
|
||||
if message.is_empty() {
|
||||
"Native clipboard command failed".to_string()
|
||||
} else {
|
||||
format!("Native clipboard command failed: {message}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn write_native_clipboard(mut command: Command, text: &str) -> Result<(), String> {
|
||||
let mut child = command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to open native clipboard command: {e}"))?;
|
||||
|
||||
let mut stdin = child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| "Native clipboard command did not expose stdin".to_string())?;
|
||||
stdin
|
||||
.write_all(text.as_bytes())
|
||||
.map_err(|e| format!("Failed to write native clipboard text: {e}"))?;
|
||||
drop(stdin);
|
||||
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.map_err(|e| format!("Native clipboard command did not finish: {e}"))?;
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(clipboard_failure_message(&output.stderr))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn read_native_clipboard(mut command: Command) -> Result<String, String> {
|
||||
let output = command
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to read native clipboard text: {e}"))?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(clipboard_failure_message(&output.stderr))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub fn copy_text_to_clipboard(text: String) -> Result<(), String> {
|
||||
write_native_clipboard(clipboard_command(), &text)
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub fn read_text_from_clipboard() -> Result<String, String> {
|
||||
read_native_clipboard(clipboard_read_command())
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[tauri::command]
|
||||
pub async fn sync_mcp_bridge_vault(
|
||||
@@ -167,6 +285,24 @@ pub async fn check_mcp_status(_vault_path: String) -> Result<crate::mcp::McpStat
|
||||
Ok(crate::mcp::McpStatus::NotInstalled)
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub async fn get_mcp_config_snippet(_vault_path: String) -> Result<String, String> {
|
||||
Err("MCP is not available on mobile".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub fn copy_text_to_clipboard(_text: String) -> Result<(), String> {
|
||||
Err("Clipboard is not available on mobile".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub fn read_text_from_clipboard() -> Result<String, String> {
|
||||
Err("Clipboard is not available on mobile".into())
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
#[tauri::command]
|
||||
pub async fn sync_mcp_bridge_vault(_vault_path: Option<String>) -> Result<String, String> {
|
||||
|
||||
@@ -53,6 +53,7 @@ mod tests {
|
||||
name: "Inbox".to_string(),
|
||||
icon: None,
|
||||
color: None,
|
||||
order: None,
|
||||
sort: None,
|
||||
list_properties_display: vec![],
|
||||
filters: crate::vault::FilterGroup::All(vec![]),
|
||||
|
||||
@@ -23,6 +23,14 @@ fn with_note_path<T>(
|
||||
)
|
||||
}
|
||||
|
||||
fn with_external_file_path<T>(
|
||||
path: &Path,
|
||||
vault_path: Option<&Path>,
|
||||
action: impl FnOnce(&Path) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
with_note_path(path, vault_path, ValidatedPathMode::Existing, action)
|
||||
}
|
||||
|
||||
fn with_expanded_vault_root<T>(
|
||||
path: &Path,
|
||||
action: impl FnOnce(&Path) -> Result<T, String>,
|
||||
@@ -75,6 +83,26 @@ pub fn sync_vault_asset_scope_for_window(
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_vault_file_external(
|
||||
app_handle: tauri::AppHandle,
|
||||
path: PathBuf,
|
||||
vault_path: Option<PathBuf>,
|
||||
) -> Result<(), String> {
|
||||
with_external_file_path(path.as_path(), vault_path.as_deref(), |validated_path| {
|
||||
open_path_with_default_app(&app_handle, validated_path)
|
||||
})
|
||||
}
|
||||
|
||||
fn open_path_with_default_app(app_handle: &tauri::AppHandle, path: &Path) -> Result<(), String> {
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
app_handle
|
||||
.opener()
|
||||
.open_path(path.to_string_lossy().into_owned(), None::<String>)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn with_writable_note_path<T>(
|
||||
path: PathBuf,
|
||||
vault_path: Option<PathBuf>,
|
||||
@@ -101,6 +129,20 @@ pub fn get_note_content(path: PathBuf, vault_path: Option<PathBuf>) -> Result<St
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn validate_note_content(
|
||||
path: PathBuf,
|
||||
content: String,
|
||||
vault_path: Option<PathBuf>,
|
||||
) -> Result<bool, String> {
|
||||
with_note_path(
|
||||
path.as_path(),
|
||||
vault_path.as_deref(),
|
||||
ValidatedPathMode::Existing,
|
||||
|validated_path| vault::note_content_matches(validated_path, &content),
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn save_note_content(
|
||||
path: PathBuf,
|
||||
@@ -229,8 +271,12 @@ pub fn list_vault(path: PathBuf) -> Result<Vec<VaultEntry>, String> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_vault_folders(path: PathBuf) -> Result<Vec<FolderNode>, String> {
|
||||
with_expanded_vault_root(path.as_path(), scan_visible_vault_folders)
|
||||
pub async fn list_vault_folders(path: PathBuf) -> Result<Vec<FolderNode>, String> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
with_expanded_vault_root(path.as_path(), scan_visible_vault_folders)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("Task panicked: {e}"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -306,8 +352,8 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_and_listing_commands_use_expanded_vault_root() {
|
||||
#[tokio::test]
|
||||
async fn folder_and_listing_commands_use_expanded_vault_root() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let root = vault_root(&dir);
|
||||
fs::write(dir.path().join("root.md"), "# Root\n").unwrap();
|
||||
@@ -322,7 +368,7 @@ mod tests {
|
||||
assert!(entries.iter().any(|entry| entry.filename == "root.md"));
|
||||
assert!(entries.iter().any(|entry| entry.filename == "project.md"));
|
||||
|
||||
let folders = list_vault_folders(root).unwrap();
|
||||
let folders = list_vault_folders(root).await.unwrap();
|
||||
assert!(folders.iter().any(|folder| folder.name == "Projects"));
|
||||
}
|
||||
|
||||
@@ -341,4 +387,53 @@ mod tests {
|
||||
.unwrap_err();
|
||||
assert!(folder_error.contains("Path must stay inside the active vault"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_file_paths_accept_files_inside_requested_vault() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let root = vault_root(&dir);
|
||||
let attachment = note_path(&dir, "attachments/photo.png");
|
||||
fs::create_dir_all(attachment.parent().unwrap()).unwrap();
|
||||
fs::write(&attachment, "image-bytes").unwrap();
|
||||
|
||||
let validated = with_external_file_path(
|
||||
attachment.as_path(),
|
||||
Some(root.as_path()),
|
||||
|validated_path| Ok(validated_path.to_path_buf()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(validated, attachment);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_file_paths_reject_files_outside_requested_vault() {
|
||||
let vault = TempDir::new().unwrap();
|
||||
let outside = TempDir::new().unwrap();
|
||||
let outside_file = outside.path().join("photo.png");
|
||||
fs::write(&outside_file, "image-bytes").unwrap();
|
||||
|
||||
let error = with_external_file_path(
|
||||
outside_file.as_path(),
|
||||
Some(vault.path()),
|
||||
|validated_path| Ok(validated_path.to_path_buf()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.contains("Path must stay inside the active vault"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_note_content_compares_against_disk() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let root = vault_root(&dir);
|
||||
let note = note_path(&dir, "note.md");
|
||||
fs::write(¬e, "# Fresh\n").unwrap();
|
||||
|
||||
assert!(
|
||||
validate_note_content(note.clone(), "# Fresh\n".to_string(), Some(root.clone()),)
|
||||
.unwrap()
|
||||
);
|
||||
assert!(!validate_note_content(note, "# Stale\n".to_string(), Some(root)).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,3 +46,90 @@ pub fn batch_archive_notes(
|
||||
Ok(count)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn note_path(dir: &tempfile::TempDir, name: &str) -> String {
|
||||
dir.path().join(name).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn write_note(path: &str, content: &str) {
|
||||
std::fs::write(path, content).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_frontmatter_command_validates_and_updates_note() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = note_path(&dir, "note.md");
|
||||
write_note(&path, "---\nStatus: Draft\n---\n# Note\n");
|
||||
|
||||
let updated = update_frontmatter(
|
||||
path.clone(),
|
||||
"Status".to_string(),
|
||||
FrontmatterValue::String("Done".to_string()),
|
||||
Some(dir.path().to_string_lossy().into_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(updated.contains("Status: Done"));
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), updated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_frontmatter_property_command_removes_existing_key() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = note_path(&dir, "note.md");
|
||||
write_note(&path, "---\nStatus: Draft\nOwner: Ada\n---\n# Note\n");
|
||||
|
||||
let updated = delete_frontmatter_property(
|
||||
path,
|
||||
"Owner".to_string(),
|
||||
Some(dir.path().to_string_lossy().into_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!updated.contains("Owner:"));
|
||||
assert!(updated.contains("Status: Draft"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_archive_notes_command_marks_each_note_archived() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let first = note_path(&dir, "first.md");
|
||||
let second = note_path(&dir, "second.md");
|
||||
write_note(&first, "---\nStatus: Draft\n---\n# First\n");
|
||||
write_note(&second, "# Second\n");
|
||||
|
||||
let count = batch_archive_notes(
|
||||
vec![first.clone(), second.clone()],
|
||||
Some(dir.path().to_string_lossy().into_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(count, 2);
|
||||
assert!(std::fs::read_to_string(first)
|
||||
.unwrap()
|
||||
.contains("_archived: true"));
|
||||
assert!(std::fs::read_to_string(second)
|
||||
.unwrap()
|
||||
.contains("_archived: true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_archive_notes_command_rejects_notes_outside_vault() {
|
||||
let vault = tempfile::TempDir::new().unwrap();
|
||||
let outside = tempfile::TempDir::new().unwrap();
|
||||
let outside_note = note_path(&outside, "outside.md");
|
||||
write_note(&outside_note, "# Outside\n");
|
||||
|
||||
let error = batch_archive_notes(
|
||||
vec![outside_note],
|
||||
Some(vault.path().to_string_lossy().into_owned()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.contains("Path must stay inside the active vault"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +87,70 @@ pub fn repair_vault(vault_path: String) -> Result<String, String> {
|
||||
let vault_path = expand_tilde(&vault_path);
|
||||
vault::migrate_is_a_to_type(&vault_path)?;
|
||||
vault::repair_config_files(&vault_path)?;
|
||||
git::ensure_gitignore(&vault_path)?;
|
||||
git::ensure_gitignore(std::path::Path::new(vault_path.as_ref()))?;
|
||||
Ok("Vault repaired".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn empty_vault_target_validation_allows_missing_or_empty_directories() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let missing = dir.path().join("new-vault");
|
||||
let empty = dir.path().join("empty-vault");
|
||||
fs::create_dir(&empty).unwrap();
|
||||
|
||||
assert_eq!(ensure_directory_is_missing_or_empty(&missing), Ok(()));
|
||||
assert_eq!(ensure_directory_is_missing_or_empty(&empty), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_vault_target_validation_rejects_files_and_nonempty_directories() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let file = dir.path().join("vault.md");
|
||||
let nonempty = dir.path().join("vault");
|
||||
fs::write(&file, "# Not a folder").unwrap();
|
||||
fs::create_dir(&nonempty).unwrap();
|
||||
fs::write(nonempty.join("note.md"), "# Existing note").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
ensure_directory_is_missing_or_empty(&file),
|
||||
Err("Choose a folder path for the new vault".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
ensure_directory_is_missing_or_empty(&nonempty),
|
||||
Err("Choose an empty folder to create a new vault".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_vault_path_uses_existing_canonical_path_or_original_path() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let existing = dir.path().join("existing");
|
||||
let missing = dir.path().join("missing");
|
||||
fs::create_dir(&existing).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
canonical_vault_path_string(&existing),
|
||||
existing.canonicalize().unwrap().to_string_lossy()
|
||||
);
|
||||
assert_eq!(
|
||||
canonical_vault_path_string(&missing),
|
||||
missing.to_string_lossy()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getting_started_target_uses_explicit_path_when_provided() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let explicit = dir.path().join("starter");
|
||||
|
||||
assert_eq!(
|
||||
resolve_getting_started_target(explicit.to_str()),
|
||||
Ok(explicit.to_string_lossy().to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,8 +112,18 @@ pub async fn search_vault(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{collect_registered_vault_roots, find_registered_vault_root};
|
||||
use super::{
|
||||
collect_registered_vault_roots, find_registered_vault_root, reload_vault_entry,
|
||||
resolve_reload_vault_path, search_vault,
|
||||
};
|
||||
use crate::vault_list::{VaultEntry as VaultListEntry, VaultList};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn write_note(root: &Path, name: &str, content: &str) -> std::path::PathBuf {
|
||||
let path = root.join(name);
|
||||
std::fs::write(&path, content).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_registered_vault_root_for_an_absolute_note_path() {
|
||||
@@ -173,4 +183,109 @@ mod tests {
|
||||
Some(nested_root),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_registered_vault_root_ignores_missing_registered_roots() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let vault_root = dir.path().join("vault");
|
||||
std::fs::create_dir_all(&vault_root).unwrap();
|
||||
let note_path = write_note(&vault_root, "note.md", "# Note\n");
|
||||
let registered_roots = vec![dir.path().join("missing"), vault_root.clone()];
|
||||
let canonical_note_path = note_path.canonicalize().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
find_registered_vault_root(canonical_note_path.as_path(), ®istered_roots),
|
||||
Some(vault_root),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_registered_vault_roots_includes_active_vault() {
|
||||
let vault_list = VaultList {
|
||||
vaults: vec![VaultListEntry {
|
||||
label: "Listed".to_string(),
|
||||
path: "/listed".to_string(),
|
||||
}],
|
||||
active_vault: Some("/active".to_string()),
|
||||
hidden_defaults: vec![],
|
||||
};
|
||||
|
||||
let roots = collect_registered_vault_roots(&vault_list);
|
||||
|
||||
assert_eq!(
|
||||
roots,
|
||||
vec![PathBuf::from("/listed"), PathBuf::from("/active")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_reload_vault_path_uses_explicit_vault_path() {
|
||||
let explicit = Path::new("/tmp/vault");
|
||||
|
||||
assert_eq!(
|
||||
resolve_reload_vault_path(Path::new("note.md"), Some(explicit)).unwrap(),
|
||||
Some(explicit.to_path_buf()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_reload_vault_path_skips_relative_note_paths() {
|
||||
assert_eq!(
|
||||
resolve_reload_vault_path(Path::new("note.md"), None).unwrap(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_vault_entry_command_reads_note_inside_vault() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let note_path = write_note(dir.path(), "note.md", "# Reloaded Title\n\nBody");
|
||||
|
||||
let entry = reload_vault_entry(note_path, Some(dir.path().to_path_buf())).unwrap();
|
||||
|
||||
assert_eq!(entry.title, "Reloaded Title");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_vault_command_uses_default_limit_and_returns_results() {
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix("scan-search-")
|
||||
.tempdir_in(std::env::current_dir().unwrap())
|
||||
.unwrap();
|
||||
write_note(dir.path(), "search.md", "# Searchable\n\nneedle");
|
||||
|
||||
let response = search_vault(
|
||||
dir.path().to_string_lossy().into_owned(),
|
||||
"needle".to_string(),
|
||||
"keyword".to_string(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.results.len(), 1);
|
||||
assert_eq!(response.results[0].title, "Searchable");
|
||||
assert_eq!(response.mode, "keyword");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_vault_command_honors_explicit_limit() {
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix("scan-search-limit-")
|
||||
.tempdir_in(std::env::current_dir().unwrap())
|
||||
.unwrap();
|
||||
write_note(dir.path(), "first.md", "# First\n\nneedle");
|
||||
write_note(dir.path(), "second.md", "# Second\n\nneedle");
|
||||
|
||||
let response = search_vault(
|
||||
dir.path().to_string_lossy().into_owned(),
|
||||
"needle".to_string(),
|
||||
"keyword".to_string(),
|
||||
Some(1),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.results.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,3 +35,60 @@ pub fn delete_view_cmd(vault_path: String, filename: String) -> Result<(), Strin
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vault::{FilterCondition, FilterGroup, FilterNode, FilterOp};
|
||||
|
||||
fn definition(name: &str) -> ViewDefinition {
|
||||
ViewDefinition {
|
||||
name: name.to_string(),
|
||||
icon: Some("star".to_string()),
|
||||
color: None,
|
||||
order: None,
|
||||
sort: Some("modified:desc".to_string()),
|
||||
list_properties_display: vec!["Priority".to_string()],
|
||||
filters: FilterGroup::All(vec![FilterNode::Condition(FilterCondition {
|
||||
field: "type".to_string(),
|
||||
op: FilterOp::Equals,
|
||||
value: Some(serde_yaml::Value::String("Project".to_string())),
|
||||
regex: false,
|
||||
})]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_commands_roundtrip_through_validated_vault_paths() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let vault_path = dir.path().to_string_lossy().to_string();
|
||||
|
||||
assert!(list_views(vault_path.clone()).unwrap().is_empty());
|
||||
|
||||
save_view_cmd(
|
||||
vault_path.clone(),
|
||||
"active-projects.yml".to_string(),
|
||||
definition("Active Projects"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let views = list_views(vault_path.clone()).unwrap();
|
||||
assert_eq!(views.len(), 1);
|
||||
assert_eq!(views[0].filename, "active-projects.yml");
|
||||
assert_eq!(views[0].definition.name, "Active Projects");
|
||||
|
||||
delete_view_cmd(vault_path.clone(), "active-projects.yml".to_string()).unwrap();
|
||||
|
||||
assert!(list_views(vault_path).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_view_command_treats_missing_backing_file_as_deleted() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let vault_path = dir.path().to_string_lossy().to_string();
|
||||
|
||||
delete_view_cmd(vault_path.clone(), "stale-view.yml".to_string()).unwrap();
|
||||
|
||||
assert!(list_views(vault_path).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
178
src-tauri/src/frontmatter/keys.rs
Normal file
178
src-tauri/src/frontmatter/keys.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct FrontmatterKeyRule {
|
||||
read_key: &'static str,
|
||||
write_key: &'static str,
|
||||
aliases: &'static [&'static str],
|
||||
canonicalize_on_write: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct FrontmatterKey<'a>(&'a str);
|
||||
|
||||
impl<'a> FrontmatterKey<'a> {
|
||||
pub(crate) fn new(key: &'a str) -> Self {
|
||||
Self(key)
|
||||
}
|
||||
|
||||
pub(crate) fn normalized(self) -> String {
|
||||
self.0.trim().to_ascii_lowercase().replace(' ', "_")
|
||||
}
|
||||
|
||||
pub(crate) fn is_reserved(self) -> bool {
|
||||
self.normalized().starts_with('_') || is_known_frontmatter_key(self)
|
||||
}
|
||||
}
|
||||
|
||||
const KNOWN_FRONTMATTER_KEYS: &[FrontmatterKeyRule] = &[
|
||||
FrontmatterKeyRule {
|
||||
read_key: "title",
|
||||
write_key: "title",
|
||||
aliases: &["title"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "type",
|
||||
write_key: "type",
|
||||
aliases: &["type", "is_a", "Is A"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "aliases",
|
||||
write_key: "aliases",
|
||||
aliases: &["aliases"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_archived",
|
||||
write_key: "_archived",
|
||||
aliases: &["_archived", "Archived", "archived"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "Status",
|
||||
write_key: "Status",
|
||||
aliases: &["Status", "status"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_icon",
|
||||
write_key: "_icon",
|
||||
aliases: &["_icon", "icon"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "color",
|
||||
write_key: "color",
|
||||
aliases: &["color"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_order",
|
||||
write_key: "_order",
|
||||
aliases: &["_order", "order"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_sidebar_label",
|
||||
write_key: "_sidebar_label",
|
||||
aliases: &["_sidebar_label", "sidebar_label", "sidebar label"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "template",
|
||||
write_key: "template",
|
||||
aliases: &["template"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_sort",
|
||||
write_key: "_sort",
|
||||
aliases: &["_sort", "sort"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "view",
|
||||
write_key: "view",
|
||||
aliases: &["view"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_width",
|
||||
write_key: "_width",
|
||||
aliases: &["_width", "width"],
|
||||
canonicalize_on_write: true,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "visible",
|
||||
write_key: "visible",
|
||||
aliases: &["visible"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_organized",
|
||||
write_key: "_organized",
|
||||
aliases: &["_organized"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_favorite",
|
||||
write_key: "_favorite",
|
||||
aliases: &["_favorite"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_favorite_index",
|
||||
write_key: "_favorite_index",
|
||||
aliases: &["_favorite_index"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
FrontmatterKeyRule {
|
||||
read_key: "_list_properties_display",
|
||||
write_key: "_list_properties_display",
|
||||
aliases: &["_list_properties_display"],
|
||||
canonicalize_on_write: false,
|
||||
},
|
||||
];
|
||||
|
||||
impl FrontmatterKeyRule {
|
||||
pub(crate) fn read_key(self) -> &'static str {
|
||||
self.read_key
|
||||
}
|
||||
|
||||
pub(crate) fn write_key(self) -> &'static str {
|
||||
self.write_key
|
||||
}
|
||||
|
||||
pub(crate) fn canonicalizes_on_write(self) -> bool {
|
||||
self.canonicalize_on_write
|
||||
}
|
||||
|
||||
fn matches(self, key: FrontmatterKey<'_>) -> bool {
|
||||
let normalized = key.normalized();
|
||||
self.aliases
|
||||
.iter()
|
||||
.any(|alias| FrontmatterKey::new(alias).normalized() == normalized)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn frontmatter_key_rule(key: FrontmatterKey<'_>) -> Option<FrontmatterKeyRule> {
|
||||
KNOWN_FRONTMATTER_KEYS
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|rule| rule.matches(key))
|
||||
}
|
||||
|
||||
pub(crate) fn canonical_known_frontmatter_key(key: FrontmatterKey<'_>) -> Option<&'static str> {
|
||||
frontmatter_key_rule(key).map(FrontmatterKeyRule::read_key)
|
||||
}
|
||||
|
||||
pub(crate) fn frontmatter_keys_match(left: FrontmatterKey<'_>, right: FrontmatterKey<'_>) -> bool {
|
||||
match (frontmatter_key_rule(left), frontmatter_key_rule(right)) {
|
||||
(Some(left_rule), Some(right_rule)) => left_rule.read_key() == right_rule.read_key(),
|
||||
_ => left.normalized() == right.normalized(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_known_frontmatter_key(key: FrontmatterKey<'_>) -> bool {
|
||||
frontmatter_key_rule(key).is_some()
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub(crate) mod keys;
|
||||
mod ops;
|
||||
#[cfg(test)]
|
||||
mod ops_update_tests;
|
||||
@@ -9,15 +10,36 @@ use std::path::Path;
|
||||
pub use ops::update_frontmatter_content;
|
||||
pub use yaml::{format_yaml_key, FrontmatterValue};
|
||||
|
||||
fn is_markdown_path(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
.is_some_and(|extension| {
|
||||
extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("markdown")
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_frontmatter_path(path: &str, file_path: &Path) -> Result<(), String> {
|
||||
if !file_path.exists() {
|
||||
return Err(format!("File does not exist: {}", path));
|
||||
}
|
||||
|
||||
if !is_markdown_path(file_path) {
|
||||
return Err(format!(
|
||||
"Frontmatter can only be updated on Markdown notes: {}",
|
||||
path
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper to read a file, apply a frontmatter transformation, and write back.
|
||||
pub fn with_frontmatter<F>(path: &str, transform: F) -> Result<String, String>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, String>,
|
||||
{
|
||||
let file_path = Path::new(path);
|
||||
if !file_path.exists() {
|
||||
return Err(format!("File does not exist: {}", path));
|
||||
}
|
||||
validate_frontmatter_path(path, file_path)?;
|
||||
|
||||
let content =
|
||||
fs::read_to_string(file_path).map_err(|e| format!("Failed to read {}: {}", path, e))?;
|
||||
@@ -58,6 +80,25 @@ mod tests {
|
||||
assert!(result.unwrap_err().contains("does not exist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_frontmatter_rejects_binary_attachment_before_utf8_read() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let attachment_dir = dir.path().join("attachments");
|
||||
fs::create_dir_all(&attachment_dir).unwrap();
|
||||
let attachment_path = attachment_dir.join("screenshot.png");
|
||||
fs::write(&attachment_path, [0xff, 0xfe, 0xfd]).unwrap();
|
||||
|
||||
let err = update_frontmatter(
|
||||
attachment_path.to_str().unwrap(),
|
||||
"Status",
|
||||
FrontmatterValue::String("Done".to_string()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.contains("Frontmatter can only be updated on Markdown notes"));
|
||||
assert!(err.contains("screenshot.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_roundtrip_update_string() {
|
||||
let content = "---\nStatus: Draft\n---\n# Test\n";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::keys::{frontmatter_key_rule, frontmatter_keys_match, FrontmatterKey};
|
||||
use super::yaml::{format_yaml_field, FrontmatterValue};
|
||||
|
||||
/// Check if a line continues the previous key's value (indented list item,
|
||||
@@ -7,31 +8,9 @@ fn is_value_continuation(line: FrontmatterLine<'_>) -> bool {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SystemKey {
|
||||
Icon,
|
||||
Order,
|
||||
SidebarLabel,
|
||||
Sort,
|
||||
}
|
||||
|
||||
impl SystemKey {
|
||||
fn canonical(self) -> &'static str {
|
||||
match self {
|
||||
Self::Icon => "_icon",
|
||||
Self::Order => "_order",
|
||||
Self::SidebarLabel => "_sidebar_label",
|
||||
Self::Sort => "_sort",
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_aliases(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Icon => &["icon"],
|
||||
Self::Order => &["order"],
|
||||
Self::SidebarLabel => &["sidebar_label", "sidebar label"],
|
||||
Self::Sort => &["sort"],
|
||||
}
|
||||
}
|
||||
enum KeyMatchMode {
|
||||
Exact,
|
||||
Canonical,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -47,31 +26,50 @@ impl<'a> PropertyKey<'a> {
|
||||
fn as_str(self) -> &'a str {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn matches(self, candidate: &str, mode: KeyMatchMode) -> bool {
|
||||
match mode {
|
||||
KeyMatchMode::Exact => candidate == self.as_str(),
|
||||
KeyMatchMode::Canonical => frontmatter_keys_match(
|
||||
FrontmatterKey::new(candidate),
|
||||
FrontmatterKey::new(self.as_str()),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> FrontmatterLine<'a> {
|
||||
fn key(self) -> Option<&'a str> {
|
||||
let trimmed = self.0.trim_start();
|
||||
if let Some(raw) = trimmed.strip_prefix('"') {
|
||||
return quoted_yaml_key(raw, '"');
|
||||
}
|
||||
if let Some(raw) = trimmed.strip_prefix('\'') {
|
||||
return quoted_yaml_key(raw, '\'');
|
||||
}
|
||||
trimmed
|
||||
.split_once(':')
|
||||
.map(|(key, _)| key.trim())
|
||||
.filter(|key| !key.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
fn quoted_yaml_key(raw: &str, quote: char) -> Option<&str> {
|
||||
let (key, rest) = raw.split_once(quote)?;
|
||||
rest.trim_start().starts_with(':').then_some(key)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct FieldUpdate<'a> {
|
||||
key: PropertyKey<'a>,
|
||||
value: Option<&'a FrontmatterValue>,
|
||||
match_mode: KeyMatchMode,
|
||||
}
|
||||
|
||||
impl<'a> FieldUpdate<'a> {
|
||||
fn matches_line(self, line: FrontmatterLine<'_>) -> bool {
|
||||
let trimmed = line.0.trim_start();
|
||||
|
||||
if trimmed.starts_with(self.key.as_str())
|
||||
&& trimmed[self.key.as_str().len()..].starts_with(':')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let double_quoted = format!("\"{}\":", self.key.as_str());
|
||||
if trimmed.starts_with(&double_quoted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let single_quoted = format!("'{}\':", self.key.as_str());
|
||||
trimmed.starts_with(&single_quoted)
|
||||
line.key()
|
||||
.is_some_and(|candidate| self.key.matches(candidate, self.match_mode))
|
||||
}
|
||||
|
||||
fn prepend_to(self, content: DocumentText<'_>) -> String {
|
||||
@@ -133,22 +131,6 @@ impl<'a> FieldUpdate<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_system_key(key: PropertyKey<'_>) -> Option<SystemKey> {
|
||||
match key
|
||||
.as_str()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
.replace(' ', "_")
|
||||
.as_str()
|
||||
{
|
||||
"_icon" | "icon" => Some(SystemKey::Icon),
|
||||
"_order" | "order" => Some(SystemKey::Order),
|
||||
"_sidebar_label" | "sidebar_label" | "sidebar label" => Some(SystemKey::SidebarLabel),
|
||||
"_sort" | "sort" => Some(SystemKey::Sort),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to update frontmatter content
|
||||
pub fn update_frontmatter_content(
|
||||
content: &str,
|
||||
@@ -158,23 +140,25 @@ pub fn update_frontmatter_content(
|
||||
let update = FieldUpdate {
|
||||
key: PropertyKey(key),
|
||||
value: value.as_ref(),
|
||||
match_mode: KeyMatchMode::Exact,
|
||||
};
|
||||
let Some(system_key) = canonical_system_key(update.key) else {
|
||||
let Some(rule) = frontmatter_key_rule(FrontmatterKey::new(update.key.as_str()))
|
||||
.filter(|rule| rule.canonicalizes_on_write())
|
||||
else {
|
||||
return update.apply_to_content(DocumentText(content));
|
||||
};
|
||||
|
||||
let mut updated = content.to_string();
|
||||
for alias in system_key.legacy_aliases() {
|
||||
updated = FieldUpdate {
|
||||
key: PropertyKey(alias),
|
||||
value: None,
|
||||
}
|
||||
.apply_to_content(DocumentText(&updated))?;
|
||||
let updated = FieldUpdate {
|
||||
key: PropertyKey(rule.write_key()),
|
||||
value: None,
|
||||
match_mode: KeyMatchMode::Canonical,
|
||||
}
|
||||
.apply_to_content(DocumentText(content))?;
|
||||
|
||||
FieldUpdate {
|
||||
key: PropertyKey(system_key.canonical()),
|
||||
key: PropertyKey(rule.write_key()),
|
||||
value: update.value,
|
||||
match_mode: KeyMatchMode::Exact,
|
||||
}
|
||||
.apply_to_content(DocumentText(&updated))
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ fn test_update_frontmatter_replaces_or_adds_scalar_fields() {
|
||||
content: "---\n\"Is A\": Note\n---\n# Test\n",
|
||||
key: "Is A",
|
||||
value: Some(FrontmatterValue::String("Project".to_string())),
|
||||
expected_present: &["\"Is A\": Project"],
|
||||
expected_absent: &["\"Is A\": Note"],
|
||||
expected_present: &["type: Project"],
|
||||
expected_absent: &["\"Is A\": Note", "\"Is A\": Project"],
|
||||
},
|
||||
UpdateCase {
|
||||
content: "---\nStatus: Draft\n---\n# Test\n",
|
||||
@@ -163,6 +163,13 @@ fn test_update_frontmatter_handles_missing_or_malformed_frontmatter() {
|
||||
#[test]
|
||||
fn test_update_frontmatter_canonicalizes_system_metadata_keys() {
|
||||
let cases = [
|
||||
UpdateCase {
|
||||
content: "---\narchived: false\n---\n# Test\n",
|
||||
key: "_archived",
|
||||
value: Some(FrontmatterValue::Bool(true)),
|
||||
expected_present: &["_archived: true"],
|
||||
expected_absent: &["archived: false"],
|
||||
},
|
||||
UpdateCase {
|
||||
content: "---\nicon: rocket\n---\n# Test\n",
|
||||
key: "icon",
|
||||
@@ -190,3 +197,41 @@ fn test_update_frontmatter_canonicalizes_system_metadata_keys() {
|
||||
assert_updated_content(case);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_frontmatter_canonicalizes_type_key_case() {
|
||||
let cases = [
|
||||
UpdateCase {
|
||||
content: "---\nType: Note\n---\n# Test\n",
|
||||
key: "type",
|
||||
value: Some(FrontmatterValue::String("Project".to_string())),
|
||||
expected_present: &["type: Project"],
|
||||
expected_absent: &["Type: Note"],
|
||||
},
|
||||
UpdateCase {
|
||||
content: "---\n\"Is A\": Note\nis_a: Topic\n---\n# Test\n",
|
||||
key: "type",
|
||||
value: Some(FrontmatterValue::String("Project".to_string())),
|
||||
expected_present: &["type: Project"],
|
||||
expected_absent: &["\"Is A\": Note", "is_a: Topic"],
|
||||
},
|
||||
UpdateCase {
|
||||
content: "---\nTYPE: Note\n---\n# Test\n",
|
||||
key: "Type",
|
||||
value: Some(FrontmatterValue::String("Person".to_string())),
|
||||
expected_present: &["type: Person"],
|
||||
expected_absent: &["TYPE: Note"],
|
||||
},
|
||||
UpdateCase {
|
||||
content: "---\nType: Note\nstatus: Active\n---\n# Test\n",
|
||||
key: "type",
|
||||
value: None,
|
||||
expected_present: &["status: Active", "# Test"],
|
||||
expected_absent: &["Type: Note", "\ntype:"],
|
||||
},
|
||||
];
|
||||
|
||||
for case in cases {
|
||||
assert_updated_content(case);
|
||||
}
|
||||
}
|
||||
|
||||
300
src-tauri/src/gemini_cli.rs
Normal file
300
src-tauri/src/gemini_cli.rs
Normal file
@@ -0,0 +1,300 @@
|
||||
use crate::ai_agents::{AiAgentAvailability, AiAgentStreamEvent};
|
||||
pub use crate::cli_agent_runtime::AgentStreamRequest;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn check_cli() -> AiAgentAvailability {
|
||||
crate::gemini_discovery::check_cli()
|
||||
}
|
||||
|
||||
pub fn run_agent_stream<F>(request: AgentStreamRequest, emit: F) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let binary = crate::gemini_discovery::find_binary()?;
|
||||
run_agent_stream_with_binary(&binary, request, emit)
|
||||
}
|
||||
|
||||
fn run_agent_stream_with_binary<F>(
|
||||
binary: &Path,
|
||||
request: AgentStreamRequest,
|
||||
emit: F,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let settings_dir = tempfile::Builder::new()
|
||||
.prefix("tolaria-gemini-agent-")
|
||||
.tempdir()
|
||||
.map_err(|error| format!("Failed to create Gemini settings directory: {error}"))?;
|
||||
let command = crate::gemini_config::build_command(binary, &request, settings_dir.path())?;
|
||||
crate::cli_agent_runtime::run_ai_agent_json_stream(
|
||||
command,
|
||||
"gemini",
|
||||
emit,
|
||||
gemini_session_id,
|
||||
dispatch_gemini_event,
|
||||
format_gemini_error,
|
||||
)
|
||||
}
|
||||
|
||||
fn gemini_session_id(json: &serde_json::Value) -> Option<&str> {
|
||||
json["session_id"].as_str()
|
||||
}
|
||||
|
||||
fn dispatch_gemini_event<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
match json["type"].as_str().unwrap_or_default() {
|
||||
"init" => emit_gemini_init(json, emit),
|
||||
"message" => emit_gemini_message(json, emit),
|
||||
"tool_use" => emit_gemini_tool_start(json, emit),
|
||||
"tool_result" => emit_gemini_tool_done(json, emit),
|
||||
"error" => emit_gemini_error(json, emit),
|
||||
"result" => emit_gemini_result(json, emit),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_gemini_init<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
if let Some(session_id) = json["session_id"].as_str() {
|
||||
emit(AiAgentStreamEvent::Init {
|
||||
session_id: session_id.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_gemini_message<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
if json["role"].as_str() != Some("assistant") {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(content) = json["content"]
|
||||
.as_str()
|
||||
.filter(|content| !content.is_empty())
|
||||
{
|
||||
emit(AiAgentStreamEvent::TextDelta {
|
||||
text: content.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_gemini_tool_start<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let tool_name = json["tool_name"].as_str().unwrap_or("Gemini tool");
|
||||
let tool_id = json["tool_id"].as_str().unwrap_or(tool_name);
|
||||
let input = (!json["parameters"].is_null()).then(|| json["parameters"].to_string());
|
||||
|
||||
emit(AiAgentStreamEvent::ToolStart {
|
||||
tool_name: tool_name.to_string(),
|
||||
tool_id: tool_id.to_string(),
|
||||
input,
|
||||
});
|
||||
}
|
||||
|
||||
fn emit_gemini_tool_done<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let tool_id = json["tool_id"].as_str().unwrap_or("gemini-tool");
|
||||
let output = json["output"]
|
||||
.as_str()
|
||||
.or_else(|| json["error"]["message"].as_str())
|
||||
.map(str::to_string);
|
||||
|
||||
emit(AiAgentStreamEvent::ToolDone {
|
||||
tool_id: tool_id.to_string(),
|
||||
output,
|
||||
});
|
||||
}
|
||||
|
||||
fn emit_gemini_error<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
if let Some(message) = json["message"].as_str() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: message.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_gemini_result<F>(json: &serde_json::Value, emit: &mut F)
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
if json["status"].as_str() != Some("error") {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(message) = json["error"]["message"].as_str() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: message.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn format_gemini_error(stderr_output: String, status: String) -> String {
|
||||
let lower = stderr_output.to_ascii_lowercase();
|
||||
if is_auth_error(&lower) {
|
||||
return "Gemini CLI is not authenticated. Run `gemini` in your terminal to sign in, or set GEMINI_API_KEY and retry.".into();
|
||||
}
|
||||
|
||||
if stderr_output.trim().is_empty() {
|
||||
format!("gemini exited with status {status}")
|
||||
} else {
|
||||
stderr_output.lines().take(3).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
fn is_auth_error(lower: &str) -> bool {
|
||||
[
|
||||
"auth",
|
||||
"login",
|
||||
"sign in",
|
||||
"api key",
|
||||
"gemini_api_key",
|
||||
"google_api_key",
|
||||
"oauth",
|
||||
"401",
|
||||
]
|
||||
.iter()
|
||||
.any(|pattern| lower.contains(pattern))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn executable_script(dir: &Path, body: &str) -> std::path::PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let script = dir.join("gemini");
|
||||
std::fs::write(&script, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
script
|
||||
}
|
||||
|
||||
fn request(vault_path: String) -> AgentStreamRequest {
|
||||
AgentStreamRequest {
|
||||
message: "Summarize".into(),
|
||||
system_prompt: None,
|
||||
vault_path,
|
||||
permission_mode: AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_maps_gemini_stream_json_response() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"init","session_id":"gemini_1","model":"gemini-2.5-pro"}'
|
||||
printf '%s\n' '{"type":"message","role":"assistant","content":"Done","delta":true}'
|
||||
printf '%s\n' '{"type":"result","status":"success","stats":{"tool_calls":0}}'
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "gemini_1");
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Init { session_id } if session_id == "gemini_1"
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "Done"
|
||||
));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_maps_gemini_tool_events_before_final_text() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"init","session_id":"gemini_2","model":"gemini-2.5-pro"}'
|
||||
printf '%s\n' '{"type":"tool_use","tool_name":"tolaria__search_notes","tool_id":"tool_1","parameters":{"query":"meeting"}}'
|
||||
printf '%s\n' '{"type":"tool_result","tool_id":"tool_1","status":"success","output":"2 notes"}'
|
||||
printf '%s\n' '{"type":"message","role":"assistant","content":"I found 2 notes.","delta":true}'
|
||||
printf '%s\n' '{"type":"result","status":"success","stats":{"tool_calls":1}}'
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "gemini_2");
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::ToolStart { tool_name, tool_id, input }
|
||||
if tool_name == "tolaria__search_notes"
|
||||
&& tool_id == "tool_1"
|
||||
&& input.as_deref() == Some(r#"{"query":"meeting"}"#)
|
||||
)));
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::ToolDone { tool_id, output }
|
||||
if tool_id == "tool_1" && output.as_deref() == Some("2 notes")
|
||||
)));
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "I found 2 notes."
|
||||
)));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_reports_gemini_auth_errors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' 'oauth login required' >&2
|
||||
exit 3
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(session_id.is_empty());
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::Error { message } if message.contains("not authenticated")
|
||||
)));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
}
|
||||
187
src-tauri/src/gemini_config.rs
Normal file
187
src-tauri/src/gemini_config.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
use crate::gemini_cli::AgentStreamRequest;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
pub(crate) fn build_command(
|
||||
binary: &Path,
|
||||
request: &AgentStreamRequest,
|
||||
settings_dir: &Path,
|
||||
) -> Result<std::process::Command, String> {
|
||||
let settings_path = write_settings(settings_dir, &request.vault_path, request.permission_mode)?;
|
||||
let mut command = crate::hidden_command(binary);
|
||||
crate::cli_agent_runtime::configure_agent_command_environment(&mut command, binary);
|
||||
command
|
||||
.args(build_args(request.permission_mode))
|
||||
.arg("--prompt")
|
||||
.arg(build_prompt(request))
|
||||
.env("GEMINI_CLI_SYSTEM_SETTINGS_PATH", settings_path)
|
||||
.env("NO_COLOR", "1")
|
||||
.current_dir(&request.vault_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
fn build_args(permission_mode: AiAgentPermissionMode) -> Vec<String> {
|
||||
vec![
|
||||
"--output-format".into(),
|
||||
"stream-json".into(),
|
||||
"--approval-mode".into(),
|
||||
approval_mode(permission_mode).into(),
|
||||
]
|
||||
}
|
||||
|
||||
fn approval_mode(permission_mode: AiAgentPermissionMode) -> &'static str {
|
||||
match permission_mode {
|
||||
AiAgentPermissionMode::Safe => "auto_edit",
|
||||
AiAgentPermissionMode::PowerUser => "yolo",
|
||||
}
|
||||
}
|
||||
|
||||
fn build_prompt(request: &AgentStreamRequest) -> String {
|
||||
crate::cli_agent_runtime::build_prompt(&request.message, request.system_prompt.as_deref())
|
||||
}
|
||||
|
||||
fn write_settings(
|
||||
settings_dir: &Path,
|
||||
vault_path: &str,
|
||||
permission_mode: AiAgentPermissionMode,
|
||||
) -> Result<PathBuf, String> {
|
||||
std::fs::create_dir_all(settings_dir)
|
||||
.map_err(|error| format!("Failed to create Gemini settings directory: {error}"))?;
|
||||
let settings_path = settings_dir.join("settings.json");
|
||||
let settings = build_settings(vault_path, permission_mode)?;
|
||||
std::fs::write(&settings_path, settings)
|
||||
.map_err(|error| format!("Failed to write Gemini settings: {error}"))?;
|
||||
Ok(settings_path)
|
||||
}
|
||||
|
||||
fn build_settings(
|
||||
vault_path: &str,
|
||||
permission_mode: AiAgentPermissionMode,
|
||||
) -> Result<String, String> {
|
||||
let mcp_server_path = crate::cli_agent_runtime::mcp_server_path_string()?;
|
||||
let mut settings = serde_json::json!({
|
||||
"mcpServers": {
|
||||
"tolaria": {
|
||||
"command": "node",
|
||||
"args": [mcp_server_path],
|
||||
"env": {
|
||||
"VAULT_PATH": vault_path,
|
||||
"WS_UI_PORT": "9711"
|
||||
},
|
||||
"description": "Tolaria active vault MCP server",
|
||||
"trust": permission_mode == AiAgentPermissionMode::PowerUser
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if permission_mode == AiAgentPermissionMode::Safe {
|
||||
settings["tools"] = serde_json::json!({
|
||||
"exclude": ["run_shell_command"]
|
||||
});
|
||||
}
|
||||
|
||||
serde_json::to_string(&settings)
|
||||
.map_err(|error| format!("Failed to serialize Gemini settings: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
fn request() -> AgentStreamRequest {
|
||||
AgentStreamRequest {
|
||||
message: "Rename the note".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode: AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_uses_headless_stream_json_mode_and_temp_settings() {
|
||||
let settings_dir = tempfile::tempdir().unwrap();
|
||||
let command =
|
||||
build_command(&PathBuf::from("gemini"), &request(), settings_dir.path()).unwrap();
|
||||
let actual_args: Vec<&OsStr> = command.get_args().collect();
|
||||
let settings_path = command
|
||||
.get_envs()
|
||||
.find(|(key, _)| *key == OsStr::new("GEMINI_CLI_SYSTEM_SETTINGS_PATH"))
|
||||
.and_then(|(_, value)| value);
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("gemini"));
|
||||
assert_eq!(actual_args[0], OsStr::new("--output-format"));
|
||||
assert_eq!(actual_args[1], OsStr::new("stream-json"));
|
||||
assert!(actual_args.contains(&OsStr::new("--prompt")));
|
||||
assert_eq!(actual_args.last(), Some(&OsStr::new("Rename the note")));
|
||||
assert_eq!(command.get_current_dir(), Some(Path::new("/tmp/vault")));
|
||||
assert!(settings_path.is_some());
|
||||
assert!(settings_dir.path().join("settings.json").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_extends_path_with_resolved_homebrew_bin() {
|
||||
let settings_dir = tempfile::tempdir().unwrap();
|
||||
let command = build_command(
|
||||
&PathBuf::from("/opt/homebrew/bin/gemini"),
|
||||
&request(),
|
||||
settings_dir.path(),
|
||||
)
|
||||
.unwrap();
|
||||
let path_value = command
|
||||
.get_envs()
|
||||
.find(|(key, _)| *key == OsStr::new("PATH"))
|
||||
.and_then(|(_, value)| value)
|
||||
.expect("PATH should be set");
|
||||
let paths = std::env::split_paths(path_value).collect::<Vec<_>>();
|
||||
|
||||
assert!(
|
||||
paths.contains(&PathBuf::from("/opt/homebrew/bin")),
|
||||
"PATH should include the resolved Gemini binary directory, got {paths:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_settings_include_tolaria_mcp_and_exclude_shell() {
|
||||
let settings = build_settings("/tmp/vault", AiAgentPermissionMode::Safe).unwrap();
|
||||
let json: serde_json::Value = serde_json::from_str(&settings).unwrap();
|
||||
|
||||
assert_eq!(json["mcpServers"]["tolaria"]["command"], "node");
|
||||
assert_eq!(
|
||||
json["mcpServers"]["tolaria"]["env"]["VAULT_PATH"],
|
||||
"/tmp/vault"
|
||||
);
|
||||
assert_eq!(json["mcpServers"]["tolaria"]["env"]["WS_UI_PORT"], "9711");
|
||||
assert_eq!(json["mcpServers"]["tolaria"]["trust"], false);
|
||||
assert_eq!(json["tools"]["exclude"][0], "run_shell_command");
|
||||
assert!(json["mcpServers"]["tolaria"]["args"][0]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.ends_with("index.js"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_user_settings_trust_tolaria_and_allow_shell_discovery() {
|
||||
let settings = build_settings("/tmp/vault", AiAgentPermissionMode::PowerUser).unwrap();
|
||||
let json: serde_json::Value = serde_json::from_str(&settings).unwrap();
|
||||
|
||||
assert_eq!(json["mcpServers"]["tolaria"]["trust"], true);
|
||||
assert!(json.get("tools").is_none());
|
||||
assert_eq!(approval_mode(AiAgentPermissionMode::PowerUser), "yolo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_keeps_system_prompt_first() {
|
||||
let prompt = build_prompt(&AgentStreamRequest {
|
||||
system_prompt: Some("Be concise".into()),
|
||||
..request()
|
||||
});
|
||||
|
||||
assert!(prompt.starts_with("System instructions:\nBe concise"));
|
||||
assert!(prompt.contains("User request:\nRename the note"));
|
||||
}
|
||||
}
|
||||
206
src-tauri/src/gemini_discovery.rs
Normal file
206
src-tauri/src/gemini_discovery.rs
Normal file
@@ -0,0 +1,206 @@
|
||||
use crate::ai_agents::AiAgentAvailability;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn check_cli() -> AiAgentAvailability {
|
||||
match find_binary() {
|
||||
Ok(binary) => AiAgentAvailability {
|
||||
installed: true,
|
||||
version: crate::cli_agent_runtime::version_for_binary(&binary),
|
||||
},
|
||||
Err(_) => AiAgentAvailability {
|
||||
installed: false,
|
||||
version: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn find_binary() -> Result<PathBuf, String> {
|
||||
if let Some(binary) = find_binary_on_path() {
|
||||
return Ok(binary);
|
||||
}
|
||||
if let Some(binary) = find_binary_in_user_shell() {
|
||||
return Ok(binary);
|
||||
}
|
||||
if let Some(binary) = crate::cli_agent_runtime::find_executable_binary_candidate(
|
||||
gemini_binary_candidates(),
|
||||
"Gemini CLI",
|
||||
)? {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
Err("Gemini CLI not found. Install it: https://google-gemini.github.io/gemini-cli/".into())
|
||||
}
|
||||
|
||||
fn find_binary_on_path() -> Option<PathBuf> {
|
||||
crate::hidden_command(path_lookup_command())
|
||||
.arg("gemini")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_lookup_command() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"where"
|
||||
} else {
|
||||
"which"
|
||||
}
|
||||
}
|
||||
|
||||
fn find_binary_in_user_shell() -> Option<PathBuf> {
|
||||
user_shell_candidates()
|
||||
.into_iter()
|
||||
.filter(|shell| shell.exists())
|
||||
.find_map(|shell| command_path_from_shell(&shell, "gemini"))
|
||||
}
|
||||
|
||||
fn user_shell_candidates() -> Vec<PathBuf> {
|
||||
let mut shells = Vec::new();
|
||||
if let Some(shell) = std::env::var_os("SHELL") {
|
||||
if !shell.is_empty() {
|
||||
shells.push(PathBuf::from(shell));
|
||||
}
|
||||
}
|
||||
shells.push(PathBuf::from("/bin/zsh"));
|
||||
shells.push(PathBuf::from("/bin/bash"));
|
||||
shells
|
||||
}
|
||||
|
||||
fn command_path_from_shell(shell: &Path, command: &str) -> Option<PathBuf> {
|
||||
crate::hidden_command(shell)
|
||||
.arg("-lc")
|
||||
.arg(format!("command -v {command}"))
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_from_successful_output(output: &std::process::Output) -> Option<PathBuf> {
|
||||
if output.status.success() {
|
||||
first_existing_path(&String::from_utf8_lossy(&output.stdout))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn first_existing_path(stdout: &str) -> Option<PathBuf> {
|
||||
stdout.lines().find_map(|line| {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let candidate = PathBuf::from(trimmed);
|
||||
candidate.exists().then_some(candidate)
|
||||
})
|
||||
}
|
||||
|
||||
fn gemini_binary_candidates() -> Vec<PathBuf> {
|
||||
dirs::home_dir()
|
||||
.map(|home| gemini_binary_candidates_for_home(&home))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn gemini_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
home.join(".local/bin/gemini"),
|
||||
home.join(".local/bin/gemini.exe"),
|
||||
home.join(".gemini/bin/gemini"),
|
||||
home.join(".gemini/bin/gemini.exe"),
|
||||
home.join(".local/share/mise/shims/gemini"),
|
||||
home.join(".local/share/mise/shims/gemini.exe"),
|
||||
home.join(".asdf/shims/gemini"),
|
||||
home.join(".asdf/shims/gemini.exe"),
|
||||
home.join(".npm-global/bin/gemini"),
|
||||
home.join(".npm-global/bin/gemini.cmd"),
|
||||
home.join(".npm-global/bin/gemini.exe"),
|
||||
home.join(".npm/bin/gemini"),
|
||||
home.join(".npm/bin/gemini.cmd"),
|
||||
home.join(".npm/bin/gemini.exe"),
|
||||
home.join(".bun/bin/gemini"),
|
||||
home.join(".bun/bin/gemini.exe"),
|
||||
home.join(".linuxbrew/bin/gemini"),
|
||||
home.join("AppData/Roaming/npm/gemini.cmd"),
|
||||
home.join("AppData/Roaming/npm/gemini.exe"),
|
||||
home.join("AppData/Local/pnpm/gemini.cmd"),
|
||||
home.join("AppData/Local/pnpm/gemini.exe"),
|
||||
home.join("scoop/shims/gemini.exe"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/gemini"),
|
||||
PathBuf::from("/usr/local/bin/gemini"),
|
||||
PathBuf::from("/opt/homebrew/bin/gemini"),
|
||||
];
|
||||
candidates.extend(nvm_binary_candidates_for_home(home));
|
||||
candidates
|
||||
}
|
||||
|
||||
fn nvm_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut candidates = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.is_dir())
|
||||
.map(|path| path.join("bin").join("gemini"))
|
||||
.collect::<Vec<_>>();
|
||||
candidates.sort();
|
||||
candidates
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_supported_installs() {
|
||||
let home = PathBuf::from("/Users/alex");
|
||||
let candidates = gemini_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".local/bin/gemini"),
|
||||
home.join(".gemini/bin/gemini"),
|
||||
home.join(".local/share/mise/shims/gemini"),
|
||||
home.join(".asdf/shims/gemini"),
|
||||
home.join(".npm-global/bin/gemini"),
|
||||
home.join(".bun/bin/gemini"),
|
||||
PathBuf::from("/opt/homebrew/bin/gemini"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_linuxbrew_installs() {
|
||||
let home = PathBuf::from("/home/alex");
|
||||
let candidates = gemini_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".linuxbrew/bin/gemini"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/gemini"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_existing_path_skips_empty_and_missing_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let missing = dir.path().join("missing-gemini");
|
||||
let gemini = dir.path().join("gemini");
|
||||
std::fs::write(&gemini, "#!/bin/sh\n").unwrap();
|
||||
|
||||
let stdout = format!("\n{}\n{}\n", missing.display(), gemini.display());
|
||||
|
||||
assert_eq!(first_existing_path(&stdout), Some(gemini));
|
||||
}
|
||||
}
|
||||
@@ -244,6 +244,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"-c".to_string(),
|
||||
"core.quotePath=false".to_string(),
|
||||
"clone".to_string(),
|
||||
"--quiet".to_string(),
|
||||
"https://example.com/repo.git".to_string(),
|
||||
|
||||
@@ -187,37 +187,53 @@ mod tests {
|
||||
use super::git_command;
|
||||
use super::*;
|
||||
use crate::git::tests::setup_git_repo;
|
||||
use std::fs;
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
fn force_quoted_git_paths(vault: &Path) {
|
||||
git_command()
|
||||
.args(["config", "core.quotePath", "true"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn write_and_commit_file(
|
||||
vault: &Path,
|
||||
relative_path: &str,
|
||||
content: &str,
|
||||
message: &str,
|
||||
) -> PathBuf {
|
||||
let file = vault.join(relative_path);
|
||||
fs::write(&file, content).unwrap();
|
||||
git_command()
|
||||
.args(["add", relative_path])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", message])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
fn head_hash(vault: &Path) -> String {
|
||||
let log = git_command()
|
||||
.args(["log", "--format=%H", "-1"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&log.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_file_history_with_commits() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let file = vault.join("test.md");
|
||||
|
||||
fs::write(&file, "# Initial\n").unwrap();
|
||||
git_command()
|
||||
.args(["add", "test.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "Initial commit"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
fs::write(&file, "# Updated\n\nNew content.").unwrap();
|
||||
git_command()
|
||||
.args(["add", "test.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "Update test"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let file = write_and_commit_file(vault, "test.md", "# Initial\n", "Initial commit");
|
||||
write_and_commit_file(vault, "test.md", "# Updated\n\nNew content.", "Update test");
|
||||
|
||||
let history = get_file_history(vault.to_str().unwrap(), file.to_str().unwrap()).unwrap();
|
||||
|
||||
@@ -245,19 +261,13 @@ mod tests {
|
||||
fn test_get_file_diff() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let file = vault.join("diff-test.md");
|
||||
|
||||
fs::write(&file, "# Test\n\nOriginal content.").unwrap();
|
||||
git_command()
|
||||
.args(["add", "diff-test.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "Add diff-test"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let file = write_and_commit_file(
|
||||
vault,
|
||||
"diff-test.md",
|
||||
"# Test\n\nOriginal content.",
|
||||
"Add diff-test",
|
||||
);
|
||||
|
||||
fs::write(&file, "# Test\n\nModified content.").unwrap();
|
||||
|
||||
@@ -272,39 +282,21 @@ mod tests {
|
||||
fn test_get_file_diff_at_commit() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let file = vault.join("diff-at-commit.md");
|
||||
|
||||
fs::write(&file, "# First\n\nOriginal content.").unwrap();
|
||||
git_command()
|
||||
.args(["add", "diff-at-commit.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "First commit"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let file = write_and_commit_file(
|
||||
vault,
|
||||
"diff-at-commit.md",
|
||||
"# First\n\nOriginal content.",
|
||||
"First commit",
|
||||
);
|
||||
write_and_commit_file(
|
||||
vault,
|
||||
"diff-at-commit.md",
|
||||
"# First\n\nModified content.",
|
||||
"Second commit",
|
||||
);
|
||||
|
||||
fs::write(&file, "# First\n\nModified content.").unwrap();
|
||||
git_command()
|
||||
.args(["add", "diff-at-commit.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "Second commit"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
// Get hash of second commit
|
||||
let log = git_command()
|
||||
.args(["log", "--format=%H", "-1"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let hash = String::from_utf8_lossy(&log.stdout).trim().to_string();
|
||||
let hash = head_hash(vault);
|
||||
|
||||
let diff = get_file_diff_at_commit(vault.to_str().unwrap(), file.to_str().unwrap(), &hash)
|
||||
.unwrap();
|
||||
@@ -318,26 +310,15 @@ mod tests {
|
||||
fn test_get_file_diff_at_initial_commit() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let file = vault.join("initial.md");
|
||||
|
||||
fs::write(&file, "# Initial\n\nHello world.").unwrap();
|
||||
git_command()
|
||||
.args(["add", "initial.md"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
git_command()
|
||||
.args(["commit", "-m", "Initial commit"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let file = write_and_commit_file(
|
||||
vault,
|
||||
"initial.md",
|
||||
"# Initial\n\nHello world.",
|
||||
"Initial commit",
|
||||
);
|
||||
|
||||
let log = git_command()
|
||||
.args(["log", "--format=%H", "-1"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
let hash = String::from_utf8_lossy(&log.stdout).trim().to_string();
|
||||
let hash = head_hash(vault);
|
||||
|
||||
let diff = get_file_diff_at_commit(vault.to_str().unwrap(), file.to_str().unwrap(), &hash)
|
||||
.unwrap();
|
||||
@@ -346,4 +327,35 @@ mod tests {
|
||||
assert!(diff.contains("+# Initial"));
|
||||
assert!(diff.contains("+Hello world."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_file_diff_at_commit_preserves_chinese_filename_and_content() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let relative_path = "中文笔记.md";
|
||||
let file = vault.join(relative_path);
|
||||
|
||||
force_quoted_git_paths(vault);
|
||||
write_and_commit_file(
|
||||
vault,
|
||||
relative_path,
|
||||
"# 初始\n\n第一行\n",
|
||||
"Add Chinese note",
|
||||
);
|
||||
write_and_commit_file(
|
||||
vault,
|
||||
relative_path,
|
||||
"# 初始\n\n第二行\n",
|
||||
"Update Chinese note",
|
||||
);
|
||||
let hash = head_hash(vault);
|
||||
|
||||
let diff = get_file_diff_at_commit(vault.to_str().unwrap(), file.to_str().unwrap(), &hash)
|
||||
.unwrap();
|
||||
|
||||
assert!(diff.contains("diff --git a/中文笔记.md b/中文笔记.md"));
|
||||
assert!(diff.contains("-第一行"));
|
||||
assert!(diff.contains("+第二行"));
|
||||
assert!(!diff.contains("\\344"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,14 +56,47 @@ const DEFAULT_GITIGNORE: &str = "# Tolaria app files (machine-specific, never co
|
||||
*.swp\n\
|
||||
*.swo\n";
|
||||
|
||||
fn git_command() -> Command {
|
||||
crate::hidden_command("git")
|
||||
pub(crate) fn git_command() -> Command {
|
||||
let mut command = crate::hidden_command("git");
|
||||
sanitize_linux_appimage_git_env(&mut command);
|
||||
command.args(["-c", "core.quotePath=false"]);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(any(test, all(desktop, target_os = "linux")))]
|
||||
const LINUX_APPIMAGE_GIT_ENV_REMOVALS: [&str; 3] =
|
||||
["LD_LIBRARY_PATH", "LD_PRELOAD", "GIT_EXEC_PATH"];
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn sanitize_linux_appimage_git_env(command: &mut Command) {
|
||||
sanitize_linux_appimage_git_env_for_launch(command, linux_appimage_env_present());
|
||||
}
|
||||
|
||||
#[cfg(not(all(desktop, target_os = "linux")))]
|
||||
fn sanitize_linux_appimage_git_env(_command: &mut Command) {}
|
||||
|
||||
#[cfg(any(test, all(desktop, target_os = "linux")))]
|
||||
fn sanitize_linux_appimage_git_env_for_launch(command: &mut Command, is_appimage: bool) {
|
||||
if !is_appimage {
|
||||
return;
|
||||
}
|
||||
|
||||
for key in LINUX_APPIMAGE_GIT_ENV_REMOVALS {
|
||||
command.env_remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn linux_appimage_env_present() -> bool {
|
||||
["APPIMAGE", "APPDIR"]
|
||||
.into_iter()
|
||||
.any(|key| std::env::var(key).is_ok_and(|value| !value.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// Ensure a `.gitignore` with sensible defaults exists in the vault directory.
|
||||
/// Creates the file if missing; leaves existing `.gitignore` files untouched.
|
||||
pub fn ensure_gitignore(path: &str) -> Result<(), String> {
|
||||
let gitignore_path = Path::new(path).join(".gitignore");
|
||||
pub fn ensure_gitignore(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
let gitignore_path = path.as_ref().join(".gitignore");
|
||||
if !gitignore_path.exists() {
|
||||
std::fs::write(&gitignore_path, DEFAULT_GITIGNORE)
|
||||
.map_err(|e| format!("Failed to write .gitignore: {}", e))?;
|
||||
@@ -72,15 +105,15 @@ pub fn ensure_gitignore(path: &str) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// Initialize a new git repository, stage all files, and create an initial commit.
|
||||
pub fn init_repo(path: &str) -> Result<(), String> {
|
||||
let dir = Path::new(path);
|
||||
pub fn init_repo(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
let dir = path.as_ref();
|
||||
|
||||
run_git(dir, &["init"])?;
|
||||
ensure_author_config(dir)?;
|
||||
|
||||
// Write .gitignore before the first commit so machine-specific and
|
||||
// macOS metadata files are never tracked and don't cause conflicts.
|
||||
ensure_gitignore(path)?;
|
||||
ensure_gitignore(dir)?;
|
||||
|
||||
run_git(dir, &["add", "."])?;
|
||||
commit_initial_vault_setup(dir)?;
|
||||
@@ -176,6 +209,7 @@ fn parse_github_repo_path(url: &str) -> Option<String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use tempfile::TempDir;
|
||||
|
||||
@@ -259,6 +293,18 @@ mod tests {
|
||||
(bare_dir, clone_a_dir, clone_b_dir)
|
||||
}
|
||||
|
||||
fn command_envs(command: &Command) -> HashMap<String, Option<String>> {
|
||||
command
|
||||
.get_envs()
|
||||
.map(|(key, value)| {
|
||||
(
|
||||
key.to_string_lossy().to_string(),
|
||||
value.map(|entry| entry.to_string_lossy().to_string()),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ensure_gitignore_creates_file() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -282,6 +328,32 @@ mod tests {
|
||||
assert_eq!(content, "my-rule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_linux_appimage_git_commands_remove_appimage_loader_env() {
|
||||
let mut command = crate::hidden_command("git");
|
||||
|
||||
sanitize_linux_appimage_git_env_for_launch(&mut command, true);
|
||||
|
||||
let envs = command_envs(&command);
|
||||
|
||||
for key in LINUX_APPIMAGE_GIT_ENV_REMOVALS {
|
||||
assert_eq!(envs.get(key), Some(&None));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_appimage_git_commands_keep_parent_env_unmodified() {
|
||||
let mut command = crate::hidden_command("git");
|
||||
|
||||
sanitize_linux_appimage_git_env_for_launch(&mut command, false);
|
||||
|
||||
let envs = command_envs(&command);
|
||||
|
||||
for key in LINUX_APPIMAGE_GIT_ENV_REMOVALS {
|
||||
assert!(!envs.contains_key(key));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_init_repo_creates_git_directory() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -300,6 +300,14 @@ mod tests {
|
||||
git_commit(vp, "initial").unwrap();
|
||||
}
|
||||
|
||||
fn force_quoted_git_paths(vault: &Path) {
|
||||
git_command()
|
||||
.args(["config", "core.quotePath", "true"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_modified_files() {
|
||||
let dir = setup_git_repo();
|
||||
@@ -380,6 +388,28 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_modified_files_preserves_chinese_markdown_path() {
|
||||
let dir = setup_git_repo();
|
||||
let vault = dir.path();
|
||||
let vp = vault.to_str().unwrap();
|
||||
let relative_path = "中文笔记.md";
|
||||
|
||||
force_quoted_git_paths(vault);
|
||||
write_and_commit_markdown(vault, vp, relative_path, "# 初始\n");
|
||||
fs::write(vault.join(relative_path), "# 初始\n\n更新\n").unwrap();
|
||||
|
||||
let modified = get_modified_files(vp).unwrap();
|
||||
let file = modified
|
||||
.iter()
|
||||
.find(|file| file.relative_path == relative_path)
|
||||
.expect("Chinese markdown path should be reported as modified");
|
||||
|
||||
assert_eq!(file.status, "modified");
|
||||
assert!(file.path.ends_with(relative_path));
|
||||
assert_eq!(file.added_lines, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_commit_flow_modified_files_then_commit_clears() {
|
||||
let dir = setup_git_repo();
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
pub mod ai_agents;
|
||||
pub mod ai_models;
|
||||
pub mod app_updater;
|
||||
pub mod claude_cli;
|
||||
mod cli_agent_runtime;
|
||||
pub mod codex_cli;
|
||||
mod commands;
|
||||
pub mod frontmatter;
|
||||
pub mod gemini_cli;
|
||||
mod gemini_config;
|
||||
mod gemini_discovery;
|
||||
pub mod git;
|
||||
#[cfg(any(test, all(desktop, target_os = "linux")))]
|
||||
mod linux_appimage;
|
||||
pub mod mcp;
|
||||
#[cfg(desktop)]
|
||||
pub mod menu;
|
||||
@@ -56,46 +64,7 @@ fn suppress_windows_console(_command: &mut Command) {}
|
||||
struct WsBridgeChild(Mutex<Option<Child>>);
|
||||
|
||||
#[cfg(desktop)]
|
||||
struct ActiveAssetScopeRoots(Mutex<Vec<PathBuf>>);
|
||||
|
||||
#[cfg(any(test, all(desktop, target_os = "linux")))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct StartupEnvOverride {
|
||||
key: &'static str,
|
||||
value: &'static str,
|
||||
}
|
||||
|
||||
#[cfg(any(test, all(desktop, target_os = "linux")))]
|
||||
fn linux_appimage_startup_env_overrides_with<F>(mut get_var: F) -> Vec<StartupEnvOverride>
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
let is_appimage = ["APPIMAGE", "APPDIR"]
|
||||
.into_iter()
|
||||
.any(|key| get_var(key).is_some_and(|value| !value.trim().is_empty()));
|
||||
if !is_appimage {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if get_var("WEBKIT_DISABLE_DMABUF_RENDERER").is_some_and(|value| !value.trim().is_empty()) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
vec![StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
value: "1",
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn apply_linux_appimage_startup_env_overrides() {
|
||||
for env_override in linux_appimage_startup_env_overrides_with(|key| std::env::var(key).ok()) {
|
||||
std::env::set_var(env_override.key, env_override.value);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(desktop, target_os = "linux")))]
|
||||
fn apply_linux_appimage_startup_env_overrides() {}
|
||||
struct AllowedAssetScopeRoots(Mutex<Vec<PathBuf>>);
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn log_startup_result(label: &str, result: Result<usize, String>) {
|
||||
@@ -178,28 +147,55 @@ pub(crate) fn sync_ws_bridge_for_vault(
|
||||
Ok("started")
|
||||
}
|
||||
|
||||
/// Run startup housekeeping on the default vault (migrate legacy frontmatter, seed configs).
|
||||
#[cfg(desktop)]
|
||||
fn run_startup_tasks() {
|
||||
let vault_path = dirs::home_dir()
|
||||
.map(|h| h.join("Laputa"))
|
||||
.unwrap_or_default();
|
||||
if !vault_path.is_dir() {
|
||||
return;
|
||||
fn spawn_background_task<F>(thread_name: &'static str, task: F)
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
if let Err(e) = std::thread::Builder::new()
|
||||
.name(thread_name.into())
|
||||
.spawn(task)
|
||||
{
|
||||
log::warn!("Failed to start {thread_name}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Run startup housekeeping on the legacy default vault (migrate legacy frontmatter, seed configs).
|
||||
#[cfg(desktop)]
|
||||
fn run_startup_tasks_for_vault(vault_path: &Path) {
|
||||
let vp_str = vault_path.to_str().unwrap_or_default();
|
||||
log_startup_result(
|
||||
"Migrated is_a to type on startup",
|
||||
vault::migrate_is_a_to_type(vp_str),
|
||||
);
|
||||
// Migrate legacy config/agents.md → root AGENTS.md (one-time, idempotent)
|
||||
// Migrate legacy config/agents.md -> root AGENTS.md (one-time, idempotent)
|
||||
vault::migrate_agents_md(vp_str);
|
||||
// Seed AGENTS.md and starter type definitions at vault root if missing
|
||||
vault::seed_config_files(vp_str);
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn spawn_ws_bridge(app: &mut tauri::App) {
|
||||
fn spawn_startup_tasks_for_vault_with<F>(vault_path: PathBuf, task: F) -> bool
|
||||
where
|
||||
F: FnOnce(PathBuf) + Send + 'static,
|
||||
{
|
||||
if !vault_path.is_dir() {
|
||||
return false;
|
||||
}
|
||||
|
||||
spawn_background_task("tolaria-startup-tasks", move || task(vault_path));
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn spawn_startup_tasks() {
|
||||
let Some(vault_path) = dirs::home_dir().map(|h| h.join("Laputa")) else {
|
||||
return;
|
||||
};
|
||||
spawn_startup_tasks_for_vault_with(vault_path, |path| run_startup_tasks_for_vault(&path));
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn sync_ws_bridge_for_selected_vault(app_handle: &tauri::AppHandle) {
|
||||
let vault_path = match vault_list::load_vault_list() {
|
||||
Ok(vault_list) => selected_mcp_bridge_vault_path(&vault_list),
|
||||
Err(e) => {
|
||||
@@ -213,11 +209,19 @@ fn spawn_ws_bridge(app: &mut tauri::App) {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Err(e) = sync_ws_bridge_for_vault(app.handle(), Some(&vault_path)) {
|
||||
if let Err(e) = sync_ws_bridge_for_vault(app_handle, Some(&vault_path)) {
|
||||
log::warn!("Failed to start ws-bridge: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn spawn_initial_ws_bridge_sync(app: &tauri::App) {
|
||||
let app_handle = app.handle().clone();
|
||||
spawn_background_task("tolaria-ws-bridge-startup", move || {
|
||||
sync_ws_bridge_for_selected_vault(&app_handle);
|
||||
});
|
||||
}
|
||||
|
||||
fn setup_common_plugins(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
@@ -307,8 +311,8 @@ fn setup_app(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
#[cfg(desktop)]
|
||||
{
|
||||
run_startup_tasks();
|
||||
spawn_ws_bridge(app);
|
||||
spawn_startup_tasks();
|
||||
spawn_initial_ws_bridge_sync(app);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -330,6 +334,18 @@ fn vault_asset_scope_roots(vault_path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
fn missing_asset_scope_roots(
|
||||
allowed_roots: &[PathBuf],
|
||||
requested_roots: &[PathBuf],
|
||||
) -> Vec<PathBuf> {
|
||||
requested_roots
|
||||
.iter()
|
||||
.filter(|root| !allowed_roots.contains(root))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
pub(crate) fn sync_vault_asset_scope(
|
||||
app_handle: &tauri::AppHandle,
|
||||
@@ -337,27 +353,22 @@ pub(crate) fn sync_vault_asset_scope(
|
||||
) -> Result<(), String> {
|
||||
use tauri::Manager;
|
||||
|
||||
let next_roots = vault_asset_scope_roots(vault_path)?;
|
||||
let requested_roots = vault_asset_scope_roots(vault_path)?;
|
||||
let scope = app_handle.asset_protocol_scope();
|
||||
let state: tauri::State<'_, ActiveAssetScopeRoots> = app_handle.state();
|
||||
let mut active_roots = state
|
||||
let state: tauri::State<'_, AllowedAssetScopeRoots> = app_handle.state();
|
||||
let mut allowed_roots = state
|
||||
.0
|
||||
.lock()
|
||||
.map_err(|_| "Failed to lock active asset scope state".to_string())?;
|
||||
.map_err(|_| "Failed to lock asset scope state".to_string())?;
|
||||
let roots_to_allow = missing_asset_scope_roots(&allowed_roots, &requested_roots);
|
||||
|
||||
for root in &next_roots {
|
||||
for root in &roots_to_allow {
|
||||
scope
|
||||
.allow_directory(root, true)
|
||||
.map_err(|e| format!("Failed to allow asset access for {}: {e}", root.display()))?;
|
||||
}
|
||||
|
||||
for previous_root in active_roots.iter() {
|
||||
if !next_roots.contains(previous_root) {
|
||||
let _ = scope.forbid_directory(previous_root, true);
|
||||
}
|
||||
}
|
||||
|
||||
*active_roots = next_roots;
|
||||
allowed_roots.extend(roots_to_allow);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -367,6 +378,7 @@ macro_rules! app_invoke_handler {
|
||||
commands::list_vault,
|
||||
commands::list_vault_folders,
|
||||
commands::get_note_content,
|
||||
commands::validate_note_content,
|
||||
commands::create_note_content,
|
||||
commands::save_note_content,
|
||||
commands::update_frontmatter,
|
||||
@@ -402,9 +414,14 @@ macro_rules! app_invoke_handler {
|
||||
commands::restore_vault_ai_guidance,
|
||||
commands::stream_claude_chat,
|
||||
commands::stream_ai_agent,
|
||||
commands::stream_ai_model,
|
||||
commands::save_ai_model_provider_api_key,
|
||||
commands::delete_ai_model_provider_api_key,
|
||||
commands::test_ai_model_provider,
|
||||
commands::reload_vault,
|
||||
commands::reload_vault_entry,
|
||||
commands::sync_vault_asset_scope_for_window,
|
||||
commands::open_vault_file_external,
|
||||
commands::sync_note_title,
|
||||
commands::save_image,
|
||||
commands::copy_image_to_vault,
|
||||
@@ -435,7 +452,11 @@ macro_rules! app_invoke_handler {
|
||||
commands::register_mcp_tools,
|
||||
commands::remove_mcp_tools,
|
||||
commands::check_mcp_status,
|
||||
commands::get_mcp_config_snippet,
|
||||
commands::copy_text_to_clipboard,
|
||||
commands::read_text_from_clipboard,
|
||||
commands::sync_mcp_bridge_vault,
|
||||
commands::get_process_memory_snapshot,
|
||||
commands::repair_vault,
|
||||
commands::reinit_telemetry,
|
||||
commands::list_views,
|
||||
@@ -460,22 +481,21 @@ fn handle_run_event(app_handle: &tauri::AppHandle, event: &tauri::RunEvent) {
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
let state: tauri::State<'_, WsBridgeChild> = app_handle.state();
|
||||
let mut guard = state.0.lock().unwrap();
|
||||
if let Some(ref mut child) = *guard {
|
||||
let _ = child.kill();
|
||||
log::info!("ws-bridge child process killed on exit");
|
||||
}
|
||||
stop_ws_bridge_child(&mut guard);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
apply_linux_appimage_startup_env_overrides();
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
linux_appimage::apply_startup_env_overrides();
|
||||
|
||||
let builder = tauri::Builder::default();
|
||||
|
||||
#[cfg(desktop)]
|
||||
let builder = builder
|
||||
.manage(WsBridgeChild(Mutex::new(None)))
|
||||
.manage(ActiveAssetScopeRoots(Mutex::new(Vec::new())))
|
||||
.manage(AllowedAssetScopeRoots(Mutex::new(Vec::new())))
|
||||
.manage(window_state::MainWindowFrameState::default())
|
||||
.manage(vault_watcher::VaultWatcherState::new());
|
||||
|
||||
@@ -491,15 +511,18 @@ pub fn run() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::linux_appimage_startup_env_overrides_with;
|
||||
use super::StartupEnvOverride;
|
||||
use super::MACOS_WEBVIEW_RESERVED_COMMAND_KEYS;
|
||||
use super::MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS;
|
||||
|
||||
#[cfg(desktop)]
|
||||
use super::{selected_mcp_bridge_vault_path, validate_mcp_bridge_vault_path};
|
||||
use super::{
|
||||
missing_asset_scope_roots, selected_mcp_bridge_vault_path,
|
||||
spawn_startup_tasks_for_vault_with, validate_mcp_bridge_vault_path,
|
||||
};
|
||||
#[cfg(desktop)]
|
||||
use crate::vault_list::VaultList;
|
||||
#[cfg(desktop)]
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(all(desktop, unix))]
|
||||
use super::vault_asset_scope_roots;
|
||||
@@ -510,40 +533,6 @@ mod tests {
|
||||
assert_eq!(MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS, ["L"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_appimage_startup_env_overrides_are_empty_outside_appimage_launches() {
|
||||
let overrides = linux_appimage_startup_env_overrides_with(|_| None);
|
||||
|
||||
assert!(overrides.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_appimage_startup_env_overrides_disable_dmabuf_for_appimages() {
|
||||
let overrides = linux_appimage_startup_env_overrides_with(|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
overrides,
|
||||
vec![StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
value: "1",
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_appimage_startup_env_overrides_preserve_explicit_user_setting() {
|
||||
let overrides = linux_appimage_startup_env_overrides_with(|key| match key {
|
||||
"APPDIR" => Some("/tmp/.mount_Tolaria".to_string()),
|
||||
"WEBKIT_DISABLE_DMABUF_RENDERER" => Some("0".to_string()),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert!(overrides.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn selected_mcp_bridge_vault_path_uses_persisted_active_vault() {
|
||||
@@ -571,6 +560,42 @@ mod tests {
|
||||
assert_eq!(selected_mcp_bridge_vault_path(&list), None);
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn startup_tasks_skip_missing_legacy_vault() {
|
||||
let missing_vault = tempfile::tempdir().unwrap().path().join("missing");
|
||||
let called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let called_from_task = called.clone();
|
||||
|
||||
let spawned = spawn_startup_tasks_for_vault_with(missing_vault, move |_| {
|
||||
called_from_task.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
});
|
||||
|
||||
assert!(!spawned);
|
||||
assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn startup_tasks_run_in_background() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel();
|
||||
|
||||
let spawned = spawn_startup_tasks_for_vault_with(dir.path().to_path_buf(), move |_| {
|
||||
entered_tx.send(()).unwrap();
|
||||
release_rx
|
||||
.recv_timeout(std::time::Duration::from_secs(1))
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
assert!(spawned);
|
||||
entered_rx
|
||||
.recv_timeout(std::time::Duration::from_secs(1))
|
||||
.unwrap();
|
||||
release_tx.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn validate_mcp_bridge_vault_path_requires_existing_directory() {
|
||||
@@ -600,4 +625,20 @@ mod tests {
|
||||
assert_eq!(roots[0], canonical_vault.canonicalize().unwrap());
|
||||
assert!(roots.contains(&symlinked_vault));
|
||||
}
|
||||
|
||||
#[cfg(desktop)]
|
||||
#[test]
|
||||
fn missing_asset_scope_roots_keeps_previously_allowed_vaults() {
|
||||
let vault_a = PathBuf::from("/vault-a");
|
||||
let vault_b = PathBuf::from("/vault-b");
|
||||
let allowed_roots = vec![vault_a.clone()];
|
||||
|
||||
assert_eq!(
|
||||
missing_asset_scope_roots(&allowed_roots, std::slice::from_ref(&vault_b)),
|
||||
vec![vault_b]
|
||||
);
|
||||
assert!(
|
||||
missing_asset_scope_roots(&allowed_roots, std::slice::from_ref(&vault_a)).is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
474
src-tauri/src/linux_appimage.rs
Normal file
474
src-tauri/src/linux_appimage.rs
Normal file
@@ -0,0 +1,474 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct StartupEnvOverride {
|
||||
key: &'static str,
|
||||
value: &'static str,
|
||||
}
|
||||
|
||||
const LINUX_APPIMAGE_WEBKIT_OVERRIDES: [StartupEnvOverride; 2] = [
|
||||
StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
value: "1",
|
||||
},
|
||||
StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_COMPOSITING_MODE",
|
||||
value: "1",
|
||||
},
|
||||
];
|
||||
|
||||
const COLRV1_EMOJI_FONT_FILE: &str = "Noto-COLRv1.ttf";
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
const TOLARIA_COLRV1_FONTCONFIG_FILE: &str = "tolaria-appimage-no-colrv1-emoji.conf";
|
||||
|
||||
const WAYLAND_CLIENT_PRELOAD_CANDIDATES: [&str; 7] = [
|
||||
"/usr/lib64/libwayland-client.so.0",
|
||||
"/usr/lib64/libwayland-client.so",
|
||||
"/lib64/libwayland-client.so.0",
|
||||
"/usr/lib/x86_64-linux-gnu/libwayland-client.so.0",
|
||||
"/lib/x86_64-linux-gnu/libwayland-client.so.0",
|
||||
"/usr/lib/libwayland-client.so.0",
|
||||
"/usr/lib/libwayland-client.so",
|
||||
];
|
||||
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
const PROCESS_ELF_CLASS: u8 = 2;
|
||||
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const PROCESS_ELF_CLASS: u8 = 1;
|
||||
|
||||
fn is_linux_appimage_launch<F>(mut get_var: F) -> bool
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
["APPIMAGE", "APPDIR"]
|
||||
.into_iter()
|
||||
.any(|key| get_var(key).is_some_and(|value| !value.trim().is_empty()))
|
||||
}
|
||||
|
||||
fn has_non_empty_env<F>(get_var: &mut F, key: &str) -> bool
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
get_var(key).is_some_and(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
fn has_explicit_fontconfig_env<F>(get_var: &mut F) -> bool
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
["FONTCONFIG_FILE", "FONTCONFIG_PATH"]
|
||||
.into_iter()
|
||||
.any(|key| has_non_empty_env(get_var, key))
|
||||
}
|
||||
|
||||
fn can_apply_colrv1_font_guard<F>(get_var: &mut F) -> bool
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
if !is_linux_appimage_launch(&mut *get_var) {
|
||||
return false;
|
||||
}
|
||||
|
||||
!has_explicit_fontconfig_env(get_var)
|
||||
}
|
||||
|
||||
fn is_wayland_session<F>(mut get_var: F) -> bool
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
has_non_empty_env(&mut get_var, "WAYLAND_DISPLAY")
|
||||
|| get_var("XDG_SESSION_TYPE")
|
||||
.is_some_and(|value| value.trim().eq_ignore_ascii_case("wayland"))
|
||||
}
|
||||
|
||||
fn elf_library_matches_process(path: &std::path::Path) -> bool {
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut header = [0; 5];
|
||||
if std::io::Read::read_exact(&mut file, &mut header).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
header[..4] == *b"\x7FELF" && header[4] == PROCESS_ELF_CLASS
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn wayland_preload_candidate_matches(path: &str) -> bool {
|
||||
let path = std::path::Path::new(path);
|
||||
|
||||
path.is_file() && elf_library_matches_process(path)
|
||||
}
|
||||
|
||||
fn wayland_client_preload_path_with<F, E>(
|
||||
mut get_var: F,
|
||||
mut candidate_matches: E,
|
||||
) -> Option<&'static str>
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
E: FnMut(&str) -> bool,
|
||||
{
|
||||
if !is_linux_appimage_launch(&mut get_var) || !is_wayland_session(&mut get_var) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if has_non_empty_env(&mut get_var, "LD_PRELOAD")
|
||||
|| get_var("TOLARIA_APPIMAGE_WAYLAND_PRELOAD_ATTEMPTED").is_some_and(|value| value == "1")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
WAYLAND_CLIENT_PRELOAD_CANDIDATES
|
||||
.into_iter()
|
||||
.find(|path| candidate_matches(path))
|
||||
}
|
||||
|
||||
fn colrv1_emoji_font_path_with<F, M>(mut get_var: F, mut match_emoji_font: M) -> Option<String>
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
M: FnMut() -> Option<String>,
|
||||
{
|
||||
if !can_apply_colrv1_font_guard(&mut get_var) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let font_path = match_emoji_font()?;
|
||||
|
||||
std::path::Path::new(font_path.trim())
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case(COLRV1_EMOJI_FONT_FILE))
|
||||
.then(|| font_path.trim().to_string())
|
||||
}
|
||||
|
||||
fn escape_xml_text(value: &str) -> String {
|
||||
value
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
fn colrv1_emoji_fontconfig_contents(rejected_font_path: &str) -> String {
|
||||
format!(
|
||||
r#"<?xml version="1.0"?>
|
||||
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
|
||||
<fontconfig>
|
||||
<include ignore_missing="yes">/etc/fonts/fonts.conf</include>
|
||||
<selectfont>
|
||||
<rejectfont>
|
||||
<pattern>
|
||||
<patelt name="file">
|
||||
<string>{}</string>
|
||||
</patelt>
|
||||
</pattern>
|
||||
</rejectfont>
|
||||
</selectfont>
|
||||
</fontconfig>
|
||||
"#,
|
||||
escape_xml_text(rejected_font_path)
|
||||
)
|
||||
}
|
||||
|
||||
fn startup_env_overrides_with<F>(mut get_var: F) -> Vec<StartupEnvOverride>
|
||||
where
|
||||
F: FnMut(&str) -> Option<String>,
|
||||
{
|
||||
if !is_linux_appimage_launch(&mut get_var) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
LINUX_APPIMAGE_WEBKIT_OVERRIDES
|
||||
.into_iter()
|
||||
.filter(|env_override| !has_non_empty_env(&mut get_var, env_override.key))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
pub(crate) fn apply_startup_env_overrides() {
|
||||
apply_wayland_client_preload();
|
||||
apply_colrv1_emoji_font_guard();
|
||||
|
||||
for env_override in startup_env_overrides_with(|key| std::env::var(key).ok()) {
|
||||
std::env::set_var(env_override.key, env_override.value);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn apply_colrv1_emoji_font_guard() {
|
||||
let Some(font_path) =
|
||||
colrv1_emoji_font_path_with(|key| std::env::var(key).ok(), match_emoji_font_path)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(config_path) = colrv1_fontconfig_file_path() else {
|
||||
eprintln!("Tolaria AppImage COLRv1 font guard skipped: failed to resolve cache directory");
|
||||
return;
|
||||
};
|
||||
let Some(parent) = config_path.parent() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Err(error) = std::fs::create_dir_all(parent) {
|
||||
eprintln!("Tolaria AppImage COLRv1 font guard skipped: failed to prepare cache ({error})");
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = std::fs::write(&config_path, colrv1_emoji_fontconfig_contents(&font_path)) {
|
||||
eprintln!("Tolaria AppImage COLRv1 font guard skipped: failed to write config ({error})");
|
||||
return;
|
||||
}
|
||||
|
||||
std::env::set_var("FONTCONFIG_FILE", config_path.as_os_str());
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn match_emoji_font_path() -> Option<String> {
|
||||
let output = std::process::Command::new("fc-match")
|
||||
.args(["-f", "%{file}\n", "emoji"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn colrv1_fontconfig_file_path() -> Option<std::path::PathBuf> {
|
||||
let cache_dir =
|
||||
dirs::cache_dir().or_else(|| dirs::home_dir().map(|home| home.join(".cache")))?;
|
||||
|
||||
Some(
|
||||
cache_dir
|
||||
.join("tolaria")
|
||||
.join(TOLARIA_COLRV1_FONTCONFIG_FILE),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(all(desktop, target_os = "linux"))]
|
||||
fn apply_wayland_client_preload() {
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
let Some(preload_path) = wayland_client_preload_path_with(
|
||||
|key| std::env::var(key).ok(),
|
||||
wayland_preload_candidate_matches,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let exe = match std::env::current_exe() {
|
||||
Ok(exe) => exe,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Tolaria AppImage Wayland preload skipped: failed to resolve executable ({e})"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let error = std::process::Command::new(exe)
|
||||
.args(std::env::args_os().skip(1))
|
||||
.env("LD_PRELOAD", preload_path)
|
||||
.env("TOLARIA_APPIMAGE_WAYLAND_PRELOAD_ATTEMPTED", "1")
|
||||
.exec();
|
||||
eprintln!("Tolaria AppImage Wayland preload skipped: failed to re-exec ({error})");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
colrv1_emoji_font_path_with, colrv1_emoji_fontconfig_contents, elf_library_matches_process,
|
||||
startup_env_overrides_with, wayland_client_preload_path_with, StartupEnvOverride,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn startup_env_overrides_are_empty_outside_appimage_launches() {
|
||||
let overrides = startup_env_overrides_with(|_| None);
|
||||
|
||||
assert!(overrides.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_env_overrides_disable_unstable_webkit_rendering_for_appimages() {
|
||||
let overrides = startup_env_overrides_with(|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
overrides,
|
||||
vec![
|
||||
StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
value: "1",
|
||||
},
|
||||
StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_COMPOSITING_MODE",
|
||||
value: "1",
|
||||
}
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_env_overrides_preserve_explicit_user_setting_per_variable() {
|
||||
let overrides = startup_env_overrides_with(|key| match key {
|
||||
"APPDIR" => Some("/tmp/.mount_Tolaria".to_string()),
|
||||
"WEBKIT_DISABLE_DMABUF_RENDERER" => Some("0".to_string()),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
overrides,
|
||||
vec![StartupEnvOverride {
|
||||
key: "WEBKIT_DISABLE_COMPOSITING_MODE",
|
||||
value: "1",
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colrv1_font_guard_targets_reported_appimage_emoji_font() {
|
||||
let font_path = colrv1_emoji_font_path_with(
|
||||
|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|| Some("/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf".to_string()),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
font_path.as_deref(),
|
||||
Some("/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colrv1_font_guard_preserves_explicit_fontconfig_settings() {
|
||||
let font_path = colrv1_emoji_font_path_with(
|
||||
|key| match key {
|
||||
"APPDIR" => Some("/tmp/.mount_Tolaria".to_string()),
|
||||
"FONTCONFIG_FILE" => Some("/tmp/custom-fontconfig.conf".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|| Some("/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf".to_string()),
|
||||
);
|
||||
|
||||
assert_eq!(font_path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colrv1_font_guard_ignores_other_emoji_fonts() {
|
||||
let font_path = colrv1_emoji_font_path_with(
|
||||
|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|| Some("/usr/share/fonts/noto/NotoColorEmoji.ttf".to_string()),
|
||||
);
|
||||
|
||||
assert_eq!(font_path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colrv1_fontconfig_includes_system_fonts_and_rejects_matched_file() {
|
||||
let contents = colrv1_emoji_fontconfig_contents("/tmp/fonts/A&B/Noto-COLRv1.ttf");
|
||||
|
||||
assert!(
|
||||
contents.contains("<include ignore_missing=\"yes\">/etc/fonts/fonts.conf</include>")
|
||||
);
|
||||
assert!(contents.contains("<patelt name=\"file\">"));
|
||||
assert!(contents.contains("<string>/tmp/fonts/A&B/Noto-COLRv1.ttf</string>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_preload_uses_first_available_system_library() {
|
||||
let preload_path = wayland_client_preload_path_with(
|
||||
|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
"XDG_SESSION_TYPE" => Some("wayland".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|path| path == "/lib/x86_64-linux-gnu/libwayland-client.so.0",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
preload_path,
|
||||
Some("/lib/x86_64-linux-gnu/libwayland-client.so.0")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_preload_prefers_fedora_lib64_over_usr_lib() {
|
||||
let preload_path = wayland_client_preload_path_with(
|
||||
|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
"XDG_SESSION_TYPE" => Some("wayland".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|path| {
|
||||
path == "/usr/lib/libwayland-client.so.0"
|
||||
|| path == "/usr/lib64/libwayland-client.so.0"
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(preload_path, Some("/usr/lib64/libwayland-client.so.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preload_library_rejects_wrong_elf_class() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let matching = dir.path().join("matching-libwayland-client.so.0");
|
||||
let mismatched = dir.path().join("mismatched-libwayland-client.so.0");
|
||||
let matching_class = if cfg!(target_pointer_width = "64") {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let mismatched_class = if matching_class == 2 { 1 } else { 2 };
|
||||
|
||||
std::fs::write(&matching, [0x7F, b'E', b'L', b'F', matching_class]).unwrap();
|
||||
std::fs::write(&mismatched, [0x7F, b'E', b'L', b'F', mismatched_class]).unwrap();
|
||||
|
||||
assert!(elf_library_matches_process(&matching));
|
||||
assert!(!elf_library_matches_process(&mismatched));
|
||||
assert!(!elf_library_matches_process(&dir.path().join("missing.so")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_preload_preserves_explicit_ld_preload() {
|
||||
let preload_path = wayland_client_preload_path_with(
|
||||
|key| match key {
|
||||
"APPDIR" => Some("/tmp/.mount_Tolaria".to_string()),
|
||||
"WAYLAND_DISPLAY" => Some("wayland-0".to_string()),
|
||||
"LD_PRELOAD" => Some("/custom/libwayland-client.so".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|_| true,
|
||||
);
|
||||
|
||||
assert_eq!(preload_path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_preload_is_empty_for_x11_sessions() {
|
||||
let preload_path = wayland_client_preload_path_with(
|
||||
|key| match key {
|
||||
"APPIMAGE" => Some("/tmp/Tolaria.AppImage".to_string()),
|
||||
"XDG_SESSION_TYPE" => Some("x11".to_string()),
|
||||
_ => None,
|
||||
},
|
||||
|_| true,
|
||||
);
|
||||
|
||||
assert_eq!(preload_path, None);
|
||||
}
|
||||
}
|
||||
@@ -17,30 +17,88 @@ pub enum McpStatus {
|
||||
|
||||
/// Find the `node` binary path at runtime.
|
||||
pub(crate) fn find_node() -> Result<PathBuf, String> {
|
||||
let output = node_lookup_command()
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to locate node on PATH: {e}"))?;
|
||||
if output.status.success() {
|
||||
if let Some(path) = first_node_lookup_path(&output.stdout) {
|
||||
verify_node_version(&path)?;
|
||||
return Ok(path);
|
||||
let mut last_error = None;
|
||||
for path in node_binary_candidates() {
|
||||
match verify_node_version(&path) {
|
||||
Ok(()) => return Ok(path),
|
||||
Err(error) => last_error = Some(error),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = fallback_node_path() {
|
||||
verify_node_version(&path)?;
|
||||
return Ok(path);
|
||||
}
|
||||
|
||||
Err("node not found in PATH or common install locations".into())
|
||||
Err(last_error.unwrap_or_else(|| "node not found in PATH or common install locations".into()))
|
||||
}
|
||||
|
||||
fn first_node_lookup_path(stdout: &[u8]) -> Option<PathBuf> {
|
||||
fn node_binary_candidates() -> Vec<PathBuf> {
|
||||
let mut candidates = find_node_on_path();
|
||||
candidates.extend(find_node_in_user_shell());
|
||||
candidates.extend(fallback_node_paths());
|
||||
candidates
|
||||
}
|
||||
|
||||
fn find_node_on_path() -> Vec<PathBuf> {
|
||||
node_lookup_command()
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| node_lookup_paths(&output.stdout))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn find_node_in_user_shell() -> Vec<PathBuf> {
|
||||
user_shell_candidates()
|
||||
.into_iter()
|
||||
.filter(|shell| shell.exists())
|
||||
.filter_map(|shell| command_path_from_shell(&shell, "node"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn node_lookup_paths(stdout: &[u8]) -> Vec<PathBuf> {
|
||||
String::from_utf8_lossy(stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn user_shell_candidates() -> Vec<PathBuf> {
|
||||
let mut shells = Vec::new();
|
||||
if let Some(shell) = std::env::var_os("SHELL") {
|
||||
if !shell.is_empty() {
|
||||
shells.push(PathBuf::from(shell));
|
||||
}
|
||||
}
|
||||
shells.push(PathBuf::from("/bin/zsh"));
|
||||
shells.push(PathBuf::from("/bin/bash"));
|
||||
shells
|
||||
}
|
||||
|
||||
fn command_path_from_shell(shell: &Path, command: &str) -> Option<PathBuf> {
|
||||
crate::hidden_command(shell)
|
||||
.arg("-lc")
|
||||
.arg(format!("command -v {command}"))
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_from_successful_output(output: &std::process::Output) -> Option<PathBuf> {
|
||||
if output.status.success() {
|
||||
first_existing_path(&String::from_utf8_lossy(&output.stdout))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn first_existing_path(stdout: &str) -> Option<PathBuf> {
|
||||
stdout.lines().find_map(|line| {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let candidate = PathBuf::from(trimmed);
|
||||
candidate.exists().then_some(candidate)
|
||||
})
|
||||
}
|
||||
|
||||
fn verify_node_version(node: &Path) -> Result<(), String> {
|
||||
@@ -91,7 +149,7 @@ fn node_lookup_command() -> Command {
|
||||
command
|
||||
}
|
||||
|
||||
fn fallback_node_path() -> Option<PathBuf> {
|
||||
fn fallback_node_paths() -> Vec<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/opt/homebrew/bin/node"),
|
||||
PathBuf::from("/usr/local/bin/node"),
|
||||
@@ -120,24 +178,39 @@ fn fallback_node_path() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
candidates.push(home.join(".volta").join("bin").join(node_binary_name()));
|
||||
|
||||
let nvm_dir = home.join(".nvm").join("versions").join("node");
|
||||
if let Ok(entries) = std::fs::read_dir(nvm_dir) {
|
||||
let mut versions = entries
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.collect::<Vec<_>>();
|
||||
versions.sort();
|
||||
versions.reverse();
|
||||
candidates.extend(
|
||||
versions
|
||||
.into_iter()
|
||||
.map(|version| version.join("bin").join("node")),
|
||||
);
|
||||
}
|
||||
candidates.extend(node_binary_candidates_for_home(&home));
|
||||
}
|
||||
|
||||
candidates.into_iter().find(|path| path.is_file())
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter(|path| path.is_file())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn node_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
home.join(".local/share/mise/shims")
|
||||
.join(node_binary_name()),
|
||||
home.join(".mise").join("shims").join(node_binary_name()),
|
||||
home.join(".asdf").join("shims").join(node_binary_name()),
|
||||
home.join(".volta").join("bin").join(node_binary_name()),
|
||||
];
|
||||
|
||||
let nvm_dir = home.join(".nvm").join("versions").join("node");
|
||||
if let Ok(entries) = std::fs::read_dir(nvm_dir) {
|
||||
let mut versions = entries
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.collect::<Vec<_>>();
|
||||
versions.sort();
|
||||
versions.reverse();
|
||||
candidates.extend(
|
||||
versions
|
||||
.into_iter()
|
||||
.map(|version| version.join("bin").join("node")),
|
||||
);
|
||||
}
|
||||
|
||||
candidates
|
||||
}
|
||||
|
||||
fn node_binary_name() -> &'static str {
|
||||
@@ -187,7 +260,7 @@ fn mcp_server_dir_candidates(
|
||||
candidates.push(exe_dir.join("mcp-server"));
|
||||
if let Some(bundle_root) = exe_dir.parent() {
|
||||
candidates.push(bundle_root.join("Resources").join("mcp-server"));
|
||||
candidates.push(bundle_root.join("lib").join("tolaria").join("mcp-server"));
|
||||
candidates.extend(linux_package_mcp_server_dirs(bundle_root));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,15 +274,23 @@ fn mcp_server_dir_candidates(
|
||||
);
|
||||
}
|
||||
|
||||
candidates.push(
|
||||
PathBuf::from("/usr")
|
||||
.join("lib")
|
||||
.join("tolaria")
|
||||
.join("mcp-server"),
|
||||
);
|
||||
candidates.extend(linux_package_mcp_server_dirs(Path::new("/usr/local")));
|
||||
candidates.extend(linux_package_mcp_server_dirs(Path::new("/usr")));
|
||||
candidates
|
||||
}
|
||||
|
||||
fn linux_package_mcp_server_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
root.join("Tolaria").join("mcp-server"),
|
||||
root.join("Tolaria").join("resources").join("mcp-server"),
|
||||
root.join("lib").join("tolaria").join("mcp-server"),
|
||||
root.join("lib")
|
||||
.join("tolaria")
|
||||
.join("resources")
|
||||
.join("mcp-server"),
|
||||
]
|
||||
}
|
||||
|
||||
fn mcp_server_dir_has_files(path: &Path) -> bool {
|
||||
path.join("index.js").is_file() && path.join("ws-bridge.js").is_file()
|
||||
}
|
||||
@@ -250,6 +331,7 @@ fn mcp_config_paths_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
home.join(".claude.json"),
|
||||
home.join(".claude").join("mcp.json"),
|
||||
home.join(".gemini").join("settings.json"),
|
||||
home.join(".cursor").join("mcp.json"),
|
||||
home.join(".config").join("mcp").join("mcp.json"),
|
||||
]
|
||||
@@ -313,6 +395,28 @@ fn build_mcp_entry(node_command: &str, index_js: &str, vault_path: &str) -> serd
|
||||
})
|
||||
}
|
||||
|
||||
fn build_mcp_config_snippet(entry: &serde_json::Value) -> Result<String, String> {
|
||||
let mut servers = serde_json::Map::new();
|
||||
servers.insert(MCP_SERVER_NAME.to_string(), entry.clone());
|
||||
let config = serde_json::json!({ "mcpServers": servers });
|
||||
|
||||
serde_json::to_string_pretty(&config)
|
||||
.map_err(|e| format!("Failed to serialize MCP config snippet: {e}"))
|
||||
}
|
||||
|
||||
/// Build the exact MCP config JSON users can copy into compatible tools.
|
||||
pub fn mcp_config_snippet(vault_path: &str) -> Result<String, String> {
|
||||
let node = find_node().map_err(|e| {
|
||||
format!("Node.js 18+ is required on PATH before Tolaria can build MCP config: {e}")
|
||||
})?;
|
||||
let server_dir = mcp_server_dir()?;
|
||||
let index_js = server_dir.join("index.js").to_string_lossy().into_owned();
|
||||
let node_command = node.to_string_lossy().into_owned();
|
||||
let entry = build_mcp_entry(&node_command, &index_js, vault_path);
|
||||
|
||||
build_mcp_config_snippet(&entry)
|
||||
}
|
||||
|
||||
/// Write MCP registration to a list of config file paths.
|
||||
/// Returns "registered" on first registration, "updated" if already present.
|
||||
fn register_mcp_to_configs(entry: &serde_json::Value, config_paths: &[PathBuf]) -> String {
|
||||
@@ -502,6 +606,20 @@ mod tests {
|
||||
write_config_json(config_path, serde_json::json!({ "mcpServers": servers }));
|
||||
}
|
||||
|
||||
struct ExpectedMcpServer<'a> {
|
||||
index_js: &'a str,
|
||||
vault_path: &'a str,
|
||||
}
|
||||
|
||||
fn assert_registered_tolaria_server(
|
||||
config: &serde_json::Value,
|
||||
expected: ExpectedMcpServer<'_>,
|
||||
) {
|
||||
let server = &config["mcpServers"][MCP_SERVER_NAME];
|
||||
assert_eq!(server["args"][0], expected.index_js);
|
||||
assert_eq!(server["env"]["VAULT_PATH"], expected.vault_path);
|
||||
}
|
||||
|
||||
fn write_index_js(dir: &Path) -> PathBuf {
|
||||
let index_js = dir.join("index.js");
|
||||
std::fs::write(&index_js, "console.log('ok');").unwrap();
|
||||
@@ -511,22 +629,84 @@ mod tests {
|
||||
#[test]
|
||||
fn build_mcp_entry_produces_correct_json() {
|
||||
let entry = build_mcp_entry("/usr/local/bin/node", "/path/to/index.js", "/my/vault");
|
||||
assert_eq!(entry["type"], "stdio");
|
||||
assert_eq!(entry["command"], "/usr/local/bin/node");
|
||||
assert_eq!(entry["args"][0], "/path/to/index.js");
|
||||
assert_eq!(entry["env"]["VAULT_PATH"], "/my/vault");
|
||||
assert_eq!(entry["env"]["WS_UI_PORT"], "9711");
|
||||
assert_eq!(
|
||||
entry,
|
||||
serde_json::json!({
|
||||
"type": "stdio",
|
||||
"command": "/usr/local/bin/node",
|
||||
"args": ["/path/to/index.js"],
|
||||
"env": {
|
||||
"VAULT_PATH": "/my/vault",
|
||||
"WS_UI_PORT": "9711"
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_node_lookup_path_uses_first_non_empty_line() {
|
||||
fn build_mcp_config_snippet_wraps_tolaria_server_entry() {
|
||||
let entry = test_mcp_entry("/path/to/index.js", "/my/vault");
|
||||
let snippet = build_mcp_config_snippet(&entry).unwrap();
|
||||
let config: serde_json::Value = serde_json::from_str(&snippet).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
config["mcpServers"][MCP_SERVER_NAME]["args"][0],
|
||||
"/path/to/index.js"
|
||||
);
|
||||
assert_eq!(
|
||||
config["mcpServers"][MCP_SERVER_NAME]["env"]["VAULT_PATH"],
|
||||
"/my/vault"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_lookup_paths_keep_non_empty_lines_in_order() {
|
||||
let stdout = b"\nC:\\Program Files\\nodejs\\node.exe\r\nC:\\Other\\node.exe\r\n";
|
||||
assert_eq!(
|
||||
first_node_lookup_path(stdout).unwrap(),
|
||||
PathBuf::from("C:\\Program Files\\nodejs\\node.exe")
|
||||
node_lookup_paths(stdout),
|
||||
vec![
|
||||
PathBuf::from("C:\\Program Files\\nodejs\\node.exe"),
|
||||
PathBuf::from("C:\\Other\\node.exe"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_existing_path_skips_empty_and_missing_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let missing = dir.path().join("missing-node");
|
||||
let node = dir.path().join("node");
|
||||
std::fs::write(&node, "#!/bin/sh\n").unwrap();
|
||||
|
||||
let stdout = format!("\n{}\n{}\n", missing.display(), node.display());
|
||||
|
||||
assert_eq!(first_existing_path(&stdout), Some(node));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn command_path_from_shell_finds_node_from_login_shell() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let node = dir.path().join("node");
|
||||
std::fs::write(&node, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&node, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let shell = dir.path().join("shell");
|
||||
std::fs::write(
|
||||
&shell,
|
||||
format!(
|
||||
"#!/bin/sh\nif [ \"$1\" = \"-lc\" ]; then echo '{}'; fi\n",
|
||||
node.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert_eq!(command_path_from_shell(&shell, "node"), Some(node));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_major_version_accepts_current_node_output() {
|
||||
assert_eq!(node_major_version("v24.13.1\n"), Some(24));
|
||||
@@ -534,6 +714,25 @@ mod tests {
|
||||
assert_eq!(node_major_version("not-node"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_binary_candidates_include_shell_managed_installs() {
|
||||
let home = PathBuf::from("/Users/alex");
|
||||
let candidates = node_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".local/share/mise/shims/node"),
|
||||
home.join(".asdf/shims/node"),
|
||||
home.join(".volta/bin/node"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_dir_candidates_prefer_exe_dir_before_macos_resources() {
|
||||
let dev_path = Path::new("/repo/mcp-server");
|
||||
@@ -555,6 +754,35 @@ mod tests {
|
||||
assert!(windows_pos < macos_pos);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_dir_candidates_include_linux_package_resource_roots() {
|
||||
let dev_path = Path::new("/repo/mcp-server");
|
||||
let exe_path = Path::new("/usr/local/tolaria/tolaria");
|
||||
let candidates = mcp_server_dir_candidates(dev_path, exe_path, None);
|
||||
let expected = [
|
||||
PathBuf::from("/usr/local/Tolaria/mcp-server"),
|
||||
PathBuf::from("/usr/local/Tolaria/resources/mcp-server"),
|
||||
PathBuf::from("/usr/local/lib/tolaria/mcp-server"),
|
||||
PathBuf::from("/usr/local/lib/tolaria/resources/mcp-server"),
|
||||
PathBuf::from("/usr/lib/tolaria/mcp-server"),
|
||||
PathBuf::from("/usr/lib/tolaria/resources/mcp-server"),
|
||||
];
|
||||
|
||||
assert!(expected.iter().all(|path| candidates.contains(path)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_dir_candidates_include_linux_appimage_resource_root() {
|
||||
let dev_path = Path::new("/repo/mcp-server");
|
||||
let exe_path = Path::new("/tmp/.mount_tolaria/usr/bin/tolaria");
|
||||
let appdir = Path::new("/tmp/.mount_tolaria");
|
||||
let candidates = mcp_server_dir_candidates(dev_path, exe_path, Some(appdir));
|
||||
|
||||
assert!(candidates.contains(&PathBuf::from(
|
||||
"/tmp/.mount_tolaria/usr/lib/tolaria/resources/mcp-server"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_creates_new_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -565,13 +793,12 @@ mod tests {
|
||||
assert!(!was_update);
|
||||
|
||||
let config = read_config(&config_path);
|
||||
assert_eq!(
|
||||
config["mcpServers"][MCP_SERVER_NAME]["args"][0],
|
||||
"/test/index.js"
|
||||
);
|
||||
assert_eq!(
|
||||
config["mcpServers"][MCP_SERVER_NAME]["env"]["VAULT_PATH"],
|
||||
"/test/vault"
|
||||
assert_registered_tolaria_server(
|
||||
&config,
|
||||
ExpectedMcpServer {
|
||||
index_js: "/test/index.js",
|
||||
vault_path: "/test/vault",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -660,10 +887,44 @@ mod tests {
|
||||
upsert_mcp_config(&config_path, &entry).unwrap();
|
||||
|
||||
let config = read_config(&config_path);
|
||||
assert_eq!(config["model"], "sonnet");
|
||||
assert_eq!(config["theme"], "dark");
|
||||
assert!(config["mcpServers"]["other-server"].is_object());
|
||||
assert!(config["mcpServers"][MCP_SERVER_NAME].is_object());
|
||||
assert_eq!(
|
||||
(
|
||||
config["model"].as_str(),
|
||||
config["theme"].as_str(),
|
||||
config["mcpServers"]["other-server"].is_object(),
|
||||
config["mcpServers"][MCP_SERVER_NAME].is_object(),
|
||||
),
|
||||
(Some("sonnet"), Some("dark"), true, true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_preserves_gemini_settings_json_fields() {
|
||||
let (_tmp, config_path) = temp_config_path("settings.json");
|
||||
write_config_json(
|
||||
&config_path,
|
||||
serde_json::json!({
|
||||
"theme": "GitHub",
|
||||
"mcpServers": {
|
||||
"other": { "command": "example" }
|
||||
}
|
||||
}),
|
||||
);
|
||||
let entry = test_mcp_entry("/gemini/index.js", "/gemini-vault");
|
||||
|
||||
let was_update = upsert_mcp_config(&config_path, &entry).unwrap();
|
||||
let config = read_config(&config_path);
|
||||
|
||||
assert!(!was_update);
|
||||
assert_eq!(config["theme"], "GitHub");
|
||||
assert_eq!(config["mcpServers"]["other"]["command"], "example");
|
||||
assert_registered_tolaria_server(
|
||||
&config,
|
||||
ExpectedMcpServer {
|
||||
index_js: "/gemini/index.js",
|
||||
vault_path: "/gemini-vault",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -736,6 +997,7 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let claude_user_cfg = tmp.path().join(".claude.json");
|
||||
let claude_cfg = tmp.path().join("claude").join("mcp.json");
|
||||
let gemini_cfg = tmp.path().join(".gemini").join("settings.json");
|
||||
let cursor_cfg = tmp.path().join("cursor").join("mcp.json");
|
||||
let generic_cfg = tmp.path().join(".config").join("mcp").join("mcp.json");
|
||||
let entry = test_mcp_entry("/test/index.js", "/vault");
|
||||
@@ -745,21 +1007,29 @@ mod tests {
|
||||
&[
|
||||
claude_user_cfg.clone(),
|
||||
claude_cfg.clone(),
|
||||
gemini_cfg.clone(),
|
||||
cursor_cfg.clone(),
|
||||
generic_cfg.clone(),
|
||||
],
|
||||
);
|
||||
let config_paths = [
|
||||
&claude_user_cfg,
|
||||
&claude_cfg,
|
||||
&gemini_cfg,
|
||||
&cursor_cfg,
|
||||
&generic_cfg,
|
||||
];
|
||||
|
||||
assert!(claude_user_cfg.exists());
|
||||
assert!(claude_cfg.exists());
|
||||
assert!(cursor_cfg.exists());
|
||||
assert!(generic_cfg.exists());
|
||||
assert!(config_paths.iter().all(|config_path| config_path.exists()));
|
||||
|
||||
let raw = std::fs::read_to_string(&claude_user_cfg).unwrap();
|
||||
let config: serde_json::Value = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(
|
||||
config["mcpServers"][MCP_SERVER_NAME]["args"][0],
|
||||
"/test/index.js"
|
||||
assert_registered_tolaria_server(
|
||||
&config,
|
||||
ExpectedMcpServer {
|
||||
index_js: "/test/index.js",
|
||||
vault_path: "/vault",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -773,6 +1043,7 @@ mod tests {
|
||||
vec![
|
||||
home.join(".claude.json"),
|
||||
home.join(".claude").join("mcp.json"),
|
||||
home.join(".gemini").join("settings.json"),
|
||||
home.join(".cursor").join("mcp.json"),
|
||||
home.join(".config").join("mcp").join("mcp.json"),
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,58 +1,120 @@
|
||||
use crate::ai_agents::{AiAgentAvailability, AiAgentStreamEvent};
|
||||
use std::io::BufRead;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AgentStreamRequest {
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub vault_path: String,
|
||||
}
|
||||
pub use crate::cli_agent_runtime::AgentStreamRequest;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn check_cli() -> AiAgentAvailability {
|
||||
crate::opencode_discovery::check_cli()
|
||||
}
|
||||
|
||||
pub fn run_agent_stream<F>(request: AgentStreamRequest, mut emit: F) -> Result<String, String>
|
||||
pub fn run_agent_stream<F>(request: AgentStreamRequest, emit: F) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let binary = crate::opencode_discovery::find_binary()?;
|
||||
let mut command = crate::opencode_config::build_command(&binary, &request)?;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Failed to spawn opencode: {error}"))?;
|
||||
|
||||
let stdout = child.stdout.take().ok_or("No stdout handle")?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
let mut session_id = String::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let json = match crate::opencode_events::parse_line(line, &mut emit) {
|
||||
Some(json) => json,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if let Some(id) = crate::opencode_events::session_id(&json) {
|
||||
session_id = id.to_string();
|
||||
}
|
||||
|
||||
crate::opencode_events::dispatch_event(&json, &mut emit);
|
||||
}
|
||||
|
||||
let stderr_output = child
|
||||
.stderr
|
||||
.take()
|
||||
.and_then(|stderr| std::io::read_to_string(stderr).ok())
|
||||
.unwrap_or_default();
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|error| format!("Wait failed: {error}"))?;
|
||||
if !status.success() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: crate::opencode_events::format_error(stderr_output, status.to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
emit(AiAgentStreamEvent::Done);
|
||||
Ok(session_id)
|
||||
run_agent_stream_with_binary(&binary, request, emit)
|
||||
}
|
||||
|
||||
fn run_agent_stream_with_binary<F>(
|
||||
binary: &Path,
|
||||
request: AgentStreamRequest,
|
||||
emit: F,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let command = crate::opencode_config::build_command(binary, &request)?;
|
||||
crate::cli_agent_runtime::run_ai_agent_json_stream(
|
||||
command,
|
||||
"opencode",
|
||||
emit,
|
||||
crate::opencode_events::session_id,
|
||||
crate::opencode_events::dispatch_event,
|
||||
crate::opencode_events::format_error,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn executable_script(dir: &Path, body: &str) -> std::path::PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let script = dir.join("opencode");
|
||||
std::fs::write(&script, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
script
|
||||
}
|
||||
|
||||
fn request(vault_path: String) -> AgentStreamRequest {
|
||||
AgentStreamRequest {
|
||||
message: "Summarize".into(),
|
||||
system_prompt: None,
|
||||
vault_path,
|
||||
permission_mode: AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_maps_opencode_json_events() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"session","sessionID":"open_1"}'
|
||||
printf '%s\n' '{"type":"message","text":"Done"}'
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "open_1");
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Init { session_id } if session_id == "open_1"
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "Done"
|
||||
));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_reports_opencode_nonzero_exit_errors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"session","sessionID":"open_1"}'
|
||||
printf '%s\n' 'provider login required' >&2
|
||||
exit 3
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "open_1");
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::Error { message } if message.contains("provider configured")
|
||||
)));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
use crate::opencode_cli::AgentStreamRequest;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
@@ -7,12 +8,13 @@ pub(crate) fn build_command(
|
||||
request: &AgentStreamRequest,
|
||||
) -> Result<std::process::Command, String> {
|
||||
let mut command = crate::hidden_command(binary);
|
||||
crate::cli_agent_runtime::configure_agent_command_environment(&mut command, binary);
|
||||
command
|
||||
.args(build_args())
|
||||
.arg(build_prompt(request))
|
||||
.env(
|
||||
"OPENCODE_CONFIG_CONTENT",
|
||||
build_config(&request.vault_path)?,
|
||||
build_config(&request.vault_path, request.permission_mode)?,
|
||||
)
|
||||
.current_dir(&request.vault_path)
|
||||
.stdin(Stdio::null())
|
||||
@@ -26,30 +28,18 @@ fn build_args() -> Vec<String> {
|
||||
}
|
||||
|
||||
fn build_prompt(request: &AgentStreamRequest) -> String {
|
||||
match request
|
||||
.system_prompt
|
||||
.as_ref()
|
||||
.map(|prompt| prompt.trim())
|
||||
.filter(|prompt| !prompt.is_empty())
|
||||
{
|
||||
Some(system_prompt) => format!(
|
||||
"System instructions:\n{system_prompt}\n\nUser request:\n{}",
|
||||
request.message
|
||||
),
|
||||
None => request.message.clone(),
|
||||
}
|
||||
crate::cli_agent_runtime::build_prompt(&request.message, request.system_prompt.as_deref())
|
||||
}
|
||||
|
||||
fn build_config(vault_path: &str) -> Result<String, String> {
|
||||
let mcp_server = crate::mcp::mcp_server_dir()?.join("index.js");
|
||||
let mcp_server_path = mcp_server
|
||||
.to_str()
|
||||
.ok_or("Invalid MCP server path")?
|
||||
.to_string();
|
||||
fn build_config(
|
||||
vault_path: &str,
|
||||
permission_mode: AiAgentPermissionMode,
|
||||
) -> Result<String, String> {
|
||||
let mcp_server_path = crate::cli_agent_runtime::mcp_server_path_string()?;
|
||||
|
||||
serde_json::to_string(&serde_json::json!({
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": permission_config(),
|
||||
"permission": permission_config(permission_mode),
|
||||
"mcp": {
|
||||
"tolaria": {
|
||||
"type": "local",
|
||||
@@ -62,7 +52,12 @@ fn build_config(vault_path: &str) -> Result<String, String> {
|
||||
.map_err(|error| format!("Failed to serialize opencode config: {error}"))
|
||||
}
|
||||
|
||||
fn permission_config() -> serde_json::Value {
|
||||
fn permission_config(permission_mode: AiAgentPermissionMode) -> serde_json::Value {
|
||||
let bash_permission = match permission_mode {
|
||||
AiAgentPermissionMode::Safe => "deny",
|
||||
AiAgentPermissionMode::PowerUser => "allow",
|
||||
};
|
||||
|
||||
serde_json::json!({
|
||||
"read": "allow",
|
||||
"edit": "allow",
|
||||
@@ -70,7 +65,7 @@ fn permission_config() -> serde_json::Value {
|
||||
"grep": "allow",
|
||||
"list": "allow",
|
||||
"external_directory": "deny",
|
||||
"bash": "deny"
|
||||
"bash": bash_permission
|
||||
})
|
||||
}
|
||||
|
||||
@@ -85,6 +80,7 @@ mod tests {
|
||||
message: "Rename the note".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode: crate::ai_agents::AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +114,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn config_includes_permissions_and_tolaria_mcp_server() {
|
||||
if let Ok(config) = build_config("/tmp/vault") {
|
||||
if let Ok(config) =
|
||||
build_config("/tmp/vault", crate::ai_agents::AiAgentPermissionMode::Safe)
|
||||
{
|
||||
let json: serde_json::Value = serde_json::from_str(&config).unwrap();
|
||||
assert_eq!(json["permission"]["edit"], "allow");
|
||||
assert_eq!(json["permission"]["external_directory"], "deny");
|
||||
@@ -136,6 +134,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_user_config_allows_bash_but_keeps_external_directories_denied() {
|
||||
if let Ok(config) = build_config(
|
||||
"/tmp/vault",
|
||||
crate::ai_agents::AiAgentPermissionMode::PowerUser,
|
||||
) {
|
||||
let json: serde_json::Value = serde_json::from_str(&config).unwrap();
|
||||
assert_eq!(json["permission"]["bash"], "allow");
|
||||
assert_eq!(json["permission"]["external_directory"], "deny");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_keeps_system_prompt_first() {
|
||||
let prompt = build_prompt(&AgentStreamRequest {
|
||||
|
||||
@@ -5,7 +5,7 @@ pub(crate) fn check_cli() -> AiAgentAvailability {
|
||||
match find_binary() {
|
||||
Ok(binary) => AiAgentAvailability {
|
||||
installed: true,
|
||||
version: version_for_binary(&binary),
|
||||
version: crate::cli_agent_runtime::version_for_binary(&binary),
|
||||
},
|
||||
Err(_) => AiAgentAvailability {
|
||||
installed: false,
|
||||
@@ -23,30 +23,32 @@ pub(crate) fn find_binary() -> Result<PathBuf, String> {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
if let Some(binary) = find_existing_binary(opencode_binary_candidates()) {
|
||||
if let Some(binary) = crate::cli_agent_runtime::find_executable_binary_candidate(
|
||||
opencode_binary_candidates(),
|
||||
"OpenCode CLI",
|
||||
)? {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
Err("OpenCode CLI not found. Install it: https://opencode.ai/docs/".into())
|
||||
}
|
||||
|
||||
fn version_for_binary(binary: &PathBuf) -> Option<String> {
|
||||
crate::hidden_command(binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn find_binary_on_path() -> Option<PathBuf> {
|
||||
crate::hidden_command("which")
|
||||
crate::hidden_command(path_lookup_command())
|
||||
.arg("opencode")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_lookup_command() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"where"
|
||||
} else {
|
||||
"which"
|
||||
}
|
||||
}
|
||||
|
||||
fn find_binary_in_user_shell() -> Option<PathBuf> {
|
||||
user_shell_candidates()
|
||||
.into_iter()
|
||||
@@ -94,10 +96,6 @@ fn first_existing_path(stdout: &str) -> Option<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
fn find_existing_binary(candidates: Vec<PathBuf>) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|candidate| candidate.exists())
|
||||
}
|
||||
|
||||
fn opencode_binary_candidates() -> Vec<PathBuf> {
|
||||
dirs::home_dir()
|
||||
.map(|home| opencode_binary_candidates_for_home(&home))
|
||||
@@ -107,12 +105,28 @@ fn opencode_binary_candidates() -> Vec<PathBuf> {
|
||||
fn opencode_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
home.join(".local/bin/opencode"),
|
||||
home.join(".local/bin/opencode.exe"),
|
||||
home.join(".opencode/bin/opencode"),
|
||||
home.join(".opencode/bin/opencode.exe"),
|
||||
home.join(".local/share/mise/shims/opencode"),
|
||||
home.join(".local/share/mise/shims/opencode.exe"),
|
||||
home.join(".asdf/shims/opencode"),
|
||||
home.join(".asdf/shims/opencode.exe"),
|
||||
home.join(".npm-global/bin/opencode"),
|
||||
home.join(".npm-global/bin/opencode.cmd"),
|
||||
home.join(".npm-global/bin/opencode.exe"),
|
||||
home.join(".npm/bin/opencode"),
|
||||
home.join(".npm/bin/opencode.cmd"),
|
||||
home.join(".npm/bin/opencode.exe"),
|
||||
home.join(".bun/bin/opencode"),
|
||||
home.join(".bun/bin/opencode.exe"),
|
||||
home.join(".linuxbrew/bin/opencode"),
|
||||
home.join("AppData/Roaming/npm/opencode.cmd"),
|
||||
home.join("AppData/Roaming/npm/opencode.exe"),
|
||||
home.join("AppData/Local/pnpm/opencode.cmd"),
|
||||
home.join("AppData/Local/pnpm/opencode.exe"),
|
||||
home.join("scoop/shims/opencode.exe"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/opencode"),
|
||||
PathBuf::from("/usr/local/bin/opencode"),
|
||||
PathBuf::from("/opt/homebrew/bin/opencode"),
|
||||
]
|
||||
@@ -145,6 +159,56 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_linuxbrew_installs() {
|
||||
let home = PathBuf::from("/home/alex");
|
||||
let candidates = opencode_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".linuxbrew/bin/opencode"),
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/opencode"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_windows_npm_and_toolchain_shims() {
|
||||
let home = PathBuf::from(r"C:\Users\alex");
|
||||
let candidates = opencode_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".npm-global/bin/opencode.cmd"),
|
||||
home.join(".npm-global/bin/opencode.exe"),
|
||||
home.join(".npm/bin/opencode.cmd"),
|
||||
home.join(".npm/bin/opencode.exe"),
|
||||
home.join("AppData/Roaming/npm/opencode.cmd"),
|
||||
home.join("AppData/Roaming/npm/opencode.exe"),
|
||||
home.join("AppData/Local/pnpm/opencode.cmd"),
|
||||
home.join("AppData/Local/pnpm/opencode.exe"),
|
||||
home.join("scoop/shims/opencode.exe"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_lookup_command_matches_current_platform() {
|
||||
let expected = if cfg!(windows) { "where" } else { "which" };
|
||||
|
||||
assert_eq!(path_lookup_command(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_existing_path_skips_empty_and_missing_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::ai_agents::AiAgentStreamEvent;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_line<F>(
|
||||
line: Result<String, std::io::Error>,
|
||||
emit: &mut F,
|
||||
@@ -7,22 +8,7 @@ pub(crate) fn parse_line<F>(
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(error) => {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: format!("Read error: {error}"),
|
||||
});
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
serde_json::from_str::<serde_json::Value>(trimmed).ok()
|
||||
crate::cli_agent_runtime::parse_ai_agent_json_line(line, emit)
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_event<F>(json: &serde_json::Value, emit: &mut F)
|
||||
@@ -33,7 +19,7 @@ where
|
||||
emit_session_event(json, emit);
|
||||
}
|
||||
|
||||
match json["type"].as_str().unwrap_or_default() {
|
||||
match event_type(json) {
|
||||
"message" | "text" => emit_text(json, emit),
|
||||
"reasoning" => emit_reasoning(json, emit),
|
||||
"tool_use" | "tool" => emit_tool_start(json, emit),
|
||||
@@ -43,6 +29,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn event_type(json: &serde_json::Value) -> &str {
|
||||
let direct = json["type"].as_str().unwrap_or_default();
|
||||
match direct {
|
||||
"session" | "message" | "text" | "reasoning" | "tool_use" | "tool" | "tool_result"
|
||||
| "tool_done" | "error" => direct,
|
||||
_ => json["part"]["type"].as_str().unwrap_or(direct),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn session_id(json: &serde_json::Value) -> Option<&str> {
|
||||
json["sessionID"]
|
||||
.as_str()
|
||||
@@ -101,12 +96,8 @@ where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let tool_id = tool_id(json).unwrap_or("tool").to_string();
|
||||
let tool_name = json["name"]
|
||||
.as_str()
|
||||
.or_else(|| json["tool"].as_str())
|
||||
.unwrap_or("tool")
|
||||
.to_string();
|
||||
let input = json.get("input").map(|input| input.to_string());
|
||||
let tool_name = tool_name(json).unwrap_or("tool").to_string();
|
||||
let input = tool_input(json);
|
||||
|
||||
emit(AiAgentStreamEvent::ToolStart {
|
||||
tool_name,
|
||||
@@ -120,10 +111,7 @@ where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let tool_id = tool_id(json).unwrap_or("tool").to_string();
|
||||
let output = json["output"]
|
||||
.as_str()
|
||||
.map(|output| output.to_string())
|
||||
.or_else(|| json.get("result").map(|result| result.to_string()));
|
||||
let output = tool_output(json);
|
||||
|
||||
emit(AiAgentStreamEvent::ToolDone { tool_id, output });
|
||||
}
|
||||
@@ -140,24 +128,50 @@ where
|
||||
}
|
||||
|
||||
fn tool_id(json: &serde_json::Value) -> Option<&str> {
|
||||
json["id"]
|
||||
.as_str()
|
||||
.or_else(|| json["toolID"].as_str())
|
||||
.or_else(|| json["tool_id"].as_str())
|
||||
first_string_field(
|
||||
json,
|
||||
&["id", "toolID", "tool_id", "toolCallID", "toolCallId"],
|
||||
)
|
||||
}
|
||||
|
||||
fn text_value(json: &serde_json::Value) -> Option<&str> {
|
||||
json["text"]
|
||||
.as_str()
|
||||
.or_else(|| json["content"].as_str())
|
||||
.or_else(|| json["message"].as_str())
|
||||
first_string_field(json, &["text", "content", "message"])
|
||||
}
|
||||
|
||||
fn message_value(json: &serde_json::Value) -> Option<&str> {
|
||||
json["message"]
|
||||
first_string_field(json, &["message", "error", "text"])
|
||||
}
|
||||
|
||||
fn tool_name(json: &serde_json::Value) -> Option<&str> {
|
||||
first_string_field(json, &["name", "tool", "toolName"])
|
||||
}
|
||||
|
||||
fn tool_input(json: &serde_json::Value) -> Option<String> {
|
||||
first_json_field(json, &["input", "args"]).map(|input| input.to_string())
|
||||
}
|
||||
|
||||
fn tool_output(json: &serde_json::Value) -> Option<String> {
|
||||
first_json_field(json, &["output", "result"]).map(display_json_value)
|
||||
}
|
||||
|
||||
fn first_string_field<'a>(json: &'a serde_json::Value, keys: &[&str]) -> Option<&'a str> {
|
||||
keys.iter()
|
||||
.find_map(|key| json[*key].as_str().or_else(|| json["part"][*key].as_str()))
|
||||
}
|
||||
|
||||
fn first_json_field<'a>(
|
||||
json: &'a serde_json::Value,
|
||||
keys: &[&str],
|
||||
) -> Option<&'a serde_json::Value> {
|
||||
keys.iter()
|
||||
.find_map(|key| json.get(*key).or_else(|| json["part"].get(*key)))
|
||||
}
|
||||
|
||||
fn display_json_value(value: &serde_json::Value) -> String {
|
||||
value
|
||||
.as_str()
|
||||
.or_else(|| json["error"].as_str())
|
||||
.or_else(|| json["text"].as_str())
|
||||
.map(|output| output.to_string())
|
||||
.unwrap_or_else(|| value.to_string())
|
||||
}
|
||||
|
||||
fn is_auth_error(lower: &str) -> bool {
|
||||
|
||||
@@ -1,5 +1,61 @@
|
||||
use super::*;
|
||||
|
||||
fn dispatch_events(events: impl IntoIterator<Item = serde_json::Value>) -> Vec<AiAgentStreamEvent> {
|
||||
let mut mapped = Vec::new();
|
||||
|
||||
for event in events {
|
||||
dispatch_event(&event, &mut |event| mapped.push(event));
|
||||
}
|
||||
|
||||
mapped
|
||||
}
|
||||
|
||||
struct ToolExpectation<'a> {
|
||||
tool_id: &'a str,
|
||||
tool_name: &'a str,
|
||||
input: Option<&'a str>,
|
||||
output: Option<&'a str>,
|
||||
}
|
||||
|
||||
fn assert_tool_pair(events: &[AiAgentStreamEvent], expected: ToolExpectation<'_>) {
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::ToolStart {
|
||||
tool_name: actual_name,
|
||||
tool_id: actual_id,
|
||||
input: actual_input,
|
||||
} if actual_name == expected.tool_name
|
||||
&& actual_id == expected.tool_id
|
||||
&& actual_input.as_deref() == expected.input
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::ToolDone {
|
||||
tool_id: actual_id,
|
||||
output: actual_output,
|
||||
} if actual_id == expected.tool_id && actual_output.as_deref() == expected.output
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_line_reports_read_errors_and_skips_blank_or_invalid_lines() {
|
||||
let mut events = Vec::new();
|
||||
|
||||
let read_error = parse_line(Err(std::io::Error::other("broken pipe")), &mut |event| {
|
||||
events.push(event)
|
||||
});
|
||||
let blank = parse_line(Ok(" ".into()), &mut |event| events.push(event));
|
||||
let invalid = parse_line(Ok("not json".into()), &mut |event| events.push(event));
|
||||
|
||||
assert!(read_error.is_none());
|
||||
assert!(blank.is_none());
|
||||
assert!(invalid.is_none());
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Error { message } if message.contains("broken pipe")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_session_reasoning_and_text() {
|
||||
let mut events = Vec::new();
|
||||
@@ -26,28 +82,137 @@ fn dispatch_maps_session_reasoning_and_text() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_tool_events() {
|
||||
fn dispatch_maps_part_backed_reasoning_and_text() {
|
||||
let mut events = Vec::new();
|
||||
let tool_start = serde_json::json!({
|
||||
"type": "tool_use",
|
||||
"id": "tool_1",
|
||||
"name": "read",
|
||||
"input": { "path": "Note.md" }
|
||||
let reasoning = serde_json::json!({
|
||||
"type": "reasoning",
|
||||
"part": { "type": "reasoning", "text": "Checking links" }
|
||||
});
|
||||
let text = serde_json::json!({
|
||||
"type": "text",
|
||||
"part": { "type": "text", "text": "Done from OpenCode" }
|
||||
});
|
||||
let tool_done = serde_json::json!({ "type": "tool_result", "id": "tool_1", "output": "ok" });
|
||||
|
||||
dispatch_event(&tool_start, &mut |event| events.push(event));
|
||||
dispatch_event(&tool_done, &mut |event| events.push(event));
|
||||
for event in [reasoning, text] {
|
||||
dispatch_event(&event, &mut |event| events.push(event));
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::ToolStart { tool_name, tool_id, input }
|
||||
if tool_name == "read" && tool_id == "tool_1" && input.as_deref() == Some(r#"{"path":"Note.md"}"#)
|
||||
AiAgentStreamEvent::ThinkingDelta { text } if text == "Checking links"
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::ToolDone { tool_id, output }
|
||||
if tool_id == "tool_1" && output.as_deref() == Some("ok")
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "Done from OpenCode"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_final_text_after_tool_part_wrappers() {
|
||||
let events = dispatch_events([
|
||||
serde_json::json!({
|
||||
"type": "part",
|
||||
"part": {
|
||||
"id": "prt_tool_1",
|
||||
"type": "tool",
|
||||
"tool": "webfetch",
|
||||
"input": { "url": "https://example.com" }
|
||||
}
|
||||
}),
|
||||
serde_json::json!({
|
||||
"type": "part",
|
||||
"part": {
|
||||
"id": "prt_text_1",
|
||||
"type": "text",
|
||||
"text": "Final answer after tool output."
|
||||
}
|
||||
}),
|
||||
serde_json::json!({
|
||||
"type": "part",
|
||||
"part": {
|
||||
"id": "prt_finish_1",
|
||||
"type": "step-finish",
|
||||
"reason": "stop"
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::ToolStart {
|
||||
tool_name,
|
||||
tool_id,
|
||||
input,
|
||||
} if tool_name == "webfetch"
|
||||
&& tool_id == "prt_tool_1"
|
||||
&& input.as_deref() == Some(r#"{"url":"https://example.com"}"#)
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "Final answer after tool output."
|
||||
));
|
||||
assert_eq!(events.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_tool_events() {
|
||||
let direct = dispatch_events([
|
||||
serde_json::json!({
|
||||
"type": "tool_use",
|
||||
"id": "tool_1",
|
||||
"name": "read",
|
||||
"input": { "path": "Note.md" }
|
||||
}),
|
||||
serde_json::json!({ "type": "tool_result", "id": "tool_1", "output": "ok" }),
|
||||
]);
|
||||
let part_backed = dispatch_events([
|
||||
serde_json::json!({
|
||||
"type": "tool_use",
|
||||
"part": {
|
||||
"id": "prt_tool_1",
|
||||
"tool": "read",
|
||||
"input": { "path": "Note.md" }
|
||||
}
|
||||
}),
|
||||
serde_json::json!({
|
||||
"type": "tool_result",
|
||||
"part": {
|
||||
"id": "prt_tool_1",
|
||||
"output": "ok"
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
assert_tool_pair(
|
||||
&direct,
|
||||
ToolExpectation {
|
||||
tool_id: "tool_1",
|
||||
tool_name: "read",
|
||||
input: Some(r#"{"path":"Note.md"}"#),
|
||||
output: Some("ok"),
|
||||
},
|
||||
);
|
||||
assert_tool_pair(
|
||||
&part_backed,
|
||||
ToolExpectation {
|
||||
tool_id: "prt_tool_1",
|
||||
tool_name: "read",
|
||||
input: Some(r#"{"path":"Note.md"}"#),
|
||||
output: Some("ok"),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_error_events() {
|
||||
let mut events = Vec::new();
|
||||
let error = serde_json::json!({ "type": "error", "message": "provider failed" });
|
||||
|
||||
dispatch_event(&error, &mut |event| events.push(event));
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Error { message } if message == "provider failed"
|
||||
));
|
||||
}
|
||||
|
||||
@@ -61,3 +226,12 @@ fn format_error_explains_missing_auth_or_provider_setup() {
|
||||
assert!(message.contains("OpenCode CLI is not authenticated"));
|
||||
assert!(message.contains("opencode auth login"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_error_uses_status_or_first_stderr_lines() {
|
||||
let empty = format_error(String::new(), "exit status: 2".into());
|
||||
let truncated = format_error("line 1\nline 2\nline 3\nline 4".into(), "ignored".into());
|
||||
|
||||
assert_eq!(empty, "opencode exited with status exit status: 2");
|
||||
assert_eq!(truncated, "line 1\nline 2\nline 3");
|
||||
}
|
||||
|
||||
@@ -1,62 +1,124 @@
|
||||
use crate::ai_agents::{AiAgentAvailability, AiAgentStreamEvent};
|
||||
use std::io::BufRead;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AgentStreamRequest {
|
||||
pub message: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub vault_path: String,
|
||||
}
|
||||
pub use crate::cli_agent_runtime::AgentStreamRequest;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn check_cli() -> AiAgentAvailability {
|
||||
crate::pi_discovery::check_cli()
|
||||
}
|
||||
|
||||
pub fn run_agent_stream<F>(request: AgentStreamRequest, mut emit: F) -> Result<String, String>
|
||||
pub fn run_agent_stream<F>(request: AgentStreamRequest, emit: F) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let binary = crate::pi_discovery::find_binary()?;
|
||||
run_agent_stream_with_binary(&binary, request, emit)
|
||||
}
|
||||
|
||||
fn run_agent_stream_with_binary<F>(
|
||||
binary: &Path,
|
||||
request: AgentStreamRequest,
|
||||
emit: F,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let agent_dir = tempfile::Builder::new()
|
||||
.prefix("tolaria-pi-agent-")
|
||||
.tempdir()
|
||||
.map_err(|error| format!("Failed to create Pi config directory: {error}"))?;
|
||||
let mut command = crate::pi_config::build_command(&binary, &request, agent_dir.path())?;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Failed to spawn pi: {error}"))?;
|
||||
|
||||
let stdout = child.stdout.take().ok_or("No stdout handle")?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
let mut session_id = String::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let json = match crate::pi_events::parse_line(line, &mut emit) {
|
||||
Some(json) => json,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if let Some(id) = crate::pi_events::session_id(&json) {
|
||||
session_id = id.to_string();
|
||||
}
|
||||
|
||||
crate::pi_events::dispatch_event(&json, &mut emit);
|
||||
}
|
||||
|
||||
let stderr_output = child
|
||||
.stderr
|
||||
.take()
|
||||
.and_then(|stderr| std::io::read_to_string(stderr).ok())
|
||||
.unwrap_or_default();
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|error| format!("Wait failed: {error}"))?;
|
||||
if !status.success() {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: crate::pi_events::format_error(stderr_output, status.to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
emit(AiAgentStreamEvent::Done);
|
||||
Ok(session_id)
|
||||
let command = crate::pi_config::build_command(binary, &request, agent_dir.path())?;
|
||||
crate::cli_agent_runtime::run_ai_agent_json_stream(
|
||||
command,
|
||||
"pi",
|
||||
emit,
|
||||
crate::pi_events::session_id,
|
||||
crate::pi_events::dispatch_event,
|
||||
crate::pi_events::format_error,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn executable_script(dir: &Path, body: &str) -> std::path::PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let script = dir.join("pi");
|
||||
std::fs::write(&script, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
script
|
||||
}
|
||||
|
||||
fn request(vault_path: String) -> AgentStreamRequest {
|
||||
AgentStreamRequest {
|
||||
message: "Summarize".into(),
|
||||
system_prompt: None,
|
||||
vault_path,
|
||||
permission_mode: AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_maps_pi_json_events() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"session","id":"pi_1"}'
|
||||
printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"Done"}}'
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "pi_1");
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Init { session_id } if session_id == "pi_1"
|
||||
));
|
||||
assert!(matches!(
|
||||
&events[1],
|
||||
AiAgentStreamEvent::TextDelta { text } if text == "Done"
|
||||
));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_agent_stream_reports_pi_nonzero_exit_errors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let binary = executable_script(
|
||||
dir.path(),
|
||||
r#"printf '%s\n' '{"type":"session","id":"pi_1"}'
|
||||
printf '%s\n' 'api key login required' >&2
|
||||
exit 4
|
||||
"#,
|
||||
);
|
||||
|
||||
let mut events = Vec::new();
|
||||
let session_id = run_agent_stream_with_binary(
|
||||
&binary,
|
||||
request(vault.path().to_string_lossy().into_owned()),
|
||||
|event| events.push(event),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session_id, "pi_1");
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
AiAgentStreamEvent::Error { message } if message.contains("not authenticated")
|
||||
)));
|
||||
assert!(matches!(events.last(), Some(AiAgentStreamEvent::Done)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::ai_agents::AiAgentPermissionMode;
|
||||
use crate::pi_cli::AgentStreamRequest;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
@@ -7,9 +8,10 @@ pub(crate) fn build_command(
|
||||
request: &AgentStreamRequest,
|
||||
agent_dir: &Path,
|
||||
) -> Result<std::process::Command, String> {
|
||||
write_mcp_config(agent_dir, &request.vault_path)?;
|
||||
write_mcp_config(agent_dir, &request.vault_path, request.permission_mode)?;
|
||||
|
||||
let mut command = crate::hidden_command(binary);
|
||||
crate::cli_agent_runtime::configure_agent_command_environment(&mut command, binary);
|
||||
command
|
||||
.args(build_args())
|
||||
.arg(build_prompt(request))
|
||||
@@ -32,34 +34,26 @@ fn build_args() -> Vec<String> {
|
||||
}
|
||||
|
||||
fn build_prompt(request: &AgentStreamRequest) -> String {
|
||||
match request
|
||||
.system_prompt
|
||||
.as_ref()
|
||||
.map(|prompt| prompt.trim())
|
||||
.filter(|prompt| !prompt.is_empty())
|
||||
{
|
||||
Some(system_prompt) => format!(
|
||||
"System instructions:\n{system_prompt}\n\nUser request:\n{}",
|
||||
request.message
|
||||
),
|
||||
None => request.message.clone(),
|
||||
}
|
||||
crate::cli_agent_runtime::build_prompt(&request.message, request.system_prompt.as_deref())
|
||||
}
|
||||
|
||||
fn write_mcp_config(agent_dir: &Path, vault_path: &str) -> Result<(), String> {
|
||||
fn write_mcp_config(
|
||||
agent_dir: &Path,
|
||||
vault_path: &str,
|
||||
permission_mode: AiAgentPermissionMode,
|
||||
) -> Result<(), String> {
|
||||
std::fs::create_dir_all(agent_dir)
|
||||
.map_err(|error| format!("Failed to create Pi agent directory: {error}"))?;
|
||||
let config = build_mcp_config(vault_path)?;
|
||||
let config = build_mcp_config(vault_path, permission_mode)?;
|
||||
std::fs::write(agent_dir.join("mcp.json"), config)
|
||||
.map_err(|error| format!("Failed to write Pi MCP config: {error}"))
|
||||
}
|
||||
|
||||
fn build_mcp_config(vault_path: &str) -> Result<String, String> {
|
||||
let mcp_server = crate::mcp::mcp_server_dir()?.join("index.js");
|
||||
let mcp_server_path = mcp_server
|
||||
.to_str()
|
||||
.ok_or("Invalid MCP server path")?
|
||||
.to_string();
|
||||
fn build_mcp_config(
|
||||
vault_path: &str,
|
||||
_permission_mode: AiAgentPermissionMode,
|
||||
) -> Result<String, String> {
|
||||
let mcp_server_path = crate::cli_agent_runtime::mcp_server_path_string()?;
|
||||
|
||||
serde_json::to_string(&serde_json::json!({
|
||||
"settings": {
|
||||
@@ -93,6 +87,7 @@ mod tests {
|
||||
message: "Rename the note".into(),
|
||||
system_prompt: None,
|
||||
vault_path: "/tmp/vault".into(),
|
||||
permission_mode: crate::ai_agents::AiAgentPermissionMode::Safe,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +124,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn mcp_config_includes_tolaria_server_for_active_vault() {
|
||||
if let Ok(config) = build_mcp_config("/tmp/vault") {
|
||||
if let Ok(config) =
|
||||
build_mcp_config("/tmp/vault", crate::ai_agents::AiAgentPermissionMode::Safe)
|
||||
{
|
||||
let json: serde_json::Value = serde_json::from_str(&config).unwrap();
|
||||
assert_eq!(json["settings"]["toolPrefix"], "none");
|
||||
assert_eq!(json["mcpServers"]["tolaria"]["command"], "node");
|
||||
@@ -147,6 +144,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_user_mode_uses_the_same_pi_mcp_config_as_safe_mode() {
|
||||
let safe =
|
||||
build_mcp_config("/tmp/vault", crate::ai_agents::AiAgentPermissionMode::Safe).unwrap();
|
||||
let power = build_mcp_config(
|
||||
"/tmp/vault",
|
||||
crate::ai_agents::AiAgentPermissionMode::PowerUser,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(safe, power);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_keeps_system_prompt_first() {
|
||||
let prompt = build_prompt(&AgentStreamRequest {
|
||||
|
||||
@@ -5,7 +5,7 @@ pub(crate) fn check_cli() -> AiAgentAvailability {
|
||||
match find_binary() {
|
||||
Ok(binary) => AiAgentAvailability {
|
||||
installed: true,
|
||||
version: version_for_binary(&binary),
|
||||
version: crate::cli_agent_runtime::version_for_binary(&binary),
|
||||
},
|
||||
Err(_) => AiAgentAvailability {
|
||||
installed: false,
|
||||
@@ -23,30 +23,32 @@ pub(crate) fn find_binary() -> Result<PathBuf, String> {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
if let Some(binary) = find_existing_binary(pi_binary_candidates()) {
|
||||
if let Some(binary) = crate::cli_agent_runtime::find_executable_binary_candidate(
|
||||
pi_binary_candidates(),
|
||||
"Pi CLI",
|
||||
)? {
|
||||
return Ok(binary);
|
||||
}
|
||||
|
||||
Err("Pi CLI not found. Install it: https://pi.dev".into())
|
||||
}
|
||||
|
||||
fn version_for_binary(binary: &PathBuf) -> Option<String> {
|
||||
crate::hidden_command(binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn find_binary_on_path() -> Option<PathBuf> {
|
||||
crate::hidden_command("which")
|
||||
crate::hidden_command(path_lookup_command())
|
||||
.arg("pi")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| path_from_successful_output(&output))
|
||||
}
|
||||
|
||||
fn path_lookup_command() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"where"
|
||||
} else {
|
||||
"which"
|
||||
}
|
||||
}
|
||||
|
||||
fn find_binary_in_user_shell() -> Option<PathBuf> {
|
||||
user_shell_candidates()
|
||||
.into_iter()
|
||||
@@ -94,30 +96,100 @@ fn first_existing_path(stdout: &str) -> Option<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
fn find_existing_binary(candidates: Vec<PathBuf>) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|candidate| candidate.exists())
|
||||
}
|
||||
|
||||
fn pi_binary_candidates() -> Vec<PathBuf> {
|
||||
dirs::home_dir()
|
||||
.map(|home| pi_binary_candidates_for_home(&home))
|
||||
.unwrap_or_default()
|
||||
let mut candidates = pi_binary_candidates_from_env();
|
||||
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
candidates.extend(pi_binary_candidates_for_home(&home));
|
||||
}
|
||||
|
||||
candidates.extend(pi_global_binary_candidates());
|
||||
candidates
|
||||
}
|
||||
|
||||
fn pi_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
vec![
|
||||
let mut candidates = pi_nvm_binary_candidates_for_home(home);
|
||||
candidates.extend([
|
||||
home.join(".local/bin/pi"),
|
||||
home.join(".local/bin/pi.exe"),
|
||||
home.join(".pi/bin/pi"),
|
||||
home.join(".pi/bin/pi.exe"),
|
||||
home.join(".local/share/mise/shims/pi"),
|
||||
home.join(".local/share/mise/shims/pi.exe"),
|
||||
home.join(".asdf/shims/pi"),
|
||||
home.join(".asdf/shims/pi.exe"),
|
||||
home.join(".npm-global/bin/pi"),
|
||||
home.join(".npm-global/bin/pi.cmd"),
|
||||
home.join(".npm-global/bin/pi.exe"),
|
||||
home.join(".npm/bin/pi"),
|
||||
home.join(".npm/bin/pi.cmd"),
|
||||
home.join(".npm/bin/pi.exe"),
|
||||
home.join(".bun/bin/pi"),
|
||||
home.join(".bun/bin/pi.exe"),
|
||||
home.join(".linuxbrew/bin/pi"),
|
||||
home.join("AppData/Roaming/npm/pi.cmd"),
|
||||
home.join("AppData/Roaming/npm/pi.exe"),
|
||||
home.join("AppData/Local/pnpm/pi.cmd"),
|
||||
home.join("AppData/Local/pnpm/pi.exe"),
|
||||
home.join("scoop/shims/pi.exe"),
|
||||
]);
|
||||
candidates
|
||||
}
|
||||
|
||||
fn pi_global_binary_candidates() -> Vec<PathBuf> {
|
||||
vec![
|
||||
PathBuf::from("/home/linuxbrew/.linuxbrew/bin/pi"),
|
||||
PathBuf::from("/usr/local/bin/pi"),
|
||||
PathBuf::from("/opt/homebrew/bin/pi"),
|
||||
]
|
||||
}
|
||||
|
||||
fn pi_binary_candidates_from_env() -> Vec<PathBuf> {
|
||||
let nvm_bin = std::env::var_os("NVM_BIN").map(PathBuf::from);
|
||||
let npm_config_prefix = std::env::var_os("npm_config_prefix").map(PathBuf::from);
|
||||
let npm_config_prefix_upper = std::env::var_os("NPM_CONFIG_PREFIX").map(PathBuf::from);
|
||||
|
||||
pi_binary_candidates_from_prefixes(nvm_bin, npm_config_prefix, npm_config_prefix_upper)
|
||||
}
|
||||
|
||||
fn pi_binary_candidates_from_prefixes(
|
||||
nvm_bin: Option<PathBuf>,
|
||||
npm_config_prefix: Option<PathBuf>,
|
||||
npm_config_prefix_upper: Option<PathBuf>,
|
||||
) -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
|
||||
if let Some(path) = nvm_bin.filter(|path| !path.as_os_str().is_empty()) {
|
||||
candidates.push(path.join("pi"));
|
||||
}
|
||||
if let Some(path) = npm_config_prefix.filter(|path| !path.as_os_str().is_empty()) {
|
||||
candidates.push(path.join("bin/pi"));
|
||||
}
|
||||
if let Some(path) = npm_config_prefix_upper.filter(|path| !path.as_os_str().is_empty()) {
|
||||
candidates.push(path.join("bin/pi"));
|
||||
}
|
||||
|
||||
candidates
|
||||
}
|
||||
|
||||
fn pi_nvm_binary_candidates_for_home(home: &Path) -> Vec<PathBuf> {
|
||||
let versions_dir = home.join(".nvm/versions/node");
|
||||
let mut version_dirs = match std::fs::read_dir(versions_dir) {
|
||||
Ok(entries) => entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.is_dir())
|
||||
.collect::<Vec<_>>(),
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
version_dirs.sort_by(|left, right| right.file_name().cmp(&left.file_name()));
|
||||
version_dirs
|
||||
.into_iter()
|
||||
.map(|version_dir| version_dir.join("bin/pi"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -133,7 +205,6 @@ mod tests {
|
||||
home.join(".asdf/shims/pi"),
|
||||
home.join(".npm-global/bin/pi"),
|
||||
home.join(".bun/bin/pi"),
|
||||
PathBuf::from("/opt/homebrew/bin/pi"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
@@ -145,6 +216,105 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_linuxbrew_installs() {
|
||||
let home = PathBuf::from("/home/alex");
|
||||
let home_candidates = pi_binary_candidates_for_home(&home);
|
||||
let global_candidates = pi_global_binary_candidates();
|
||||
let expected_home = home.join(".linuxbrew/bin/pi");
|
||||
let expected_global = PathBuf::from("/home/linuxbrew/.linuxbrew/bin/pi");
|
||||
|
||||
assert!(
|
||||
home_candidates.contains(&expected_home),
|
||||
"missing {}",
|
||||
expected_home.display()
|
||||
);
|
||||
assert!(
|
||||
global_candidates.contains(&expected_global),
|
||||
"missing {}",
|
||||
expected_global.display()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_windows_npm_and_toolchain_shims() {
|
||||
let home = PathBuf::from(r"C:\Users\alex");
|
||||
let candidates = pi_binary_candidates_for_home(&home);
|
||||
let expected = [
|
||||
home.join(".npm-global/bin/pi.cmd"),
|
||||
home.join(".npm-global/bin/pi.exe"),
|
||||
home.join(".npm/bin/pi.cmd"),
|
||||
home.join(".npm/bin/pi.exe"),
|
||||
home.join("AppData/Roaming/npm/pi.cmd"),
|
||||
home.join("AppData/Roaming/npm/pi.exe"),
|
||||
home.join("AppData/Local/pnpm/pi.cmd"),
|
||||
home.join("AppData/Local/pnpm/pi.exe"),
|
||||
home.join("scoop/shims/pi.exe"),
|
||||
];
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"missing {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_lookup_command_matches_current_platform() {
|
||||
let expected = if cfg!(windows) { "where" } else { "which" };
|
||||
|
||||
assert_eq!(path_lookup_command(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_nvm_node_version_installs() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let pi = home.path().join(".nvm/versions/node/v22.20.0/bin/pi");
|
||||
|
||||
std::fs::create_dir_all(pi.parent().unwrap()).unwrap();
|
||||
std::fs::write(&pi, "#!/bin/sh\n").unwrap();
|
||||
|
||||
let candidates = pi_binary_candidates_for_home(home.path());
|
||||
|
||||
assert!(
|
||||
candidates.contains(&pi),
|
||||
"missing nvm candidate {}",
|
||||
pi.display()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_static_global_fallbacks() {
|
||||
let candidates = pi_global_binary_candidates();
|
||||
|
||||
assert!(candidates.contains(&PathBuf::from("/usr/local/bin/pi")));
|
||||
assert!(candidates.contains(&PathBuf::from("/opt/homebrew/bin/pi")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_candidates_include_env_provided_npm_and_nvm_prefixes() {
|
||||
let nvm_bin = PathBuf::from("/Users/alex/.nvm/versions/node/v22.20.0/bin");
|
||||
let npm_config_prefix = PathBuf::from("/Users/alex/.npm-global");
|
||||
let npm_config_prefix_upper = PathBuf::from("/Users/alex/.npm");
|
||||
|
||||
let candidates = pi_binary_candidates_from_prefixes(
|
||||
Some(nvm_bin.clone()),
|
||||
Some(npm_config_prefix.clone()),
|
||||
Some(npm_config_prefix_upper.clone()),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
vec![
|
||||
nvm_bin.join("pi"),
|
||||
npm_config_prefix.join("bin/pi"),
|
||||
npm_config_prefix_upper.join("bin/pi"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_existing_path_skips_empty_and_missing_lines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::ai_agents::AiAgentStreamEvent;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_line<F>(
|
||||
line: Result<String, std::io::Error>,
|
||||
emit: &mut F,
|
||||
@@ -7,22 +8,7 @@ pub(crate) fn parse_line<F>(
|
||||
where
|
||||
F: FnMut(AiAgentStreamEvent),
|
||||
{
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(error) => {
|
||||
emit(AiAgentStreamEvent::Error {
|
||||
message: format!("Read error: {error}"),
|
||||
});
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
serde_json::from_str::<serde_json::Value>(trimmed).ok()
|
||||
crate::cli_agent_runtime::parse_ai_agent_json_line(line, emit)
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_event<F>(json: &serde_json::Value, emit: &mut F)
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_line_reports_read_errors_and_skips_blank_or_invalid_lines() {
|
||||
let mut events = Vec::new();
|
||||
|
||||
let read_error = parse_line(Err(std::io::Error::other("broken pipe")), &mut |event| {
|
||||
events.push(event)
|
||||
});
|
||||
let blank = parse_line(Ok(" ".into()), &mut |event| events.push(event));
|
||||
let invalid = parse_line(Ok("not json".into()), &mut |event| events.push(event));
|
||||
|
||||
assert!(read_error.is_none());
|
||||
assert!(blank.is_none());
|
||||
assert!(invalid.is_none());
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Error { message } if message.contains("broken pipe")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_session_thinking_and_text() {
|
||||
let mut events = Vec::new();
|
||||
@@ -62,6 +81,19 @@ fn dispatch_maps_tool_events() {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_maps_error_events() {
|
||||
let mut events = Vec::new();
|
||||
let error = serde_json::json!({ "type": "error", "message": "provider failed" });
|
||||
|
||||
dispatch_event(&error, &mut |event| events.push(event));
|
||||
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
AiAgentStreamEvent::Error { message } if message == "provider failed"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_error_explains_missing_auth_or_provider_setup() {
|
||||
let message = format_error(
|
||||
@@ -72,3 +104,12 @@ fn format_error_explains_missing_auth_or_provider_setup() {
|
||||
assert!(message.contains("Pi CLI is not authenticated"));
|
||||
assert!(message.contains("pi /login"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_error_uses_status_or_first_stderr_lines() {
|
||||
let empty = format_error(String::new(), "exit status: 2".into());
|
||||
let truncated = format_error("line 1\nline 2\nline 3\nline 4".into(), "ignored".into());
|
||||
|
||||
assert_eq!(empty, "pi exited with status exit status: 2");
|
||||
assert_eq!(truncated, "line 1\nline 2\nline 3");
|
||||
}
|
||||
|
||||
@@ -28,41 +28,90 @@ pub struct SearchOptions<'a> {
|
||||
pub hide_gitignored_files: bool,
|
||||
}
|
||||
|
||||
fn extract_snippet(content: &str, query_lower: &str) -> String {
|
||||
let content_lower = content.to_lowercase();
|
||||
let pos = match content_lower.find(query_lower) {
|
||||
Some(p) => p,
|
||||
None => return String::new(),
|
||||
};
|
||||
let start = content[..pos]
|
||||
.rfind('\n')
|
||||
.map(|i| i + 1)
|
||||
.unwrap_or(pos.saturating_sub(60));
|
||||
let end = content[pos..]
|
||||
.find('\n')
|
||||
.map(|i| pos + i)
|
||||
.unwrap_or_else(|| (pos + 120).min(content.len()));
|
||||
let snippet = &content[start..end];
|
||||
if snippet.len() > 200 {
|
||||
format!("{}…", &snippet[..200])
|
||||
} else {
|
||||
snippet.to_string()
|
||||
struct Utf8Boundary<'a> {
|
||||
text: &'a str,
|
||||
}
|
||||
|
||||
struct SnippetRequest<'a> {
|
||||
content: &'a str,
|
||||
query_lower: &'a str,
|
||||
}
|
||||
|
||||
struct MatchScoreRequest<'a> {
|
||||
title_lower: &'a str,
|
||||
content_lower: &'a str,
|
||||
query_lower: &'a str,
|
||||
}
|
||||
|
||||
impl Utf8Boundary<'_> {
|
||||
fn floor(&self, index: usize) -> usize {
|
||||
let mut boundary = index.min(self.text.len());
|
||||
while boundary > 0 && !self.text.is_char_boundary(boundary) {
|
||||
boundary -= 1;
|
||||
}
|
||||
boundary
|
||||
}
|
||||
|
||||
fn lower_to_source(&self, lower_index: usize) -> usize {
|
||||
let mut lowered_len = 0;
|
||||
for (source_index, ch) in self.text.char_indices() {
|
||||
if lowered_len >= lower_index {
|
||||
return source_index;
|
||||
}
|
||||
lowered_len += ch.to_lowercase().map(|c| c.len_utf8()).sum::<usize>();
|
||||
if lowered_len > lower_index {
|
||||
return source_index;
|
||||
}
|
||||
}
|
||||
self.text.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn score_match(title_lower: &str, content_lower: &str, query_lower: &str) -> f64 {
|
||||
let title_exact = title_lower.contains(query_lower);
|
||||
let title_word = title_lower.split_whitespace().any(|w| w == query_lower);
|
||||
let content_count = content_lower.matches(query_lower).count();
|
||||
|
||||
let mut score = 0.0;
|
||||
if title_word {
|
||||
score += 10.0;
|
||||
} else if title_exact {
|
||||
score += 5.0;
|
||||
impl SnippetRequest<'_> {
|
||||
fn extract(&self) -> String {
|
||||
let content_lower = self.content.to_lowercase();
|
||||
let lower_pos = match content_lower.find(self.query_lower) {
|
||||
Some(p) => p,
|
||||
None => return String::new(),
|
||||
};
|
||||
let content_boundary = Utf8Boundary { text: self.content };
|
||||
let pos = content_boundary.lower_to_source(lower_pos);
|
||||
let start = self.content[..pos]
|
||||
.rfind('\n')
|
||||
.map(|i| i + 1)
|
||||
.unwrap_or_else(|| content_boundary.floor(pos.saturating_sub(60)));
|
||||
let end = self.content[pos..]
|
||||
.find('\n')
|
||||
.map(|i| pos + i)
|
||||
.unwrap_or_else(|| content_boundary.floor((pos + 120).min(self.content.len())));
|
||||
let snippet = &self.content[start..end];
|
||||
if snippet.len() > 200 {
|
||||
let end = Utf8Boundary { text: snippet }.floor(200);
|
||||
format!("{}…", &snippet[..end])
|
||||
} else {
|
||||
snippet.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MatchScoreRequest<'_> {
|
||||
fn score(&self) -> f64 {
|
||||
let title_exact = self.title_lower.contains(self.query_lower);
|
||||
let title_word = self
|
||||
.title_lower
|
||||
.split_whitespace()
|
||||
.any(|word| word == self.query_lower);
|
||||
let content_count = self.content_lower.matches(self.query_lower).count();
|
||||
|
||||
let mut score = 0.0;
|
||||
if title_word {
|
||||
score += 10.0;
|
||||
} else if title_exact {
|
||||
score += 5.0;
|
||||
}
|
||||
score += (content_count as f64).min(20.0) * 0.5;
|
||||
score
|
||||
}
|
||||
score += (content_count as f64).min(20.0) * 0.5;
|
||||
score
|
||||
}
|
||||
|
||||
pub fn search_vault(
|
||||
@@ -126,8 +175,17 @@ pub fn search_vault_with_options(options: SearchOptions<'_>) -> Result<SearchRes
|
||||
continue;
|
||||
}
|
||||
|
||||
let score = score_match(&title_lower, &content_lower, &query_lower);
|
||||
let snippet = extract_snippet(&content, &query_lower);
|
||||
let score = MatchScoreRequest {
|
||||
title_lower: &title_lower,
|
||||
content_lower: &content_lower,
|
||||
query_lower: &query_lower,
|
||||
}
|
||||
.score();
|
||||
let snippet = SnippetRequest {
|
||||
content: &content,
|
||||
query_lower: &query_lower,
|
||||
}
|
||||
.extract();
|
||||
let full_path = path.to_string_lossy().to_string();
|
||||
|
||||
results.push(SearchResult {
|
||||
@@ -170,28 +228,49 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
macro_rules! snippet {
|
||||
($content:expr, $query_lower:expr) => {
|
||||
SnippetRequest {
|
||||
content: $content,
|
||||
query_lower: $query_lower,
|
||||
}
|
||||
.extract()
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! match_score {
|
||||
($title_lower:expr, $content_lower:expr, $query_lower:expr) => {
|
||||
MatchScoreRequest {
|
||||
title_lower: $title_lower,
|
||||
content_lower: $content_lower,
|
||||
query_lower: $query_lower,
|
||||
}
|
||||
.score()
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_basic() {
|
||||
let content = "line one\nline with keyword here\nline three";
|
||||
let snippet = extract_snippet(content, "keyword");
|
||||
let snippet = snippet!(content, "keyword");
|
||||
assert!(snippet.contains("keyword"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_no_match() {
|
||||
let snippet = extract_snippet("nothing here", "missing");
|
||||
let snippet = snippet!("nothing here", "missing");
|
||||
assert!(snippet.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_score_match_title_word() {
|
||||
let score = score_match("my keyword", "", "keyword");
|
||||
let score = match_score!("my keyword", "", "keyword");
|
||||
assert!(score >= 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_score_match_content_only() {
|
||||
let score = score_match("unrelated", "some keyword text keyword", "keyword");
|
||||
let score = match_score!("unrelated", "some keyword text keyword", "keyword");
|
||||
assert!(score > 0.0);
|
||||
assert!(score < 10.0);
|
||||
}
|
||||
@@ -200,10 +279,52 @@ mod tests {
|
||||
fn test_extract_snippet_long() {
|
||||
let long_line = "a".repeat(300);
|
||||
let content = format!("start\n{}keyword{}\nend", long_line, long_line);
|
||||
let snippet = extract_snippet(&content, "keyword");
|
||||
let snippet = snippet!(&content, "keyword");
|
||||
assert!(snippet.len() <= 203); // 200 + "…" (3 bytes UTF-8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_multibyte_context_start() {
|
||||
let prefix = format!("{}a", "한".repeat(21));
|
||||
let content = format!("{prefix}needle after multibyte prefix");
|
||||
|
||||
let snippet = snippet!(&content, "needle");
|
||||
|
||||
assert!(snippet.contains("needle"));
|
||||
assert!(snippet.is_char_boundary(snippet.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_multibyte_context_end() {
|
||||
let content = format!("x{}", "한".repeat(50));
|
||||
|
||||
let snippet = snippet!(&content, "x");
|
||||
|
||||
assert!(snippet.starts_with('x'));
|
||||
assert!(snippet.is_char_boundary(snippet.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_multibyte_truncation() {
|
||||
let content = format!("key {}\n", "한".repeat(100));
|
||||
|
||||
let snippet = snippet!(&content, "key");
|
||||
|
||||
assert!(snippet.starts_with("key"));
|
||||
assert!(snippet.ends_with('…'));
|
||||
assert!(snippet.is_char_boundary(snippet.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_snippet_maps_expanded_lowercase_to_source_boundary() {
|
||||
let content = "İstanbul needle";
|
||||
|
||||
let snippet = snippet!(content, "i");
|
||||
|
||||
assert!(snippet.starts_with("İstanbul"));
|
||||
assert!(snippet.is_char_boundary(snippet.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_search_vault_uses_h1_for_result_title() {
|
||||
let dir = Builder::new()
|
||||
|
||||
@@ -2,10 +2,66 @@ use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::ai_models::{normalize_ai_model_providers, AiModelProvider};
|
||||
|
||||
const APP_CONFIG_DIR: &str = "com.tolaria.app";
|
||||
const LEGACY_APP_CONFIG_DIR: &str = "com.laputa.app";
|
||||
const SUPPORTED_DEFAULT_AI_AGENTS: &[&str] = &["claude_code", "codex", "opencode", "pi"];
|
||||
const SUPPORTED_DEFAULT_AI_AGENTS: &[&str] = &["claude_code", "codex", "opencode", "pi", "gemini"];
|
||||
pub const DEFAULT_HIDE_GITIGNORED_FILES: bool = true;
|
||||
const SUPPORTED_NOTE_WIDTH_MODES: &[&str] = &["normal", "wide"];
|
||||
const SUPPORTED_UI_LANGUAGE_ALIASES: &[(&str, &str)] = &[
|
||||
("en", "en"),
|
||||
("en-us", "en"),
|
||||
("en-gb", "en"),
|
||||
("en-ca", "en"),
|
||||
("en-au", "en"),
|
||||
("it", "it-IT"),
|
||||
("it-it", "it-IT"),
|
||||
("fr", "fr-FR"),
|
||||
("fr-fr", "fr-FR"),
|
||||
("de", "de-DE"),
|
||||
("de-de", "de-DE"),
|
||||
("ru", "ru-RU"),
|
||||
("ru-ru", "ru-RU"),
|
||||
("es-es", "es-ES"),
|
||||
("pt-br", "pt-BR"),
|
||||
("pt-pt", "pt-PT"),
|
||||
("es-419", "es-419"),
|
||||
("es-ar", "es-419"),
|
||||
("es-bo", "es-419"),
|
||||
("es-cl", "es-419"),
|
||||
("es-co", "es-419"),
|
||||
("es-cr", "es-419"),
|
||||
("es-cu", "es-419"),
|
||||
("es-do", "es-419"),
|
||||
("es-ec", "es-419"),
|
||||
("es-gt", "es-419"),
|
||||
("es-hn", "es-419"),
|
||||
("es-mx", "es-419"),
|
||||
("es-ni", "es-419"),
|
||||
("es-pa", "es-419"),
|
||||
("es-pe", "es-419"),
|
||||
("es-pr", "es-419"),
|
||||
("es-py", "es-419"),
|
||||
("es-sv", "es-419"),
|
||||
("es-us", "es-419"),
|
||||
("es-uy", "es-419"),
|
||||
("es-ve", "es-419"),
|
||||
("zh", "zh-CN"),
|
||||
("zh-cn", "zh-CN"),
|
||||
("zh-hans", "zh-CN"),
|
||||
("zh-sg", "zh-CN"),
|
||||
("zh-tw", "zh-TW"),
|
||||
("zh-hant", "zh-TW"),
|
||||
("zh-hk", "zh-TW"),
|
||||
("zh-mo", "zh-TW"),
|
||||
("ja", "ja-JP"),
|
||||
("ja-jp", "ja-JP"),
|
||||
("ko", "ko-KR"),
|
||||
("ko-kr", "ko-KR"),
|
||||
("vi", "vi"),
|
||||
("vi-vn", "vi"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct Settings {
|
||||
@@ -21,9 +77,15 @@ pub struct Settings {
|
||||
pub release_channel: Option<String>,
|
||||
pub theme_mode: Option<String>,
|
||||
pub ui_language: Option<String>,
|
||||
pub note_width_mode: Option<String>,
|
||||
pub initial_h1_auto_rename_enabled: Option<bool>,
|
||||
pub default_ai_agent: Option<String>,
|
||||
pub default_ai_target: Option<String>,
|
||||
pub ai_model_providers: Option<Vec<AiModelProvider>>,
|
||||
pub hide_gitignored_files: Option<bool>,
|
||||
pub all_notes_show_pdfs: Option<bool>,
|
||||
pub all_notes_show_images: Option<bool>,
|
||||
pub all_notes_show_unsupported: Option<bool>,
|
||||
}
|
||||
|
||||
fn normalize_optional_string(value: Option<String>) -> Option<String> {
|
||||
@@ -65,6 +127,13 @@ pub fn normalize_theme_mode(value: Option<&str>) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_note_width_mode(value: Option<&str>) -> Option<String> {
|
||||
match value.map(|candidate| candidate.trim().to_ascii_lowercase()) {
|
||||
Some(mode) if SUPPORTED_NOTE_WIDTH_MODES.contains(&mode.as_str()) => Some(mode),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn should_hide_gitignored_files(settings: &Settings) -> bool {
|
||||
settings
|
||||
.hide_gitignored_files
|
||||
@@ -86,23 +155,11 @@ fn canonical_language_code(value: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_english_language(code: &str) -> bool {
|
||||
code == "en" || code.starts_with("en-")
|
||||
}
|
||||
|
||||
fn is_simplified_chinese_language(code: &str) -> bool {
|
||||
matches!(code, "zh" | "zh-cn" | "zh-hans" | "zh-sg")
|
||||
}
|
||||
|
||||
pub fn normalize_ui_language(value: Option<&str>) -> Option<String> {
|
||||
let language = canonical_language_code(value?)?;
|
||||
if is_english_language(&language) {
|
||||
return Some("en".to_string());
|
||||
}
|
||||
if is_simplified_chinese_language(&language) {
|
||||
return Some("zh-Hans".to_string());
|
||||
}
|
||||
None
|
||||
SUPPORTED_UI_LANGUAGE_ALIASES
|
||||
.iter()
|
||||
.find_map(|(alias, canonical)| (*alias == language).then(|| (*canonical).to_string()))
|
||||
}
|
||||
|
||||
fn normalize_settings(settings: Settings) -> Settings {
|
||||
@@ -123,9 +180,15 @@ fn normalize_settings(settings: Settings) -> Settings {
|
||||
release_channel: normalize_release_channel(settings.release_channel.as_deref()),
|
||||
theme_mode: normalize_theme_mode(settings.theme_mode.as_deref()),
|
||||
ui_language: normalize_ui_language(settings.ui_language.as_deref()),
|
||||
note_width_mode: normalize_note_width_mode(settings.note_width_mode.as_deref()),
|
||||
initial_h1_auto_rename_enabled: settings.initial_h1_auto_rename_enabled,
|
||||
default_ai_agent: normalize_default_ai_agent(settings.default_ai_agent.as_deref()),
|
||||
default_ai_target: normalize_optional_string(settings.default_ai_target),
|
||||
ai_model_providers: normalize_ai_model_providers(settings.ai_model_providers),
|
||||
hide_gitignored_files: settings.hide_gitignored_files,
|
||||
all_notes_show_pdfs: settings.all_notes_show_pdfs,
|
||||
all_notes_show_images: settings.all_notes_show_images,
|
||||
all_notes_show_unsupported: settings.all_notes_show_unsupported,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,9 +329,15 @@ mod tests {
|
||||
release_channel: Some("alpha".to_string()),
|
||||
theme_mode: Some("dark".to_string()),
|
||||
ui_language: Some("zh-Hans".to_string()),
|
||||
note_width_mode: Some("wide".to_string()),
|
||||
initial_h1_auto_rename_enabled: Some(false),
|
||||
default_ai_agent: Some("codex".to_string()),
|
||||
default_ai_target: Some("agent:codex".to_string()),
|
||||
ai_model_providers: None,
|
||||
hide_gitignored_files: Some(false),
|
||||
all_notes_show_pdfs: Some(true),
|
||||
all_notes_show_images: Some(true),
|
||||
all_notes_show_unsupported: Some(false),
|
||||
};
|
||||
let json = serde_json::to_string(&settings).unwrap();
|
||||
let parsed: Settings = serde_json::from_str(&json).unwrap();
|
||||
@@ -294,9 +363,13 @@ mod tests {
|
||||
release_channel: Some("alpha".to_string()),
|
||||
theme_mode: Some("dark".to_string()),
|
||||
ui_language: Some("zh-Hans".to_string()),
|
||||
note_width_mode: Some("wide".to_string()),
|
||||
initial_h1_auto_rename_enabled: Some(false),
|
||||
default_ai_agent: Some("codex".to_string()),
|
||||
hide_gitignored_files: Some(false),
|
||||
all_notes_show_pdfs: Some(true),
|
||||
all_notes_show_images: Some(false),
|
||||
all_notes_show_unsupported: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(loaded.auto_pull_interval_minutes, Some(10));
|
||||
@@ -306,10 +379,14 @@ mod tests {
|
||||
assert_eq!(loaded.auto_advance_inbox_after_organize, Some(true));
|
||||
assert_eq!(loaded.release_channel.as_deref(), Some("alpha"));
|
||||
assert_eq!(loaded.theme_mode.as_deref(), Some("dark"));
|
||||
assert_eq!(loaded.ui_language.as_deref(), Some("zh-Hans"));
|
||||
assert_eq!(loaded.ui_language.as_deref(), Some("zh-CN"));
|
||||
assert_eq!(loaded.note_width_mode.as_deref(), Some("wide"));
|
||||
assert_eq!(loaded.initial_h1_auto_rename_enabled, Some(false));
|
||||
assert_eq!(loaded.default_ai_agent.as_deref(), Some("codex"));
|
||||
assert_eq!(loaded.hide_gitignored_files, Some(false));
|
||||
assert_eq!(loaded.all_notes_show_pdfs, Some(true));
|
||||
assert_eq!(loaded.all_notes_show_images, Some(false));
|
||||
assert_eq!(loaded.all_notes_show_unsupported, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -332,13 +409,15 @@ mod tests {
|
||||
release_channel: Some(" alpha ".to_string()),
|
||||
theme_mode: Some(" dark ".to_string()),
|
||||
ui_language: Some(" zh-cn ".to_string()),
|
||||
note_width_mode: Some(" WIDE ".to_string()),
|
||||
default_ai_agent: Some(" codex ".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(loaded.anonymous_id.as_deref(), Some("test-uuid"));
|
||||
assert_eq!(loaded.release_channel.as_deref(), Some("alpha"));
|
||||
assert_eq!(loaded.theme_mode.as_deref(), Some("dark"));
|
||||
assert_eq!(loaded.ui_language.as_deref(), Some("zh-Hans"));
|
||||
assert_eq!(loaded.ui_language.as_deref(), Some("zh-CN"));
|
||||
assert_eq!(loaded.note_width_mode.as_deref(), Some("wide"));
|
||||
assert_eq!(loaded.default_ai_agent.as_deref(), Some("codex"));
|
||||
}
|
||||
|
||||
@@ -398,6 +477,15 @@ mod tests {
|
||||
assert_eq!(loaded.default_ai_agent.as_deref(), Some("pi"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gemini_default_ai_agent_is_preserved() {
|
||||
let loaded = save_and_reload(Settings {
|
||||
default_ai_agent: Some("gemini".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(loaded.default_ai_agent.as_deref(), Some("gemini"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_theme_mode_is_filtered() {
|
||||
let loaded = save_and_reload(Settings {
|
||||
@@ -407,21 +495,61 @@ mod tests {
|
||||
assert!(loaded.theme_mode.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_note_width_mode_is_filtered() {
|
||||
let loaded = save_and_reload(Settings {
|
||||
note_width_mode: Some("expanded".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(loaded.note_width_mode.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_ui_language_is_filtered() {
|
||||
let loaded = save_and_reload(Settings {
|
||||
ui_language: Some("fr-FR".to_string()),
|
||||
ui_language: Some("xx-ZZ".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(loaded.ui_language.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supported_ui_languages_are_saved_and_reloaded() {
|
||||
let expected_languages = [
|
||||
("it-IT", "it-IT"),
|
||||
("fr-FR", "fr-FR"),
|
||||
("de-DE", "de-DE"),
|
||||
("ru-RU", "ru-RU"),
|
||||
("es-ES", "es-ES"),
|
||||
("pt-BR", "pt-BR"),
|
||||
("pt-PT", "pt-PT"),
|
||||
("es-419", "es-419"),
|
||||
("zh-CN", "zh-CN"),
|
||||
("zh-TW", "zh-TW"),
|
||||
("ja-JP", "ja-JP"),
|
||||
("ko-KR", "ko-KR"),
|
||||
("vi", "vi"),
|
||||
];
|
||||
|
||||
for (input, expected) in expected_languages {
|
||||
let loaded = save_and_reload(Settings {
|
||||
ui_language: Some(input.to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(loaded.ui_language.as_deref(), Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ui_language_aliases_are_canonicalized() {
|
||||
assert_eq!(normalize_ui_language(Some("en-US")).as_deref(), Some("en"));
|
||||
assert_eq!(
|
||||
normalize_ui_language(Some("zh_CN")).as_deref(),
|
||||
Some("zh-Hans")
|
||||
Some("zh-CN")
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_ui_language(Some("zh-Hant")).as_deref(),
|
||||
Some("zh-TW")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::settings;
|
||||
use chrono::NaiveDate;
|
||||
use regex::Regex;
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Global Sentry guard — must live for the duration of the app.
|
||||
@@ -44,6 +46,41 @@ fn parse_embedded_sentry_dsn(raw: Option<&str>) -> Option<sentry::types::Dsn> {
|
||||
normalize_http_like_value(&normalized).parse().ok()
|
||||
}
|
||||
|
||||
fn is_stable_calendar_release(version: &str) -> bool {
|
||||
let mut parts = version.split('.');
|
||||
let (Some(year), Some(month), Some(day)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if parts.next().is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (Ok(year), Ok(month), Ok(day)) = (
|
||||
year.parse::<i32>(),
|
||||
month.parse::<u32>(),
|
||||
day.parse::<u32>(),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
NaiveDate::from_ymd_opt(year, month, day).is_some()
|
||||
}
|
||||
|
||||
fn sentry_release_for_version(version: &'static str) -> Option<Cow<'static, str>> {
|
||||
is_stable_calendar_release(version).then(|| version.into())
|
||||
}
|
||||
|
||||
fn sentry_release_kind(version: &str) -> &'static str {
|
||||
if is_stable_calendar_release(version) {
|
||||
"stable"
|
||||
} else if version.contains('-') {
|
||||
"prerelease"
|
||||
} else {
|
||||
"internal"
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize Sentry if the user has opted in to crash reporting.
|
||||
/// Returns `true` if Sentry was initialized, `false` if skipped.
|
||||
pub fn init_sentry_from_settings() -> bool {
|
||||
@@ -61,9 +98,10 @@ pub fn init_sentry_from_settings() -> bool {
|
||||
};
|
||||
|
||||
let anonymous_id = settings.anonymous_id.unwrap_or_default();
|
||||
let build_version = env!("CARGO_PKG_VERSION");
|
||||
let guard = sentry::init(sentry::ClientOptions {
|
||||
dsn: Some(dsn),
|
||||
release: Some(env!("CARGO_PKG_VERSION").into()),
|
||||
release: sentry_release_for_version(build_version),
|
||||
send_default_pii: false,
|
||||
before_send: Some(std::sync::Arc::new(|mut event| {
|
||||
if let Some(ref mut msg) = event.message {
|
||||
@@ -79,6 +117,8 @@ pub fn init_sentry_from_settings() -> bool {
|
||||
id: Some(anonymous_id),
|
||||
..Default::default()
|
||||
}));
|
||||
scope.set_tag("tolaria.build_version", build_version);
|
||||
scope.set_tag("tolaria.release_kind", sentry_release_kind(build_version));
|
||||
});
|
||||
|
||||
*SENTRY_GUARD.lock().unwrap() = Some(guard);
|
||||
@@ -160,4 +200,26 @@ mod tests {
|
||||
// Without SENTRY_DSN env var set at compile time, init should return false
|
||||
assert!(!init_sentry_from_settings());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sentry_release_for_stable_calendar_version() {
|
||||
assert!(sentry_release_for_version("2026.4.28").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sentry_release_for_alpha_version_is_none() {
|
||||
assert!(sentry_release_for_version("2026.4.28-alpha.7").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sentry_release_for_local_dev_version_is_none() {
|
||||
assert!(sentry_release_for_version("0.1.0").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sentry_release_kind_classifies_versions() {
|
||||
assert_eq!(sentry_release_kind("2026.4.28"), "stable");
|
||||
assert_eq!(sentry_release_kind("2026.4.28-alpha.7"), "prerelease");
|
||||
assert_eq!(sentry_release_kind("0.1.0"), "internal");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ fn git_head_hash(vault: &Path) -> Option<String> {
|
||||
|
||||
/// Run a git command in the given directory and return stdout if successful.
|
||||
fn run_git(vault: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = crate::hidden_command("git")
|
||||
let output = crate::git::git_command()
|
||||
.args(args)
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
@@ -768,6 +768,14 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn force_quoted_git_paths(vault: &Path) {
|
||||
crate::hidden_command("git")
|
||||
.args(["config", "core.quotePath", "true"])
|
||||
.current_dir(vault)
|
||||
.output()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cache_path_is_outside_vault() {
|
||||
let _lock = ENV_LOCK.lock().unwrap();
|
||||
@@ -1007,6 +1015,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_git_uncommitted_files_preserves_chinese_markdown_path() {
|
||||
let (_lock, _cache_tmp, dir) = setup_git_vault();
|
||||
let vault = dir.path();
|
||||
let relative_path = "中文笔记.md";
|
||||
|
||||
force_quoted_git_paths(vault);
|
||||
create_test_file(vault, relative_path, "# 初始\n");
|
||||
git_add_commit(vault, "init");
|
||||
create_test_file(vault, relative_path, "# 初始\n\n更新\n");
|
||||
|
||||
let changed = git_uncommitted_files(vault);
|
||||
|
||||
assert_eq!(changed, vec![relative_path.to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_same_commit_new_file_still_added() {
|
||||
let (_lock, _cache_tmp, dir) = setup_git_vault();
|
||||
|
||||
@@ -58,6 +58,16 @@ _organized: true
|
||||
This file is only a Claude Code compatibility shim. Keep shared agent instructions in `AGENTS.md`.
|
||||
";
|
||||
|
||||
const GEMINI_MD_SHIM: &str = "---
|
||||
type: Note
|
||||
_organized: true
|
||||
---
|
||||
|
||||
@AGENTS.md
|
||||
|
||||
This file is only a Gemini CLI compatibility shim. Keep shared agent instructions in `AGENTS.md`.
|
||||
";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AiGuidanceFileState {
|
||||
@@ -71,9 +81,16 @@ pub enum AiGuidanceFileState {
|
||||
pub struct VaultAiGuidanceStatus {
|
||||
pub agents_state: AiGuidanceFileState,
|
||||
pub claude_state: AiGuidanceFileState,
|
||||
pub gemini_state: AiGuidanceFileState,
|
||||
pub can_restore: bool,
|
||||
}
|
||||
|
||||
struct GuidancePaths {
|
||||
agents: PathBuf,
|
||||
claude: PathBuf,
|
||||
gemini: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct LegacyAgentsMigrationOutcome {
|
||||
copied_to_root: bool,
|
||||
@@ -109,6 +126,10 @@ fn matches_claude_shim(content: &str) -> bool {
|
||||
|| trimmed == CLAUDE_MD_SHIM.trim()
|
||||
}
|
||||
|
||||
fn matches_gemini_shim(content: &str) -> bool {
|
||||
content.trim() == GEMINI_MD_SHIM.trim()
|
||||
}
|
||||
|
||||
fn claude_shim_can_be_replaced(path: &Path) -> bool {
|
||||
!path.exists() || {
|
||||
let content = read_file_or_empty(path);
|
||||
@@ -116,6 +137,13 @@ fn claude_shim_can_be_replaced(path: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn gemini_shim_can_be_replaced(path: &Path) -> bool {
|
||||
!path.exists() || {
|
||||
let content = read_file_or_empty(path);
|
||||
content.trim().is_empty() || matches_gemini_shim(&content)
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_managed_file(
|
||||
path: &Path,
|
||||
content: &str,
|
||||
@@ -150,9 +178,12 @@ fn classify_guidance_file(
|
||||
AiGuidanceFileState::Custom
|
||||
}
|
||||
|
||||
fn guidance_paths(vault_path: &Path) -> (PathBuf, PathBuf) {
|
||||
let vault = vault_path;
|
||||
(vault.join("AGENTS.md"), vault.join("CLAUDE.md"))
|
||||
fn guidance_paths(vault_path: &Path) -> GuidancePaths {
|
||||
GuidancePaths {
|
||||
agents: vault_path.join("AGENTS.md"),
|
||||
claude: vault_path.join("CLAUDE.md"),
|
||||
gemini: vault_path.join("GEMINI.md"),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_agents_file(path: &Path) -> AiGuidanceFileState {
|
||||
@@ -167,6 +198,10 @@ fn classify_claude_file(path: &Path) -> AiGuidanceFileState {
|
||||
classify_guidance_file(path, matches_claude_shim, claude_shim_can_be_replaced)
|
||||
}
|
||||
|
||||
fn classify_gemini_file(path: &Path) -> AiGuidanceFileState {
|
||||
classify_guidance_file(path, matches_gemini_shim, gemini_shim_can_be_replaced)
|
||||
}
|
||||
|
||||
fn guidance_file_needs_restore(state: AiGuidanceFileState) -> bool {
|
||||
matches!(
|
||||
state,
|
||||
@@ -175,29 +210,43 @@ fn guidance_file_needs_restore(state: AiGuidanceFileState) -> bool {
|
||||
}
|
||||
|
||||
fn build_ai_guidance_status(vault_path: &Path) -> VaultAiGuidanceStatus {
|
||||
let (agents_path, claude_path) = guidance_paths(vault_path);
|
||||
let agents_state = classify_agents_file(&agents_path);
|
||||
let claude_state = classify_claude_file(&claude_path);
|
||||
let paths = guidance_paths(vault_path);
|
||||
let agents_state = classify_agents_file(&paths.agents);
|
||||
let claude_state = classify_claude_file(&paths.claude);
|
||||
let gemini_state = classify_gemini_file(&paths.gemini);
|
||||
|
||||
VaultAiGuidanceStatus {
|
||||
agents_state,
|
||||
claude_state,
|
||||
gemini_state,
|
||||
can_restore: guidance_file_needs_restore(agents_state)
|
||||
|| guidance_file_needs_restore(claude_state),
|
||||
|| guidance_file_needs_restore(claude_state)
|
||||
|| guidance_file_needs_restore(gemini_state),
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_claude_shim_file(vault_path: &Path) -> Result<bool, String> {
|
||||
let (_, claude_path) = guidance_paths(vault_path);
|
||||
sync_managed_file(&claude_path, CLAUDE_MD_SHIM, claude_shim_can_be_replaced)
|
||||
let paths = guidance_paths(vault_path);
|
||||
sync_managed_file(&paths.claude, CLAUDE_MD_SHIM, claude_shim_can_be_replaced)
|
||||
}
|
||||
|
||||
fn sync_ai_guidance_files(vault_path: &Path) -> Result<bool, String> {
|
||||
fn sync_gemini_shim_file(vault_path: &Path) -> Result<bool, String> {
|
||||
let paths = guidance_paths(vault_path);
|
||||
sync_managed_file(&paths.gemini, GEMINI_MD_SHIM, gemini_shim_can_be_replaced)
|
||||
}
|
||||
|
||||
fn sync_required_ai_guidance_files(vault_path: &Path) -> Result<bool, String> {
|
||||
let wrote_agents = sync_default_agents_file(vault_path)?;
|
||||
let wrote_claude = sync_claude_shim_file(vault_path)?;
|
||||
Ok(wrote_agents || wrote_claude)
|
||||
}
|
||||
|
||||
fn sync_all_ai_guidance_files(vault_path: &Path) -> Result<bool, String> {
|
||||
let wrote_required = sync_required_ai_guidance_files(vault_path)?;
|
||||
let wrote_gemini = sync_gemini_shim_file(vault_path)?;
|
||||
Ok(wrote_required || wrote_gemini)
|
||||
}
|
||||
|
||||
fn migrate_legacy_agents_file(
|
||||
root_agents: &Path,
|
||||
config_agents: &Path,
|
||||
@@ -241,8 +290,8 @@ fn cleanup_empty_config_dir(vault: &Path) -> Result<bool, String> {
|
||||
}
|
||||
|
||||
pub(super) fn sync_default_agents_file(vault_path: &Path) -> Result<bool, String> {
|
||||
let (agents_path, _) = guidance_paths(vault_path);
|
||||
sync_managed_file(&agents_path, AGENTS_MD, root_agents_can_be_replaced)
|
||||
let paths = guidance_paths(vault_path);
|
||||
sync_managed_file(&paths.agents, AGENTS_MD, root_agents_can_be_replaced)
|
||||
}
|
||||
|
||||
pub fn get_ai_guidance_status(
|
||||
@@ -255,7 +304,7 @@ pub fn restore_ai_guidance_files(
|
||||
vault_path: impl AsRef<str>,
|
||||
) -> Result<VaultAiGuidanceStatus, String> {
|
||||
let vault_path = Path::new(vault_path.as_ref());
|
||||
sync_ai_guidance_files(vault_path)?;
|
||||
sync_all_ai_guidance_files(vault_path)?;
|
||||
Ok(build_ai_guidance_status(vault_path))
|
||||
}
|
||||
|
||||
@@ -263,7 +312,7 @@ pub fn restore_ai_guidance_files(
|
||||
/// Also seeds Tolaria-managed root type definitions used by repair/bootstrap flows.
|
||||
pub fn seed_config_files(vault_path: impl AsRef<str>) {
|
||||
let vault_path = Path::new(vault_path.as_ref());
|
||||
if sync_ai_guidance_files(vault_path).unwrap_or(false) {
|
||||
if sync_required_ai_guidance_files(vault_path).unwrap_or(false) {
|
||||
log::info!("Seeded vault AI guidance files at vault root");
|
||||
}
|
||||
|
||||
@@ -307,7 +356,7 @@ pub fn migrate_agents_md(vault_path: impl AsRef<str>) {
|
||||
log::info!("Removed empty config/ directory");
|
||||
}
|
||||
|
||||
let _ = sync_ai_guidance_files(vault);
|
||||
let _ = sync_required_ai_guidance_files(vault);
|
||||
}
|
||||
|
||||
/// Repair config files: ensure `AGENTS.md` at vault root and root type definitions.
|
||||
@@ -320,7 +369,7 @@ pub fn repair_config_files(vault_path: impl AsRef<str>) -> Result<String, String
|
||||
|
||||
migrate_legacy_agents_file(&root_agents, &config_agents)?;
|
||||
let _ = cleanup_empty_config_dir(vault)?;
|
||||
sync_ai_guidance_files(vault)?;
|
||||
sync_required_ai_guidance_files(vault)?;
|
||||
|
||||
write_if_missing(&vault.join("type.md"), TYPE_TYPE_DEFINITION)?;
|
||||
write_if_missing(&vault.join("note.md"), NOTE_TYPE_DEFINITION)?;
|
||||
@@ -355,6 +404,10 @@ mod tests {
|
||||
fs::write(vault.join("CLAUDE.md"), content).unwrap();
|
||||
}
|
||||
|
||||
fn write_root_gemini(vault: &Path, content: &str) {
|
||||
fs::write(vault.join("GEMINI.md"), content).unwrap();
|
||||
}
|
||||
|
||||
fn write_legacy_agents(vault: &Path, content: &str) {
|
||||
fs::write(config_dir(vault).join("agents.md"), content).unwrap();
|
||||
}
|
||||
@@ -367,6 +420,10 @@ mod tests {
|
||||
fs::read_to_string(vault.join("CLAUDE.md")).unwrap()
|
||||
}
|
||||
|
||||
fn read_root_gemini(vault: &Path) -> String {
|
||||
fs::read_to_string(vault.join("GEMINI.md")).unwrap()
|
||||
}
|
||||
|
||||
type VaultOperation = fn(&Path);
|
||||
|
||||
fn run_seed(vault: &Path) {
|
||||
@@ -454,15 +511,52 @@ mod tests {
|
||||
assert!(content.contains(expected_root_text));
|
||||
}
|
||||
|
||||
fn assert_required_agents_file_seeded(vault: &Path) {
|
||||
assert!(vault.join("AGENTS.md").exists());
|
||||
assert!(read_root_agents(vault).contains("Tolaria Vault"));
|
||||
}
|
||||
|
||||
fn assert_required_guidance_shims_seeded(vault: &Path) {
|
||||
assert_eq!(read_root_claude(vault), CLAUDE_MD_SHIM);
|
||||
assert!(!vault.join("GEMINI.md").exists());
|
||||
}
|
||||
|
||||
fn assert_required_guidance_files_seeded(vault: &Path) {
|
||||
assert_required_agents_file_seeded(vault);
|
||||
assert_required_guidance_shims_seeded(vault);
|
||||
}
|
||||
|
||||
fn assert_root_type_definitions_seeded(vault: &Path) {
|
||||
assert!(vault.join("type.md").exists());
|
||||
assert!(vault.join("note.md").exists());
|
||||
assert!(!vault.join("config").exists());
|
||||
}
|
||||
|
||||
fn assert_type_definition_content(vault: &Path) {
|
||||
let type_content = fs::read_to_string(vault.join("type.md")).unwrap();
|
||||
let note_content = fs::read_to_string(vault.join("note.md")).unwrap();
|
||||
assert_type_definition_body(&type_content);
|
||||
assert_note_definition_body(¬e_content);
|
||||
}
|
||||
|
||||
fn assert_type_definition_body(type_content: &str) {
|
||||
assert!(type_content.contains("type: Type"));
|
||||
assert!(type_content.contains("# Type"));
|
||||
assert!(type_content.contains("visible: false"));
|
||||
}
|
||||
|
||||
fn assert_note_definition_body(note_content: &str) {
|
||||
assert!(note_content.contains("type: Type"));
|
||||
assert!(note_content.contains("# Note"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_seed_config_files_creates_guidance_files_at_root() {
|
||||
let (_dir, vault) = create_vault();
|
||||
|
||||
seed_config_files(vault.to_str().unwrap());
|
||||
|
||||
assert!(vault.join("AGENTS.md").exists());
|
||||
assert!(read_root_agents(&vault).contains("Tolaria Vault"));
|
||||
assert_eq!(read_root_claude(&vault), CLAUDE_MD_SHIM);
|
||||
assert_required_guidance_files_seeded(&vault);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -471,16 +565,8 @@ mod tests {
|
||||
|
||||
seed_config_files(vault.to_str().unwrap());
|
||||
|
||||
assert!(vault.join("type.md").exists());
|
||||
assert!(vault.join("note.md").exists());
|
||||
let type_content = fs::read_to_string(vault.join("type.md")).unwrap();
|
||||
let note_content = fs::read_to_string(vault.join("note.md")).unwrap();
|
||||
assert!(type_content.contains("type: Type"));
|
||||
assert!(type_content.contains("# Type"));
|
||||
assert!(type_content.contains("visible: false"));
|
||||
assert!(note_content.contains("type: Type"));
|
||||
assert!(note_content.contains("# Note"));
|
||||
assert!(!vault.join("config").exists());
|
||||
assert_root_type_definitions_seeded(&vault);
|
||||
assert_type_definition_content(&vault);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -604,20 +690,12 @@ mod tests {
|
||||
let msg = repair_config_files(vault.to_str().unwrap()).unwrap();
|
||||
assert_eq!(msg, "Config files repaired");
|
||||
|
||||
assert!(vault.join("AGENTS.md").exists());
|
||||
assert!(vault.join("CLAUDE.md").exists());
|
||||
assert!(vault.join("type.md").exists());
|
||||
assert!(vault.join("note.md").exists());
|
||||
assert!(!vault.join("config").exists());
|
||||
|
||||
let agents = read_root_agents(&vault);
|
||||
assert!(agents.contains("Tolaria Vault"));
|
||||
let type_content = fs::read_to_string(vault.join("type.md")).unwrap();
|
||||
assert!(type_content.contains("# Type"));
|
||||
assert!(type_content.contains("visible: false"));
|
||||
let note_content = fs::read_to_string(vault.join("note.md")).unwrap();
|
||||
assert!(note_content.contains("type: Type"));
|
||||
assert!(note_content.contains("general-purpose document"));
|
||||
assert_required_guidance_files_seeded(&vault);
|
||||
assert_root_type_definitions_seeded(&vault);
|
||||
assert_type_definition_content(&vault);
|
||||
assert!(fs::read_to_string(vault.join("note.md"))
|
||||
.unwrap()
|
||||
.contains("general-purpose document"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -656,9 +734,15 @@ mod tests {
|
||||
write_root_claude(&vault, "");
|
||||
|
||||
let status = get_ai_guidance_status(vault.to_str().unwrap()).unwrap();
|
||||
assert_eq!(status.agents_state, AiGuidanceFileState::Custom);
|
||||
assert_eq!(status.claude_state, AiGuidanceFileState::Broken);
|
||||
assert!(status.can_restore);
|
||||
assert_eq!(
|
||||
status,
|
||||
VaultAiGuidanceStatus {
|
||||
agents_state: AiGuidanceFileState::Custom,
|
||||
claude_state: AiGuidanceFileState::Broken,
|
||||
gemini_state: AiGuidanceFileState::Missing,
|
||||
can_restore: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -668,11 +752,18 @@ mod tests {
|
||||
write_root_claude(&vault, "");
|
||||
|
||||
let status = restore_ai_guidance_files(vault.to_str().unwrap()).unwrap();
|
||||
assert_eq!(status.agents_state, AiGuidanceFileState::Custom);
|
||||
assert_eq!(status.claude_state, AiGuidanceFileState::Managed);
|
||||
assert!(!status.can_restore);
|
||||
assert_eq!(
|
||||
status,
|
||||
VaultAiGuidanceStatus {
|
||||
agents_state: AiGuidanceFileState::Custom,
|
||||
claude_state: AiGuidanceFileState::Managed,
|
||||
gemini_state: AiGuidanceFileState::Managed,
|
||||
can_restore: false,
|
||||
}
|
||||
);
|
||||
assert!(read_root_agents(&vault).contains("Custom Agent Config"));
|
||||
assert_eq!(read_root_claude(&vault), CLAUDE_MD_SHIM);
|
||||
assert_eq!(read_root_gemini(&vault), GEMINI_MD_SHIM);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -681,8 +772,28 @@ mod tests {
|
||||
write_root_agents(&vault, "");
|
||||
|
||||
let status = restore_ai_guidance_files(vault.to_str().unwrap()).unwrap();
|
||||
assert_eq!(status.agents_state, AiGuidanceFileState::Managed);
|
||||
assert_eq!(status.claude_state, AiGuidanceFileState::Managed);
|
||||
assert_eq!(
|
||||
status,
|
||||
VaultAiGuidanceStatus {
|
||||
agents_state: AiGuidanceFileState::Managed,
|
||||
claude_state: AiGuidanceFileState::Managed,
|
||||
gemini_state: AiGuidanceFileState::Managed,
|
||||
can_restore: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_ai_guidance_files_preserves_custom_gemini() {
|
||||
let (_dir, vault) = create_vault();
|
||||
write_root_agents(&vault, AGENTS_MD);
|
||||
write_root_claude(&vault, CLAUDE_MD_SHIM);
|
||||
write_root_gemini(&vault, "# Custom Gemini instructions\nDo not overwrite\n");
|
||||
|
||||
let status = restore_ai_guidance_files(vault.to_str().unwrap()).unwrap();
|
||||
|
||||
assert_eq!(status.gemini_state, AiGuidanceFileState::Custom);
|
||||
assert!(!status.can_restore);
|
||||
assert!(read_root_gemini(&vault).contains("Custom Gemini instructions"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,9 @@ pub struct VaultEntry {
|
||||
/// Default view mode for the note list when viewing instances of this Type.
|
||||
/// Stored as a string: "all", "editor-list", or "editor-only".
|
||||
pub view: Option<String>,
|
||||
/// Rich-editor width mode for this note. None means use the app default.
|
||||
#[serde(rename = "noteWidth")]
|
||||
pub note_width: Option<String>,
|
||||
/// Whether this Type is visible in the sidebar. Defaults to true when absent.
|
||||
pub visible: Option<bool>,
|
||||
/// Whether this note has been explicitly organized (removed from Inbox).
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user