From f91b87d790f9d78dbe522cd700ca723f69405a69 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:53:08 +0800 Subject: [PATCH] feat: move configuration, user data and logs with environment variables (#3035) OPENIDEA_CONFIG_DIR, OPENIDEA_DATA_DIR and OPENIDEA_LOG_DIR take an absolute path, like OPENIDEA_LOCAL_DATA_DIR, and the IDE uses / under it. Every place that resolved these directories now goes through ide_host::data_dirs (app state, invalidate caches, window zoom and window state, the MCP stdio bridge, logging, the openidea-plugin CLI), and the frontend takes the user data directory from app_info instead of Tauri's appDataDir. A relative path for the configuration or user data shows an error and exits. Closes #2814 --- .../ide-host/src/bin/openidea-plugin/main.rs | 6 +- crates/ide-host/src/data_dirs.rs | 70 +++++++++++++++++-- docs/en/reference/data-directories.mdx | 16 ++++- docs/zh/reference/data-directories.mdx | 16 ++++- src-tauri/src/commands/app.rs | 3 + src-tauri/src/commands/caches.rs | 4 +- src-tauri/src/lib.rs | 16 ++++- src-tauri/src/linux_window_state.rs | 6 +- src-tauri/src/logging.rs | 8 +-- src-tauri/src/state.rs | 7 +- src-tauri/src/window_zoom.rs | 2 +- src/bindings.ts | 2 + src/features/http-client/generatedRequests.ts | 6 +- src/features/http-client/index.ts | 6 +- .../http-client/spring/generate.test.ts | 7 +- src/features/scratch/scratches.ts | 8 +-- src/platform/platformInfo.test.ts | 7 +- src/platform/platformInfo.ts | 8 +++ 18 files changed, 154 insertions(+), 44 deletions(-) diff --git a/crates/ide-host/src/bin/openidea-plugin/main.rs b/crates/ide-host/src/bin/openidea-plugin/main.rs index 64d335117..e7b47418d 100644 --- a/crates/ide-host/src/bin/openidea-plugin/main.rs +++ b/crates/ide-host/src/bin/openidea-plugin/main.rs @@ -426,9 +426,9 @@ fn plugins_dir() -> Result { if let Some(dir) = std::env::var_os("OPENIDEA_PLUGINS_DIR") { return Ok(PathBuf::from(dir)); } - dirs::data_dir() - .map(|d| d.join("ai.l0ng.openidea").join("plugins")) - .ok_or_else(|| "cannot find the app data directory; set OPENIDEA_PLUGINS_DIR".into()) + ide_host::data_dirs::data_dir("ai.l0ng.openidea") + .map(|d| d.join("plugins")) + .map_err(|error| format!("{error}; set OPENIDEA_PLUGINS_DIR")) } #[derive(Default, serde::Serialize, serde::Deserialize)] diff --git a/crates/ide-host/src/data_dirs.rs b/crates/ide-host/src/data_dirs.rs index 66b782d83..6c9b9e7e7 100644 --- a/crates/ide-host/src/data_dirs.rs +++ b/crates/ide-host/src/data_dirs.rs @@ -5,9 +5,52 @@ use std::fs; use std::io; use std::path::{Path, PathBuf}; -/// Moves the rebuildable local data (tools, language servers, indexes, caches); -/// configuration and roaming data keep following the OS. +/// Moves the rebuildable local data (tools, language servers, indexes, caches). pub const LOCAL_DATA_ENV: &str = "OPENIDEA_LOCAL_DATA_DIR"; +/// Moves the configuration (settings, recent projects, language definitions, window state). +pub const CONFIG_ENV: &str = "OPENIDEA_CONFIG_DIR"; +/// Moves the user data (plugins, scratches, Local History, trusted projects). +pub const DATA_ENV: &str = "OPENIDEA_DATA_DIR"; +/// Moves the logs. +pub const LOG_ENV: &str = "OPENIDEA_LOG_DIR"; + +/// `$OPENIDEA_CONFIG_DIR/` when set, else the OS configuration directory +/// (Tauri's `app_config_dir`). Like the local data, the identifier keeps release and +/// per-worktree debug builds apart under one root; a relative path is an error. +pub fn config_dir(identifier: &str) -> Result { + resolve_env(CONFIG_ENV, std::env::var_os(CONFIG_ENV), dirs::config_dir(), identifier) +} + +/// `$OPENIDEA_DATA_DIR/` when set, else the OS data directory (Tauri's `app_data_dir`). +pub fn data_dir(identifier: &str) -> Result { + resolve_env(DATA_ENV, std::env::var_os(DATA_ENV), dirs::data_dir(), identifier) +} + +/// `$OPENIDEA_LOG_DIR/` when set, else `~/Library/Logs/` on macOS and +/// `//logs` elsewhere (Tauri's `app_log_dir`). +pub fn log_dir(identifier: &str) -> Result { + let os = if cfg!(target_os = "macos") { + dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier)) + } else { + dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs")) + }; + match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) { + Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier), + None => os.ok_or_else(|| "cannot find the log directory".into()), + } +} + +/// The directory under `$` when set (absolute, not created here), else under the OS directory. +fn resolve_env(env: &str, var: Option, os: Option, identifier: &str) -> Result { + let Some(root) = var.filter(|v| !v.is_empty()).map(PathBuf::from) else { + return os.map(|dir| dir.join(identifier)).ok_or_else(|| format!("cannot find the directory {env} replaces")); + }; + // The working directory depends on how the IDE was launched. + if !root.is_absolute() { + return Err(format!("{env} must be an absolute path: {}", root.display())); + } + Ok(root.join(identifier)) +} /// A custom local-data root chosen in Settings › System Settings › Caches, /// stored in the configuration directory. The environment variable still wins. @@ -51,11 +94,11 @@ fn startup_resolve( /// The file holding the custom local-data root, if the platform exposes its /// configuration directory. Both startup and Settings use this one path. pub fn override_path(identifier: &str) -> Option { - dirs::config_dir().map(|dir| dir.join(identifier).join(OVERRIDE_FILE)) + config_dir(identifier).ok().map(|dir| dir.join(OVERRIDE_FILE)) } fn migration_path(identifier: &str) -> Option { - dirs::config_dir().map(|dir| dir.join(identifier).join(MIGRATION_FILE)) + config_dir(identifier).ok().map(|dir| dir.join(MIGRATION_FILE)) } /// The custom root stored by Settings, if any (validated when it is used). @@ -493,6 +536,25 @@ fn relative_wrapper(text: &str, source: &Path) -> String { mod tests { use super::*; + #[test] + fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() { + let os = Some(PathBuf::from("/os")); + for env in [CONFIG_ENV, DATA_ENV, LOG_ENV] { + for var in [None, Some(OsString::new())] { + assert_eq!(resolve_env(env, var, os.clone(), "id").unwrap(), PathBuf::from("/os/id")); + } + let root = std::env::temp_dir().join("openidea-moved"); + assert_eq!(resolve_env(env, Some(root.clone().into()), os.clone(), "id").unwrap(), root.join("id")); + // Release and per-worktree debug builds stay apart under one root. + assert_ne!( + resolve_env(env, Some(root.clone().into()), None, "dev-a").unwrap(), + resolve_env(env, Some(root.clone().into()), None, "dev-b").unwrap() + ); + let error = resolve_env(env, Some("relative/dir".into()), os.clone(), "id").unwrap_err(); + assert!(error.contains(env) && error.contains("absolute"), "{error}"); + } + } + #[test] fn local_dir_follows_the_os_unless_the_variable_is_set() { let os = Some(PathBuf::from("/os-local")); diff --git a/docs/en/reference/data-directories.mdx b/docs/en/reference/data-directories.mdx index 7e8022bc1..d0cc290f2 100644 --- a/docs/en/reference/data-directories.mdx +++ b/docs/en/reference/data-directories.mdx @@ -65,9 +65,23 @@ setx OPENIDEA_LOCAL_DATA_DIR "E:\OpenIDEA" On macOS and Linux, set it in the environment OpenIDEA starts from. - If the path is relative or can't be written to, OpenIDEA shows an error and exits instead of falling back to the default location. -- Configuration, user data and logs stay where they are. Logs are still written when the variable is wrong, so you can find out why. +- Configuration, user data and logs stay where they are unless you move them too (see below). Logs are still written when the variable is wrong, so you can find out why. - Existing data is not moved. Either let OpenIDEA download and rebuild it, or quit OpenIDEA and move only `tools/`, `language-server-runtimes/`, `index/`, `cache/`, `lsp/`, `notebook-runtime/`, `server/`, `logs/`, `agents/tools/`, `agents/registry.json` and the top-level `java-usages-*.jar` / `java-usages-*.tmp` files, keeping their relative paths. Leave everything else in place. +## Move configuration, user data or logs + +Each of the other directories has its own variable, set the same way as `OPENIDEA_LOCAL_DATA_DIR`: an absolute path, read when OpenIDEA starts. OpenIDEA then uses `/ai.l0ng.openidea` and creates it if missing. + +| Variable | Moves | +| --------------------- | ------------- | +| `OPENIDEA_CONFIG_DIR` | Configuration | +| `OPENIDEA_DATA_DIR` | User data | +| `OPENIDEA_LOG_DIR` | Logs | + +- Set only the ones you want to move; the rest keep their default locations. Pointing several variables at the same path is fine. +- If the configuration or user data path is relative or can't be used, OpenIDEA shows an error and exits instead of falling back to the default location. A wrong log path only turns off the log file. +- Existing files are not moved. To keep your settings, plugins and history, quit OpenIDEA and copy the old folder's contents to the new location first. + ## Logs OpenIDEA writes one log file per day, `openidea..log`, and keeps the last 7. Panics are written to the current log too. diff --git a/docs/zh/reference/data-directories.mdx b/docs/zh/reference/data-directories.mdx index 43628f298..ccc8129ec 100644 --- a/docs/zh/reference/data-directories.mdx +++ b/docs/zh/reference/data-directories.mdx @@ -65,9 +65,23 @@ setx OPENIDEA_LOCAL_DATA_DIR "E:\OpenIDEA" 在 macOS 和 Linux 上,需要在启动 OpenIDEA 的环境中设置这个变量。 - 如果路径是相对路径或不可写,OpenIDEA 会显示错误并退出,而不会退回默认位置。 -- 配置、用户数据和日志的位置不变。即使变量设置有误,日志仍会写入,方便排查原因。 +- 配置、用户数据和日志的位置不变,除非也移动它们(见下文)。即使变量设置有误,日志仍会写入,方便排查原因。 - 已有数据不会自动迁移。可以让 OpenIDEA 重新下载和重建;也可以先退出 OpenIDEA,只移动 `tools/`、`language-server-runtimes/`、`index/`、`cache/`、`lsp/`、`notebook-runtime/`、`server/`、`logs/`、`agents/tools/`、`agents/registry.json` 以及顶层的 `java-usages-*.jar` / `java-usages-*.tmp` 文件,并保持相对路径不变。其他内容请留在原处。 +## 移动配置、用户数据或日志 + +其他几个目录各有一个变量,设置方法和 `OPENIDEA_LOCAL_DATA_DIR` 相同:设为绝对路径,OpenIDEA 启动时读取。IDE 随后会使用 `<路径>/ai.l0ng.openidea`,不存在时自动创建。 + +| 变量 | 移动的目录 | +| --------------------- | ---------- | +| `OPENIDEA_CONFIG_DIR` | 配置 | +| `OPENIDEA_DATA_DIR` | 用户数据 | +| `OPENIDEA_LOG_DIR` | 日志 | + +- 只设置想移动的那几个,其余仍在默认位置。几个变量指向同一路径也可以。 +- 如果配置或用户数据的路径是相对路径或不可用,OpenIDEA 会显示错误并退出,而不会退回默认位置;日志路径有误只会不写日志文件。 +- 已有文件不会自动迁移。想保留设置、插件和历史记录,先退出 OpenIDEA,把原文件夹里的内容复制到新位置。 + ## 日志 OpenIDEA 每天写一个日志文件 `openidea.<日期>.log`,保留最近 7 个。程序崩溃(panic)的信息也会写入当前日志。 diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs index 4fd3a506f..d315c96c2 100644 --- a/src-tauri/src/commands/app.rs +++ b/src-tauri/src/commands/app.rs @@ -16,6 +16,8 @@ pub struct AppInfo { pub platform: String, pub windows_build_number: Option, pub config_dir: ide_core::IpcPath, + /// User data (plugins, scratches, Local History); follows `OPENIDEA_DATA_DIR`. + pub data_dir: ide_core::IpcPath, /// Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges. pub wayland: bool, } @@ -31,6 +33,7 @@ pub fn app_info(state: State<'_, AppState>) -> AppInfo { platform: std::env::consts::OS.into(), windows_build_number: ide_core::platform::windows_build_number(), config_dir: state.config_dir.clone().into(), + data_dir: state.data_dir.clone().into(), #[cfg(target_os = "linux")] wayland: crate::linux_window_state::is_wayland(), #[cfg(not(target_os = "linux"))] diff --git a/src-tauri/src/commands/caches.rs b/src-tauri/src/commands/caches.rs index 241f8fb4f..d6b61711a 100644 --- a/src-tauri/src/commands/caches.rs +++ b/src-tauri/src/commands/caches.rs @@ -7,13 +7,13 @@ use ide_host::data_dirs; use ide_workspace::caches::{self, InvalidateCachesOptions}; use serde::Serialize; use std::path::PathBuf; -use tauri::{AppHandle, Manager, State}; +use tauri::{AppHandle, State}; /// Schedules the invalidation for the next start (`None` cancels a pending one). #[tauri::command] #[specta::specta] pub fn caches_schedule_invalidation(app: AppHandle, options: Option) -> IdeResult<()> { - let data_dir = app.path().app_data_dir().map_err(|e| ide_core::IdeError::internal(e.to_string()))?; + let data_dir = ide_host::data_dirs::data_dir(&app.config().identifier).map_err(ide_core::IdeError::internal)?; match options { Some(o) => caches::schedule(&data_dir, &o), None => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 53c5e5abe..d54071b92 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -80,7 +80,7 @@ pub fn run() { #[cfg(debug_assertions)] let context = dev::configure(context); if let Some(project) = ide_mcp::stdio_request(&std::env::args().collect::>()) { - let app_data = dirs::data_dir().unwrap_or_default().join(&context.config().identifier); + let app_data = ide_host::data_dirs::data_dir(&context.config().identifier).unwrap_or_default(); std::process::exit(ide_mcp::stdio::run(&ide_mcp::discovery_path(&app_data), project)); } // The `openidea` command: answer and exit, no UI. @@ -129,6 +129,13 @@ pub fn run() { .with_state_flags(window_state_flags()) // One remembered geometry per kind of auxiliary window (all projects' settings windows share one). .map_label(windows::state_key); + // The plugin stores its file in the OS configuration directory; an absolute name follows + // `OPENIDEA_CONFIG_DIR` instead. + #[cfg(not(target_os = "linux"))] + let window_state = match ide_host::data_dirs::config_dir(&context.config().identifier) { + Ok(dir) => window_state.with_filename(dir.join(tauri_plugin_window_state::DEFAULT_FILENAME).to_string_lossy()), + Err(_) => window_state, + }; #[cfg(target_os = "macos")] let window_state = window_state.with_filter(windows::keeps_window_state); #[cfg(not(target_os = "linux"))] @@ -187,6 +194,13 @@ pub fn run() { }) .setup(move |app| { builder.mount_events(app); + // An unusable directory variable stops the start with a message, never a silent fallback. + let identifier = app.config().identifier.clone(); + let local_data_dir = local_data_dir.and_then(|dir| { + ide_host::data_dirs::config_dir(&identifier)?; + ide_host::data_dirs::data_dir(&identifier)?; + Ok(dir) + }); let local_data_dir = match local_data_dir { Ok(dir) => dir, Err(error) => { diff --git a/src-tauri/src/linux_window_state.rs b/src-tauri/src/linux_window_state.rs index 22ffaa901..b8434c88a 100644 --- a/src-tauri/src/linux_window_state.rs +++ b/src-tauri/src/linux_window_state.rs @@ -419,7 +419,7 @@ mod runtime { fn persist(app: &AppHandle) { let write = || -> Result<(), Box> { - let dir = app.path().app_config_dir()?; + let dir = ide_host::data_dirs::config_dir(&app.config().identifier)?; std::fs::create_dir_all(&dir)?; let cache = app.state::>(); let data = serde_json::to_vec_pretty(&cache.lock().saved)?; @@ -439,9 +439,7 @@ mod runtime { // Plugins are set up on the main thread once GTK is initialised, before any window exists. use gtk::gdk::prelude::DisplayExtManual; let _ = WAYLAND.set(gtk::gdk::Display::default().is_some_and(|d| d.backend().is_wayland())); - let saved = app - .path() - .app_config_dir() + let saved = ide_host::data_dirs::config_dir(&app.config().identifier) .ok() .and_then(|dir| std::fs::read(dir.join(FILE)).ok()) .and_then(|data| serde_json::from_slice(&data).ok()) diff --git a/src-tauri/src/logging.rs b/src-tauri/src/logging.rs index 635812fd6..c130e012d 100644 --- a/src-tauri/src/logging.rs +++ b/src-tauri/src/logging.rs @@ -1,6 +1,6 @@ //! Logging: stdout (as before) plus a daily-rotated file in the app log dir //! (`~/Library/Logs/` on macOS, `//logs` -//! elsewhere — the same place as Tauri's `app_log_dir`). +//! elsewhere — the same place as Tauri's `app_log_dir` — or under `OPENIDEA_LOG_DIR`). use std::fmt::Write as _; use std::io::Write as _; @@ -20,11 +20,7 @@ static LOG_DIR: OnceLock = OnceLock::new(); static GUARD: OnceLock = OnceLock::new(); pub fn log_dir_for(identifier: &str) -> Option { - if cfg!(target_os = "macos") { - dirs::home_dir().map(|h| h.join("Library/Logs").join(identifier)) - } else { - dirs::data_local_dir().map(|d| d.join(identifier).join("logs")) - } + ide_host::data_dirs::log_dir(identifier).map_err(|error| eprintln!("{error}")).ok() } fn filter() -> EnvFilter { diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index e2bab4ff0..cbe028106 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -5,7 +5,7 @@ use ide_workspace::RecentProjects; use std::path::Path; use std::sync::{Arc, OnceLock}; use std::time::Duration; -use tauri::{AppHandle, Manager}; +use tauri::AppHandle; pub use ide_host::{Host, Project}; @@ -63,8 +63,9 @@ impl AppState { syntax.get_or_init(|| Arc::new(Syntax::new())); })?; } - let config_dir = app.path().app_config_dir()?; - let data_dir = app.path().app_data_dir()?; + // `OPENIDEA_CONFIG_DIR` / `OPENIDEA_DATA_DIR` move these; an unusable value fails the start. + let config_dir = ide_host::data_dirs::config_dir(&app.config().identifier)?; + let data_dir = ide_host::data_dirs::data_dir(&app.config().identifier)?; std::fs::create_dir_all(&config_dir)?; std::fs::create_dir_all(&data_dir)?; if let Err(error) = std::fs::create_dir_all(&local_data_dir) { diff --git a/src-tauri/src/window_zoom.rs b/src-tauri/src/window_zoom.rs index 316125518..99883ea96 100644 --- a/src-tauri/src/window_zoom.rs +++ b/src-tauri/src/window_zoom.rs @@ -96,7 +96,7 @@ fn work_area_of(window: &WebviewWindow, monitor: &Monitor) -> IdeResult { } fn frames_path(window: &WebviewWindow) -> Option { - window.app_handle().path().app_data_dir().ok().map(|dir| dir.join("window-zoom.json")) + ide_host::data_dirs::data_dir(&window.app_handle().config().identifier).ok().map(|dir| dir.join("window-zoom.json")) } fn load_frames(path: &Path) -> HashMap { diff --git a/src/bindings.ts b/src/bindings.ts index 274300016..d79a6f703 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2276,6 +2276,8 @@ export type AppInfo = { platform: string, windowsBuildNumber: number | null, configDir: IpcPath, + /** User data (plugins, scratches, Local History); follows `OPENIDEA_DATA_DIR`. */ + dataDir: IpcPath, /** Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges. */ wayland: boolean, }; diff --git a/src/features/http-client/generatedRequests.ts b/src/features/http-client/generatedRequests.ts index 67998f9f1..7d0ce495a 100644 --- a/src/features/http-client/generatedRequests.ts +++ b/src/features/http-client/generatedRequests.ts @@ -2,16 +2,14 @@ import { EditorView } from "@codemirror/view"; import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api"; import { tx } from "@/platform/i18n"; import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc"; -import { ipcPath } from "@/platform/paths"; +import { appDataDir } from "@/platform/platformInfo"; import { editorService } from "@/workbench/contributions"; import { appendRequests } from "./spring/request"; export const GENERATED_REQUESTS = "generated-requests.http"; async function scratchFile(): Promise<{ path: string; created: boolean }> { - const { appDataDir } = await import("@tauri-apps/api/path"); - // `appDataDir()` is native (`C:\…`): the editor is found by its `/` path. - const dir = `${ipcPath(await appDataDir()).replace(/\/+$/, "")}/scratches`; + const dir = `${await appDataDir()}/scratches`; const ignoreExisting = (e: unknown) => { if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e; }; diff --git a/src/features/http-client/index.ts b/src/features/http-client/index.ts index 85d4fb932..1586bf165 100644 --- a/src/features/http-client/index.ts +++ b/src/features/http-client/index.ts @@ -8,7 +8,7 @@ import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api"; import { executeAction, getAction, registerActions } from "@/platform/actions"; import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc"; -import { ipcPath } from "@/platform/paths"; +import { appDataDir } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { editorService, @@ -106,9 +106,7 @@ function directoryArg(arg: unknown): string | null { /** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */ async function newRequest(directory?: string) { try { - const { appDataDir } = await import("@tauri-apps/api/path"); - // `appDataDir()` is native (`C:\…`): the UI holds paths `/`-separated. - const dir = directory ?? `${ipcPath(await appDataDir()).replace(/\/+$/, "")}/scratches`; + const dir = directory ?? `${await appDataDir()}/scratches`; try { await call(commands.fsCreateDir(dir)); } catch (e) { diff --git a/src/features/http-client/spring/generate.test.ts b/src/features/http-client/spring/generate.test.ts index 111f72553..14c9add7a 100644 --- a/src/features/http-client/spring/generate.test.ts +++ b/src/features/http-client/spring/generate.test.ts @@ -4,9 +4,10 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co import { springControllers } from "./endpoints"; import { generateRequests } from "./editor"; -// `appDataDir()` is a native path: `\`-separated on Windows. -vi.mock("@tauri-apps/api/path", () => ({ - appDataDir: async () => String.raw`C:\Users\me\AppData\Roaming\ai.l0ng.openidea`, +// The backend reports the user data directory `/`-separated on every OS. +vi.mock("@/platform/platformInfo", async (importOriginal) => ({ + ...(await importOriginal()), + appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea", })); // No backend here: the file commands answer like a project without Spring diff --git a/src/features/scratch/scratches.ts b/src/features/scratch/scratches.ts index ef552c487..a08103f01 100644 --- a/src/features/scratch/scratches.ts +++ b/src/features/scratch/scratches.ts @@ -4,7 +4,7 @@ * `scratch[_n].` name and opens it as a normal document. */ import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc"; -import { ipcPath } from "@/platform/paths"; +import { appDataDir } from "@/platform/platformInfo"; import { editorService, notifications } from "@/workbench/contributions"; import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model"; @@ -19,11 +19,7 @@ export interface ScratchBackend { } export const tauriScratchBackend: ScratchBackend = { - // `appDataDir()` is native (`C:\…`); the scratch paths are used as UI paths. - dataDir: async () => { - const { appDataDir } = await import("@tauri-apps/api/path"); - return ipcPath(await appDataDir()); - }, + dataDir: appDataDir, listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name), createDir: async (dir) => void (await call(commands.fsCreateDir(dir))), createFile: async (path, text) => diff --git a/src/platform/platformInfo.test.ts b/src/platform/platformInfo.test.ts index 16706051d..dd7af7811 100644 --- a/src/platform/platformInfo.test.ts +++ b/src/platform/platformInfo.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, it, vi } from "vitest"; -import { loadPlatformInfo, usePlatform } from "./platformInfo"; +import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo"; const appInfo = vi.hoisted(() => vi.fn()); vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } })); @@ -23,3 +23,8 @@ it("keeps platform defaults when the query fails", async () => { await loadPlatformInfo(); expect(usePlatform.getState()).toEqual(initialPlatform); }); + +it("takes the user data directory from the backend, which may have moved it", async () => { + appInfo.mockResolvedValue({ platform: "windows", dataDir: "E:/OpenIDEA/ai.l0ng.openidea/" }); + expect(await appDataDir()).toBe("E:/OpenIDEA/ai.l0ng.openidea"); +}); diff --git a/src/platform/platformInfo.ts b/src/platform/platformInfo.ts index 063c44162..a1ae1a11c 100644 --- a/src/platform/platformInfo.ts +++ b/src/platform/platformInfo.ts @@ -36,6 +36,14 @@ export const usePlatform = create(() => { }; }); +let dataDir: Promise | undefined; + +/** The user data directory (scratches, plugins, Local History), which `OPENIDEA_DATA_DIR` can move. */ +export function appDataDir(): Promise { + dataDir ??= commands.appInfo().then((info) => info.dataDir.replace(/\/+$/, "")); + return dataDir; +} + export async function loadPlatformInfo() { if (!isTauri()) return; try {