Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

33.3 KB
Raw Blame
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
    sync::{Arc, Mutex, OnceLock},
};

use dbx_core::storage::{
    AppAppearanceSettings, AppAppearanceSettingsPatch, DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState,
};
use tauri::{AppHandle, Manager, State, Window};

use super::connection::AppState;
use crate::{
    apply_debug_log_level, apply_desktop_settings, clear_startup_probe_after_frontend_ready,
    hide_main_window_for_close, refresh_native_menus, request_app_close, AppLocaleState, CloseBehaviorState,
};

const DEVELOPMENT_OPEN_TABS_STATE_KEY: &str = "development_open_tabs";
const DETACHED_TABS_STATE_KEY: &str = "detached_tabs";
static DETACHED_TABS_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
static APPROVED_DETACHED_CLOSES: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();

fn detached_tabs_lock() -> &'static tokio::sync::Mutex<()> {
    DETACHED_TABS_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

fn approved_detached_closes() -> &'static Mutex<HashSet<String>> {
    APPROVED_DETACHED_CLOSES.get_or_init(|| Mutex::new(HashSet::new()))
}

pub(crate) fn take_approved_detached_window_close(label: &str) -> bool {
    approved_detached_closes().lock().map(|mut labels| labels.remove(label)).unwrap_or(false)
}

async fn load_detached_tabs_map(state: &AppState) -> Result<serde_json::Map<String, serde_json::Value>, String> {
    Ok(state
        .storage
        .load_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY)
        .await?
        .and_then(|value| value.as_object().cloned())
        .unwrap_or_default())
}

