Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Merge pull request #8952 from janhq/jamesdam/windows-e2e-support
James Dam7205d770c1e0
diff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.ymlindex 55ef971e1..5a06231c7 100644--- a/.github/workflows/jan-linter-and-test.yml+++ b/.github/workflows/jan-linter-and-test.yml@@ -90,11 +90,27 @@ jobs:- name: Install cargo-llvm-covuses: taiki-e/install-action@9e57365e36de1e26dea5145e57d471261468d9f7 # cargo-llvm-cov- # The same script the coverage job uses. It stubs the engine worker and a- # libggml* too, which the bundle config now requires and this inline copy- # did not.+ # This job is the one place two trees meet: the steps are this workflow's,+ # from the PR, but the checkout above is the base branch's. So a step that+ # runs a script out of the repo gets the base tree's copy -- which is the+ # one that does not have whatever the PR just changed. Take the script from+ # the PR head, and put it in `scripts/` rather than running it in place:+ # it resolves the repo root from its own location, so a copy sitting+ # anywhere else would stub that directory instead.+ - name: Check out this PR's stub script+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6+ with:+ ref: ${{ github.event.pull_request.head.sha }}+ sparse-checkout: scripts/stub-tauri-resources.mjs+ sparse-checkout-cone-mode: false+ path: .pr-head++ # Stubs the engine worker and a libggml* as well, which the bundle config+ # requires.- name: Create Tauri resource stubs for CI- run: ./scripts/stub-tauri-resources.sh+ run: |+ cp .pr-head/scripts/stub-tauri-resources.mjs scripts/+ node scripts/stub-tauri-resources.mjs- name: Run Rust test coveragerun: |diff --git a/.github/workflows/rust-check.yml b/.github/workflows/rust-check.ymlindex bb3eae52a..f4ff4264a 100644--- a/.github/workflows/rust-check.yml+++ b/.github/workflows/rust-check.yml@@ -71,7 +71,7 @@ jobs:- name: Create Tauri resource stubsif: matrix.tauri- run: ./scripts/stub-tauri-resources.sh+ run: node scripts/stub-tauri-resources.mjs- name: cargo checkrun: |diff --git a/Makefile b/Makefileindex 3c24bf002..10e8a0990 100644--- a/Makefile+++ b/Makefile@@ -166,17 +166,13 @@ test: test-prepare install-rust-targets# so we never clobber a real local build or churn the cargo:rerun-if-changed# stamps these paths emit.#-# scripts/stub-tauri-resources.sh is the one implementation, shared with the+# scripts/stub-tauri-resources.mjs is the one implementation, shared with the# coverage and rust-check workflows; keeping a second copy here is how the-# engine worker ended up stubbed in one place and not the other. The PowerShell-# arm exists only because cmd.exe cannot run it: CI runs make from a shell where-# sh.exe is on PATH, so it takes the script.+# engine worker ended up stubbed in one place and not the other. It is Node and+# not shell so this recipe needs no cmd.exe arm -- `node` is spelled the same+# whichever shell make picked, and a stock Windows box has no `sh` on PATH.stub-resources:-ifeq ($(RECIPE_SHELL_IS_CMD),yes)- -powershell -Command "New-Item -ItemType Directory -Force -Path src-tauri/resources/bin | Out-Null; foreach ($$f in @('jan-llama-worker.exe','ggml-base.dll')) { $$p = Join-Path 'src-tauri/resources/bin' $$f; if (-not (Test-Path $$p)) { New-Item -ItemType File -Path $$p | Out-Null } }"-else- @./scripts/stub-tauri-resources.sh-endif+ @node scripts/stub-tauri-resources.mjstest-ci: test-prepare$(MAKE) test-rustdiff --git a/e2e/README.md b/e2e/README.mdindex c2b646ea4..e8c035a68 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -3,8 +3,9 @@WebDriver-driven end-to-end tests against a real Jan desktop build, using[WebdriverIO](https://webdriver.io) and `@wdio/tauri-service`.-**macOS and Linux.** Windows cannot be isolated and the config refuses to run-there — see [Isolation](#isolation).+**macOS, Linux and Windows.** Each can have the app's data folder redirected by+environment — on macOS and Linux through the OS's own variables, on Windows+through one Jan provides. See [Isolation](#isolation).On Linux you need the Tauri build dependencies plus a display. `libssl-dev` iseasy to miss: `openssl-sys` is in the app's default dependency graph, but GitHub@@ -85,9 +86,11 @@ which is why this is the approach Tauri documents.On macOS there is no WKWebView driver to attach from outside, so the app hostsan **embedded** WebDriver server itself via `tauri-plugin-wdio-webdriver`. Linux-uses the same embedded provider — it could drive `WebKitWebDriver` through the-`official` provider instead, but sharing one path means neither platform needs-`tauri-driver` installed. That plugin is an optional dependency behind the `e2e`+and Windows use the same embedded provider — they could drive `WebKitWebDriver`+and `msedgedriver` through the `official` provider instead, but sharing one path+means no platform needs `tauri-driver` installed. The plugin backs all three+natively rather than assuming a Unix webview (`src/platform/windows.rs` talks to+WebView2 through `webview2-com`). That plugin is an optional dependency behind the `e2e`cargo feature, and the `e2e` feature is not enabled by any supported build path— not `default`, not `desktop`, and not by any command in the `Makefile` or`.github/workflows/`.@@ -116,17 +119,14 @@ server ever bound.Each run gets a throwaway profile in a temp dir, so tests never touch real Jandata. The desktop app resolves its data folder from-`app_handle.path().data_dir()`; which variables that leaves you needing to+`core::app::paths::data_dir()`; which variables that leaves you needing tooverride depends on the platform.-`dirs::data_dir()` resolves differently per platform, which is what decides-where the suite can run at all:-| Platform | `data_dir()` | Redirected by || --- | --- | --- || macOS | `$HOME/Library/Application Support` | `HOME` || Linux | `$XDG_DATA_HOME`, else `$HOME/.local/share` | `HOME` **and** `XDG_DATA_HOME` |-| Windows | `FOLDERID_RoamingAppData` (Win32 known-folder API) | nothing — no env override exists |+| Windows | `FOLDERID_RoamingAppData` | nothing the OS provides — see below |On Linux the harness pins **every** XDG base directory(`XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, `XDG_CACHE_HOME`) rather@@ -140,13 +140,77 @@ that variable inherited, a run **deletes** the developer's real`~/.config/Jan/settings.json` — confirmed against a decoy, which did not survivea single run.-Windows has no equivalent lever, so the config refuses to run there rather than-write into a real Jan profile.+On Windows there is no OS lever at all: `dirs` calls+`SHGetKnownFolderPath(FOLDERID_RoamingAppData, ..)`, which reads the registry and+takes no environment input. So Jan supplies its own — `core/app/paths.rs` prefers+`JAN_DATA_ROOT` and falls back to `dirs`.++It is Jan's own variable rather than `%APPDATA%`, which would also have worked.+The cost is what rules it out: Windows sets `%APPDATA%` for every interactive+session and processes inherit it, so honouring it would move the data root of+every existing install onto a value Jan does not control — and the blast radius+includes the legacy-config migration's `fs::copy` + `fs::remove_file`. A+dedicated name is unset in every real install, so the shipping binary resolves+byte-identically to `dirs` on all three platforms.++`paths.rs` honours the variable everywhere — one that silently did nothing on two+platforms out of three would be a trap — but the harness sets it on Windows only.+macOS and Linux already have a lever, and pushing them down the override branch+would stop the suite exercising the `dirs` lookup a real user gets.++That closes the destructive legacy-config migration too, though not because one+known folder serves both: `dirs::config_dir()` sits behind+`#[cfg(target_os = "linux")]` in `legacy_app_config_candidate_paths()`, so the+only Windows candidate comes from `resolve_bundle_app_data_dir()` —+`paths::data_dir()` joined with the bundle identifier. One variable moves both+because both go through `paths.rs`.++`APPDATA` is still set alongside it, for agreement rather than because `paths.rs`+reads it: anything else in the process tree that reads the variable directly+would otherwise see the real profile.++`USERPROFILE` and `LOCALAPPDATA` are redirected as well, and the harness must+create `AppData\Roaming` and `AppData\Local` under the throwaway profile before+the app starts. `SHGetKnownFolderPath` resolves the Roaming and Local known+folders from `REG_EXPAND_SZ` values of the form `%USERPROFILE%\AppData\...`,+expands them against the process environment — so the `USERPROFILE` override does+move them — and then verifies the result exists, because `dirs` does not pass+`KF_FLAG_DONT_VERIFY`. Miss `AppData\Local` and `dirs::cache_dir()` is `None`,+which `tauri-plugin-http`'s cookie jar turns into a startup panic+(`PluginInitialization("http", "unknown path")`, exit 101) before a window+exists; the embedded driver never binds and the run fails in `onPrepare`+reporting only `code=101`. The pair also takes the WebView2 user-data folder with+it, which Tauri puts at `%LOCALAPPDATA%\<identifier>\EBWebView` — keyed on the+bundle identifier (`jan.ai.app`) rather than on the executable name, so without+the override a test run and an installed Jan share one browser profile. Those+registry values are the default rather than a guarantee, though: folder+redirection or policy can make them literal paths that ignore `USERPROFILE`, so+isolation still rests on `JAN_DATA_ROOT` and `paths.rs`.++Two things Windows still cannot isolate, both of them accepted gaps enumerated+in `isolation.ts` next to `XDG_RUNTIME_DIR`:++- `dirs::home_dir()` resolves `FOLDERID_Profile` from the user's token rather+ than from a `%USERPROFILE%` template, so `USERPROFILE` does not move it the way+ it moves the AppData pair. The readers under `~/.jan` — `config.toml` and the+ subagent directory — therefore read the real user profile where `HOME`+ redirects them on macOS and Linux. The reachable desktop callers are reads, so+ this is a read leak rather than a destructive one.+- `updater.json` is written through `tauri-plugin-store`, which resolves its+ base with Tauri's own resolver rather than `core/app/paths.rs`, landing it in+ the real `%APPDATA%\jan.ai.app\`. Created only when absent.++Both are residue or reads. The one Windows escape that was destructive —+deep-link registration, which rewrites the `HKCU` `jan://` handler to point at+whichever binary is running — is compiled out under the `e2e` feature instead of+being documented, since no environment variable reaches the registry.Two things that look like they'd work but don't:-- `JAN_DATA_FOLDER` is read only by `resolve_jan_data_folder()`, the CLI path.- The desktop build ignores it.+- `JAN_DATA_FOLDER` — despite the name, a different variable from+ `JAN_DATA_ROOT` above: it names the data folder itself rather than the OS root+ it sits under, and only `resolve_jan_data_folder()` reads it, which is the CLI+ path. The desktop build ignores it.- `CI=e2e` short-circuits `get_app_configurations()` to a hardcoded `"./data"`,which would skip the config resolution these tests exist to cover.diff --git a/e2e/isolation.ts b/e2e/isolation.tsindex a651f5121..27ed3c31e 100644--- a/e2e/isolation.ts+++ b/e2e/isolation.ts@@ -5,6 +5,8 @@ import { join } from 'node:path'** Its own module, with no side effects, so specs can assert on it without* re-evaluating wdio.conf.ts (which creates the temp profile at import time).+ * Callers must create the directories these variables name -- nothing here does,+ * and on Windows one of them not existing is fatal (see below).** On Linux every XDG base directory is pinned, not just the ones Jan is known to* read today. Each outranks its `$HOME`-relative default, so any single one@@ -18,23 +20,115 @@ import { join } from 'node:path'* inherited, a run DELETES the developer's real ~/.config/Jan/settings.json.* Confirmed against a decoy: the file did not survive one run.*- * TMPDIR is pinned on both platforms, not just Linux. `std::env::temp_dir()`- * reads it on Unix, and tauri-plugin-agent-tools puts agent scratch at- * `temp_dir()/jan-agent-<session>` -- then sweep_stale_scratch_dirs()- * (workspace.rs) DELETES every `jan-agent-*` older than 24h it finds there. The- * current smoke suite never reaches that sweep (it is gated on an existing- * thread, and a fresh profile has none), so this is pre-emptive rather than a- * live bug. It stops being pre-emptive the moment a spec creates a thread.+ * The scratch directory is pinned on every platform, not just Linux.+ * `std::env::temp_dir()` reads TMPDIR on Unix and TMP/TEMP on Windows, and+ * tauri-plugin-agent-tools puts agent scratch at `temp_dir()/jan-agent-<session>`+ * -- then sweep_stale_scratch_dirs() (workspace.rs) DELETES every `jan-agent-*`+ * older than 24h it finds there. The current smoke suite never reaches that+ * sweep (it is gated on an existing thread, and a fresh profile has none), so+ * this is pre-emptive rather than a live bug. It stops being pre-emptive the+ * moment a spec creates a thread.+ *+ * On Windows the lever is `JAN_DATA_ROOT`, which is Jan's own rather than+ * something `dirs` provides: `dirs` asks the known-folder API for+ * FOLDERID_RoamingAppData and offers no override at all, so core/app/paths.rs+ * prefers the variable and falls back to `dirs`. It is honoured on every+ * platform but only needed here -- macOS and Linux keep resolving through HOME+ * and XDG_DATA_HOME, so those two go on exercising the same `dirs` lookup a real+ * user gets rather than the override branch.+ *+ * That closes the destructive legacy-config migration too, though not via+ * `dirs::config_dir()`: that call sits behind `#[cfg(target_os = "linux")]` in+ * legacy_app_config_candidate_paths(), so the only Windows candidate comes from+ * resolve_bundle_app_data_dir() -- `paths::data_dir()` joined with the bundle+ * identifier. One variable moves both because both go through paths.rs, not+ * because one known folder serves both.+ *+ * `APPDATA` is set alongside it for agreement, not because paths.rs reads it any+ * more: the shipping binary would otherwise answer one question two ways, and+ * anything else in the process tree that reads the variable directly would see+ * the real profile.+ *+ * `USERPROFILE` moves the known folders too, but only indirectly and only where+ * the target already exists, which is why it is not the lever. SHGetKnownFolderPath+ * resolves them through HKCU\...\Explorer\User Shell Folders, where the stock+ * values are REG_EXPAND_SZ `%USERPROFILE%\AppData\{Roaming,Local}`; it expands+ * those against the *process* environment, and then -- absent+ * KF_FLAG_DONT_VERIFY, which `dirs` does not pass -- fails outright if the+ * directory is not there. Two consequences:+ *+ * - The directories must exist before the app starts. Redirect USERPROFILE+ * without creating `AppData\Local` under it and `dirs::cache_dir()` returns+ * None, which is not a soft failure: tauri-plugin-http's cookie jar calls+ * `app_cache_dir()?` from its setup hook (that is+ * `dirs::cache_dir().ok_or(Error::UnknownPath)`), so the Tauri builder dies+ * with PluginInitialization("http", "unknown path") before a window exists.+ * wdio.conf.ts creates them; the comment there says why.+ * - Those registry values are the default, not a guarantee. Folder redirection+ * or policy can make them literal paths that ignore USERPROFILE entirely, so+ * isolation still rests on JAN_DATA_ROOT and paths.rs rather than on this.+ *+ * `LOCALAPPDATA` is set for agreement, not because `dirs` reads it -- it does+ * not. With the known folder already resolving inside the profile, leaving the+ * variable pointed at the real one would hand the app two different answers to+ * the same question. Together they also take the WebView2 user-data folder with+ * them, which matters more than it looks: Tauri puts it at+ * `%LOCALAPPDATA%\<identifier>\EBWebView`, keyed on the bundle identifier+ * (`jan.ai.app`) and not on the executable name, so an unconfined test run and+ * an installed Jan share one browser profile.** Deliberately absent:* - XDG_DATA_DIRS / XDG_CONFIG_DIRS: read-only system paths; overriding them* breaks GTK schema and theme lookup.* - XDG_RUNTIME_DIR: the app needs the real one for D-Bus. It cannot be* isolated, which is an accepted gap rather than an oversight.+ * - A Windows override for `dirs::home_dir()`: there isn't one. It resolves+ * FOLDERID_Profile (dirs-6.0.0 src/win.rs -> dirs_sys::known_folder_profile),+ * which comes from the user's token rather than from a `%USERPROFILE%`+ * template, so USERPROFILE does not move it the way it moves the AppData+ * pair. The two readers under `~/.jan` -- `config.toml`+ * (core/agent/global_config.rs) and `agent/subagents/`+ * (core/agent/subagent.rs user_subagents_dir) -- therefore read the real user+ * profile on Windows where HOME redirects them on macOS and Linux. Both are+ * reads: the write at global_config.rs:469 is an explicit save no spec+ * triggers, and user_subagents_dir's is gated behind prompt_subagent_create,+ * which no spec reaches. So this is a read leak, not a destructive one.+ * Strictly weaker than the other two platforms, and an accepted gap rather+ * than an oversight.+ *+ * One Windows write still lands outside `home` and no variable here can move it.+ * It is residue rather than damage, and it is listed so the next person does not+ * have to rediscover it: `updater.json`, via tauri-plugin-store. The frontend's+ * update check (web-app/src/services/updater/tauri.ts) stores a nonce seed+ * through the plugin, which resolves BaseDirectory::AppData with Tauri's own+ * resolver -- `dirs::data_dir()`, not core/app/paths.rs -- so it lands in the+ * real `%APPDATA%\jan.ai.app\`. It is created only when absent and never+ * overwrites an existing seed, so the worst case is planting a file the real app+ * would have written itself.+ *+ * The one Windows escape that *was* destructive is gone rather than documented:+ * deep-link registration writes HKCU Software\Classes\jan, outside anything an+ * environment variable can reach, so it is compiled out under the `e2e` feature+ * (src-tauri/src/lib.rs) alongside single-instance.+ *+ * HOME is set on Windows as well. It moves nothing in `dirs`; it is there for+ * tooling that reads it directly, and setting it costs nothing.*/export function isolationEnv(home: string): Record<string, string> {- // Callers must ensure TMPDIR exists: temp_dir() does not create it.+ // Callers must ensure the scratch directory exists: temp_dir() does not+ // create it.const tmp = join(home, 'tmp')+ if (process.platform === 'win32') {+ return {+ JAN_DATA_ROOT: join(home, 'AppData', 'Roaming'),+ APPDATA: join(home, 'AppData', 'Roaming'),+ LOCALAPPDATA: join(home, 'AppData', 'Local'),+ USERPROFILE: home,+ HOME: home,+ TEMP: tmp,+ TMP: tmp,+ }+ }if (process.platform !== 'linux') return { HOME: home, TMPDIR: tmp }return {HOME: home,diff --git a/e2e/specs/smoke.e2e.ts b/e2e/specs/smoke.e2e.tsindex fdd0af149..482dd77af 100644--- a/e2e/specs/smoke.e2e.ts+++ b/e2e/specs/smoke.e2e.ts@@ -83,8 +83,8 @@ describe('Jan desktop app', () => {// stopped passing that env to the app at all.//// This asserts the opposite end: a file the Rust side wrote, at a path the Rust-// side resolved through dirs::data_dir(). It only exists here if the overridden-// environment actually reached the app process.+// side resolved through core::app::paths::data_dir(). It only exists here if the+// overridden environment actually reached the app process.describe('on-disk isolation', () => {it('wrote its config inside the throwaway profile', async () => {// app_data_dir_with_fallback() -> data_dir()/Jan, + CONFIGURATION_FILE_NAME@@ -92,7 +92,9 @@ describe('on-disk isolation', () => {const settings =process.platform === 'darwin'? join(testHome, 'Library/Application Support/Jan/settings.json')- : join(testHome, '.local/share/Jan/settings.json')+ : process.platform === 'win32'+ ? join(testHome, 'AppData/Roaming/Jan/settings.json')+ : join(testHome, '.local/share/Jan/settings.json')await browser.waitUntil(() => existsSync(settings), {timeout: 30_000,diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.tsindex 672865aaf..e28baf20e 100644--- a/e2e/wdio.conf.ts+++ b/e2e/wdio.conf.ts@@ -6,29 +6,31 @@ import type { TauriCapabilities, TauriServiceOptions } from '@wdio/tauri-serviceimport { SevereServiceError } from 'webdriverio'import { isolationEnv } from './isolation.js'-// The app resolves its data folder through `dirs::data_dir()`, so isolation is-// only sound where that call can be redirected by environment:+// The app resolves its data folder through `core::app::paths::data_dir()`, and+// isolation is only sound where that call can be redirected by environment://-// macOS $HOME/Library/Application Support -> HOME-// Linux $XDG_DATA_HOME, else $HOME/.local/share -> both (see isolationEnv)-// Windows FOLDERID_RoamingAppData via the Win32-// known-folder API -> no env override exists+// macOS $HOME/Library/Application Support -> HOME+// Linux $XDG_DATA_HOME, else $HOME/.local/share -> both (see isolationEnv)+// Windows FOLDERID_RoamingAppData -> nothing//-// Windows therefore cannot be isolated at all, and a run there would use a real-// Jan profile. Failing loudly beats pretending.-if (process.platform !== 'darwin' && process.platform !== 'linux') {- throw new Error(- `e2e isolation is not possible on ${process.platform}; refusing to run. ` +- 'On Windows `dirs::data_dir()` reads FOLDERID_RoamingAppData through the ' +- 'known-folder API, which has no environment override.'- )-}+// Windows has no lever of its own -- `dirs` goes straight to the known-folder+// API, which takes no environment input -- so Jan reads `JAN_DATA_ROOT` ahead of+// it, and isolationEnv() sets that variable there. `paths.rs` honours it on all+// three platforms, but the harness sets it only on Windows: macOS and Linux+// already have a lever, and pushing them down the override branch would stop the+// suite exercising the `dirs` lookup a real user actually gets. See+// src-tauri/src/core/app/paths.rs for why the variable is Jan's own rather than+// `%APPDATA%`, and isolationEnv() for what is still not isolated on Windows.const repoRoot = resolve(import.meta.dirname, '..')// The desktop binary built by `yarn build:e2e:app`. Debug profile: the e2e// feature is a test-only opt-in and never goes near a release artifact.-const appBinary = join(repoRoot, 'src-tauri/target/debug/Jan-Desktop')+const appBinary = join(+ repoRoot,+ 'src-tauri/target/debug',+ process.platform === 'win32' ? 'Jan-Desktop.exe' : 'Jan-Desktop'+)// Fail here rather than 2 minutes later inside a driver-connection retry loop,// which is what a missing binary otherwise looks like.@@ -43,8 +45,10 @@ if (!existsSync(appBinary)) {// developer's real Jan data. See isolationEnv() for the variables that confine// the app to it -- HOME alone is not sufficient on Linux.//-// Deliberately NOT using JAN_DATA_FOLDER: only resolve_jan_data_folder() reads-// it, and that is the CLI path. The desktop build ignores it.+// Deliberately NOT using JAN_DATA_FOLDER, which despite the name is a different+// variable from JAN_DATA_ROOT above: it names the data folder itself rather than+// the OS root it sits under, and only resolve_jan_data_folder() reads it, which+// is the CLI path. The desktop build ignores it.// Deliberately NOT using CI=e2e: that hook short-circuits// get_app_configurations() to a hardcoded "./data", which would skip the very// config resolution this test is meant to cover.@@ -74,6 +78,15 @@ if (ownsTestHome) {// the app. Removing the tree from onComplete would race a live Jan process// that still holds store/log handles -- which can throw EBUSY (force: true// only swallows ENOENT) or let the app recreate paths under the deleted tree.+ //+ // The retries are the second half of that: the exit hook runs after the+ // service killed the app, but a kill is not a barrier -- Windows keeps a+ // handle's file locked until the last one closes, and an antivirus scan of the+ // freshly written profile can hold one for a moment longer. rmSync defaults to+ // maxRetries: 0, so one EBUSY/EPERM would throw, and a throw in an 'exit'+ // listener is not routed through uncaughtException: node prints it and exits+ // 1, turning a green run red on cleanup alone. A second of backoff costs+ // nothing on the runs that do not need it.process.once('exit', () => {if (process.env.JAN_E2E_KEEP) {console.log(`e2e profile kept at ${testHome}`)@@ -81,7 +94,12 @@ if (ownsTestHome) {}// Belt and braces: never recurse outside the temp root.if (!testHome.startsWith(realpathSync(tmpdir()))) return- rmSync(testHome, { recursive: true, force: true })+ rmSync(testHome, {+ recursive: true,+ force: true,+ maxRetries: 10,+ retryDelay: 100,+ })})// No SIGINT/SIGTERM handler on purpose. wdio installs its own, and a second// listener would delete the tree while that one is still tearing the app@@ -93,6 +111,21 @@ if (ownsTestHome) {// it. An app that cannot write scratch is a confusing failure; make it exist.mkdirSync(join(testHome, 'tmp'), { recursive: true })+// The AppData pair is not optional on Windows, and getting it wrong does not+// look like a path problem. SHGetKnownFolderPath resolves the Roaming and Local+// known folders from REG_EXPAND_SZ values of the form+// `%USERPROFILE%\AppData\...`, expands them against this process's environment+// -- so the USERPROFILE override moves them -- and then verifies the result+// exists, because `dirs` does not pass KF_FLAG_DONT_VERIFY. Miss `AppData\Local`+// and `dirs::cache_dir()` is None, which tauri-plugin-http's cookie jar turns+// into a panic at startup: PluginInitialization("http", "unknown path"). The app+// then dies before the embedded driver binds, and the run fails in onPrepare+// reporting only `code=101`.+if (process.platform === 'win32') {+ mkdirSync(join(testHome, 'AppData', 'Roaming'), { recursive: true })+ mkdirSync(join(testHome, 'AppData', 'Local'), { recursive: true })+}+// Resolved exactly as the service resolves it -- getEmbeddedPort(): the// TAURI_WEBDRIVER_PORT env var, else a hardcoded 4445.const driverPort = Number(process.env.TAURI_WEBDRIVER_PORT) || 4445@@ -113,9 +146,11 @@ function somethingIsListening(port: number): Promise<boolean> {const tauriServiceOptions: TauriServiceOptions = {// Embedded WebDriver server (tauri-plugin-wdio-webdriver). Required on macOS,- // where there is no WKWebView driver to attach from outside; used on Linux too- // so both platforms exercise one path and neither needs `tauri-driver`- // installed (Linux could otherwise drive WebKitWebDriver via 'official').+ // where there is no WKWebView driver to attach from outside; used on Linux and+ // Windows too so all three exercise one path and none needs `tauri-driver`+ // installed (those two could otherwise drive WebKitWebDriver / msedgedriver via+ // 'official'). The plugin has a real WebView2 backend, not just a Unix one:+ // src/platform/windows.rs.driverProvider: 'embedded',env: isolationEnv(testHome),}@@ -169,8 +204,11 @@ export const config: WebdriverIO.Config = {'embedded WebDriver server uses. This run would drive that process ' +'instead of the app it launches. Most likely another e2e run is in ' +'progress, or a previous one was killed and left Jan-Desktop alive ' +- '(`pkill -f Jan-Desktop`). To use a different port instead, set ' +- 'TAURI_WEBDRIVER_PORT.'+ `(\`${+ process.platform === 'win32'+ ? 'taskkill /IM Jan-Desktop.exe /F'+ : 'pkill -f Jan-Desktop'+ }\`). To use a different port instead, set TAURI_WEBDRIVER_PORT.`)},}diff --git a/package.json b/package.jsonindex a46311a9c..ec10a61bf 100644--- a/package.json+++ b/package.json@@ -50,7 +50,7 @@"build:extensions": "yarn workspace @janhq/core build && yarn workspaces foreach -Apt --include '@janhq/*-extension' run build","prepare": "husky","e2e": "yarn build:e2e:app && cd e2e && yarn install --immutable && yarn test",- "build:e2e:app": "yarn build:icon && ./scripts/stub-tauri-resources.sh && yarn build:e2e:deps && cross-env IS_TAURI=true yarn build:web && cargo build --locked --manifest-path src-tauri/Cargo.toml --features e2e --bin Jan-Desktop",+ "build:e2e:app": "yarn build:icon && node ./scripts/stub-tauri-resources.mjs && yarn build:e2e:deps && cross-env IS_TAURI=true yarn build:web && cargo build --locked --manifest-path src-tauri/Cargo.toml --features e2e --bin Jan-Desktop","build:e2e:deps": "yarn install && yarn build:tauri:plugin:api && yarn build:core && yarn build:extensions"},"devDependencies": {diff --git a/scripts/rust-coverage.sh b/scripts/rust-coverage.shindex 9a144ae14..b2e62b1d8 100755--- a/scripts/rust-coverage.sh+++ b/scripts/rust-coverage.sh@@ -3,7 +3,7 @@# Outputs: rust-lcov.info in the current directory.set -euo pipefail-"$(dirname "$0")/stub-tauri-resources.sh"+node "$(dirname "$0")/stub-tauri-resources.mjs"cargo llvm-cov clean --workspace --manifest-path src-tauri/Cargo.tomlcargo llvm-cov --no-report --manifest-path src-tauri/Cargo.toml --no-default-features --features test-tauri -- --test-threads=1diff --git a/scripts/stub-tauri-resources.mjs b/scripts/stub-tauri-resources.mjsnew file mode 100644index 000000000..b46159df3--- /dev/null+++ b/scripts/stub-tauri-resources.mjs@@ -0,0 +1,105 @@+// The Tauri build script validates resources, externalBin, icons and+// frontendDist exist. Create stubs so a compile-only run succeeds in CI, where+// none of them are built.+//+// Node rather than shell because a stock Windows box has neither `bash` nor+// `sh` on PATH -- a default Git for Windows install puts only `Git\cmd` there,+// which is `git.exe` alone. Every caller already needs `node`, and this uses+// only builtins, so it also runs before `yarn install` has produced a+// node_modules (which is the state the rust-check workflow calls it in).+import { execFileSync } from 'node:child_process'+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ readdirSync,+ writeFileSync,+} from 'node:fs'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'++// Resolved against the repo root, not the caller's cwd: the callers are a+// package.json script, a Makefile recipe, two workflows and rust-coverage.sh,+// and not all of them pin where they run from. (import.meta.dirname would say+// this more directly, but it needs Node 20.11 and CI only asks for 20.)+const repoRoot = fileURLToPath(new URL('..', import.meta.url))+const path = (...parts) => join(repoRoot, ...parts)++// Every stub is guarded so we never clobber a real local build or churn the+// cargo:rerun-if-changed stamps these paths emit.+function touch(target) {+ if (!existsSync(target)) writeFileSync(target, '')+}++const triple = execFileSync('rustc', ['-vV'], { encoding: 'utf8' })+ .split('\n')+ .find((line) => line.startsWith('host:'))+ .slice('host:'.length)+ .trim()++for (const dir of [+ 'src-tauri/resources/bin',+ 'src-tauri/resources/pre-install',+ 'src-tauri/icons',+ 'web-app/dist',+]) {+ mkdirSync(path(dir), { recursive: true })+}++touch(path('src-tauri/resources/LICENSE'))+touch(path('web-app/dist/index.html'))+if (readdirSync(path('src-tauri/resources/pre-install')).length === 0) {+ touch(path('src-tauri/resources/pre-install/.gitkeep'))+}++// The executable suffix, and the ggml runtime that ships beside the engine+// worker. `libggml*` is a glob in the bundle config, and a glob that matches+// nothing is an error (GlobPathNotFound), not an empty set -- so one stub+// library is required, not optional.+let exe = ''+let lib+if (process.platform === 'darwin') {+ lib = 'libggml-base.dylib'+ // macOS also bundles the MLX server and the resource bundle beside it.+ touch(path('src-tauri/resources/bin/mlx-server'))+ mkdirSync(path('src-tauri/resources/bin/mlx-swift_Cmlx.bundle'), {+ recursive: true,+ })+} else if (process.platform === 'win32') {+ exe = '.exe'+ lib = 'ggml-base.dll'+} else {+ lib = 'libggml-base.so'+}++// Tauri resolves an externalBin entry to `<name>-<triple><exe>`. The shell+// version omitted the suffix, which nothing caught because it could not run on+// the one platform where the suffix is not empty.+for (const bin of ['uv', 'bun']) {+ touch(path('src-tauri/resources/bin', `${bin}-${triple}${exe}`))+}++for (const bin of ['jan-llama-worker']) {+ touch(path('src-tauri/resources/bin', `${bin}${exe}`))+}++// Any name mentioning ggml that carries the platform's library extension+// counts, matching what the bundle config globs for.+const libExt = lib.slice(lib.lastIndexOf('.'))+const haveRuntime = readdirSync(path('src-tauri/resources/bin')).some((name) => {+ const ggml = name.indexOf('ggml')+ return ggml !== -1 && name.indexOf(libExt, ggml) !== -1+})+if (!haveRuntime) touch(path('src-tauri/resources/bin', lib))++// Icons are gitignored; generate_context!() requires them at compile time+for (const icon of [+ '32x32.png',+ '128x128.png',+ '[email protected]',+ 'icon.icns',+ 'icon.ico',+]) {+ const target = path('src-tauri/icons', icon)+ if (!existsSync(target)) copyFileSync(path('src-tauri/icons/icon.png'), target)+}diff --git a/scripts/stub-tauri-resources.sh b/scripts/stub-tauri-resources.shdeleted file mode 100755index 181a37c9c..000000000--- a/scripts/stub-tauri-resources.sh+++ /dev/null@@ -1,36 +0,0 @@-#!/usr/bin/env bash-# The Tauri build script validates resources, externalBin, icons and-# frontendDist exist. Create stubs so a compile-only run succeeds in CI, where-# none of them are built.-set -euo pipefail--TRIPLE=$(rustc -vV | awk '/^host:/ { print $2 }')-mkdir -p src-tauri/resources/bin src-tauri/resources/pre-install src-tauri/icons web-app/dist-[ -f src-tauri/resources/LICENSE ] || touch src-tauri/resources/LICENSE-[ -f web-app/dist/index.html ] || touch web-app/dist/index.html-[ "$(ls -A src-tauri/resources/pre-install 2>/dev/null)" ] || touch src-tauri/resources/pre-install/.gitkeep-for bin in uv bun; do- stub="src-tauri/resources/bin/${bin}-${TRIPLE}"- [ -f "$stub" ] || touch "$stub"-done-# The engine worker and the ggml runtime beside it. `libggml*` is a glob in the-# bundle config, and a glob that matches nothing is an error (GlobPathNotFound),-# not an empty set -- so one stub library is required, not optional.-case "$(uname -s)" in- Darwin)- EXE=""; LIB="libggml-base.dylib"- # macOS also bundles the MLX server and the resource bundle beside it.- [ -f src-tauri/resources/bin/mlx-server ] || touch src-tauri/resources/bin/mlx-server- [ -e src-tauri/resources/bin/mlx-swift_Cmlx.bundle ] || mkdir -p src-tauri/resources/bin/mlx-swift_Cmlx.bundle- ;;- MINGW* | MSYS* | CYGWIN*) EXE=".exe"; LIB="ggml-base.dll" ;;- *) EXE=""; LIB="libggml-base.so" ;;-esac-for bin in jan-llama-worker; do- [ -f "src-tauri/resources/bin/${bin}${EXE}" ] || touch "src-tauri/resources/bin/${bin}${EXE}"-done-ls src-tauri/resources/bin/*ggml*."${LIB##*.}"* >/dev/null 2>&1 || touch "src-tauri/resources/bin/$LIB"-# Icons are gitignored; generate_context!() requires them at compile time-for icon in 32x32.png 128x128.png [email protected] icon.icns icon.ico; do- [ -f "src-tauri/icons/$icon" ] || cp src-tauri/icons/icon.png "src-tauri/icons/$icon"-donediff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 35e296788..bf48dadf5 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -8044,7 +8044,6 @@ dependencies = [name = "tauri-plugin-vector-db"version = "0.1.0"dependencies = [- "dirs","log","rusqlite","serde",diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lockindex ed82c595c..e2b312572 100644--- a/src-tauri/jan-cli/Cargo.lock+++ b/src-tauri/jan-cli/Cargo.lock@@ -5126,7 +5126,6 @@ dependencies = [name = "tauri-plugin-vector-db"version = "0.1.0"dependencies = [- "dirs","log","rusqlite","serde",diff --git a/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml b/src-tauri/plugins/tauri-plugin-vector-db/Cargo.tomlindex 179027523..cfc774433 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml@@ -25,7 +25,6 @@ tokio = { version = "1", features = ["full"] }log = "0.4"rusqlite = { version = "0.32", features = ["bundled", "load_extension"] }uuid = { version = "1.7", features = ["v4", "serde"] }-dirs = "6.0.0"[build-dependencies]tauri-plugin = { version = "2.3.1", features = ["build"] }diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rsindex 290dfebc5..c4c1e3a75 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs@@ -49,10 +49,16 @@ pub struct MinimalChunkInput {// ============================================================================/// Canonical base directory for all vector-db collections (RAG chunks and the-/// agent memory store). Single source of truth shared by `VectorDBState` and any-/// out-of-plugin consumer so they operate on the same `.db` files.-pub fn default_base_dir() -> PathBuf {- let mut base = dirs::data_dir().unwrap_or_else(|| PathBuf::from("."));+/// agent memory store), given the OS app-data root. Single source of truth+/// shared by `VectorDBState` and any out-of-plugin consumer so they operate on+/// the same `.db` files.+///+/// The root is passed in rather than looked up here: this crate is a workspace+/// member and cannot see the app's `core::app::paths`, which is where the+/// Windows `%APPDATA%` override lives. Resolving `dirs::data_dir()` locally+/// would put the plugin -- and only the plugin -- back on the real profile.+pub fn base_dir_in(data_root: &Path) -> PathBuf {+ let mut base = data_root.to_path_buf();base.push("Jan");base.push("data");base.push("db");diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rsindex f58ee1520..1d48626e4 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs@@ -9,7 +9,7 @@ pub use error::VectorDBError;pub use state::VectorDBState;#[cfg(feature = "tauri")]-pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {+pub fn init<R: tauri::Runtime>(base_dir: std::path::PathBuf) -> tauri::plugin::TauriPlugin<R> {use tauri::Manager;tauri::plugin::Builder::new("vector-db")@@ -29,8 +29,8 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::memory_search,commands::memory_clear,])- .setup(|app, _api| {- app.manage(state::VectorDBState::new());+ .setup(move |app, _api| {+ app.manage(state::VectorDBState::new(base_dir));Ok(())}).build()diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/state.rsindex 065157f0b..6de61f376 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs@@ -4,16 +4,11 @@ pub struct VectorDBState {pub base_dir: PathBuf,}-impl Default for VectorDBState {- fn default() -> Self {- Self::new()- }-}-impl VectorDBState {- pub fn new() -> Self {- let base = crate::db::default_base_dir();- std::fs::create_dir_all(&base).ok();- Self { base_dir: base }+ /// `base_dir` comes from the host app (see `db::base_dir_in`). There is no+ /// `Default`, so the plugin cannot silently fall back to the real profile.+ pub fn new(base_dir: PathBuf) -> Self {+ std::fs::create_dir_all(&base_dir).ok();+ Self { base_dir }}}diff --git a/src-tauri/src/core/agent/memory.rs b/src-tauri/src/core/agent/memory.rsindex 0f4a512e4..3b9bc8fba 100644--- a/src-tauri/src/core/agent/memory.rs+++ b/src-tauri/src/core/agent/memory.rs@@ -1,6 +1,6 @@//! Project-scoped agent memory: retrieve past excerpts into the system prompt//! and index the user query + final assistant answer after a run. Backed by the-//! vector-db plugin's FTS5/BM25 store (`default_base_dir`), so desktop memory+//! vector-db plugin's FTS5/BM25 store (`paths::vector_db_dir`), so desktop memory//! settings and the loop operate on the same DB.use std::hash::{Hash, Hasher};@@ -8,6 +8,8 @@ use std::path::Path;use tauri_plugin_vector_db::db;+use crate::core::app::paths;+const TOP_K: usize = 3;const MAX_EXCERPT_CHARS: usize = 500;@@ -42,7 +44,7 @@ pub(crate) fn index_message(project_root: &Path, role: &str, text: &str) {}let pid = project_id(project_root);let id = content_id(&pid, role, text);- let path = db::collection_path(&db::default_base_dir(), db::MEMORY_COLLECTION);+ let path = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION);if let Ok(conn) = db::open_or_init_conn(&path) {let _ = db::memory_index(&conn, &id, &pid, text, role, now_ts());}@@ -52,7 +54,7 @@ pub(crate) fn index_message(project_root: &Path, role: &str, text: &str) {/// for the system prompt. None when nothing is recalled (or the store is empty).pub(crate) fn retrieve_block(project_root: &Path, query: &str) -> Option<String> {let pid = project_id(project_root);- let path = db::collection_path(&db::default_base_dir(), db::MEMORY_COLLECTION);+ let path = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION);let conn = db::open_or_init_conn(&path).ok()?;let hits = db::memory_search(&conn, &pid, query, TOP_K).ok()?;if hits.is_empty() {diff --git a/src-tauri/src/core/app/commands.rs b/src-tauri/src/core/app/commands.rsindex 7b95bfbd6..4b6ef5d9e 100644--- a/src-tauri/src/core/app/commands.rs+++ b/src-tauri/src/core/app/commands.rs@@ -3,10 +3,11 @@ use std::{path::{Path, PathBuf},};#[cfg(not(feature = "cli"))]-use tauri::{AppHandle, Manager, Runtime, State};+use tauri::{AppHandle, Runtime, State};use super::constants::{CONFIGURATION_FILE_NAME, TAURI_BUNDLE_IDENTIFIER};use super::models::AppConfiguration;+use super::paths;#[cfg(not(feature = "cli"))]use super::helpers::copy_dir_recursive;#[cfg(not(feature = "cli"))]@@ -14,12 +15,12 @@ use crate::core::state::AppState;/// Canonical Jan app support directory (`%APPDATA%/Jan` on Windows).fn resolve_human_readable_app_data_dir() -> Option<PathBuf> {- dirs::data_dir().map(|d| d.join(env!("CARGO_PKG_NAME")))+ paths::data_dir().map(|d| d.join(env!("CARGO_PKG_NAME")))}/// Tauri bundle-id app support directory (e.g. `%APPDATA%/jan.ai.app` on Windows).fn resolve_bundle_app_data_dir() -> Option<PathBuf> {- dirs::data_dir().map(|d| d.join(TAURI_BUNDLE_IDENTIFIER))+ paths::data_dir().map(|d| d.join(TAURI_BUNDLE_IDENTIFIER))}/// Keep `%APPDATA%/Jan/settings.json` as canonical, but recover from legacy or@@ -82,9 +83,7 @@ fn legacy_app_config_candidate_paths(_app_data_dir: &Path) -> Vec<PathBuf> {#[cfg(not(feature = "cli"))]fn app_data_dir_with_fallback<R: Runtime>(app_handle: &tauri::AppHandle<R>) -> PathBuf {let package_name = env!("CARGO_PKG_NAME");- app_handle- .path()- .data_dir()+ paths::data_dir_for(app_handle).unwrap_or_else(|err| {log::error!("Failed to get data directory: {err}. Using home directory instead.");@@ -166,7 +165,7 @@ pub fn resolve_jan_data_folder() -> PathBuf {// Default: data_dir/Jan/data (mirrors default_data_folder_path)let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| "Jan".to_string());- if let Some(data_dir) = dirs::data_dir() {+ if let Some(data_dir) = paths::data_dir() {return data_dir.join(&app_name).join("data");}let home = std::env::var("HOME")@@ -291,7 +290,7 @@ pub fn get_configuration_file_path<R: Runtime>(app_handle: tauri::AppHandle<R>)#[cfg(not(feature = "cli"))]#[tauri::command]pub fn default_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) -> String {- let mut path = app_handle.path().data_dir().unwrap_or_else(|err| {+ let mut path = paths::data_dir_for(&app_handle).unwrap_or_else(|err| {log::error!("Failed to get data directory: {err}. Falling back to home directory.");let home = std::env::var(if cfg!(target_os = "windows") {"USERPROFILE"diff --git a/src-tauri/src/core/app/mod.rs b/src-tauri/src/core/app/mod.rsindex 2dc65d6b3..698b62afe 100644--- a/src-tauri/src/core/app/mod.rs+++ b/src-tauri/src/core/app/mod.rs@@ -3,6 +3,9 @@ pub mod constants;#[cfg(not(feature = "cli"))]pub mod helpers;pub mod models;+// Resolves the OS app-data root. Every `dirs::data_dir()` / `path().data_dir()`+// call in the app goes through here so Windows has an env lever at all.+pub mod paths;// Desktop settings.json store, driven by Tauri commands + a flush thread.#[cfg(not(feature = "cli"))]pub mod settings_store;diff --git a/src-tauri/src/core/app/paths.rs b/src-tauri/src/core/app/paths.rsnew file mode 100644index 000000000..2d995fa9e--- /dev/null+++ b/src-tauri/src/core/app/paths.rs@@ -0,0 +1,189 @@+//! Where Jan's app-data root lives, and the one place that decision is made.+//!+//! `dirs::data_dir()`, `app.path().data_dir()` and `app.path().app_data_dir()`+//! all bottom out in the same per-OS lookup -- Tauri's resolvers are thin+//! wrappers over `dirs` (`tauri::path::desktop`). On Windows that lookup is+//! `SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, ..)`, which reads the+//! registry and ignores `%APPDATA%` entirely. With flags `0` and a null token,+//! the only input that can move the result is running as a different Windows+//! user.+//!+//! Every other desktop platform has a lever -- `HOME` on macOS, `HOME` plus+//! `XDG_DATA_HOME` on Linux -- so a test harness can confine a run to a+//! throwaway profile there, and on Windows it cannot. `JAN_DATA_ROOT` is that+//! lever.+//!+//! It is Jan's own variable rather than `%APPDATA%`, which would also have+//! worked -- Electron, Chromium and Python's `platformdirs` all read it, and+//! `dirs` declining to is a `dirs` design choice rather than a Windows+//! convention. The cost is the part that matters: `%APPDATA%` is set by Windows+//! for every interactive session and inherited by whatever a process was+//! launched from, so honouring it moves the data root of every existing install+//! onto a value Jan does not control. The blast radius is not read-only either+//! -- the legacy-config migration in `core/app/commands.rs` does `fs::copy`+//! followed by `fs::remove_file`. A dedicated name is unset in every real+//! install, so these helpers resolve byte-identically to `dirs` on all three+//! platforms unless someone deliberately points them elsewhere.+//!+//! Honoured on every platform, not just Windows: a variable that silently does+//! nothing on two of three platforms is a trap for whoever sets it there+//! expecting isolation.+//!+//! Read by the shipping binary and deliberately not gated behind the `e2e`+//! feature. The resolution these tests exist to cover has to be the resolution+//! that ships; compiling a different lookup into the test binary is the flaw+//! that ruled out `CI=e2e`, which short-circuits `get_app_configurations()` to a+//! hardcoded `"./data"` and so skips that resolution entirely.+//!+//! Distinct from `JAN_DATA_FOLDER`, which is older, read by+//! `resolve_jan_data_folder()`, and names the *data folder itself*+//! (`<root>/Jan/data` by default). `JAN_DATA_ROOT` names the OS-level root that+//! folder is resolved under.++use std::ffi::OsString;+use std::path::PathBuf;++#[cfg(not(feature = "cli"))]+use tauri::{AppHandle, Manager, Runtime};++/// Jan's override for the OS app-data root. See the module docs for why this is+/// not `%APPDATA%`.+const DATA_ROOT_ENV: &str = "JAN_DATA_ROOT";++/// The rules for reading [`DATA_ROOT_ENV`], split out from the lookup so the+/// validation is testable without touching the process environment.+///+/// An empty value means "unset", not "the current directory" -- joining onto+/// `PathBuf::from("")` would silently produce a relative data folder. A+/// non-absolute value is rejected for the same reason: the point of the+/// override is to make the data root *addressable*, and a relative one would+/// instead follow the working directory, landing a different run in a different+/// folder. Falling back to the OS default is the safer reading of a malformed+/// value than rooting the profile wherever the process happened to start.+fn absolute_override(raw: Option<OsString>) -> Option<PathBuf> {+ raw.map(PathBuf::from).filter(|value| value.is_absolute())+}++/// The override, or `None` when it is unset or malformed.+fn env_data_dir() -> Option<PathBuf> {+ absolute_override(std::env::var_os(DATA_ROOT_ENV))+}++/// The OS app-data root: `$JAN_DATA_ROOT` when set, else `dirs::data_dir()`.+///+/// Use in place of `dirs::data_dir()`.+pub fn data_dir() -> Option<PathBuf> {+ env_data_dir().or_else(dirs::data_dir)+}++/// Same as [`data_dir`], for code that already holds an `AppHandle`.+///+/// Use in place of `app.path().data_dir()`. Falls through to Tauri's resolver+/// when there is no override, so the error type and the `UnknownPath` case are+/// unchanged.+#[cfg(not(feature = "cli"))]+pub fn data_dir_for<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<PathBuf> {+ match env_data_dir() {+ Some(dir) => Ok(dir),+ None => app.path().data_dir(),+ }+}++/// The bundle-identifier subdirectory of [`data_dir_for`], e.g.+/// `<root>/jan.ai.app`.+///+/// Use in place of `app.path().app_data_dir()`. Mirrors Tauri's own definition+/// (`data_dir()` joined with `config.identifier`) rather than the+/// `TAURI_BUNDLE_IDENTIFIER` constant, because+/// `.github/scripts/rename-tauri-app.sh` rewrites the identifier per release+/// channel (`jan-nightly.ai.app`, ...) and a nightly build has to keep+/// resolving to its own directory.+#[cfg(not(feature = "cli"))]+pub fn app_data_dir_for<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<PathBuf> {+ match env_data_dir() {+ Some(dir) => Ok(dir.join(&app.config().identifier)),+ None => app.path().app_data_dir(),+ }+}++/// The vector-db plugin's collection root, under [`data_dir`].+///+/// The plugin is a separate workspace crate and cannot call into this module,+/// so the app resolves the root and hands it over -- at `init()` for the Tauri+/// command surface, and per call for the agent memory store.+pub fn vector_db_dir() -> PathBuf {+ let root = data_dir().unwrap_or_else(|| PathBuf::from("."));+ tauri_plugin_vector_db::db::base_dir_in(&root)+}++#[cfg(test)]+mod tests {+ use super::*;++ // An absolute path spelled the way the host spells them, so the rule under+ // test is exercised on every platform rather than only on one.+ #[cfg(target_os = "windows")]+ const ABSOLUTE: &str = r"C:\throwaway\Roaming";+ #[cfg(not(target_os = "windows"))]+ const ABSOLUTE: &str = "/throwaway/Roaming";++ #[test]+ fn only_an_absolute_override_counts_as_set() {+ assert_eq!(absolute_override(None), None);+ assert_eq!(absolute_override(Some(OsString::from(""))), None);+ // Relative: would otherwise resolve against the working directory.+ assert_eq!(absolute_override(Some(OsString::from("Roaming"))), None);+ assert_eq!(+ absolute_override(Some(OsString::from(ABSOLUTE))),+ Some(PathBuf::from(ABSOLUTE))+ );+ }++ // Mutates the process environment, so it takes SECRET_STORE_TEST_LOCK --+ // the lock every env-mutating test in this crate shares, for the reason+ // `with_temp_data_folder` spells out (core/app/commands.rs): the+ // environment is process-wide, so a lock private to this test would+ // exclude only the other tests that take *it*.+ //+ // That is necessary and not sufficient. Readers of `data_dir()` take no+ // lock and cannot be made to -- they are production code -- so nothing+ // stops a test on another thread from observing the override while it is+ // set. The guarantee is the shared lock plus `--test-threads=1`, which+ // `make test-rust` passes and every CI job reaches through `make test-ci`.+ // A bare `cargo test` without it can flake here, which is a property of+ // every env-mutating test in this crate rather than of this one.+ //+ // Unlike the `%APPDATA%` lookup this replaced, the override is honoured on+ // every platform, so this runs in `rust-check.yml` (ubuntu-only) as well as+ // on `test-on-windows-pr` rather than only the latter.+ #[test]+ fn the_override_outranks_the_os_default() {+ let _guard = crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());++ let previous = std::env::var_os(DATA_ROOT_ENV);++ std::env::set_var(DATA_ROOT_ENV, ABSOLUTE);+ assert_eq!(data_dir(), Some(PathBuf::from(ABSOLUTE)));++ // Malformed values fall back rather than rooting the profile relative+ // to the working directory.+ std::env::set_var(DATA_ROOT_ENV, "");+ assert_eq!(data_dir(), dirs::data_dir());++ std::env::set_var(DATA_ROOT_ENV, "Roaming");+ assert_eq!(data_dir(), dirs::data_dir());++ // Unset -- the state every real install is in -- resolves exactly where+ // it did before this module existed.+ std::env::remove_var(DATA_ROOT_ENV);+ assert!(env_data_dir().is_none());+ assert_eq!(data_dir(), dirs::data_dir());++ match previous {+ Some(value) => std::env::set_var(DATA_ROOT_ENV, value),+ None => std::env::remove_var(DATA_ROOT_ENV),+ }+ }+}diff --git a/src-tauri/src/core/mcp/lockfile.rs b/src-tauri/src/core/mcp/lockfile.rsindex 6291970d8..b914be082 100644--- a/src-tauri/src/core/mcp/lockfile.rs+++ b/src-tauri/src/core/mcp/lockfile.rs@@ -1,7 +1,7 @@use serde::{Deserialize, Serialize};use std::fs;use std::path::PathBuf;-use tauri::{AppHandle, Manager, Runtime};+use tauri::{AppHandle, Runtime};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct McpLockFile {@@ -15,10 +15,8 @@ pub struct McpLockFile {}fn get_lock_file_path<R: Runtime>(app: &AppHandle<R>, port: u16) -> PathBuf {- let app_data_dir = app- .path()- .app_data_dir()- .expect("Failed to get app data dir");+ let app_data_dir =+ crate::core::app::paths::app_data_dir_for(app).expect("Failed to get app data dir");app_data_dir.join(format!("mcp_lock_{}.json", port))}@@ -148,10 +146,8 @@ pub async fn check_and_cleanup_stale_lock<R: Runtime>(}pub async fn cleanup_all_stale_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {- let app_data_dir = app- .path()- .app_data_dir()- .expect("Failed to get app data dir");+ let app_data_dir =+ crate::core::app::paths::app_data_dir_for(app).expect("Failed to get app data dir");let pattern = app_data_dir.join("mcp_lock_*.json");let pattern_str = pattern.to_string_lossy();@@ -181,10 +177,8 @@ pub async fn cleanup_all_stale_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(}pub fn cleanup_own_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {- let app_data_dir = app- .path()- .app_data_dir()- .expect("Failed to get app data dir");+ let app_data_dir =+ crate::core::app::paths::app_data_dir_for(app).expect("Failed to get app data dir");let pattern = app_data_dir.join("mcp_lock_*.json");let pattern_str = pattern.to_string_lossy();diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 0a4482cd1..70ac972f6 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -84,7 +84,7 @@ fn clear_webview_profile<R: Runtime>(app_handle: &tauri::AppHandle<R>,data_folder: &std::path::Path,) {- let webview_dir = match app_handle.path().app_data_dir() {+ let webview_dir = match crate::core::app::paths::app_data_dir_for(app_handle) {Ok(dir) => dir,Err(e) => {log::warn!("Cannot resolve webview profile dir: {e}");diff --git a/src-tauri/src/core/threads/db.rs b/src-tauri/src/core/threads/db.rsindex aaeb488af..79e50c1d4 100644--- a/src-tauri/src/core/threads/db.rs+++ b/src-tauri/src/core/threads/db.rs@@ -26,9 +26,7 @@ static DB_POOL: OnceLock<Mutex<Option<SqlitePool>>> = OnceLock::new();/// Initialize database with connection pool and run migrationspub async fn init_database<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {// Get app data directory- let app_data_dir = app- .path()- .app_data_dir()+ let app_data_dir = crate::core::app::paths::app_data_dir_for(app).map_err(|e| format!("Failed to get app data dir: {}", e))?;// Ensure directory existsdiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 3672745e2..6e8494fe7 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -280,7 +280,9 @@ pub fn run() {.plugin(tauri_plugin_store::Builder::new().build()).plugin(tauri_plugin_shell::init()).plugin(tauri_plugin_llamacpp::init())- .plugin(tauri_plugin_vector_db::init())+ .plugin(tauri_plugin_vector_db::init(+ crate::core::app::paths::vector_db_dir(),+ )).plugin(tauri_plugin_rag::init()).plugin(tauri_plugin_websearch::init()).plugin(tauri_plugin_agent_tools::init());@@ -386,7 +388,18 @@ pub fn run() {let _ = setup::setup_tray(app.handle());}- #[cfg(all(feature = "deep-link", any(windows, target_os = "linux")))]+ // Not in e2e builds: on Windows `register_all` writes HKCU+ // Software\Classes\jan\shell\open\command and points it at the+ // running exe, so every run would repoint the developer's real+ // `jan://` handler at target/debug/Jan-Desktop.exe. The registry is+ // outside everything the harness's env overrides can reach. (On+ // Linux it writes into `data_dir()/applications`, which XDG_DATA_HOME+ // does redirect -- but no spec opens a deep link, so skip both.)+ #[cfg(all(+ feature = "deep-link",+ not(feature = "e2e"),+ any(windows, target_os = "linux")+ ))]{use tauri_plugin_deep_link::DeepLinkExt;app.deep_link().register_all()?;