fn open_tabs_state_key(debug_build: bool) -> &'static str {
    if debug_build {
        DEVELOPMENT_OPEN_TABS_STATE_KEY
    } else {
        "open_tabs"
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DriverStoreMigrationResult {
    pub driver_store_dir: Option<String>,
    pub plugin_store_dir: Option<String>,
    pub agent_store_dir: Option<String>,
    pub plugins_dir: String,
    pub agents_dir: String,
    pub migrated_plugins: bool,
    pub migrated_agents: bool,
}

#[tauri::command]
pub async fn load_desktop_settings(state: State<'_, Arc<AppState>>) -> Result<DesktopSettings, String> {
    state.storage.load_desktop_settings().await
}

#[tauri::command]
pub async fn save_desktop_settings(
    app: AppHandle,
    state: State<'_, Arc<AppState>>,
    settings: DesktopSettings,
) -> Result<(), String> {
    state.storage.save_desktop_settings(&settings).await?;
    state.apply_duckdb_worker_process_isolation(settings.duckdb_worker_process_isolation).await;
    apply_debug_log_level(settings.debug_logging_enabled);
    if let Err(err) = apply_desktop_settings(&app, &settings) {
        eprintln!("Failed to apply desktop settings: {err}");
    }
    Ok(())
}

#[tauri::command]
pub async fn load_max_agent_turns(state: State<'_, Arc<AppState>>) -> Result<u32, String> {
    state.storage.load_max_agent_turns().await
}

#[tauri::command]
pub async fn load_app_appearance_settings(state: State<'_, Arc<AppState>>) -> Result<AppAppearanceSettings, String> {
    state.storage.load_app_appearance_settings().await
}

#[tauri::command]
pub async fn update_app_appearance_settings(
    state: State<'_, Arc<AppState>>,
    patch: AppAppearanceSettingsPatch,
) -> Result<(), String> {
    state.storage.update_app_appearance_settings(&patch).await
}

#[tauri::command]
pub async fn set_app_locale(
    app: AppHandle,
    state: State<'_, Arc<AppState>>,
    locale_state: State<'_, AppLocaleState>,
    locale: String,
) -> Result<(), String> {
    locale_state.set(locale);
    let persistence = state
        .storage
        .update_app_appearance_settings(&AppAppearanceSettingsPatch {
            locale: Some(locale_state.get()),
            ..Default::default()
        })
        .await;
    let refresh = refresh_native_menus(&app).map_err(|err| format!("failed to refresh native menus: {err}"));
    persistence?;
    refresh
}

#[tauri::command]
pub async fn save_max_agent_turns(state: State<'_, Arc<AppState>>, max_agent_turns: u32) -> Result<(), String> {
    state.storage.save_max_agent_turns(max_agent_turns).await
}

#[tauri::command]
pub async fn load_history_retention_limit(state: State<'_, Arc<AppState>>) -> Result<u32, String> {
    state.storage.load_history_retention_limit().await
}

#[tauri::command]
pub async fn save_history_retention_limit(state: State<'_, Arc<AppState>>, limit: u32) -> Result<(), String> {
    state.storage.save_history_retention_limit(limit).await
}

#[tauri::command]
pub async fn load_mcp_history_retention_limit(state: State<'_, Arc<AppState>>) -> Result<u32, String> {
    state.storage.load_mcp_history_retention_limit().await
}

#[tauri::command]
pub async fn save_mcp_history_retention_limit(state: State<'_, Arc<AppState>>, limit: u32) -> Result<(), String> {
    state.storage.save_mcp_history_retention_limit(limit).await
}

#[tauri::command]
pub async fn load_max_retries(state: State<'_, Arc<AppState>>) -> Result<u32, String> {
    state.storage.load_max_retries().await
}

#[tauri::command]
pub async fn save_max_retries(state: State<'_, Arc<AppState>>, max_retries: u32) -> Result<(), String> {
    state.storage.save_max_retries(max_retries).await
}

#[tauri::command]
pub async fn complete_app_close(app: AppHandle, window: Window, action: String) -> Result<(), String> {
    match action.as_str() {
        "quit" => {
            if let Some(state) = app.try_state::<CloseBehaviorState>() {
                state.allow_next_exit();
            }
            #[cfg(target_os = "macos")]
            {
                // Take the whole app off-screen first so WKWebView teardown during
                // process exit cannot flash the window red on macOS 12. `AppHandle::hide`
                // is macOS-only, so this block is compiled per-platform.
                // Hiding can blank the frame, and the window-state plugin saves
                // at exit; keep the geometry `request_app_close` captured while
                // the window was still visible (issue #13168).
                crate::window_state_guard::remember_main_window_geometry(&app);
                let _ = window.hide();
                let _ = app.hide();
                tokio::time::sleep(std::time::Duration::from_millis(crate::EXIT_HIDE_GRACE_MS)).await;
            }
            app.exit(0);
        }
        "hide" => {
            hide_main_window_for_close(&app, &window);
        }
        _ => return Err(format!("unsupported close action: {action}")),
    }
    Ok(())
}

#[tauri::command]
pub fn mark_frontend_ready(app: AppHandle) -> Result<(), String> {
    let state =
        app.try_state::<CloseBehaviorState>().ok_or_else(|| "close behavior state is unavailable".to_string())?;
    state.set_frontend_ready(true);
    let main_window_visible = app.get_webview_window("main").is_some_and(|window| window.is_visible().unwrap_or(false));
    clear_startup_probe_after_frontend_ready(main_window_visible);
    Ok(())
}

#[tauri::command]
pub async fn request_app_close_from_window_controls(app: AppHandle) -> Result<(), String> {
    request_app_close(&app, "settings");
    Ok(())
}

#[tauri::command]
pub async fn load_pinned_tree_node_ids(state: State<'_, Arc<AppState>>) -> Result<Vec<String>, String> {
    state.storage.load_pinned_tree_node_ids().await
}

#[tauri::command]
pub async fn save_pinned_tree_node_ids(state: State<'_, Arc<AppState>>, ids: Vec<String>) -> Result<(), String> {
    state.storage.save_pinned_tree_node_ids(&ids).await
}

#[tauri::command]
pub async fn load_mcp_global_policy(state: State<'_, Arc<AppState>>) -> Result<McpGlobalPolicyState, String> {
    state.storage.load_mcp_global_policy().await
}

#[tauri::command]
pub fn load_mcp_tool_catalog() -> dbx_core::mcp_catalog::McpToolCatalog {
    dbx_mcp::DbxMcpServer::tool_catalog()
}

/// Plugin cards of the MCP capability tab (probes plugin sidecars).
#[tauri::command]
pub async fn list_plugin_mcp_views(
    state: State<'_, Arc<AppState>>,
) -> Result<Vec<dbx_core::plugin_mcp::PluginMcpView>, String> {
    dbx_core::plugin_mcp::list_plugin_views(state.inner()).await
}

#[tauri::command]
pub async fn load_plugin_mcp_view(
    state: State<'_, Arc<AppState>>,
    plugin_id: String,
) -> Result<dbx_core::plugin_mcp::PluginMcpView, String> {
    dbx_core::plugin_mcp::plugin_view_for(state.inner(), &plugin_id).await
}

#[tauri::command]
pub async fn list_mcp_plugin_scopes(
    state: State<'_, Arc<AppState>>,
    plugin_id: String,
    connection_id: String,
) -> Result<serde_json::Value, String> {
    let manifest = state
        .plugins
        .list_installed()?
        .into_iter()
        .find(|plugin| plugin.manifest.id == plugin_id)
        .ok_or_else(|| format!("Plugin `{plugin_id}` is not installed."))?
        .manifest;
    let method = manifest
        .mcp_contribution()
        .and_then(|mcp| mcp.scope.as_ref())
        .and_then(|scope| scope.list_method.as_deref())
        .ok_or_else(|| "This plugin does not declare a scope list method.".to_string())?;
    let policy = state.storage.load_enforced_mcp_policy().await?.policy();
    let group_paths = match state.storage.load_sidebar_layout().await? {
        Some(layout) => dbx_core::mcp_policy::connection_group_paths(&layout)
            .map_err(|error| format!("MCP_POLICY_UNAVAILABLE: {error}"))?,
        None => std::collections::HashMap::new(),
    };
    let connection = state
        .storage
        .load_connections()
        .await?
        .into_iter()
        .find(|connection| connection.id == connection_id)
        .ok_or_else(|| "CONNECTION_NOT_FOUND: connection is not available.".to_string())?;
    if connection.plugin_id.as_deref() != Some(plugin_id.as_str()) {
        return Err("CONNECTION_OUT_OF_SCOPE: connection is not owned by this plugin.".to_string());
    }
    if !dbx_core::mcp_policy::policy_allows_connection(&policy, group_paths.get(&connection.id), &connection.id) {
        return Err("CONNECTION_OUT_OF_SCOPE: connection is not allowed by DBX MCP settings.".to_string());
    }
    let value = state
        .plugin_host
        .invoke::<serde_json::Value>(
            &plugin_id,
            method,
            serde_json::json!({ "connectionId": connection.id }),
            None,
            Some(std::time::Duration::from_secs(8)),
        )
        .await?;
    let values: Vec<String> = serde_json::from_value(
        value
            .get("values")
            .cloned()
            .ok_or_else(|| "Plugin scope list must return { values: string[] }.".to_string())?,
    )
    .map_err(|_| "Plugin scope list must return { values: string[] }.".to_string())?;
    Ok(serde_json::json!({ "values": values }))
}

#[tauri::command]
pub async fn save_plugin_mcp_grant(
    state: State<'_, Arc<AppState>>,
    plugin_id: String,
    grant: dbx_core::storage::PluginMcpGrant,
    approve_current: bool,
) -> Result<dbx_core::plugin_mcp::PluginMcpView, String> {
    dbx_core::plugin_mcp::save_plugin_grant(state.inner(), &plugin_id, grant, approve_current).await
}

#[tauri::command]
pub async fn load_mcp_access_policy(
    state: State<'_, Arc<AppState>>,
) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
    state.storage.load_mcp_access_policy().await
}

#[tauri::command]
pub async fn set_mcp_plugin_scope_rule(
    state: State<'_, Arc<AppState>>,
    connection_id: String,
    kind: String,
    value: Option<String>,
    rule: Option<dbx_core::mcp_access::McpAccessRule>,
    sub_scope: Option<dbx_core::mcp_access::McpSubScopeMode>,
) -> Result<dbx_core::mcp_access::McpAccessPolicy, String> {
    let access =
        dbx_core::plugin_mcp::set_scope_rule(&state, &connection_id, &kind, value.as_deref(), rule, sub_scope).await?;
    super::mcp_bridge::clear_mcp_sql_approvals();
    Ok(access)
}

#[tauri::command]
pub async fn reset_invalid_mcp_access_policy(state: State<'_, Arc<AppState>>) -> Result<(), String> {
    state.storage.reset_invalid_mcp_access_policy().await?;
    super::mcp_bridge::clear_mcp_sql_approvals();
    Ok(())
}

#[tauri::command]
pub async fn save_mcp_global_policy(state: State<'_, Arc<AppState>>, policy: McpGlobalPolicy) -> Result<(), String> {
    state.storage.save_mcp_global_policy(&policy).await?;
    super::mcp_bridge::clear_mcp_sql_approvals();
    Ok(())
}

#[tauri::command]
pub async fn load_editor_settings(state: State<'_, Arc<AppState>>) -> Result<Option<serde_json::Value>, String> {
    state.storage.load_editor_settings().await
}

#[tauri::command]
pub async fn save_editor_settings(state: State<'_, Arc<AppState>>, settings: serde_json::Value) -> Result<(), String> {
    state.storage.save_editor_settings(&settings).await
}

const GLOBAL_SEARCH_SETTINGS_FILE: &str = "global-search-settings.json";

#[tauri::command]
pub async fn load_global_search_settings(app: AppHandle) -> Result<Option<serde_json::Value>, String> {
    let default_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
    let data_dir = crate::data_dir::resolve_data_dir_with_mode(default_data_dir).data_dir;
    let path = data_dir.join(GLOBAL_SEARCH_SETTINGS_FILE);
    if !path.exists() {
        return Ok(None);
    }
    let bytes = std::fs::read(&path).map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
    serde_json::from_slice(&bytes).map(Some).map_err(|e| format!("Failed to parse {}: {e}", path.display()))
}

#[tauri::command]
pub async fn save_global_search_settings(app: AppHandle, settings: serde_json::Value) -> Result<(), String> {
    let default_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
    let data_dir = crate::data_dir::resolve_data_dir_with_mode(default_data_dir).data_dir;
    std::fs::create_dir_all(&data_dir).map_err(|e| format!("Failed to create {}: {e}", data_dir.display()))?;
    let path = data_dir.join(GLOBAL_SEARCH_SETTINGS_FILE);
    let bytes = serde_json::to_vec_pretty(&settings).map_err(|e| e.to_string())?;
    std::fs::write(&path, bytes).map_err(|e| format!("Failed to write {}: {e}", path.display()))
}

#[tauri::command]
pub async fn load_open_tabs_state(state: State<'_, Arc<AppState>>) -> Result<Option<serde_json::Value>, String> {
    state.storage.load_open_tabs_state_with_key(open_tabs_state_key(cfg!(debug_assertions))).await
}

#[tauri::command]
pub async fn save_open_tabs_state(state: State<'_, Arc<AppState>>, payload: serde_json::Value) -> Result<(), String> {
    state.storage.save_open_tabs_state_with_key(open_tabs_state_key(cfg!(debug_assertions)), &payload).await
}

#[tauri::command]
pub async fn save_detached_tab_handoff(
    state: State<'_, Arc<AppState>>,
    tab_id: String,
    handoff: serde_json::Value,
) -> Result<(), String> {
    let _guard = detached_tabs_lock().lock().await;
    let mut tabs = load_detached_tabs_map(state.inner()).await?;
    tabs.insert(tab_id, handoff);
    state.storage.save_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY, &serde_json::Value::Object(tabs)).await
}

#[tauri::command]
pub async fn load_detached_tab_handoff(
    state: State<'_, Arc<AppState>>,
    tab_id: String,
) -> Result<Option<serde_json::Value>, String> {
    let _guard = detached_tabs_lock().lock().await;
    Ok(load_detached_tabs_map(state.inner()).await?.remove(&tab_id))
}

#[tauri::command]
pub async fn list_detached_tab_handoffs(state: State<'_, Arc<AppState>>) -> Result<Vec<serde_json::Value>, String> {
    let _guard = detached_tabs_lock().lock().await;
    Ok(load_detached_tabs_map(state.inner()).await?.into_values().collect())
}

#[tauri::command]
pub async fn delete_detached_tab_handoff(state: State<'_, Arc<AppState>>, tab_id: String) -> Result<(), String> {
    let _guard = detached_tabs_lock().lock().await;
    let mut tabs = load_detached_tabs_map(state.inner()).await?;
    tabs.remove(&tab_id);
    state.storage.save_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY, &serde_json::Value::Object(tabs)).await
}

#[tauri::command]
pub fn approve_detached_window_close(window: Window) -> Result<(), String> {
    if !window.label().starts_with("detached-tab-") {
        return Err("current window is not a detached tab window".to_string());
    }
    approved_detached_closes()
        .lock()
        .map_err(|_| "detached window close state is unavailable".to_string())?
        .insert(window.label().to_string());
    Ok(())
}

#[tauri::command]
pub async fn load_saved_sql_editor_positions(
    state: State<'_, Arc<AppState>>,
) -> Result<Option<serde_json::Value>, String> {
    state.storage.load_saved_sql_editor_positions().await
}

#[tauri::command]
pub async fn save_saved_sql_editor_positions(
    state: State<'_, Arc<AppState>>,
    positions: serde_json::Value,
) -> Result<(), String> {
    state.storage.save_saved_sql_editor_positions(&positions).await
}

#[tauri::command]
pub async fn load_transfer_task_library(state: State<'_, Arc<AppState>>) -> Result<Option<serde_json::Value>, String> {
    state.storage.load_transfer_task_library().await
}

#[tauri::command]
pub async fn save_transfer_task_library(
    state: State<'_, Arc<AppState>>,
    library: serde_json::Value,
) -> Result<(), String> {
    state.storage.save_transfer_task_library(&library).await
}

#[tauri::command]
pub async fn load_native_debug_logs(app: AppHandle) -> Result<String, String> {
    let log_dir = app.path().app_log_dir().map_err(|e| e.to_string())?;
    tauri::async_runtime::spawn_blocking(move || load_native_debug_logs_from_dir(log_dir))
        .await
        .map_err(|err| err.to_string())?
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct DriverStorePathInfo {
    pub driver_store_dir: Option<String>,
    pub plugin_store_dir: Option<String>,
    pub agent_store_dir: Option<String>,
    pub plugins_dir: String,
    pub agents_dir: String,
}

#[tauri::command]
pub async fn get_driver_store_path(state: State<'_, Arc<AppState>>) -> Result<DriverStorePathInfo, String> {
    let settings = state.storage.load_desktop_settings().await.unwrap_or_default();
    Ok(DriverStorePathInfo {
        driver_store_dir: settings.driver_store_dir,
        plugin_store_dir: settings.plugin_store_dir,
        agent_store_dir: settings.agent_store_dir,
        plugins_dir: state.plugins.root_dir().to_string_lossy().to_string(),
        agents_dir: state.agent_manager.base_dir().to_string_lossy().to_string(),
    })
}

#[tauri::command]
pub async fn set_driver_store_dir(
    app: AppHandle,
    state: State<'_, Arc<AppState>>,
    new_dir: Option<String>,
) -> Result<DriverStoreMigrationResult, String> {
    let new_dir = normalize_store_dir(new_dir);
    let current_plugins_dir = state.plugins.root_dir().to_path_buf();
    let current_agents_dir = state.agent_manager.base_dir().clone();
    let (target_plugins_dir, target_agents_dir) = match new_dir.as_ref() {
        Some(dir) => {
            let driver_base = PathBuf::from(dir);
            (driver_base.join("plugins"), driver_base.join("agents"))
        }
        None => default_store_dirs(&app)?,
    };

    state.agent_manager.stop_daemons().await;
    let migrated_plugins = migrate_store_directory(&current_plugins_dir, &target_plugins_dir)?;
    let migrated_agents = migrate_store_directory(&current_agents_dir, &target_agents_dir)?;

    let mut settings = state.storage.load_desktop_settings().await.unwrap_or_default();
    settings.driver_store_dir = new_dir.clone();
    settings.plugin_store_dir = None;
    settings.agent_store_dir = None;
    state.storage.save_desktop_settings(&settings).await?;

    Ok(driver_store_migration_result(
        settings,
        &target_plugins_dir,
        &target_agents_dir,
        migrated_plugins,
        migrated_agents,
    ))
}

#[tauri::command]
pub async fn set_plugin_store_dir(
    app: AppHandle,
    state: State<'_, Arc<AppState>>,
    new_dir: Option<String>,
) -> Result<DriverStoreMigrationResult, String> {
    let new_dir = normalize_store_dir(new_dir);
    let current_plugins_dir = state.plugins.root_dir().to_path_buf();
    let current_agents_dir = state.agent_manager.base_dir().clone();
    let target_plugins_dir = match new_dir.as_ref() {
        Some(dir) => PathBuf::from(dir),
        None => default_plugin_store_dir(&app)?,
    };

    let migrated_plugins = migrate_store_directory(&current_plugins_dir, &target_plugins_dir)?;

    let mut settings = state.storage.load_desktop_settings().await.unwrap_or_default();
    convert_legacy_driver_store(&mut settings, &current_plugins_dir, &current_agents_dir);
    settings.plugin_store_dir = new_dir;
    state.storage.save_desktop_settings(&settings).await?;

    Ok(driver_store_migration_result(settings, &target_plugins_dir, &current_agents_dir, migrated_plugins, false))
}

#[tauri::command]
pub async fn set_agent_store_dir(
    app: AppHandle,
    state: State<'_, Arc<AppState>>,
    new_dir: Option<String>,
) -> Result<DriverStoreMigrationResult, String> {
    let new_dir = normalize_store_dir(new_dir);
    let current_plugins_dir = state.plugins.root_dir().to_path_buf();
    let current_agents_dir = state.agent_manager.base_dir().clone();
    let target_agents_dir = match new_dir.as_ref() {
        Some(dir) => PathBuf::from(dir),
        None => default_agent_store_dir(&app)?,
    };

    state.agent_manager.stop_daemons().await;
    let migrated_agents = migrate_store_directory(&current_agents_dir, &target_agents_dir)?;

    let mut settings = state.storage.load_desktop_settings().await.unwrap_or_default();
    convert_legacy_driver_store(&mut settings, &current_plugins_dir, &current_agents_dir);
    settings.agent_store_dir = new_dir;
    state.storage.save_desktop_settings(&settings).await?;

    Ok(driver_store_migration_result(settings, &current_plugins_dir, &target_agents_dir, false, migrated_agents))
}

fn normalize_store_dir(dir: Option<String>) -> Option<String> {
    dir.and_then(|value| {
        let trimmed = value.trim();
        (!trimmed.is_empty()).then(|| trimmed.to_string())
    })
}

fn default_store_dirs(app: &AppHandle) -> Result<(PathBuf, PathBuf), String> {
    Ok((default_plugin_store_dir(app)?, default_agent_store_dir(app)?))
}

fn default_plugin_store_dir(app: &AppHandle) -> Result<PathBuf, String> {
    let default_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
    Ok(crate::data_dir::resolve_data_dir_with_mode(default_data_dir).data_dir.join("plugins"))
}

fn default_agent_store_dir(app: &AppHandle) -> Result<PathBuf, String> {
    let default_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
    let data_dir_resolution = crate::data_dir::resolve_data_dir_with_mode(default_data_dir);
    Ok(if data_dir_resolution.uses_custom_data_dir() {
        data_dir_resolution.data_dir.join("agents")
    } else {
        dbx_core::connection::default_agent_dir()
    })
}

pub(crate) fn resolve_driver_store_dirs_from_settings(
    settings: &DesktopSettings,
    data_dir: &Path,
    default_agent_dir: Option<PathBuf>,
) -> (PathBuf, Option<PathBuf>) {
    let legacy_driver_base =
        settings.driver_store_dir.as_ref().filter(|value| !value.trim().is_empty()).map(PathBuf::from);
    let plugin_dir = settings
        .plugin_store_dir
        .as_ref()
        .filter(|value| !value.trim().is_empty())
        .map(PathBuf::from)
        .or_else(|| legacy_driver_base.as_ref().map(|base| base.join("plugins")))
        .unwrap_or_else(|| data_dir.join("plugins"));
    let agent_dir = settings
        .agent_store_dir
        .as_ref()
        .filter(|value| !value.trim().is_empty())
        .map(PathBuf::from)
        .or_else(|| legacy_driver_base.as_ref().map(|base| base.join("agents")))
        .or(default_agent_dir);

    (plugin_dir, agent_dir)
}

fn convert_legacy_driver_store(settings: &mut DesktopSettings, current_plugins_dir: &Path, current_agents_dir: &Path) {
    if settings.driver_store_dir.is_none() {
        return;
    }
    if settings.plugin_store_dir.is_none() {
        settings.plugin_store_dir = Some(current_plugins_dir.to_string_lossy().to_string());
    }
    if settings.agent_store_dir.is_none() {
        settings.agent_store_dir = Some(current_agents_dir.to_string_lossy().to_string());
    }
    settings.driver_store_dir = None;
}

fn driver_store_migration_result(
    settings: DesktopSettings,
    plugins_dir: &Path,
    agents_dir: &Path,
    migrated_plugins: bool,
    migrated_agents: bool,
) -> DriverStoreMigrationResult {
    DriverStoreMigrationResult {
        driver_store_dir: settings.driver_store_dir,
        plugin_store_dir: settings.plugin_store_dir,
        agent_store_dir: settings.agent_store_dir,
        plugins_dir: plugins_dir.to_string_lossy().to_string(),
        agents_dir: agents_dir.to_string_lossy().to_string(),
        migrated_plugins,
        migrated_agents,
    }
}

fn migrate_store_directory(current_dir: &Path, target_dir: &Path) -> Result<bool, String> {
    std::fs::create_dir_all(target_dir)
        .map_err(|e| format!("Failed to create directory {}: {e}", target_dir.display()))?;
    let target_canonical =
        target_dir.canonicalize().map_err(|e| format!("Invalid path {}: {e}", target_dir.display()))?;

    if !current_dir.exists() {
        return Ok(false);
    }

    let current_canonical =
        current_dir.canonicalize().map_err(|e| format!("Invalid path {}: {e}", current_dir.display()))?;
    if current_canonical == target_canonical {
        return Ok(false);
    }
    if target_canonical.starts_with(&current_canonical) {
        return Err(format!(
            "Target directory {} cannot be inside current directory {}",
            target_dir.display(),
            current_dir.display()
        ));
    }
    if target_dir_has_entries(target_dir)? {
        return Err(format!(
            "Target directory {} is not empty. Please choose an empty directory or remove the existing data first.",
            target_dir.display()
        ));
    }

    migrate_directory(current_dir, target_dir)?;
    verify_migration(current_dir, target_dir)?;
    if let Err(err) = std::fs::remove_dir_all(current_dir) {
        log::warn!("Failed to remove old driver store dir {}: {err}", current_dir.display());
    }
    Ok(true)
}

fn target_dir_has_entries(dir: &Path) -> Result<bool, String> {
    let mut entries = std::fs::read_dir(dir).map_err(|e| format!("Failed to read {}: {e}", dir.display()))?;
    Ok(entries.next().transpose().map_err(|e| e.to_string())?.is_some())
}

/// Recursively copy a directory to a new location.
fn migrate_directory(src: &Path, dst: &Path) -> Result<(), String> {
    if !src.exists() {
        return Ok(());
    }
    std::fs::create_dir_all(dst).map_err(|e| format!("Failed to create {}: {e}", dst.display()))?;
    copy_dir_recursive(src, dst)
}

fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> Result<(), String> {
    std::fs::create_dir_all(dst).map_err(|e| format!("Failed to create {}: {e}", dst.display()))?;
    for entry in std::fs::read_dir(src).map_err(|e| format!("Failed to read {}: {e}", src.display()))? {
        let entry = entry.map_err(|e| e.to_string())?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else {
            std::fs::copy(&src_path, &dst_path)
                .map_err(|e| format!("Failed to copy {} to {}: {e}", src_path.display(), dst_path.display()))?;
        }
    }
    Ok(())
}

/// Verify that the migrated directory has the same file count and total size.
fn verify_migration(src: &Path, dst: &Path) -> Result<(), String> {
    let src_info = count_files_recursive(src)?;
    let dst_info = count_files_recursive(dst)?;
    if src_info.count != dst_info.count || src_info.total_size != dst_info.total_size {
        // Rollback: remove the incomplete destination
        let _ = std::fs::remove_dir_all(dst);
        return Err(format!(
            "Migration verification failed: source had {} files ({} bytes), destination has {} files ({} bytes)",
            src_info.count, src_info.total_size, dst_info.count, dst_info.total_size
        ));
    }
    Ok(())
}

struct DirStats {
    count: usize,
    total_size: u64,
}

fn count_files_recursive(dir: &std::path::Path) -> Result<DirStats, String> {
    let mut count = 0usize;
    let mut total_size = 0u64;
    fn walk(dir: &std::path::Path, count: &mut usize, total_size: &mut u64) -> Result<(), String> {
        for entry in std::fs::read_dir(dir).map_err(|e| e.to_string())? {
            let entry = entry.map_err(|e| e.to_string())?;
            let path = entry.path();
            if path.is_dir() {
                walk(&path, count, total_size)?;
            } else {
                *count += 1;
                *total_size += entry.metadata().map(|m| m.len()).unwrap_or(0);
            }
        }
        Ok(())
    }
    walk(dir, &mut count, &mut total_size)?;
    Ok(DirStats { count, total_size })
}

fn load_native_debug_logs_from_dir(log_dir: PathBuf) -> Result<String, String> {
    const MAX_FILES: usize = 6;
    const MAX_FILE_BYTES: u64 = 512 * 1024;
    if !log_dir.exists() {
        return Ok(format!("Native log dir does not exist yet: {}", log_dir.display()));
    }
    let mut files = std::fs::read_dir(&log_dir)
        .map_err(|e| e.to_string())?
        .filter_map(|entry| entry.ok())
        .filter_map(|entry| {
            let path = entry.path();
            let metadata = entry.metadata().ok()?;
            if !metadata.is_file() {
                return None;
            }
            let modified = metadata.modified().ok()?;
            Some((path, modified, metadata.len()))
        })
        .collect::<Vec<_>>();
    files.sort_by_key(|(_, modified, _)| *modified);
    files.reverse();

    let mut output = String::new();
    output.push_str(&format!("Native log dir: {}\n", log_dir.display()));
    for (path, _, len) in files.into_iter().take(MAX_FILES) {
        let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("unknown");
        output.push_str(&format!("\n===== {name} =====\n"));
        let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
        let start = if len > MAX_FILE_BYTES { bytes.len().saturating_sub(MAX_FILE_BYTES as usize) } else { 0 };
        if start > 0 {
            output.push_str("[truncated to last 512 KiB]\n");
        }
        output.push_str(&String::from_utf8_lossy(&bytes[start..]));
        output.push('\n');
    }
    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::{
        driver_store_migration_result, open_tabs_state_key, resolve_driver_store_dirs_from_settings, DesktopSettings,
        DEVELOPMENT_OPEN_TABS_STATE_KEY,
    };
    use std::path::PathBuf;

    #[test]
    fn plugin_store_result_uses_selected_directory_without_agent_prefix() {
        let settings = DesktopSettings {
            plugin_store_dir: Some(path("D:/develop/DBX")),
            agent_store_dir: Some(path("D:/develop/DBX/agents")),
            ..Default::default()
        };
        let plugins_dir = PathBuf::from(path("D:/develop/DBX"));
        let agents_dir = PathBuf::from(path("D:/develop/DBX/agents"));

        let result = driver_store_migration_result(settings, &plugins_dir, &agents_dir, true, false);

        assert_eq!(result.plugin_store_dir.as_deref(), Some(path("D:/develop/DBX").as_str()));
        assert_eq!(result.plugins_dir, path("D:/develop/DBX"));
        assert_eq!(result.agents_dir, path("D:/develop/DBX/agents"));
        assert!(!result.plugins_dir.contains(&path("agents/com.dbx.app/plugins")));
    }

    #[test]
    fn legacy_driver_store_result_keeps_plugins_and_agents_as_siblings() {
        let settings = DesktopSettings { driver_store_dir: Some(path("D:/develop/DBX")), ..Default::default() };
        let plugins_dir = PathBuf::from(path("D:/develop/DBX/plugins"));
        let agents_dir = PathBuf::from(path("D:/develop/DBX/agents"));

        let result = driver_store_migration_result(settings, &plugins_dir, &agents_dir, true, true);

        assert_eq!(result.driver_store_dir.as_deref(), Some(path("D:/develop/DBX").as_str()));
        assert_eq!(result.plugins_dir, path("D:/develop/DBX/plugins"));
        assert_eq!(result.agents_dir, path("D:/develop/DBX/agents"));
    }

    #[test]
    fn resolves_separate_plugin_store_dir_as_exact_selected_dir() {
        let settings = DesktopSettings {
            driver_store_dir: Some(path("D:/legacy-base")),
            plugin_store_dir: Some(path("D:/develop/DBX")),
            agent_store_dir: Some(path("D:/develop/DBX/agents")),
            ..Default::default()
        };

        let (plugins_dir, agents_dir) = resolve_driver_store_dirs_from_settings(
            &settings,
            &PathBuf::from(path("C:/Users/lenovo/AppData/Roaming/com.dbx.app")),
            Some(PathBuf::from(path("C:/Users/lenovo/.dbx/agents"))),
        );

        assert_eq!(plugins_dir, PathBuf::from(path("D:/develop/DBX")));
        assert_eq!(agents_dir, Some(PathBuf::from(path("D:/develop/DBX/agents"))));
    }

    #[test]
    fn resolves_legacy_driver_store_dir_to_sibling_plugins_and_agents() {
        let settings = DesktopSettings { driver_store_dir: Some(path("D:/develop/DBX")), ..Default::default() };

        let (plugins_dir, agents_dir) = resolve_driver_store_dirs_from_settings(
            &settings,
            &PathBuf::from(path("C:/Users/lenovo/AppData/Roaming/com.dbx.app")),
            Some(PathBuf::from(path("C:/Users/lenovo/.dbx/agents"))),
        );

        assert_eq!(plugins_dir, PathBuf::from(path("D:/develop/DBX/plugins")));
        assert_eq!(agents_dir, Some(PathBuf::from(path("D:/develop/DBX/agents"))));
    }

    #[test]
    fn isolates_open_tabs_for_development_builds() {
        assert_eq!(open_tabs_state_key(true), DEVELOPMENT_OPEN_TABS_STATE_KEY);
        assert_eq!(open_tabs_state_key(false), "open_tabs");
    }

    fn path(value: &str) -> String {
        value.replace('/', std::path::MAIN_SEPARATOR_STR)
    }
}