From 24a97e8dfdb22c73f327c3a70d1d41e0dc39584c Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 11:11:01 +0200 Subject: [PATCH 1/6] feat(server): build the container image without Tauri A default-on `desktop` feature now carries Tauri, its plugins, tauri-build and gtk. `cargo build --no-default-features` produces a server that only runs `tabularis web` and `--mcp` and links no GUI libraries. Tauri commands that need Tauri types compile only with `desktop`; the others keep `#[tauri::command]` behind `cfg_attr` because the web RPC calls them directly. `async_rt` picks Tauri's runtime in the desktop app and the ambient Tokio runtime otherwise. The image drops from 462 MB to 170 MB unpacked (176 MB to 58 MB pulled). It stays on Debian: registry driver plugins are glibc binaries and fail on Alpine even with gcompat. CI checks the server-only build. --- .github/workflows/ci.yml | 5 + docker/Dockerfile | 42 ++---- src-tauri/Cargo.toml | 45 ++++-- src-tauri/build.rs | 3 + src-tauri/src/ai.rs | 9 ++ src-tauri/src/ai_approval_watcher.rs | 9 +- src-tauri/src/ai_commands.rs | 18 +-- src-tauri/src/askpass/mod.rs | 16 +- src-tauri/src/backup/mod.rs | 12 +- src-tauri/src/chatgpt/auth.rs | 2 + src-tauri/src/chatgpt/mod.rs | 13 +- src-tauri/src/clipboard_import.rs | 2 + src-tauri/src/commands.rs | 145 +++++++++++++++++-- src-tauri/src/config.rs | 44 +++++- src-tauri/src/connection_appearance.rs | 3 + src-tauri/src/connection_import_commands.rs | 10 +- src-tauri/src/connection_tags.rs | 7 + src-tauri/src/connection_window.rs | 4 +- src-tauri/src/dump_commands.rs | 5 + src-tauri/src/e2e_dialog_mock.rs | 11 +- src-tauri/src/explain_import.rs | 7 +- src-tauri/src/export.rs | 3 + src-tauri/src/health_check.rs | 7 + src-tauri/src/heartbeat.rs | 4 +- src-tauri/src/json_viewer.rs | 4 + src-tauri/src/lib.rs | 42 +++++- src-tauri/src/log_commands.rs | 11 +- src-tauri/src/mcp/install.rs | 3 + src-tauri/src/notebooks.rs | 12 +- src-tauri/src/plugins/commands.rs | 18 ++- src-tauri/src/plugins/connection_metadata.rs | 2 + src-tauri/src/plugins/deep_link.rs | 3 + src-tauri/src/plugins/force_install.rs | 6 + src-tauri/src/plugins/manager.rs | 4 +- src-tauri/src/plugins/runtime_version.rs | 2 +- src-tauri/src/preferences.rs | 5 + src-tauri/src/proxy/mod.rs | 6 +- src-tauri/src/query_history.rs | 7 + src-tauri/src/results_window.rs | 3 + src-tauri/src/runtime/events.rs | 4 + src-tauri/src/runtime/lifecycle.rs | 3 +- src-tauri/src/runtime/tests.rs | 1 + src-tauri/src/saved_queries.rs | 12 ++ src-tauri/src/sql_file.rs | 4 +- src-tauri/src/sqlite_database.rs | 4 +- src-tauri/src/storage_location.rs | 12 +- src-tauri/src/system_theme.rs | 6 +- src-tauri/src/task_manager.rs | 11 +- src-tauri/src/theme_commands.rs | 18 ++- src-tauri/src/theme_packages/commands.rs | 22 ++- src-tauri/src/theme_packages/transport.rs | 2 +- src-tauri/src/ui_state_commands.rs | 4 + src-tauri/src/updater.rs | 10 +- src-tauri/src/window_decorations.rs | 2 + src-tauri/src/window_placement.rs | 6 + web-ui-project/docs/WEB_MODE_CONTAINERS.md | 6 +- 56 files changed, 550 insertions(+), 131 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 91024cc56..1a0ecc4ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,6 +87,11 @@ jobs: - name: Test run: pnpm run test:all + # The container image builds the server without Tauri. + - name: Check the server-only build + working-directory: src-tauri + run: cargo check --locked --no-default-features --bin tabularis + web-e2e: runs-on: ubuntu-24.04 diff --git a/docker/Dockerfile b/docker/Dockerfile index c92a2251f..7ee39cdae 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -3,8 +3,9 @@ # Tabularis Web as a container image: # docker build -f docker/Dockerfile -t tabularis . # -# The binary still links WebKitGTK (Tauri is not optional), so the runtime -# carries those shared libraries even though `tabularis web` never opens a window. +# The server is built without the desktop app, so the image carries no GUI +# libraries. Debian rather than Alpine: registry driver plugins are glibc +# binaries and do not run on musl, not even through gcompat. ARG NODE_VERSION=24.18.0 ARG DEBIAN_VERSION=trixie @@ -24,55 +25,36 @@ RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \ && pnpm build # ── Server ─────────────────────────────────────────────────────────────────── +# Built without the `desktop` feature: no Tauri, GTK or WebKitGTK, only the +# `tabularis web` and `--mcp` entry points. FROM rust:1-${DEBIAN_VERSION} AS server +ARG TABULARIS_BUILD_COMMIT= RUN apt-get update \ - && apt-get install -y --no-install-recommends \ - libwebkit2gtk-4.1-dev libgtk-3-dev libsoup-3.0-dev libdbus-1-dev \ - pkg-config perl make \ + && apt-get install -y --no-install-recommends libdbus-1-dev pkg-config perl make \ && rm -rf /var/lib/apt/lists/* - -# Reported by the server contract (`option_env!`); empty for local builds. -ARG TABULARIS_BUILD_COMMIT= WORKDIR /src -# The crate embeds the built frontend (`tauri::generate_context!`) and a few -# JSON schemas from outside src-tauri. +# JSON schemas and themes the crate embeds from outside src-tauri. COPY plugins/manifest.schema.json ./plugins/manifest.schema.json COPY packages/web-ui/src/schemas ./packages/web-ui/src/schemas COPY packages/web-ui/src/themes ./packages/web-ui/src/themes -COPY --from=web-ui /src/packages/web-ui/dist ./packages/web-ui/dist COPY src-tauri ./src-tauri RUN --mount=type=cache,id=cargo-registry,target=/usr/local/cargo/registry \ --mount=type=cache,id=cargo-target,target=/src/src-tauri/target \ cd src-tauri \ - && cargo build --release --locked --bin tabularis \ + && cargo build --release --locked --no-default-features --bin tabularis \ && install -Dm755 target/release/tabularis /out/tabularis -# ── Shared libraries ───────────────────────────────────────────────────────── -# Installing WebKitGTK drags in Mesa/LLVM, GStreamer, speech synthesis and more -# (~700 MB) that `tabularis web` never loads: GTK is never initialised. Only -# the libraries the binary links (its `ldd` closure) go into the runtime, -# under their canonical directory so merged-/usr symlinks such as /lib stay. -FROM debian:${DEBIAN_VERSION}-slim AS libs -RUN apt-get update \ - && apt-get install -y --no-install-recommends libwebkit2gtk-4.1-0 libdbus-1-3 -COPY --from=server /out/tabularis /usr/bin/tabularis -RUN mkdir /libs \ - && ldd /usr/bin/tabularis | awk '/=> \// { print $3 }' | while read -r lib; do \ - dir="$(readlink -f "$(dirname "$lib")")"; \ - mkdir -p "/libs$dir" && cp -L "$lib" "/libs$dir/"; \ - done # ── Runtime ────────────────────────────────────────────────────────────────── FROM debian:${DEBIAN_VERSION}-slim RUN apt-get update \ - && apt-get install -y --no-install-recommends ca-certificates curl tini openssh-client \ + && apt-get install -y --no-install-recommends \ + ca-certificates curl tini openssh-client libdbus-1-3 \ && rm -rf /var/lib/apt/lists/* \ && useradd --system --uid 10001 --user-group --home-dir /data --no-create-home tabularis \ && install -d -o 10001 -g 10001 -m 0750 /data -COPY --from=libs /libs/ / COPY --from=server /out/tabularis /usr/bin/tabularis -# Fails the build if a linked library is missing. -RUN ldconfig && tabularis --help >/dev/null +RUN tabularis --help >/dev/null COPY --from=web-ui /src/packages/web-ui/dist /usr/lib/tabularis/web-ui COPY docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh ENV HOME=/data \ diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9e0662f32..5d0b812b2 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -16,7 +16,24 @@ crate-type = ["staticlib", "cdylib", "rlib"] # Off by default — normal and CI builds exclude it. Only the e2e-macos workflow # builds with `--features e2e-testing` so tauri-wd can drive the real WKWebView. [features] -e2e-testing = ["dep:tauri-plugin-webdriver-automation"] +default = ["desktop"] +# The Tauri desktop app. Without it the binary only serves `tabularis web` and +# `--mcp`, and links neither GTK nor WebKitGTK (the container image build). +desktop = [ + "dep:tauri", + "dep:tauri-build", + "dep:tauri-plugin-log", + "dep:tauri-plugin-dialog", + "dep:tauri-plugin-fs", + "dep:tauri-plugin-notification", + "dep:tauri-plugin-opener", + "dep:tauri-plugin-clipboard-manager", + "dep:tauri-plugin-deep-link", + "dep:tauri-plugin-single-instance", + "dep:tauri-plugin-updater", + "dep:gtk", +] +e2e-testing = ["desktop", "dep:tauri-plugin-webdriver-automation"] [profile.release] codegen-units = 1 @@ -26,7 +43,7 @@ panic = "abort" strip = true [build-dependencies] -tauri-build = { version = "2.5.3", features = [] } +tauri-build = { version = "2.5.3", features = [], optional = true } [dependencies] serde_json = { version = "1.0", features = ["raw_value"] } @@ -36,9 +53,9 @@ fs2 = "0.4" serde = { version = "1.0", features = ["derive"] } bytes = "1" toon-format = { version = "0.5.0", default-features = false } -log = "0.4" -tauri = { version = "2.10.2", features = ["protocol-asset", "devtools"] } -tauri-plugin-log = "2" +log = { version = "0.4", features = ["std"] } +tauri = { version = "2.10.2", features = ["protocol-asset", "devtools"], optional = true } +tauri-plugin-log = { version = "2", optional = true } sqlx = { version = "0.8.6", features = ["runtime-tokio", "sqlite", "mysql", "postgres", "tls-rustls-ring-native-roots", "chrono", "uuid", "rust_decimal", "json"] } tokio = { version = "1.49.0", features = ["full"] } tokio-util = { version = "0.7", features = ["io"] } @@ -50,9 +67,9 @@ uuid = { version = "1.20.0", features = ["v4", "serde"] } rust_decimal = { version = "1.36", features = ["db-tokio-postgres", "serde"] } chrono = { version = "0.4.43", features = ["serde"] } chrono-tz = "0.10" -tauri-plugin-dialog = "2.6.0" -tauri-plugin-fs = "2.4.5" -tauri-plugin-notification = "2" +tauri-plugin-dialog = { version = "2.6.0", optional = true } +tauri-plugin-fs = { version = "2.4.5", optional = true } +tauri-plugin-notification = { version = "2", optional = true } russh = "0.43" russh-keys = "0.43" async-trait = "0.1" @@ -65,7 +82,7 @@ sha2 = "0.10" ed25519-dalek = "2" futures = "0.3.31" keyring = { version = "3.6.3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } -tauri-plugin-opener = "2" +tauri-plugin-opener = { version = "2", optional = true } once_cell = "1.20" csv = "1.4.0" reqwest = { version = "0.13.1", features = ["json", "socks"] } @@ -90,9 +107,9 @@ zip = "4.2.0" tabularium-sdk = "0.2" url = "2" semver = "1" -tauri-plugin-clipboard-manager = "2" -tauri-plugin-deep-link = "2" -tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } +tauri-plugin-clipboard-manager = { version = "2", optional = true } +tauri-plugin-deep-link = { version = "2", optional = true } +tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true } tokio-postgres = { version = "0.7.13", features = ["with-chrono-0_4", "with-uuid-1", "with-serde_json-1", "array-impls"] } deadpool-postgres = "0.14.1" # sqlx uses `tls-rustls-ring-native-roots` for both the MySQL pool and the @@ -132,7 +149,7 @@ libc = "0.2" # GTK dependencies for Wayland window title workaround (Linux only) [target.'cfg(target_os = "linux")'.dependencies] -gtk = "0.18" +gtk = { version = "0.18", optional = true } # Keep zbus on the async-io backend. The `tokio` feature makes # `zbus::utils::block_on` drive a Tokio runtime, which panics when invoked from # inside a Tokio task and, in a `panic = "abort"` release build, aborts the @@ -142,7 +159,7 @@ gtk = "0.18" zbus = { version = "5.14", default-features = false, features = ["async-io"] } [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] -tauri-plugin-updater = "2" +tauri-plugin-updater = { version = "2", optional = true } [dev-dependencies] tauri = { version = "2.10.2", features = ["test"] } diff --git a/src-tauri/build.rs b/src-tauri/build.rs index d860e1e6a..7f77d51e3 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,3 +1,6 @@ fn main() { + // Set by tauri-build in the desktop build; declared for the server-only one. + println!("cargo::rustc-check-cfg=cfg(mobile)"); + #[cfg(feature = "desktop")] tauri_build::build() } diff --git a/src-tauri/src/ai.rs b/src-tauri/src/ai.rs index fd4ef0941..abbcc3cc7 100644 --- a/src-tauri/src/ai.rs +++ b/src-tauri/src/ai.rs @@ -8,6 +8,7 @@ use std::collections::{HashMap, HashSet}; use std::fs; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager}; // --- Data Structures --- @@ -384,6 +385,7 @@ async fn fetch_custom_openai_models(base_url: &str, api_key: &str) -> Vec Result<(), String> { clear_models_cache(&app.state::()) @@ -397,6 +399,7 @@ pub fn clear_models_cache(runtime: &RuntimeContext) -> Result<(), String> { Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_ai_models( app: AppHandle, @@ -580,6 +583,7 @@ pub async fn get_models( Ok(models) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result { generate_query( @@ -590,6 +594,7 @@ pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result { explain_query( @@ -600,6 +605,7 @@ pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result Result { generate_cellname( @@ -893,6 +900,7 @@ pub async fn generate_cellname( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn suggest_table_name( app: AppHandle, @@ -969,6 +977,7 @@ pub async fn suggest_table_name_with_runtime( } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn generate_tab_rename( app: AppHandle, diff --git a/src-tauri/src/ai_approval_watcher.rs b/src-tauri/src/ai_approval_watcher.rs index a96df60ba..6d8881514 100644 --- a/src-tauri/src/ai_approval_watcher.rs +++ b/src-tauri/src/ai_approval_watcher.rs @@ -8,6 +8,7 @@ use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use std::collections::{HashMap, HashSet}; use std::sync::{mpsc, Arc}; use std::time::Duration; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter, Runtime}; use crate::ai_approval; @@ -109,22 +110,24 @@ pub fn spawn_headless( }) } +#[cfg(feature = "desktop")] /// Spawn the watcher + cleanup tasks. The watcher returns immediately if it /// fails to initialise (e.g. unsupported filesystem); cleanup keeps running. pub fn spawn(app: AppHandle) { let app_for_watcher = app.clone(); - tauri::async_runtime::spawn_blocking(move || { + crate::async_rt::spawn_blocking(move || { if let Err(e) = run_watcher(app_for_watcher) { log::warn!("AI approval watcher disabled: {}", e); } }); let app_for_cleanup = app.clone(); - tauri::async_runtime::spawn(async move { + crate::async_rt::spawn(async move { run_cleanup_loop(app_for_cleanup).await; }); } +#[cfg(feature = "desktop")] fn run_watcher(app: AppHandle) -> Result<(), String> { let dir = ai_approval::approvals_dir_path(); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; @@ -149,6 +152,7 @@ fn run_watcher(app: AppHandle) -> Result<(), String> { Ok(()) } +#[cfg(feature = "desktop")] fn handle_event(app: &AppHandle, event: &Event) { if !matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_)) { return; @@ -173,6 +177,7 @@ fn handle_event(app: &AppHandle, event: &Event) { } } +#[cfg(feature = "desktop")] async fn run_cleanup_loop(_app: AppHandle) { let mut ticker = tokio::time::interval(Duration::from_secs(CLEANUP_INTERVAL_SECS)); // Skip the immediate first tick. diff --git a/src-tauri/src/ai_commands.rs b/src-tauri/src/ai_commands.rs index b73a0131c..0dedb54e8 100644 --- a/src-tauri/src/ai_commands.rs +++ b/src-tauri/src/ai_commands.rs @@ -6,7 +6,7 @@ use crate::ai_activity::{self, AiActivityEvent, EventFilter, SessionSummary}; use crate::ai_approval::{self, ApprovalDecision, PendingApproval}; use crate::ai_notebook_export::NotebookExport; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_ai_activity(filter: Option) -> Result, String> { let f = filter.unwrap_or_default(); tokio::task::spawn_blocking(move || ai_activity::read_events(&f)) @@ -14,50 +14,50 @@ pub async fn get_ai_activity(filter: Option) -> Result Result, String> { tokio::task::spawn_blocking(ai_activity::read_sessions) .await .map_err(|e| e.to_string())? } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_ai_session_events(session_id: String) -> Result, String> { tokio::task::spawn_blocking(move || ai_activity::read_session_events(&session_id)) .await .map_err(|e| e.to_string())? } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn clear_ai_activity() -> Result<(), String> { tokio::task::spawn_blocking(ai_activity::clear) .await .map_err(|e| e.to_string())? } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn export_ai_activity_json() -> Result { crate::application::generic_exports::generate_ai_activity_json().await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn export_ai_activity_csv() -> Result { crate::application::generic_exports::generate_ai_activity_csv().await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn export_ai_session_as_notebook(session_id: String) -> Result { crate::application::generic_exports::generate_ai_session_notebook(session_id).await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn list_pending_approvals() -> Result, String> { tokio::task::spawn_blocking(ai_approval::list_pending) .await .map_err(|e| e.to_string())? } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn decide_pending_approval( approval_id: String, decision: String, diff --git a/src-tauri/src/askpass/mod.rs b/src-tauri/src/askpass/mod.rs index d0e837194..624f100a3 100644 --- a/src-tauri/src/askpass/mod.rs +++ b/src-tauri/src/askpass/mod.rs @@ -24,7 +24,9 @@ pub use client::maybe_run_askpass_client; pub use protocol::PromptKind; pub use server::{AskpassOptions, AskpassServer, AskpassUi}; -use crate::runtime::events::{RuntimeEvents, TauriRuntimeEvents}; +use crate::runtime::events::RuntimeEvents; +#[cfg(feature = "desktop")] +use crate::runtime::events::TauriRuntimeEvents; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{sync_channel, SyncSender}; @@ -32,6 +34,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use serde::Serialize; +#[cfg(feature = "desktop")] use tauri::AppHandle; use uuid::Uuid; @@ -46,6 +49,7 @@ const RESPONSE_TIMEOUT_SECS: u64 = 300; /// Global handle for code paths (the SSH tunnel module) that run without a /// Tauri context. Set once during application setup. +#[cfg(feature = "desktop")] static APP_HANDLE: OnceLock = OnceLock::new(); static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1); @@ -60,6 +64,7 @@ fn pending_responses() -> &'static Mutex> { PENDING.get_or_init(|| Mutex::new(HashMap::new())) } +#[cfg(feature = "desktop")] /// Store the app handle so SSH tunnel code can reach the frontend. pub fn set_app_handle(app: AppHandle) { let _ = APP_HANDLE.set(app); @@ -76,9 +81,16 @@ pub fn start_frontend_server() -> Result { /// Like [`start_frontend_server`], with stored credentials that answer matching /// prompts without opening the modal. pub fn start_frontend_server_with(options: AskpassOptions) -> Result { + #[cfg(not(feature = "desktop"))] + { + let _ = options; + Err("Askpass UI unavailable: application not initialised".to_string()) + } + #[cfg(feature = "desktop")] let app = APP_HANDLE .get() .ok_or_else(|| "Askpass UI unavailable: application not initialised".to_string())?; + #[cfg(feature = "desktop")] start_scoped_server_with( Arc::new(TauriRuntimeEvents::new(app.clone())), None, @@ -180,7 +192,7 @@ impl AskpassUi for FrontendUi { /// Frontend answer to an askpass prompt. `response = None` means the user /// cancelled. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn respond_ssh_askpass(id: u64, response: Option) { let _ = respond_for_session(None, id, response); } diff --git a/src-tauri/src/backup/mod.rs b/src-tauri/src/backup/mod.rs index eaae67163..1ee6113ff 100644 --- a/src-tauri/src/backup/mod.rs +++ b/src-tauri/src/backup/mod.rs @@ -11,6 +11,7 @@ use chrono::NaiveDateTime; use keyring::Entry; use std::fs; use std::path::PathBuf; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; use crate::runtime::RuntimeContext; @@ -416,6 +417,7 @@ pub async fn run_backup_for_runtime( }) } +#[cfg(feature = "desktop")] pub async fn run_backup(app: AppHandle, trigger: &str) -> Result { Ok( run_backup_for_runtime(app.state::().inner(), trigger) @@ -432,12 +434,14 @@ fn backup_mode(config: &crate::config::AppConfig) -> String { .unwrap_or_else(|| "manual".to_string()) } +#[cfg(feature = "desktop")] async fn run_and_log(app: &AppHandle, trigger: &str) { if let Err(e) = run_backup(app.clone(), trigger).await { log::warn!("Connections backup ({trigger}) failed: {e}"); } } +#[cfg(feature = "desktop")] /// Interval mode: runs one backup when the newest one is older than the /// configured interval. async fn run_if_due(app: &AppHandle) { @@ -457,6 +461,7 @@ async fn run_if_due(app: &AppHandle) { } } +#[cfg(feature = "desktop")] /// Called from the `RunEvent::Exit` handler. In on-close mode every exit /// writes a backup so the freshest state is what gets saved. Synchronous: /// the process is about to end. @@ -479,13 +484,14 @@ pub fn run_exit_backup(app: &AppHandle) { } } +#[cfg(feature = "desktop")] /// Background task started at app launch. In on-launch mode it writes one /// backup right away; in interval mode it checks periodically whether a /// backup is due. Config is re-read on every tick so settings changes apply /// without a restart (a switch to on-launch only takes effect at the next /// start, like the mode's name says). pub fn spawn_scheduler(app: AppHandle) { - tauri::async_runtime::spawn(async move { + crate::async_rt::spawn(async move { if backup_mode(&crate::config::load_config_internal(&app)) == "onLaunch" { run_and_log(&app, "on launch").await; } @@ -572,6 +578,7 @@ pub fn set_backup_target_password( } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connections_backup_status( app: AppHandle, @@ -579,6 +586,7 @@ pub async fn get_connections_backup_status( backup_status(app.state::().inner()).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_connections_backup_password( app: AppHandle, @@ -589,6 +597,7 @@ pub async fn set_connections_backup_password( /// Stores (or clears, with an empty password) the credential of one backup /// target, keyed by its id (e.g. `"webdav"`). +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_connections_backup_target_password( app: AppHandle, @@ -598,6 +607,7 @@ pub async fn set_connections_backup_target_password( set_backup_target_password(app.state::().inner(), &target_id, &password) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn run_connections_backup(app: AppHandle) -> Result { Ok( diff --git a/src-tauri/src/chatgpt/auth.rs b/src-tauri/src/chatgpt/auth.rs index d03cf9492..9bdfab59b 100644 --- a/src-tauri/src/chatgpt/auth.rs +++ b/src-tauri/src/chatgpt/auth.rs @@ -158,11 +158,13 @@ async fn callback( } } +#[cfg(feature = "desktop")] pub(super) async fn sign_in( app: &tauri::AppHandle, store: Store, profile_id: Option<&str>, ) -> Result { + #[cfg(feature = "desktop")] use tauri_plugin_opener::OpenerExt; let existing = profile_id .map(|id| { diff --git a/src-tauri/src/chatgpt/mod.rs b/src-tauri/src/chatgpt/mod.rs index 0042a35ca..5bd5e80a2 100644 --- a/src-tauri/src/chatgpt/mod.rs +++ b/src-tauri/src/chatgpt/mod.rs @@ -41,13 +41,14 @@ fn http_client() -> Result { crate::proxy::ai_http_client("chatgpt") } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_chatgpt_session() -> Result { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; Ok(session(&disk.load()?)) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn sign_in_chatgpt( app: tauri::AppHandle, @@ -84,7 +85,7 @@ pub async fn sign_in_chatgpt( Ok(session(&result?)) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_chatgpt_sign_in() { if let Ok(mut sender) = SIGN_IN_CANCEL.lock() { if let Some(sender) = sender.take() { @@ -93,7 +94,7 @@ pub fn cancel_chatgpt_sign_in() { } } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn select_chatgpt_profile(profile_id: String) -> Result { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; @@ -106,7 +107,7 @@ pub async fn select_chatgpt_profile(profile_id: String) -> Result Result, String> { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; @@ -130,8 +131,10 @@ pub async fn sign_out_chatgpt(profile_id: String) -> Result, Stri Ok(warning) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn open_chatgpt_usage(app: tauri::AppHandle) -> Result<(), String> { + #[cfg(feature = "desktop")] use tauri_plugin_opener::OpenerExt; app.opener() .open_url("https://chatgpt.com/#settings/Usage", None::<&str>) @@ -140,7 +143,7 @@ pub fn open_chatgpt_usage(app: tauri::AppHandle) -> Result<(), String> { pub use inference::{generate, list_models}; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_chatgpt_models() -> Result, String> { list_models().await } diff --git a/src-tauri/src/clipboard_import.rs b/src-tauri/src/clipboard_import.rs index 0aaca403b..64c08a2ad 100644 --- a/src-tauri/src/clipboard_import.rs +++ b/src-tauri/src/clipboard_import.rs @@ -3,6 +3,7 @@ use crate::models::TableColumn; use crate::{drivers::driver_trait::DatabaseDriver, models::ColumnDefinition}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; #[derive(Deserialize, Debug)] @@ -172,6 +173,7 @@ fn table_ref(table_name: &str, schema: Option<&str>, quote: &str) -> String { } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn execute_clipboard_import( app: AppHandle, diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 0c6e57f24..d7a6e7c89 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::fs; use std::path::PathBuf; use std::sync::{Arc, Mutex}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter, Manager, Runtime, State}; use tokio::task::AbortHandle; use urlencoding::encode; @@ -33,6 +34,7 @@ async fn driver_for_params( crate::drivers::registry::get_connection_driver(params).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connection_metadata( app: AppHandle, @@ -103,6 +105,7 @@ pub(crate) fn unregister_abort_handle( // --- Persistence Helpers --- +#[cfg(feature = "desktop")] pub async fn expand_ssh_connection_params( app: &AppHandle, params: &ConnectionParams, @@ -230,6 +233,7 @@ pub fn resolve_connection_params_with_id( resolve_connection_params(&with_id) } +#[cfg(feature = "desktop")] pub fn get_config_path(_app: &AppHandle) -> Result { let config_dir = crate::paths::get_app_config_dir(); if !config_dir.exists() { @@ -238,6 +242,7 @@ pub fn get_config_path(_app: &AppHandle) -> Result(_app: &AppHandle) -> Result { let config_dir = crate::paths::get_app_config_dir(); if !config_dir.exists() { @@ -463,6 +468,7 @@ fn restore_runtime_connection_uri( } } +#[cfg(feature = "desktop")] /// Saved connection as stored, without any keychain secret. fn lookup_saved_connection( app: &AppHandle, @@ -489,6 +495,7 @@ fn lookup_saved_connection( Ok(conn) } +#[cfg(feature = "desktop")] /// Load a saved connection with its host-owned credentials (keychain password, /// SSH secrets, connection URI) but without plugin-owned secrets. Used by the /// edit modal and by the Test Connection / Load Databases flows, which resolve @@ -533,6 +540,7 @@ pub fn find_connection_metadata_by_id( Ok(conn) } +#[cfg(feature = "desktop")] /// Load a connection for driver execution. Unlike the metadata/edit path, /// this resolves plugin-owned secrets into `params.extra` only in memory. pub fn find_connection_by_id( @@ -591,6 +599,7 @@ fn validate_environment(env: Option) -> Result, String> { } } +#[cfg(feature = "desktop")] pub(crate) fn save_connections_and_invalidate( app: &AppHandle, path: &std::path::Path, @@ -604,6 +613,7 @@ pub(crate) fn save_connections_and_invalidate( // --- Commands --- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connection_by_id( app: AppHandle, @@ -612,6 +622,7 @@ pub async fn get_connection_by_id( find_connection_metadata_by_id(&app, &id) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_schemas( app: AppHandle, @@ -627,6 +638,7 @@ pub async fn get_schemas( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_available_databases( app: AppHandle, @@ -640,6 +652,7 @@ pub async fn get_available_databases( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_selected_databases( app: AppHandle, @@ -657,6 +670,7 @@ pub async fn set_selected_databases( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_routines( app: AppHandle, @@ -674,6 +688,7 @@ pub async fn get_routines( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_routine_parameters( app: AppHandle, @@ -696,6 +711,7 @@ pub async fn get_routine_parameters( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_routine_definition( app: AppHandle, @@ -720,6 +736,7 @@ pub async fn get_routine_definition( } /// Preview generation only; the returned SQL is never executed here. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_table_query_template( app: AppHandle, @@ -740,6 +757,7 @@ pub async fn get_table_query_template( /// Column statistics through the optional plugin RPC (issue #1137). `None` /// means the driver doesn't provide them; the frontend then falls back to its /// generic SQL or hides the entry. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_column_stats( app: AppHandle, @@ -757,6 +775,7 @@ pub async fn get_column_stats( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn build_routine_call_sql( app: AppHandle, @@ -778,6 +797,7 @@ pub async fn build_routine_call_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_routine_create_template( app: AppHandle, @@ -796,6 +816,7 @@ pub async fn get_routine_create_template( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_routine_edit_script( app: AppHandle, @@ -819,6 +840,7 @@ pub async fn get_routine_edit_script( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_routine( app: AppHandle, @@ -842,6 +864,7 @@ pub async fn drop_routine( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_schema_snapshot( app: AppHandle, @@ -859,6 +882,7 @@ pub async fn get_schema_snapshot( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_ai_schema_context( app: AppHandle, @@ -889,6 +913,7 @@ pub async fn get_ai_schema_context( )) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_connection( app: AppHandle, @@ -1034,6 +1059,7 @@ pub async fn save_connection( Ok(returned_conn) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_connection(app: AppHandle, id: String) -> Result<(), String> { log::info!("Deleting connection: {}", id); @@ -1109,6 +1135,7 @@ pub async fn delete_connection(app: AppHandle, id: String) -> Res Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_connection( app: AppHandle, @@ -1365,6 +1392,7 @@ fn set_appearance_impl( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_connection_appearance( app: AppHandle, @@ -1378,6 +1406,7 @@ pub async fn set_connection_appearance( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn duplicate_connection( app: AppHandle, @@ -1551,6 +1580,7 @@ pub async fn duplicate_connection( Ok(returned_conn) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connections( app: AppHandle, @@ -1565,6 +1595,7 @@ pub async fn get_connections( // ==================== SSH Connection Management ==================== +#[cfg(feature = "desktop")] /// Migrates old embedded SSH connections to separate SSH connection entries async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), String> { let conn_path = get_config_path(app)?; @@ -1698,6 +1729,7 @@ async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), S // core, and invalidate the connection cache only if it actually rewrote // something. +#[cfg(feature = "desktop")] /// Migrates already-persisted `ssl_mode` values on postgres-dialect /// connections (driver id other than the builtin `"postgres"`) from the /// stale MySQL-style spelling to the Postgres-style spelling the plugin @@ -1718,6 +1750,7 @@ async fn migrate_postgres_ssl_mode_spelling(app: &AppHandle) -> R Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_ssh_connections( app: AppHandle, @@ -1728,6 +1761,7 @@ pub async fn get_ssh_connections( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_ssh_connection( app: AppHandle, @@ -1742,6 +1776,7 @@ pub async fn save_ssh_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_ssh_connection( app: AppHandle, @@ -1758,6 +1793,7 @@ pub async fn update_ssh_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_ssh_connection( app: AppHandle, @@ -1769,6 +1805,7 @@ pub async fn delete_ssh_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn test_ssh_connection( app: AppHandle, @@ -1786,6 +1823,7 @@ pub async fn test_ssh_connection( // Kubernetes Connections // --------------------------------------------------------------------------- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_connections( app: AppHandle, @@ -1793,6 +1831,7 @@ pub async fn get_k8s_connections( crate::application::tunnels::get_k8s_connections(&app.state::()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_k8s_connection( app: AppHandle, @@ -1804,6 +1843,7 @@ pub async fn save_k8s_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_k8s_connection( app: AppHandle, @@ -1817,6 +1857,7 @@ pub async fn update_k8s_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_k8s_connection( app: AppHandle, @@ -1828,6 +1869,7 @@ pub async fn delete_k8s_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn test_k8s_connection_cmd( _app: AppHandle, @@ -1840,6 +1882,7 @@ pub async fn test_k8s_connection_cmd( crate::k8s_tunnel::test_k8s_connection(&context, &namespace, &options) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_contexts_cmd( _app: AppHandle, @@ -1850,6 +1893,7 @@ pub async fn get_k8s_contexts_cmd( crate::k8s_tunnel::get_k8s_contexts(&options) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_namespaces_cmd( _app: AppHandle, @@ -1861,6 +1905,7 @@ pub async fn get_k8s_namespaces_cmd( crate::k8s_tunnel::get_k8s_namespaces(&context, &options) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_resources_cmd( _app: AppHandle, @@ -1874,6 +1919,7 @@ pub async fn get_k8s_resources_cmd( crate::k8s_tunnel::get_k8s_resources(&context, &namespace, &resource_type, &options) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_resource_ports_cmd( _app: AppHandle, @@ -1894,6 +1940,7 @@ pub async fn get_k8s_resource_ports_cmd( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn validate_k8s_path_cmd( _app: AppHandle, @@ -1907,6 +1954,7 @@ pub async fn validate_k8s_path_cmd( // AWS SSM // --------------------------------------------------------------------------- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn test_ssm_connection_cmd( app: AppHandle, @@ -1931,6 +1979,7 @@ pub async fn test_ssm_connection_cmd( serde_json::from_value(result).map_err(|e| e.to_string()) } +#[cfg(feature = "desktop")] /// Expand K8s connection params by loading saved config and creating/reusing a tunnel. pub async fn expand_k8s_connection_params( app: &AppHandle, @@ -1944,6 +1993,7 @@ pub async fn expand_k8s_connection_params( crate::application::tunnels::resolve_expanded_connection_params(&expanded, None) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn test_connection( app: AppHandle, @@ -2131,6 +2181,7 @@ pub async fn test_connection( Ok("Connection successful!".to_string()) } +#[cfg(feature = "desktop")] /// Emits one step of a connection test's live progress log. A no-op when the /// caller did not request progress (no id). fn emit_test_progress( @@ -2152,6 +2203,7 @@ fn emit_test_progress( ); } +#[cfg(feature = "desktop")] /// Emits a failed step and passes the error through, for use in `map_err`. fn emit_test_failure( app: &AppHandle, @@ -3625,6 +3677,7 @@ mod tests { } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn list_databases( app: AppHandle, @@ -3694,6 +3747,7 @@ pub async fn list_databases( drv.get_databases(&resolved_params).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_tables( app: AppHandle, @@ -3711,6 +3765,7 @@ pub async fn get_tables( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_columns( app: AppHandle, @@ -3730,6 +3785,7 @@ pub async fn get_columns( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_foreign_keys( app: AppHandle, @@ -3749,6 +3805,7 @@ pub async fn get_foreign_keys( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_indexes( app: AppHandle, @@ -3768,6 +3825,7 @@ pub async fn get_indexes( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_record( app: AppHandle, @@ -3789,6 +3847,7 @@ pub async fn delete_record( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_record( app: AppHandle, @@ -3814,6 +3873,7 @@ pub async fn update_record( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_blob_to_file( app: AppHandle, @@ -3844,6 +3904,7 @@ pub async fn save_blob_to_file( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_blob( app: AppHandle, @@ -3870,6 +3931,7 @@ pub async fn fetch_blob( /// Fetches a BLOB column from the database and returns it as a data: URL for image preview. /// Same query logic as save_blob_to_file but returns the data in-memory instead of writing to disk. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_blob_as_data_url( app: AppHandle, @@ -3896,7 +3958,7 @@ pub async fn fetch_blob_as_data_url( /// Detects the MIME type of base64-encoded binary data using magic-byte analysis /// and returns the canonical blob wire format: "BLOB:::". /// Called by the frontend after the user selects a file to upload. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn detect_blob_mime(base64_data: String) -> Result { crate::application::records::detect_blob_mime(&base64_data) } @@ -3905,6 +3967,7 @@ pub fn detect_blob_mime(base64_data: String) -> Result { /// The actual file content is NOT transferred over IPC, avoiding massive string allocations. /// The file content will be read directly from disk when needed (e.g., during INSERT/UPDATE). /// Returns a special "BLOB_FILE_REF" format that includes file path, size, and MIME type. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn load_blob_from_file( app: AppHandle, @@ -3957,14 +4020,14 @@ pub async fn load_blob_from_file( /// Detects the MIME type from a small base64-encoded header (first ~8KB). /// Returns only the MIME type string — the frontend constructs the wire format /// locally, avoiding a full round-trip of the entire file over IPC. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn detect_mime_type(header_base64: String) -> Result { crate::application::records::detect_mime_type(&header_base64) } /// Gets file statistics (size and MIME type) without reading the entire file. /// Used after streaming upload to construct the final wire format. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_file_stats(file_path: String) -> Result { use std::io::Read; @@ -3995,7 +4058,7 @@ pub fn get_file_stats(file_path: String) -> Result { /// Reads a file from disk and returns it as a base64-encoded data URL. /// Used for image preview of BLOB_FILE_REF values without requiring frontend FS permissions. /// Only available for image files; returns an error for non-image MIME types. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn read_file_as_data_url(file_path: String) -> Result { use base64::Engine; use std::io::Read; @@ -4030,6 +4093,7 @@ pub async fn read_file_as_data_url(file_path: String) -> Result .map_err(|e| format!("Task join error: {}", e))? } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn insert_record( app: AppHandle, @@ -4059,6 +4123,7 @@ pub(crate) fn cancel_query_impl( crate::application::queries::cancel_registered_queries(state, None, connection_id, None) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_query( state: State<'_, QueryCancellationState>, @@ -4067,6 +4132,7 @@ pub async fn cancel_query( crate::application::queries::cancel_query(&state, None, &connection_id, None) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn execute_query( app: AppHandle, @@ -4095,6 +4161,7 @@ pub async fn execute_query( .await } +#[cfg(feature = "desktop")] pub(crate) async fn release_connection_sessions( app: &AppHandle, connection_id: &str, @@ -4108,6 +4175,7 @@ pub(crate) async fn release_connection_sessions( .await; } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn release_query_session( app: AppHandle, @@ -4135,6 +4203,7 @@ pub async fn release_query_session( /// When `batch_id` is supplied, a `batch-statement-complete` event is emitted /// after each statement so the UI updates result tabs progressively. The full /// `Vec` is still returned at the end for final reconciliation / fallback. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn execute_query_batch( app: AppHandle, @@ -4167,6 +4236,7 @@ pub async fn execute_query_batch( // --- Explain Query Plan --- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn explain_query_plan( app: AppHandle, @@ -4224,6 +4294,7 @@ pub(crate) async fn read_in_open_transaction( // --- Count Query --- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn count_query( app: AppHandle, @@ -4257,6 +4328,7 @@ pub async fn count_query( /// See: https://github.com/tauri-apps/tauri/issues/13749 /// /// This workaround should be removed once the upstream issue is resolved. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_window_title(app: AppHandle, title: String) -> Result<(), String> { // Get the main window @@ -4272,7 +4344,9 @@ pub async fn set_window_title(app: AppHandle, title: String) -> Result<(), Strin // Apply Wayland-specific workaround on Linux #[cfg(target_os = "linux")] { + #[cfg(feature = "desktop")] use gtk::prelude::{BinExt, Cast, GtkWindowExt, HeaderBarExt}; + #[cfg(feature = "desktop")] use gtk::{EventBox, HeaderBar}; // Get the GTK window @@ -4297,6 +4371,7 @@ pub async fn set_window_title(app: AppHandle, title: String) -> Result<(), Strin Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_er_diagram_window( app: AppHandle, @@ -4307,6 +4382,7 @@ pub async fn open_er_diagram_window( schema: Option, database: Option, ) -> Result<(), String> { + #[cfg(feature = "desktop")] use tauri::{WebviewUrl, WebviewWindowBuilder}; use urlencoding::encode; @@ -4518,6 +4594,7 @@ fn resolve_ssh_test_password( // ==================== View Management Commands ==================== +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_views( app: AppHandle, @@ -4535,6 +4612,7 @@ pub async fn get_views( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_view_definition( app: AppHandle, @@ -4554,6 +4632,7 @@ pub async fn get_view_definition( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_view( app: AppHandle, @@ -4575,6 +4654,7 @@ pub async fn create_view( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn alter_view( app: AppHandle, @@ -4596,6 +4676,7 @@ pub async fn alter_view( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_view( app: AppHandle, @@ -4615,6 +4696,7 @@ pub async fn drop_view( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_view_columns( app: AppHandle, @@ -4634,6 +4716,7 @@ pub async fn get_view_columns( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_materialized_views( app: AppHandle, @@ -4651,6 +4734,7 @@ pub async fn get_materialized_views( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_materialized_view_columns( app: AppHandle, @@ -4670,6 +4754,7 @@ pub async fn get_materialized_view_columns( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_materialized_view_definition( app: AppHandle, @@ -4689,6 +4774,7 @@ pub async fn get_materialized_view_definition( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn refresh_materialized_view( app: AppHandle, @@ -4708,6 +4794,7 @@ pub async fn refresh_materialized_view( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_triggers( app: AppHandle, @@ -4725,6 +4812,7 @@ pub async fn get_triggers( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_trigger_definition( app: AppHandle, @@ -4746,6 +4834,7 @@ pub async fn get_trigger_definition( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_trigger( app: AppHandle, @@ -4765,6 +4854,7 @@ pub async fn create_trigger( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_trigger( app: AppHandle, @@ -4788,6 +4878,7 @@ pub async fn drop_trigger( // --- User management (gated by `DriverCapabilities::user_management`) ------- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_db_privilege_catalog( app: AppHandle, @@ -4800,6 +4891,7 @@ pub async fn get_db_privilege_catalog( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_db_users( app: AppHandle, @@ -4813,6 +4905,7 @@ pub async fn get_db_users( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_db_user_grants( app: AppHandle, @@ -4830,6 +4923,7 @@ pub async fn get_db_user_grants( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_db_user( app: AppHandle, @@ -4849,6 +4943,7 @@ pub async fn create_db_user( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_db_user( app: AppHandle, @@ -4866,6 +4961,7 @@ pub async fn drop_db_user( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_db_user_password( app: AppHandle, @@ -4885,6 +4981,7 @@ pub async fn set_db_user_password( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_db_user_privileges( app: AppHandle, @@ -4902,6 +4999,7 @@ pub async fn get_db_user_privileges( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn apply_db_user_privileges( app: AppHandle, @@ -4928,6 +5026,7 @@ pub async fn apply_db_user_privileges( } /// Register a connection as active for health-check pinging. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn register_active_connection(app: AppHandle, connection_id: String) { crate::application::connections::register_active_connection( @@ -4941,12 +5040,13 @@ pub async fn register_active_connection(app: AppHandle, connectio /// Snapshot of connection ids currently open in the shared backend (across all /// windows). Used by each window to render cross-window connection status. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_active_connections() -> Vec { crate::health_check::active_connections().await } /// Disconnect from a database connection by closing all of its connection pools +#[cfg(feature = "desktop")] #[tauri::command] pub async fn disconnect_connection( app: AppHandle, @@ -4963,7 +5063,7 @@ pub async fn disconnect_connection( // --- Type Registry --- -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_data_types(driver: String) -> Result { log::debug!("Fetching data types for driver: {}", driver); @@ -4975,6 +5075,7 @@ pub async fn get_data_types(driver: String) -> Result( app: AppHandle, @@ -5054,6 +5155,7 @@ pub(crate) fn sql_builder_params( params } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_create_table_sql( app: AppHandle, @@ -5074,6 +5176,7 @@ pub async fn get_create_table_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_add_column_sql( app: AppHandle, @@ -5094,6 +5197,7 @@ pub async fn get_add_column_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_alter_column_sql( app: AppHandle, @@ -5116,6 +5220,7 @@ pub async fn get_alter_column_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_create_index_sql( app: AppHandle, @@ -5140,6 +5245,7 @@ pub async fn get_create_index_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_create_foreign_key_sql( app: AppHandle, @@ -5174,6 +5280,7 @@ pub async fn get_create_foreign_key_sql( /// explorer build its generic `DROP TABLE`. Only plugins declaring /// `capabilities.drop_table_sql` are asked; every other driver (built-ins /// included) returns `None` without resolving credentials or params. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_drop_table_sql( app: AppHandle, @@ -5192,6 +5299,7 @@ pub async fn get_drop_table_sql( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_index_action( app: AppHandle, @@ -5213,6 +5321,7 @@ pub async fn drop_index_action( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn drop_foreign_key_action( app: AppHandle, @@ -5234,16 +5343,18 @@ pub async fn drop_foreign_key_action( .await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_registered_drivers() -> Vec { crate::drivers::registry::list_drivers().await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_keybindings(app: AppHandle) -> Result { crate::application::persistence::get_keybindings(&app.state::()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_keybindings( app: AppHandle, @@ -5255,7 +5366,7 @@ pub async fn save_keybindings( ) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_driver_manifest( driver_id: String, ) -> Option { @@ -5271,6 +5382,7 @@ pub async fn get_driver_manifest( // ==================== Connection Groups Management ==================== +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connection_groups( app: AppHandle, @@ -5279,6 +5391,7 @@ pub async fn get_connection_groups( persistence::load_groups(&path) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_connections_with_groups( app: AppHandle, @@ -5291,6 +5404,7 @@ pub async fn get_connections_with_groups( persistence::load_connections_file(&path) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_connection_group( app: AppHandle, @@ -5362,6 +5476,7 @@ pub(crate) fn find_child_group<'a>( /// missing segments are created in order. The final segment is returned. /// The hierarchy is created atomically: either every missing segment is /// persisted or none are. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_group_path( app: AppHandle, @@ -5411,6 +5526,7 @@ pub async fn create_group_path( last_created.ok_or_else(|| "Group path resolved to an empty hierarchy".to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_connection_group( app: AppHandle, @@ -5445,6 +5561,7 @@ pub async fn update_connection_group( } /// Re-parent a group. Pass `Some(id)` to make it a child of that group, /// or `None` to make it a top-level root. Cycles are rejected. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn move_group_to_parent( app: AppHandle, @@ -5524,6 +5641,7 @@ pub(crate) fn reject_if_would_create_cycle( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_connection_group( app: AppHandle, @@ -5577,6 +5695,7 @@ pub async fn delete_connection_group( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn move_connection_to_group( app: AppHandle, @@ -5604,6 +5723,7 @@ pub async fn move_connection_to_group( Ok(updated) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn reorder_groups( app: AppHandle, @@ -5622,6 +5742,7 @@ pub async fn reorder_groups( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn reorder_connections_in_group( app: AppHandle, @@ -5640,6 +5761,7 @@ pub async fn reorder_connections_in_group( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_server_now( app: AppHandle, @@ -5653,6 +5775,7 @@ pub async fn get_server_now( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn export_connections_payload( app: AppHandle, @@ -5667,7 +5790,7 @@ pub async fn export_connections_payload( .await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn encrypt_export_payload( payload: ExportPayload, password: String, @@ -5676,7 +5799,7 @@ pub async fn encrypt_export_payload( crate::export_crypto::encrypt(&plaintext, &password) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn decrypt_export_payload( envelope: crate::export_crypto::EncryptedEnvelope, password: String, @@ -5685,6 +5808,7 @@ pub async fn decrypt_export_payload( serde_json::from_str(&plaintext).map_err(|e| format!("Invalid export payload: {e}")) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn import_connections_payload( app: AppHandle, @@ -5693,6 +5817,7 @@ pub async fn import_connections_payload( apply_export_payload(app, payload).await } +#[cfg(feature = "desktop")] /// Merge an `ExportPayload` into the user's stored connections, groups, SSH and /// K8s records, moving any inline secrets into the keychain. Shared by the JSON /// import command above and the foreign-app import flow. diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 6dd2fa7e6..1748c75f1 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -3,7 +3,9 @@ use serde::{Deserialize, Serialize}; use std::fs; use std::path::PathBuf; use std::sync::RwLock; +#[cfg(feature = "desktop")] use tauri::AppHandle; +#[cfg(feature = "desktop")] use tauri::Manager; use std::collections::HashMap; @@ -306,6 +308,7 @@ pub enum MigrationMode { static CONFIG_CACHE: Lazy> = Lazy::new(|| RwLock::new(AppConfig::default())); +#[cfg(feature = "desktop")] pub fn get_config_dir(_app: &AppHandle) -> Option { Some(crate::paths::get_app_config_dir()) } @@ -391,6 +394,7 @@ pub fn is_connection_readonly(config: &AppConfig, connection_id: &str) -> bool { } // Internal load +#[cfg(feature = "desktop")] pub fn load_config_internal(app: &AppHandle) -> AppConfig { if let Some(config_dir) = get_config_dir(app) { let config_path = config_dir.join("config.json"); @@ -409,11 +413,13 @@ pub fn load_config_internal(app: &AppHandle) -> AppConfig default_config } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_config(app: AppHandle) -> AppConfig { crate::application::persistence::load_config(&app.state::()) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_config(app: AppHandle, config: AppConfig) -> Result<(), String> { let runtime = app.state::(); @@ -430,7 +436,7 @@ pub fn save_config(app: AppHandle, config: AppConfig) -> Result<(), String> { let interval = saved .ping_interval .unwrap_or(crate::health_check::DEFAULT_PING_INTERVAL); - tauri::async_runtime::spawn(crate::health_check::restart_ping_loop(app, interval as u64)); + crate::async_rt::spawn(crate::health_check::restart_ping_loop(app, interval as u64)); } Ok(()) } @@ -471,6 +477,7 @@ pub(crate) fn resolve_schema_preference( None } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_schema_preference( app: AppHandle, @@ -484,6 +491,7 @@ pub fn get_schema_preference( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_schema_preference( app: AppHandle, @@ -499,12 +507,14 @@ pub fn set_schema_preference( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_last_active_connection(app: AppHandle) -> Option { crate::application::persistence::load_config(&app.state::()) .last_active_connection_id } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_last_active_connection( app: AppHandle, @@ -516,6 +526,7 @@ pub fn set_last_active_connection( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_last_open_connections(app: AppHandle) -> Vec { crate::application::persistence::load_config(&app.state::()) @@ -523,6 +534,7 @@ pub fn get_last_open_connections(app: AppHandle) -> Vec { .unwrap_or_default() } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_last_open_connections( app: AppHandle, @@ -534,6 +546,7 @@ pub fn set_last_open_connections( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_selected_schemas( app: AppHandle, @@ -547,6 +560,7 @@ pub fn get_selected_schemas( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_selected_schemas( app: AppHandle, @@ -562,6 +576,7 @@ pub fn set_selected_schemas( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_ai_key(app: AppHandle, provider: String, key: String) -> Result<(), String> { crate::application::ai::set_key( @@ -572,6 +587,7 @@ pub fn set_ai_key(app: AppHandle, provider: String, key: String) -> Result<(), S ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn delete_ai_key(app: AppHandle, provider: String) -> Result<(), String> { crate::application::ai::delete_key( @@ -581,6 +597,7 @@ pub fn delete_ai_key(app: AppHandle, provider: String) -> Result<(), String> { ) } +#[cfg(feature = "desktop")] /// Get the configured maximum BLOB size in bytes, or DEFAULT_MAX_BLOB_SIZE if not set pub fn get_max_blob_size(app: &AppHandle) -> u64 { let config = load_config_internal(app); @@ -589,6 +606,7 @@ pub fn get_max_blob_size(app: &AppHandle) -> u64 { .unwrap_or(crate::drivers::common::DEFAULT_MAX_BLOB_SIZE) } +#[cfg(feature = "desktop")] pub fn get_ai_api_key(app: &AppHandle, provider: &str) -> Result { // 1. Try Keychain First (Override) — via the in-memory credential cache so // repeated lookups don't trigger a macOS Keychain authorization prompt @@ -632,6 +650,7 @@ pub struct AiKeyStatus { pub from_env: bool, } +#[cfg(feature = "desktop")] pub fn get_ai_api_key_status(app: &AppHandle, provider: &str) -> AiKeyStatus { // 1. Check Keychain (through the cache to avoid repeated auth prompts) let cache = app.state::>(); @@ -678,6 +697,7 @@ pub fn get_ai_api_key_status(app: &AppHandle, provider: &str) -> AiKeyStatus { } } +#[cfg(feature = "desktop")] #[tauri::command] pub fn check_ai_key(app: AppHandle, provider: String) -> bool { crate::application::ai::get_api_key( @@ -688,6 +708,7 @@ pub fn check_ai_key(app: AppHandle, provider: String) -> bool { .is_ok() } +#[cfg(feature = "desktop")] #[tauri::command] pub fn check_ai_key_status( app: AppHandle, @@ -700,6 +721,7 @@ pub fn check_ai_key_status( ) } +#[cfg(feature = "desktop")] fn prompt_kind(app: &AppHandle, kind: crate::application::persistence::PromptKind) -> String { crate::application::persistence::get_prompt( &app.state::(), @@ -707,6 +729,7 @@ fn prompt_kind(app: &AppHandle, kind: crate::application::persistence::PromptKin ) } +#[cfg(feature = "desktop")] fn save_prompt_kind( app: &AppHandle, kind: crate::application::persistence::PromptKind, @@ -719,6 +742,7 @@ fn save_prompt_kind( ) } +#[cfg(feature = "desktop")] fn reset_prompt_kind( app: &AppHandle, kind: crate::application::persistence::PromptKind, @@ -729,10 +753,12 @@ fn reset_prompt_kind( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_system_prompt(app: AppHandle) -> String { prompt_kind(&app, crate::application::persistence::PromptKind::System) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_system_prompt(app: AppHandle, prompt: String) -> Result<(), String> { save_prompt_kind( @@ -741,15 +767,18 @@ pub fn save_system_prompt(app: AppHandle, prompt: String) -> Result<(), String> &prompt, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn reset_system_prompt(app: AppHandle) -> Result { reset_prompt_kind(&app, crate::application::persistence::PromptKind::System) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_explain_prompt(app: AppHandle) -> String { prompt_kind(&app, crate::application::persistence::PromptKind::Explain) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_explain_prompt(app: AppHandle, prompt: String) -> Result<(), String> { save_prompt_kind( @@ -758,11 +787,13 @@ pub fn save_explain_prompt(app: AppHandle, prompt: String) -> Result<(), String> &prompt, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn reset_explain_prompt(app: AppHandle) -> Result { reset_prompt_kind(&app, crate::application::persistence::PromptKind::Explain) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_explainplan_prompt(app: AppHandle) -> String { prompt_kind( @@ -770,6 +801,7 @@ pub fn get_explainplan_prompt(app: AppHandle) -> String { crate::application::persistence::PromptKind::ExplainPlan, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_explainplan_prompt(app: AppHandle, prompt: String) -> Result<(), String> { save_prompt_kind( @@ -778,6 +810,7 @@ pub fn save_explainplan_prompt(app: AppHandle, prompt: String) -> Result<(), Str &prompt, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn reset_explainplan_prompt(app: AppHandle) -> Result { reset_prompt_kind( @@ -786,10 +819,12 @@ pub fn reset_explainplan_prompt(app: AppHandle) -> Result { ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_cellname_prompt(app: AppHandle) -> String { prompt_kind(&app, crate::application::persistence::PromptKind::CellName) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_cellname_prompt(app: AppHandle, prompt: String) -> Result<(), String> { save_prompt_kind( @@ -798,15 +833,18 @@ pub fn save_cellname_prompt(app: AppHandle, prompt: String) -> Result<(), String &prompt, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn reset_cellname_prompt(app: AppHandle) -> Result { reset_prompt_kind(&app, crate::application::persistence::PromptKind::CellName) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_tabrename_prompt(app: AppHandle) -> String { prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_tabrename_prompt(app: AppHandle, prompt: String) -> Result<(), String> { save_prompt_kind( @@ -815,11 +853,13 @@ pub fn save_tabrename_prompt(app: AppHandle, prompt: String) -> Result<(), Strin &prompt, ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn reset_tabrename_prompt(app: AppHandle) -> Result { reset_prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_config_json(app: AppHandle) -> Result { crate::application::persistence::get_config_json_for_desktop( @@ -827,12 +867,14 @@ pub fn get_config_json(app: AppHandle) -> Result { ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn relaunch_app(app: AppHandle) { crate::window_placement::persist_cached(&app); app.restart(); } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_config_json(app: AppHandle, json: String) -> Result<(), String> { crate::application::persistence::save_config_json_for_desktop( diff --git a/src-tauri/src/connection_appearance.rs b/src-tauri/src/connection_appearance.rs index e44466167..d404e14f4 100644 --- a/src-tauri/src/connection_appearance.rs +++ b/src-tauri/src/connection_appearance.rs @@ -1,6 +1,7 @@ use std::fs; use std::path::Path; use sha2::{Digest, Sha256}; +#[cfg(feature = "desktop")] use tauri::AppHandle; pub(crate) const MAX_ICON_BYTES: u64 = 512 * 1024; @@ -175,6 +176,7 @@ pub fn copy_icon_for_duplicate( Ok(format!("connection-icons/{filename}")) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_connection_icon( _app: AppHandle, @@ -187,6 +189,7 @@ pub async fn save_connection_icon( .map_err(|e| e.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_connection_icon( _app: AppHandle, diff --git a/src-tauri/src/connection_import_commands.rs b/src-tauri/src/connection_import_commands.rs index 7f4a98379..6e620e60f 100644 --- a/src-tauri/src/connection_import_commands.rs +++ b/src-tauri/src/connection_import_commands.rs @@ -1,5 +1,6 @@ //! Desktop transport wrappers for shared connection import and export services. +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; use crate::application::connection_files::{ @@ -11,6 +12,7 @@ use crate::models::ExportPayload; pub use crate::application::connection_files::ImportEnvelopeCache; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn export_connections_file( app: AppHandle, @@ -28,11 +30,12 @@ pub async fn export_connections_file( .await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn list_connection_import_sources() -> Result, String> { connection_files::list_import_sources().await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn preview_connection_import( app: AppHandle, @@ -52,6 +55,7 @@ pub async fn preview_connection_import( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn apply_connection_import( app: AppHandle, @@ -73,6 +77,7 @@ pub async fn apply_connection_import( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn preview_tabularis_import( app: AppHandle, @@ -85,6 +90,7 @@ pub async fn preview_tabularis_import( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn apply_tabularis_import( app: AppHandle, @@ -107,6 +113,7 @@ pub async fn apply_tabularis_import( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn preview_tabularis_import_file( app: AppHandle, @@ -124,6 +131,7 @@ pub async fn preview_tabularis_import_file( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn apply_prepared_tabularis_import( app: AppHandle, diff --git a/src-tauri/src/connection_tags.rs b/src-tauri/src/connection_tags.rs index 2c0757e4d..6c2edcb64 100644 --- a/src-tauri/src/connection_tags.rs +++ b/src-tauri/src/connection_tags.rs @@ -2,9 +2,11 @@ //! `connections.json` next to the groups. Tags are purely organizational; //! assignment lives on `SavedConnection.tag_ids`. +#[cfg(feature = "desktop")] use tauri::{AppHandle, Runtime}; use uuid::Uuid; +#[cfg(feature = "desktop")] use crate::commands::{get_config_path, save_connections_and_invalidate}; use crate::models::{ConnectionTag, ConnectionsFile}; use crate::persistence; @@ -172,6 +174,7 @@ pub fn merge_imported_tags( // ---------- Tauri commands ---------- +#[cfg(feature = "desktop")] #[tauri::command] pub async fn list_connection_tags( app: AppHandle, @@ -180,6 +183,7 @@ pub async fn list_connection_tags( Ok(persistence::load_connections_file(&path)?.tags) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_connection_tag( app: AppHandle, @@ -193,6 +197,7 @@ pub async fn create_connection_tag( Ok(tag) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_connection_tag( app: AppHandle, @@ -206,6 +211,7 @@ pub async fn update_connection_tag( save_connections_and_invalidate(&app, &path, &file) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_connection_tag( app: AppHandle, @@ -217,6 +223,7 @@ pub async fn delete_connection_tag( save_connections_and_invalidate(&app, &path, &file) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_connection_tags( app: AppHandle, diff --git a/src-tauri/src/connection_window.rs b/src-tauri/src/connection_window.rs index 525c2c436..7858b4b76 100644 --- a/src-tauri/src/connection_window.rs +++ b/src-tauri/src/connection_window.rs @@ -1,3 +1,4 @@ +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use urlencoding::encode; @@ -29,6 +30,7 @@ pub fn connection_route(connection_id: &str) -> String { /// Open (or focus) a standalone window bound to a specific connection. The new /// window loads the shared connections route with a `connect` query parameter, /// which the frontend reads on startup to auto-connect and jump to the editor. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_connection_window( app: AppHandle, @@ -74,7 +76,7 @@ pub async fn open_connection_window( if let WindowEvent::CloseRequested { .. } = event { let app = close_app.clone(); let connection_id = close_connection_id.clone(); - tauri::async_runtime::spawn(async move { + crate::async_rt::spawn(async move { if let Err(e) = crate::commands::disconnect_connection(app, connection_id.clone()).await { diff --git a/src-tauri/src/dump_commands.rs b/src-tauri/src/dump_commands.rs index 9265866b5..41c8b9f92 100644 --- a/src-tauri/src/dump_commands.rs +++ b/src-tauri/src/dump_commands.rs @@ -3,8 +3,10 @@ use crate::application::database_transfers::{self, DumpDestination, ImportSource pub use crate::application::database_transfers::{DumpCancellationState, DumpOptions}; use crate::runtime::RuntimeContext; use std::path::PathBuf; +#[cfg(feature = "desktop")] use tauri::State; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_dump( state: State<'_, DumpCancellationState>, @@ -13,6 +15,7 @@ pub async fn cancel_dump( database_transfers::cancel_job(state.inner(), None, JobKind::Dump, &connection_id) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn dump_database( runtime: State<'_, RuntimeContext>, @@ -36,6 +39,7 @@ pub async fn dump_database( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_import( state: State<'_, DumpCancellationState>, @@ -44,6 +48,7 @@ pub async fn cancel_import( database_transfers::cancel_job(state.inner(), None, JobKind::Import, &connection_id) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn import_database( runtime: State<'_, RuntimeContext>, diff --git a/src-tauri/src/e2e_dialog_mock.rs b/src-tauri/src/e2e_dialog_mock.rs index 955ad0c85..0eed11fe8 100644 --- a/src-tauri/src/e2e_dialog_mock.rs +++ b/src-tauri/src/e2e_dialog_mock.rs @@ -22,6 +22,7 @@ //! / `Value::Null` satisfy. use serde_json::{json, Value}; +#[cfg(feature = "desktop")] use tauri::{plugin::{Builder, TauriPlugin}, Runtime}; fn env_path(var: &str) -> Value { @@ -31,27 +32,27 @@ fn env_path(var: &str) -> Value { } } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] async fn ask(_message: Value, _title: Option, _kind: Option, _yes_button_label: Option, _no_button_label: Option) -> Result { Ok(json!(true)) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] async fn confirm(_message: Value, _title: Option, _kind: Option, _ok_button_label: Option, _cancel_button_label: Option) -> Result { Ok(json!(true)) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] async fn message(_message: Value, _title: Option, _kind: Option, _ok_button_label: Option, _buttons: Option) -> Result { Ok(Value::Null) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] async fn open(_options: Value) -> Result { Ok(env_path("E2E_DIALOG_OPEN_PATH")) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] async fn save(_options: Value) -> Result { Ok(env_path("E2E_DIALOG_SAVE_PATH")) } diff --git a/src-tauri/src/explain_import.rs b/src-tauri/src/explain_import.rs index 350546605..1592a965f 100644 --- a/src-tauri/src/explain_import.rs +++ b/src-tauri/src/explain_import.rs @@ -9,6 +9,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use serde::{Deserialize, Serialize}; +#[cfg(feature = "desktop")] use tauri::{Manager, Runtime, State}; /// A plan file read from disk, parsed on the frontend by `@tabularis/explain`. @@ -44,7 +45,7 @@ impl PendingExplainFile { /// /// The content comes back untouched; the frontend sniffs the format and /// parses it with `@tabularis/explain`. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn load_explain_from_file(path: String) -> Result { load_from_file(&path).await } @@ -53,11 +54,13 @@ pub async fn load_explain_from_file(path: String) -> Result) -> Option { state.take() } +#[cfg(feature = "desktop")] /// Creates (or focuses) the standalone Visual Explain window. /// /// Runs fully synchronously so it can be invoked from the Tauri `setup` hook @@ -66,6 +69,7 @@ pub fn spawn_visual_explain_window>( app: &M, file: Option, ) -> Result<(), String> { + #[cfg(feature = "desktop")] use tauri::{WebviewUrl, WebviewWindowBuilder}; if let Some(path) = file.as_ref() { @@ -98,6 +102,7 @@ pub fn spawn_visual_explain_window>( } /// Tauri command wrapper around [`spawn_visual_explain_window`]. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_visual_explain_window( app: tauri::AppHandle, diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs index 34ef4b22c..6d9b9926f 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -15,6 +15,7 @@ use std::path::PathBuf; use std::sync::{Arc, Mutex}; use serde_json::Value; +#[cfg(feature = "desktop")] use tauri::State; use crate::commands::AbortHandleMap; @@ -34,6 +35,7 @@ impl Default for ExportCancellationState { } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_export( state: State<'_, ExportCancellationState>, @@ -42,6 +44,7 @@ pub async fn cancel_export( crate::application::generic_exports::cancel_export(state.inner(), None, &connection_id) } +#[cfg(feature = "desktop")] #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn export_query_to_file( diff --git a/src-tauri/src/health_check.rs b/src-tauri/src/health_check.rs index fcfcb66b2..891beb475 100644 --- a/src-tauri/src/health_check.rs +++ b/src-tauri/src/health_check.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use std::time::Duration; use once_cell::sync::Lazy; +#[cfg(feature = "desktop")] use tauri::Emitter; use tokio::sync::{oneshot, Mutex, RwLock}; @@ -42,6 +43,7 @@ pub async fn active_connections() -> Vec { ACTIVE_CONNECTIONS.read().await.iter().cloned().collect() } +#[cfg(feature = "desktop")] /// Broadcast the current active-connection set to all windows. pub async fn emit_active_changed(app: &tauri::AppHandle) { let ids = active_connections().await; @@ -54,6 +56,7 @@ pub async fn emit_active_changed(app: &tauri::AppHandle) { } } +#[cfg(feature = "desktop")] /// Start the periodic ping loop. If a loop is already running it is stopped first. pub async fn start_ping_loop(app: tauri::AppHandle, interval_secs: u64) { // Stop any existing loop @@ -101,12 +104,14 @@ pub async fn stop_ping_loop() { } } +#[cfg(feature = "desktop")] /// Restart the ping loop with a new interval. pub async fn restart_ping_loop(app: tauri::AppHandle, interval_secs: u64) { stop_ping_loop().await; start_ping_loop(app, interval_secs).await; } +#[cfg(feature = "desktop")] /// Ping every registered connection. On failure beyond the threshold, /// close the pool and emit an event to the frontend. async fn ping_all_connections(app: &tauri::AppHandle, failure_counts: &mut HashMap) { @@ -158,6 +163,7 @@ async fn ping_all_connections(app: &tauri::AppHandle, failure_counts: &mut HashM } } +#[cfg(feature = "desktop")] /// Ping a single connection by resolving its params and calling driver.ping(). async fn ping_single_connection(app: &tauri::AppHandle, connection_id: &str) -> Result<(), String> { let saved_conn = crate::commands::find_connection_by_id(app, connection_id)?; @@ -184,6 +190,7 @@ async fn ping_single_connection(app: &tauri::AppHandle, connection_id: &str) -> .map_err(|_| "Ping timed out".to_string())? } +#[cfg(feature = "desktop")] /// Close the pool, unregister the connection, and emit a failure event. async fn handle_connection_failure(app: &tauri::AppHandle, connection_id: &str, error: &str) { // Unregister first to prevent further pings. diff --git a/src-tauri/src/heartbeat.rs b/src-tauri/src/heartbeat.rs index 78c5374f6..5a8aa7a03 100644 --- a/src-tauri/src/heartbeat.rs +++ b/src-tauri/src/heartbeat.rs @@ -97,7 +97,7 @@ pub fn is_alive() -> bool { /// Owns the approval host ticker; dropping it stops refreshing the shared file. #[must_use = "Keep the heartbeat task alive for the lifetime of the approval host"] -pub struct HeartbeatTask(tauri::async_runtime::JoinHandle<()>); +pub struct HeartbeatTask(crate::async_rt::JoinHandle<()>); impl HeartbeatTask { pub fn stop(&self) { @@ -117,7 +117,7 @@ pub fn spawn_in(base: PathBuf) -> HeartbeatTask { if let Err(error) = write_now_in(&base) { log::warn!("Failed to write initial heartbeat: {}", error); } - let task = tauri::async_runtime::spawn(async move { + let task = crate::async_rt::spawn(async move { let mut ticker = tokio::time::interval(TICK_INTERVAL); ticker.tick().await; loop { diff --git a/src-tauri/src/json_viewer.rs b/src-tauri/src/json_viewer.rs index efeb7dc8d..91d90512f 100644 --- a/src-tauri/src/json_viewer.rs +++ b/src-tauri/src/json_viewer.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::sync::Mutex; use serde::{Deserialize, Serialize}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use ulid::Ulid; use urlencoding::encode; @@ -36,6 +37,7 @@ pub struct JsonViewerStore { pub last_bounds: Mutex>, } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_json_viewer_window( app: AppHandle, @@ -180,6 +182,7 @@ pub async fn open_json_viewer_window( } } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_json_viewer_session( store: State<'_, JsonViewerStore>, @@ -195,6 +198,7 @@ pub async fn get_json_viewer_session( .ok_or_else(|| format!("JSON viewer session '{}' not found", session_id)) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn complete_json_viewer_session( app: AppHandle, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 588bd1e37..951a309a2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,8 @@ +// ponytail: without `desktop`, helpers used only by Tauri command wrappers go +// unused; silenced here instead of gating each one. The desktop build still +// reports real dead code. +#![cfg_attr(not(feature = "desktop"), allow(unused_imports, dead_code))] + pub mod ai; pub mod ai_activity; #[cfg(test)] @@ -8,6 +13,7 @@ pub mod ai_approval; #[cfg(test)] pub mod ai_approval_tests; pub mod ai_approval_watcher; +#[cfg(feature = "desktop")] pub mod ai_commands; pub mod ai_notebook_export; #[cfg(test)] @@ -30,11 +36,13 @@ pub mod connection_cache; #[cfg(test)] pub mod connection_cache_tests; pub mod connection_import; +#[cfg(feature = "desktop")] pub mod connection_import_commands; pub mod connection_migrations; #[cfg(test)] pub mod connection_migrations_tests; pub mod connection_tags; +#[cfg(feature = "desktop")] pub mod connection_window; #[cfg(test)] pub mod connection_window_tests; @@ -70,6 +78,7 @@ pub mod mcp; pub mod models; #[cfg(test)] pub mod models_tests; +#[cfg(feature = "desktop")] pub mod notebooks; pub mod paths; // Added #[cfg(test)] @@ -111,24 +120,39 @@ pub mod ssm_tunnel; pub mod storage_location; #[cfg(test)] pub mod storage_location_tests; +#[cfg(feature = "desktop")] mod system_theme; +#[cfg(feature = "desktop")] pub mod task_manager; pub mod team_share; +#[cfg(feature = "desktop")] pub mod theme_commands; pub mod theme_models; pub mod theme_packages; pub mod transport; pub mod ui_state; +#[cfg(feature = "desktop")] pub mod ui_state_commands; #[cfg(test)] pub mod ui_state_tests; +#[cfg(feature = "desktop")] pub mod updater; +#[cfg(feature = "desktop")] pub mod window_decorations; // E2E-only mock of the `dialog` plugin (auto-accepts ask/confirm, stubs // open/save via env vars). Only compiled with --features e2e-testing. #[cfg(feature = "e2e-testing")] pub mod e2e_dialog_mock; +#[cfg(feature = "desktop")] mod window_placement; +/// Tauri's global runtime in the desktop app; the ambient Tokio runtime of +/// `tabularis web` and `--mcp` otherwise. +pub mod async_rt { + #[cfg(feature = "desktop")] + pub use tauri::async_runtime::{spawn, spawn_blocking, JoinHandle}; + #[cfg(not(feature = "desktop"))] + pub use tokio::task::{spawn, spawn_blocking, JoinHandle}; +} pub mod drivers { pub mod common; pub mod driver_trait; @@ -146,21 +170,24 @@ pub mod drivers { pub mod sqlite; } +#[cfg(feature = "desktop")] use tauri::Manager; pub use runtime::bootstrap::get_log_buffer; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] fn is_debug_mode() -> bool { runtime::bootstrap::is_debug_mode() } +#[cfg(feature = "desktop")] #[tauri::command] fn open_devtools(window: tauri::WebviewWindow) { window.open_devtools(); log::info!("DevTools opened"); } +#[cfg(feature = "desktop")] #[tauri::command] fn close_devtools(window: tauri::WebviewWindow) { window.close_devtools(); @@ -263,6 +290,18 @@ pub fn run() { return; } + #[cfg(feature = "desktop")] + run_desktop(args, log_buffer); + #[cfg(not(feature = "desktop"))] + { + drop(log_buffer); + eprintln!("This build has no desktop app. Run `tabularis web` or `tabularis --mcp`."); + std::process::exit(2); + } +} + +#[cfg(feature = "desktop")] +fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { // Log startup message log::info!("Tabularis application starting..."); if args.debug { @@ -436,6 +475,7 @@ pub fn run() { // has neither `xdg-mime` nor write access to the host's // mimeapps.list — so skip the call instead of logging a failure. { + #[cfg(feature = "desktop")] use tauri_plugin_deep_link::DeepLinkExt; let handle = app.handle().clone(); let deep_link = app.deep_link(); diff --git a/src-tauri/src/log_commands.rs b/src-tauri/src/log_commands.rs index aaf25b712..18b6de232 100644 --- a/src-tauri/src/log_commands.rs +++ b/src-tauri/src/log_commands.rs @@ -1,35 +1,42 @@ use crate::application::operations; use crate::logger::{LogEntry, SharedLogBuffer}; use std::path::PathBuf; +#[cfg(feature = "desktop")] use tauri::State; pub use operations::{GetLogsRequest, LogSettings}; +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_logs(log_buffer: State, request: GetLogsRequest) -> Vec { operations::get_logs(log_buffer.inner(), request) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn clear_logs(log_buffer: State) -> Result<(), String> { operations::clear_logs(log_buffer.inner()) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn get_log_settings(log_buffer: State) -> LogSettings { operations::get_log_settings(log_buffer.inner()) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_log_enabled(log_buffer: State, enabled: bool) -> Result<(), String> { operations::set_log_enabled(log_buffer.inner(), enabled) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_log_max_size(log_buffer: State, max_size: usize) -> Result<(), String> { operations::set_log_max_size(log_buffer.inner(), max_size) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn export_logs( runtime: State<'_, crate::runtime::RuntimeContext>, @@ -49,7 +56,7 @@ pub async fn export_logs( /// Lets the frontend record user-relevant events (e.g. a database pruned from /// a connection's selection) in the activity log shown in Settings → Logs. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn log_frontend_event(level: String, message: String) { match level.as_str() { "error" => log::error!(target: "frontend", "{}", message), @@ -60,7 +67,7 @@ pub fn log_frontend_event(level: String, message: String) { } } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn test_log() -> Result<(), String> { log::info!("Test log message from frontend"); log::debug!("Debug test message: {}", 42); diff --git a/src-tauri/src/mcp/install.rs b/src-tauri/src/mcp/install.rs index 2ba1948fd..05ccd1b59 100644 --- a/src-tauri/src/mcp/install.rs +++ b/src-tauri/src/mcp/install.rs @@ -1,5 +1,7 @@ +#[cfg(feature = "desktop")] use tauri::{AppHandle, Runtime}; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_mcp_status( _app: AppHandle, @@ -7,6 +9,7 @@ pub async fn get_mcp_status( crate::application::mcp_host::get_status().await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn install_mcp_config( _app: AppHandle, diff --git a/src-tauri/src/notebooks.rs b/src-tauri/src/notebooks.rs index c349b8725..f5f546f31 100644 --- a/src-tauri/src/notebooks.rs +++ b/src-tauri/src/notebooks.rs @@ -3,7 +3,7 @@ use crate::paths::get_app_config_dir; pub use crate::application::notebooks::NotebookMetadata; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn create_notebook( connection_id: String, notebook_id: String, @@ -20,7 +20,7 @@ pub async fn create_notebook( Ok(()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn save_notebook( connection_id: String, notebook_id: String, @@ -37,7 +37,7 @@ pub async fn save_notebook( Ok(()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn load_notebook( connection_id: String, notebook_id: String, @@ -52,7 +52,7 @@ pub async fn load_notebook( serde_json::from_value(value).map_err(|error| error.to_string()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Result<(), String> { execute( &get_app_config_dir(), @@ -64,7 +64,7 @@ pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Resu Ok(()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn rename_notebook( connection_id: String, notebook_id: String, @@ -81,7 +81,7 @@ pub async fn rename_notebook( Ok(()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn list_notebooks(connection_id: String) -> Result, String> { let value = execute( &get_app_config_dir(), diff --git a/src-tauri/src/plugins/commands.rs b/src-tauri/src/plugins/commands.rs index 9c340da7e..9785ad037 100644 --- a/src-tauri/src/plugins/commands.rs +++ b/src-tauri/src/plugins/commands.rs @@ -2,8 +2,10 @@ use crate::drivers::driver_trait::PluginManifest; use crate::plugins::installer::{self, InstalledPluginInfo}; use crate::plugins::registry::{PluginReadme, RegistryPluginWithStatus}; use crate::runtime::RuntimeContext; +#[cfg(feature = "desktop")] use tauri::{AppHandle, State}; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_plugin_registry( runtime: State<'_, RuntimeContext>, @@ -11,6 +13,7 @@ pub async fn fetch_plugin_registry( crate::application::plugins::fetch_plugin_registry(runtime.inner()).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn install_plugin( runtime: State<'_, RuntimeContext>, @@ -22,11 +25,12 @@ pub async fn install_plugin( .await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_plugin_install(plugin_id: String) -> bool { crate::application::plugins::cancel_plugin_install(plugin_id).unwrap_or(false) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn uninstall_plugin( runtime: State<'_, RuntimeContext>, @@ -35,6 +39,7 @@ pub async fn uninstall_plugin( crate::application::plugins::uninstall_plugin(runtime.inner(), plugin_id).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_installed_plugins( runtime: State<'_, RuntimeContext>, @@ -44,11 +49,12 @@ pub async fn get_installed_plugins( )) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn disable_plugin(plugin_id: String) -> Result<(), String> { crate::application::plugins::disable_plugin(plugin_id).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn enable_plugin( runtime: State<'_, RuntimeContext>, @@ -57,6 +63,7 @@ pub async fn enable_plugin( crate::application::plugins::enable_plugin(runtime.inner(), plugin_id).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_plugin_manifest( runtime: State<'_, RuntimeContext>, @@ -67,7 +74,7 @@ pub async fn get_plugin_manifest( /// Returns the absolute filesystem path of an installed plugin's directory. /// Desktop-only: browser RPC deliberately does not expose server filesystem paths. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_plugin_dir(plugin_id: String) -> Result { let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; plugin_dir @@ -78,8 +85,10 @@ pub fn get_plugin_dir(plugin_id: String) -> Result { /// Opens the plugins directory in the desktop file manager. /// Browser sessions never receive an equivalent server-path operation. +#[cfg(feature = "desktop")] #[tauri::command] pub fn open_plugins_dir(app: AppHandle) -> Result<(), String> { + #[cfg(feature = "desktop")] use tauri_plugin_opener::OpenerExt; let plugins_dir = installer::get_plugins_dir()?; app.opener() @@ -87,6 +96,7 @@ pub fn open_plugins_dir(app: AppHandle) -> Result<(), String> { .map_err(|error| format!("Failed to open plugins directory: {error}")) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_tabularium_plugin_preview( runtime: State<'_, RuntimeContext>, @@ -98,6 +108,7 @@ pub async fn fetch_tabularium_plugin_preview( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_plugin_readme( runtime: State<'_, RuntimeContext>, @@ -111,6 +122,7 @@ pub async fn fetch_plugin_readme( /// Reads a file from an installed plugin's directory for the desktop UI loader. /// Browser plugin assets use the authenticated asset route implemented separately. +#[cfg(feature = "desktop")] #[tauri::command] pub fn read_plugin_file( runtime: State<'_, RuntimeContext>, diff --git a/src-tauri/src/plugins/connection_metadata.rs b/src-tauri/src/plugins/connection_metadata.rs index ca1db2f6d..783434cac 100644 --- a/src-tauri/src/plugins/connection_metadata.rs +++ b/src-tauri/src/plugins/connection_metadata.rs @@ -18,9 +18,11 @@ pub struct DriverManifestDetails { pub connection_metadata: Option, } +#[cfg(feature = "desktop")] /// The UI invalidates only discovery-enabled contexts. Emitting for every /// replacement also covers an update that removes a plugin's discovery opt-in. pub async fn notify_plugin_reload(app: &tauri::AppHandle, driver_id: &str) { + #[cfg(feature = "desktop")] use tauri::Emitter; let _ = app.emit( "connection-metadata-invalidated", diff --git a/src-tauri/src/plugins/deep_link.rs b/src-tauri/src/plugins/deep_link.rs index 44bb4d1a1..88e47e52c 100644 --- a/src-tauri/src/plugins/deep_link.rs +++ b/src-tauri/src/plugins/deep_link.rs @@ -24,6 +24,7 @@ use std::sync::Mutex; use serde::{Deserialize, Serialize}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter, Manager}; use url::Url; @@ -136,6 +137,7 @@ fn is_valid_slug(s: &str) -> bool { bytes.iter().all(valid_char) && bytes.first().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) } +#[cfg(feature = "desktop")] /// Dispatch a single URL to the frontend. Called from: /// * the deep-link plugin's `on_open_url` handler (warm handoff), /// * the cold-start `get_current()` path on app boot, @@ -182,6 +184,7 @@ pub fn handle_url(app: &AppHandle, raw: &str) { /// Drains the pending deep-link install request, if any. Called from the /// frontend immediately after the listener mounts to recover URLs that /// arrived during cold-start before the event subscription existed. +#[cfg(feature = "desktop")] #[tauri::command] pub fn consume_pending_deep_link_install( state: tauri::State<'_, PendingInstall>, diff --git a/src-tauri/src/plugins/force_install.rs b/src-tauri/src/plugins/force_install.rs index 7d5f876bc..eb4103e72 100644 --- a/src-tauri/src/plugins/force_install.rs +++ b/src-tauri/src/plugins/force_install.rs @@ -15,6 +15,7 @@ //! [`MIGRATABLE_DRIVERS`] and a call site, not a new function. use serde::Serialize; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter}; use crate::config::{self, AppConfig}; @@ -46,6 +47,7 @@ struct PluginActivatedPayload<'a> { plugin_id: &'a str, } +#[cfg(feature = "desktop")] /// Ensure the plugin for `builtin_id` is installed, but only when at least one /// saved connection is still on the built-in driver. A user with no such /// connection is left untouched — no plugin they don't need. @@ -63,6 +65,7 @@ pub async fn ensure_plugin_installed_if_needed(app: &AppHandle, builtin_id: &str ensure_plugin_installed(app, plugin_id).await; } +#[cfg(feature = "desktop")] /// Install (and activate) `plugin_id` if it isn't already installed and the /// latest release is compatible with this app build. Every failure path /// logs and returns silently — there's no UI-visible error and no retry loop @@ -111,6 +114,7 @@ pub async fn ensure_plugin_installed(app: &AppHandle, plugin_id: &str) { } } +#[cfg(feature = "desktop")] /// Persist `plugin_id` into `active_external_drivers` via the `save_config` /// merge, leaving every other config field untouched. Idempotent: a no-op if /// the id is already active. @@ -185,6 +189,7 @@ pub(crate) fn merge_active_driver( } } +#[cfg(feature = "desktop")] /// True when at least one saved connection has `params.driver == driver_id`. /// Reads the connections file directly via `persistence::load_connections` /// (the same path `get_connections` uses internally) rather than invoking the @@ -196,6 +201,7 @@ fn connections_use_driver(app: &AppHandle, driver_id: &str) -> Result Vec { crate::application::plugins::get_plugin_startup_errors() } @@ -110,6 +111,7 @@ pub struct ConfigManifest { /// swallowed because the built-in of the same id is already registered. const BUILTIN_DRIVER_IDS: [&str; 3] = ["mysql", "postgres", "sqlite"]; +#[cfg(feature = "desktop")] /// Load installed plugins at startup. /// /// `enabled_ids` controls which plugins are started: diff --git a/src-tauri/src/plugins/runtime_version.rs b/src-tauri/src/plugins/runtime_version.rs index 8d0de94b4..b65cf5a01 100644 --- a/src-tauri/src/plugins/runtime_version.rs +++ b/src-tauri/src/plugins/runtime_version.rs @@ -56,7 +56,7 @@ pub fn take_runtime_warnings() -> Vec { std::mem::take(&mut *guard) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_plugin_runtime_warnings() -> Vec { take_runtime_warnings() } diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs index 3ee41845d..4e241cdf2 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -1,5 +1,6 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -8,6 +9,7 @@ pub struct EditorPreferences { pub active_tab_id: Option, } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_editor_preferences( app: AppHandle, @@ -21,6 +23,7 @@ pub async fn save_editor_preferences( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn load_editor_preferences( app: AppHandle, @@ -32,6 +35,7 @@ pub async fn load_editor_preferences( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_editor_preferences( app: AppHandle, @@ -43,6 +47,7 @@ pub async fn delete_editor_preferences( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn list_all_preferences( app: AppHandle, diff --git a/src-tauri/src/proxy/mod.rs b/src-tauri/src/proxy/mod.rs index 5ced6c4bd..8ce27b0dd 100644 --- a/src-tauri/src/proxy/mod.rs +++ b/src-tauri/src/proxy/mod.rs @@ -27,7 +27,7 @@ pub use types::{ use crate::keychain_utils; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn set_proxy_password(slot: String, password: String) -> Result<(), String> { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); @@ -39,7 +39,7 @@ pub fn set_proxy_password(slot: String, password: String) -> Result<(), String> } } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn proxy_password_is_set(slot: String) -> Result { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); @@ -49,7 +49,7 @@ pub fn proxy_password_is_set(slot: String) -> Result { .unwrap_or(false)) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn delete_proxy_password(slot: String) -> Result<(), String> { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); diff --git a/src-tauri/src/query_history.rs b/src-tauri/src/query_history.rs index ece854a37..cf6330cbf 100644 --- a/src-tauri/src/query_history.rs +++ b/src-tauri/src/query_history.rs @@ -1,5 +1,6 @@ use crate::application::productivity::{self, ProductivityCommand}; use serde_json::from_value; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime, State}; pub use crate::application::productivity::backfill_history_entries as backfill_missing_database; @@ -12,6 +13,7 @@ pub use crate::application::productivity::{QueryHistoryEntry, QueryHistoryRespon #[derive(Default)] pub struct QueryHistoryState; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_query_history( app: AppHandle, @@ -30,6 +32,7 @@ pub async fn get_query_history( .map_err(|error| error.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn add_query_history_entry( @@ -65,6 +68,7 @@ pub async fn add_query_history_entry( .map_err(|error| error.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_query_history_entry( app: AppHandle, @@ -82,6 +86,7 @@ pub async fn delete_query_history_entry( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn clear_query_history( app: AppHandle, @@ -98,6 +103,7 @@ pub async fn clear_query_history( Ok(()) } +#[cfg(feature = "desktop")] pub async fn backfill_missing_database_for_connection( app: &AppHandle, connection_id: &str, @@ -108,6 +114,7 @@ pub async fn backfill_missing_database_for_connection( productivity::backfill_query_history_for_connection(config_dir, connection_id, database) } +#[cfg(feature = "desktop")] pub async fn remove_history_for_connection( app: &AppHandle, connection_id: &str, diff --git a/src-tauri/src/results_window.rs b/src-tauri/src/results_window.rs index 879a7e313..327ef73ae 100644 --- a/src-tauri/src/results_window.rs +++ b/src-tauri/src/results_window.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::sync::Mutex; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use urlencoding::encode; @@ -31,6 +32,7 @@ fn window_label(tab_id: &str) -> String { /// Open (or focus) the detached results window for a given tab. Result data is /// streamed from the main window via `resultsSyncEvent(tabId)` in /// `src/utils/resultsWindowSync.ts`, so no payload is passed here. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_results_window( app: AppHandle, @@ -111,6 +113,7 @@ pub async fn open_results_window( /// Programmatically close a tab's detached results window (used by the /// "Re-attach" button and when the bound tab is closed). +#[cfg(feature = "desktop")] #[tauri::command] pub async fn close_results_window(app: AppHandle, tab_id: String) -> Result<(), String> { if let Some(window) = app.get_webview_window(&window_label(&tab_id)) { diff --git a/src-tauri/src/runtime/events.rs b/src-tauri/src/runtime/events.rs index 44b1ac537..87bd3b318 100644 --- a/src-tauri/src/runtime/events.rs +++ b/src-tauri/src/runtime/events.rs @@ -1,4 +1,5 @@ use serde_json::Value; +#[cfg(feature = "desktop")] use tauri::Emitter; pub trait RuntimeEvents: Send + Sync { @@ -18,16 +19,19 @@ impl RuntimeEvents for NoopRuntimeEvents { } } +#[cfg(feature = "desktop")] pub struct TauriRuntimeEvents { app: tauri::AppHandle, } +#[cfg(feature = "desktop")] impl TauriRuntimeEvents { pub fn new(app: tauri::AppHandle) -> Self { Self { app } } } +#[cfg(feature = "desktop")] impl RuntimeEvents for TauriRuntimeEvents { fn emit(&self, event: &str, payload: Value) -> Result<(), String> { self.app diff --git a/src-tauri/src/runtime/lifecycle.rs b/src-tauri/src/runtime/lifecycle.rs index d2ab2c8f3..cba57fbdd 100644 --- a/src-tauri/src/runtime/lifecycle.rs +++ b/src-tauri/src/runtime/lifecycle.rs @@ -38,9 +38,10 @@ pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { crate::drivers::registry::shutdown_external_drivers().await; } +#[cfg(feature = "desktop")] pub fn start_desktop_schedulers(app: tauri::AppHandle, ping_interval_secs: u64) { let health_check_app = app.clone(); - tauri::async_runtime::spawn(async move { + crate::async_rt::spawn(async move { crate::health_check::start_ping_loop(health_check_app, ping_interval_secs).await; }); crate::ai_approval_watcher::spawn(app.clone()); diff --git a/src-tauri/src/runtime/tests.rs b/src-tauri/src/runtime/tests.rs index 3f0ca5854..688ac395e 100644 --- a/src-tauri/src/runtime/tests.rs +++ b/src-tauri/src/runtime/tests.rs @@ -157,6 +157,7 @@ fn shutdown_hooks_run_without_a_tauri_runtime() { #[tokio::test] async fn desktop_productivity_commands_use_the_managed_custom_config_directory() { use crate::{query_history, saved_queries}; + #[cfg(feature = "desktop")] use tauri::Manager; let root = tempfile::tempdir().unwrap(); let config = root.path().join("custom-config"); diff --git a/src-tauri/src/saved_queries.rs b/src-tauri/src/saved_queries.rs index 25511d91a..e19b0bd3c 100644 --- a/src-tauri/src/saved_queries.rs +++ b/src-tauri/src/saved_queries.rs @@ -1,10 +1,12 @@ use crate::application::productivity::{self, ProductivityCommand}; use serde_json::from_value; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; pub use crate::application::productivity::{SavedQuery, SavedQueryMeta}; use crate::saved_query_folders::SavedQueryFolder; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_saved_queries( app: AppHandle, @@ -22,6 +24,7 @@ pub async fn get_saved_queries( .map_err(|error| error.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn save_query( app: AppHandle, @@ -47,6 +50,7 @@ pub async fn save_query( .map_err(|error| error.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn update_saved_query( app: AppHandle, @@ -74,6 +78,7 @@ pub async fn update_saved_query( .map_err(|error| error.to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_saved_query( app: AppHandle, @@ -92,6 +97,7 @@ pub async fn delete_saved_query( pub use crate::application::productivity::backfill_saved_query_metadata as backfill_missing_database; +#[cfg(feature = "desktop")] pub fn backfill_missing_database_for_connection( app: &AppHandle, connection_id: &str, @@ -102,6 +108,7 @@ pub fn backfill_missing_database_for_connection( productivity::backfill_saved_queries_for_connection(config_dir, connection_id, database) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_saved_query_folders( app: AppHandle, @@ -110,6 +117,7 @@ pub async fn get_saved_query_folders( execute_typed(&app, ProductivityCommand::GetSavedQueryFolders { connection_id }).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_saved_query_folder( app: AppHandle, @@ -126,6 +134,7 @@ pub async fn create_saved_query_folder( .await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn rename_saved_query_folder( app: AppHandle, @@ -145,6 +154,7 @@ pub async fn rename_saved_query_folder( } /// Only empty folders can be deleted; see `saved_query_folders::delete_folder`. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_saved_query_folder( app: AppHandle, @@ -159,6 +169,7 @@ pub async fn delete_saved_query_folder( } /// Moves a saved query into a folder, or to Unfiled when `folder_id` is null. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn move_saved_query( app: AppHandle, @@ -177,6 +188,7 @@ pub async fn move_saved_query( .await } +#[cfg(feature = "desktop")] async fn execute_typed( app: &AppHandle, command: ProductivityCommand, diff --git a/src-tauri/src/sql_file.rs b/src-tauri/src/sql_file.rs index 8430c75af..f2133c87c 100644 --- a/src-tauri/src/sql_file.rs +++ b/src-tauri/src/sql_file.rs @@ -50,7 +50,7 @@ pub fn write_sql_file_to_disk(path: &Path, content: &str) -> Result<(), String> .map_err(|e| format!("Failed to write SQL file {}: {}", path.display(), e)) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn read_sql_file(path: String) -> Result { let path = validate_sql_file_path(&path)?; spawn_blocking(move || read_sql_file_from_disk(&path, MAX_SQL_FILE_BYTES)) @@ -58,7 +58,7 @@ pub async fn read_sql_file(path: String) -> Result { .map_err(|e| e.to_string())? } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn write_sql_file(path: String, content: String) -> Result<(), String> { let path = validate_sql_file_path(&path)?; spawn_blocking(move || write_sql_file_to_disk(&path, &content)) diff --git a/src-tauri/src/sqlite_database.rs b/src-tauri/src/sqlite_database.rs index d6b8b48a2..4370ef390 100644 --- a/src-tauri/src/sqlite_database.rs +++ b/src-tauri/src/sqlite_database.rs @@ -3,6 +3,7 @@ use sqlx::sqlite::SqliteConnectOptions; use sqlx::{Connection, Executor, SqliteConnection}; use std::fs::{self, OpenOptions}; use std::path::{Path, PathBuf}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Runtime}; const SQLITE_EXTENSIONS: [&str; 3] = ["db", "sqlite", "sqlite3"]; @@ -101,7 +102,7 @@ pub(crate) async fn initialize_sqlite_file(path: &Path) -> Result<(), String> { Ok(()) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn create_sqlite_file(path: String) -> Result { let path = normalize_sqlite_path(&path)?; initialize_sqlite_file(&path).await?; @@ -111,6 +112,7 @@ pub async fn create_sqlite_file(path: String) -> Result { .ok_or_else(|| "The selected SQLite database path is not valid UTF-8.".to_string()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn create_sqlite_database( app: AppHandle, diff --git a/src-tauri/src/storage_location.rs b/src-tauri/src/storage_location.rs index f5d7fd23f..47524026d 100644 --- a/src-tauri/src/storage_location.rs +++ b/src-tauri/src/storage_location.rs @@ -312,12 +312,12 @@ fn info() -> StorageLocationInfo { } } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_storage_location() -> StorageLocationInfo { info() } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn inspect_storage_location(path: String) -> Result { let target = PathBuf::from(path); validate_target(&target, &crate::paths::get_app_config_dir())?; @@ -326,7 +326,7 @@ pub fn inspect_storage_location(path: String) -> Result Result { let target = PathBuf::from(path); let current = crate::paths::get_app_config_dir(); @@ -352,7 +352,7 @@ pub fn set_storage_location(path: String, copy_data: bool) -> Result Result { clear_pointer(&crate::paths::get_default_app_config_dir())?; log::info!("[StorageLocation] Storage folder reset to default"); @@ -360,8 +360,10 @@ pub fn reset_storage_location() -> Result { } /// Reveal the folder currently in use in the system file manager. +#[cfg(feature = "desktop")] #[tauri::command] pub fn open_storage_location(app: tauri::AppHandle) -> Result<(), String> { + #[cfg(feature = "desktop")] use tauri_plugin_opener::OpenerExt; let dir = crate::paths::get_app_config_dir(); fs::create_dir_all(&dir).map_err(|e| e.to_string())?; @@ -373,7 +375,7 @@ pub fn open_storage_location(app: tauri::AppHandle) -> Result<(), String> { /// Absolute data directory, for the frontend to build `asset://` URLs of /// connection icons. Replaces `appDataDir()` from the Tauri JS API, which /// knows nothing about the custom location. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_app_data_dir() -> String { crate::paths::get_app_data_dir() .to_string_lossy() diff --git a/src-tauri/src/system_theme.rs b/src-tauri/src/system_theme.rs index 619f3f34d..5bd68802e 100644 --- a/src-tauri/src/system_theme.rs +++ b/src-tauri/src/system_theme.rs @@ -2,7 +2,7 @@ mod portal; /// Linux desktop preference, independent of the GTK theme name. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_linux_system_theme() -> Option { #[cfg(target_os = "linux")] { @@ -15,10 +15,12 @@ pub async fn get_linux_system_theme() -> Option { None } +#[cfg(feature = "desktop")] #[cfg(target_os = "linux")] pub fn watch(app: tauri::AppHandle) { - tauri::async_runtime::spawn(async move { + crate::async_rt::spawn(async move { if let Err(error) = portal::watch(move |theme| { + #[cfg(feature = "desktop")] use tauri::Emitter; if let Err(error) = app.emit("linux-system-theme-changed", theme) { log::warn!("Failed to emit system theme change: {error}"); diff --git a/src-tauri/src/task_manager.rs b/src-tauri/src/task_manager.rs index 36503d81a..e1f659197 100644 --- a/src-tauri/src/task_manager.rs +++ b/src-tauri/src/task_manager.rs @@ -1,31 +1,33 @@ use crate::application::operations; use crate::runtime::RuntimeContext; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, State, WebviewUrl, WebviewWindowBuilder}; pub use operations::{ ChildProcessInfo, ProcessInfo, SystemStats, TabularisChildProcess, TabularisSelfStats, }; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_process_list() -> Result, String> { operations::get_process_list().await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_system_stats() -> Result { operations::get_system_stats().await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_tabularis_children() -> Result, String> { operations::get_tabularis_children().await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn kill_plugin_process(plugin_id: String) -> Result<(), String> { crate::application::plugins::kill_plugin_process(plugin_id).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn restart_plugin_process( runtime: State<'_, RuntimeContext>, @@ -34,6 +36,7 @@ pub async fn restart_plugin_process( crate::application::plugins::restart_plugin_process(runtime.inner(), plugin_id).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn open_task_manager_window(app: AppHandle) -> Result<(), String> { if let Some(existing) = app.get_webview_window("task-manager") { diff --git a/src-tauri/src/theme_commands.rs b/src-tauri/src/theme_commands.rs index a84f1e289..0551773f9 100644 --- a/src-tauri/src/theme_commands.rs +++ b/src-tauri/src/theme_commands.rs @@ -1,8 +1,10 @@ use crate::paths::{get_app_config_dir, get_default_app_data_dir}; use crate::theme_packages::{self, ThemeCatalog, ThemeContribution}; use serde_json::Value; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter}; +#[cfg(feature = "desktop")] fn committed(app: &AppHandle, result: Result) -> Result { let value = result?; if let Err(error) = app.emit("theme-catalog-changed", ()) { @@ -11,7 +13,7 @@ fn committed(app: &AppHandle, result: Result) -> Result Ok(value) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_theme_catalog() -> ThemeCatalog { theme_packages::read_theme_catalog( &get_app_config_dir(), @@ -22,7 +24,7 @@ pub fn get_theme_catalog() -> ThemeCatalog { /// Legacy command names and argument names remain available. Raw metadata is /// retained instead of round-tripping files through the historical Rust model. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_all_themes() -> Result, String> { get_theme_catalog() .themes @@ -38,7 +40,7 @@ pub fn get_all_themes() -> Result, String> { .collect() } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_theme(theme_id: String) -> Result { let entry = get_theme_catalog() .themes @@ -54,6 +56,7 @@ pub fn get_theme(theme_id: String) -> Result { Ok(value) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn save_custom_theme(app: AppHandle, theme: Value) -> Result<(), String> { committed( @@ -62,6 +65,7 @@ pub fn save_custom_theme(app: AppHandle, theme: Value) -> Result<(), String> { ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn delete_custom_theme(app: AppHandle, theme_id: String) -> Result<(), String> { committed( @@ -70,6 +74,7 @@ pub fn delete_custom_theme(app: AppHandle, theme_id: String) -> Result<(), Strin ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn import_theme( app: AppHandle, @@ -84,11 +89,12 @@ pub fn import_theme( committed(&app, result) } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn export_theme(theme_id: String) -> Result { theme_packages::export_personal_theme(&get_app_config_dir(), &theme_id) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn create_personal_theme( app: AppHandle, @@ -101,6 +107,7 @@ pub fn create_personal_theme( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn create_personal_snapshot( app: AppHandle, @@ -113,6 +120,7 @@ pub fn create_personal_snapshot( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn update_personal_theme( app: AppHandle, @@ -133,6 +141,7 @@ pub fn update_personal_theme( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn update_personal_snapshot( app: AppHandle, @@ -155,6 +164,7 @@ pub fn update_personal_snapshot( ) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn duplicate_personal_theme( app: AppHandle, diff --git a/src-tauri/src/theme_packages/commands.rs b/src-tauri/src/theme_packages/commands.rs index ba04d2ee7..a03efa1bf 100644 --- a/src-tauri/src/theme_packages/commands.rs +++ b/src-tauri/src/theme_packages/commands.rs @@ -2,8 +2,10 @@ use super::{catalog::PACKAGES_DIR, lifecycle, *}; use crate::plugins::{install_cancellation, registry, tabularium}; use sha2::{Digest, Sha256}; use std::path::Path; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Emitter}; +#[cfg(feature = "desktop")] fn registry_base(app: &AppHandle) -> Result { let config = crate::config::load_config_internal(app); let base = config @@ -17,6 +19,7 @@ fn operation_id(registry: &str, package: &str) -> String { format!("theme:{registry}:{package}") } +#[cfg(feature = "desktop")] fn refresh(app: &AppHandle) { if let Err(error) = app.emit("theme-catalog-changed", ()) { log::warn!( @@ -27,7 +30,7 @@ fn refresh(app: &AppHandle) { } /// Standalone import preview validates without creating a personal file. -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn preview_theme_document(source: String, name: String) -> Result { catalog::validate_name(&name)?; let value = parse_bounded_json(source.as_bytes(), legacy::LEGACY_BYTES * 2, 128, 262_144)?; @@ -61,7 +64,7 @@ pub fn preview_theme_document(source: String, name: String) -> Result, ) -> Result { - tauri::async_runtime::spawn_blocking(move || { + crate::async_rt::spawn_blocking(move || { lifecycle::local_preview(&bytes, env!("CARGO_PKG_VERSION")) }) .await @@ -79,7 +82,7 @@ pub async fn install_local_package( let key = lifecycle::local_registry_key(); let guard = install_cancellation::begin(&operation_id(&key, &package_name))?; let cancellation = guard.cancellation().clone(); - tauri::async_runtime::spawn_blocking(move || { + crate::async_rt::spawn_blocking(move || { cancellation.check()?; let bytes = read_archive()?; if format!("{:x}", Sha256::digest(&bytes)) != expected_digest { @@ -111,11 +114,11 @@ pub fn read_local_archive(path: &Path) -> Result, String> { /// Largest accepted local theme archive. pub const MAX_LOCAL_ARCHIVE_BYTES: usize = lifecycle::ARCHIVE_BYTES; -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub async fn preview_local_theme_package( path: String, ) -> Result { - let bytes = tauri::async_runtime::spawn_blocking(move || { + let bytes = crate::async_rt::spawn_blocking(move || { lifecycle::read_local_archive(Path::new(&path)) }) .await @@ -123,6 +126,7 @@ pub async fn preview_local_theme_package( preview_local_package_bytes(bytes).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn install_local_theme_package( app: AppHandle, @@ -148,6 +152,7 @@ pub struct ThemeRegistrySnapshot { pub plugins: Vec, } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_theme_registry( app: AppHandle, @@ -191,6 +196,7 @@ pub async fn fetch_registry( } /// Read-only details: never resolve a tracked download during discovery. +#[cfg(feature = "desktop")] #[tauri::command] pub async fn fetch_theme_package_detail( app: AppHandle, @@ -231,6 +237,7 @@ pub async fn fetch_package_detail( Ok(detail) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn install_registry_theme( app: AppHandle, @@ -267,11 +274,12 @@ pub async fn install_registry( .await } -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_theme_install(registry_key: String, package_name: String) -> bool { install_cancellation::cancel(&operation_id(®istry_key, &package_name)) } +#[cfg(feature = "desktop")] #[tauri::command] pub fn set_theme_package_enabled( app: AppHandle, @@ -298,6 +306,7 @@ pub fn set_package_enabled( } /// Recovery is an explicit action, never a catalog-read or hydration side effect. +#[cfg(feature = "desktop")] #[tauri::command] pub fn recover_theme_packages(app: AppHandle) -> Result, String> { let failures = recover_packages(); @@ -316,6 +325,7 @@ pub fn recover_packages() -> Vec { } } +#[cfg(feature = "desktop")] #[tauri::command] pub fn uninstall_theme_package( app: AppHandle, diff --git a/src-tauri/src/theme_packages/transport.rs b/src-tauri/src/theme_packages/transport.rs index db01dbb73..61950748c 100644 --- a/src-tauri/src/theme_packages/transport.rs +++ b/src-tauri/src/theme_packages/transport.rs @@ -92,7 +92,7 @@ pub(super) async fn install_registry_package( let target = target.to_string(); let package_name = package_name.to_string(); let host_version = host_version.to_string(); - tauri::async_runtime::spawn_blocking(move || { + crate::async_rt::spawn_blocking(move || { let package = validate_theme_archive(&bytes, &package_name, &target, &host_version, &|| { cancellation.check() diff --git a/src-tauri/src/ui_state_commands.rs b/src-tauri/src/ui_state_commands.rs index b8ec1ff89..e194501b4 100644 --- a/src-tauri/src/ui_state_commands.rs +++ b/src-tauri/src/ui_state_commands.rs @@ -3,8 +3,10 @@ use crate::application::ui_state::{execute, UiStateCommand}; use crate::runtime::RuntimeContext; use serde_json::Value; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; +#[cfg(feature = "desktop")] #[tauri::command] pub async fn get_ui_state( app: AppHandle, @@ -13,6 +15,7 @@ pub async fn get_ui_state( execute(&app.state::(), UiStateCommand::Get { keys }).await } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn set_ui_state( app: AppHandle, @@ -27,6 +30,7 @@ pub async fn set_ui_state( Ok(()) } +#[cfg(feature = "desktop")] #[tauri::command] pub async fn delete_ui_state(app: AppHandle, key: String) -> Result<(), String> { execute( diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs index 8fa37ddf7..b6bfc2aa8 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/updater.rs @@ -2,7 +2,9 @@ use serde::{Deserialize, Serialize}; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; +#[cfg(feature = "desktop")] use tauri::Emitter; +#[cfg(feature = "desktop")] use tauri::AppHandle; mod installation_source; @@ -61,12 +63,13 @@ struct GitHubAsset { const GITHUB_REPO: &str = "TabularisDB/tabularis"; const CACHE_DURATION_SECS: u64 = 43200; // 12 hours -#[tauri::command] +#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_installation_source() -> Option { detect_installation_source() } // Helper functions +#[cfg(feature = "desktop")] fn get_cache_path(_app: &AppHandle) -> Option { Some(crate::paths::get_app_config_dir().join("update_check_cache.json")) } @@ -178,6 +181,7 @@ fn categorize_asset(name: &str) -> String { } } +#[cfg(feature = "desktop")] /// Effective update channel from config. Anything other than "nightly" ⇒ stable. fn release_channel(app: &tauri::AppHandle) -> String { crate::config::load_config_internal(app) @@ -186,6 +190,7 @@ fn release_channel(app: &tauri::AppHandle) -> String { } // Tauri commands +#[cfg(feature = "desktop")] #[tauri::command] pub async fn check_for_updates(app: AppHandle, force: bool) -> Result { // Package-managed installations should not use the built-in updater. @@ -213,6 +218,7 @@ pub async fn check_for_updates(app: AppHandle, force: bool) -> Result Result Result<(), String> { if is_managed_package() { @@ -341,6 +348,7 @@ pub async fn download_and_install_update(app: AppHandle) -> Result<(), String> { } // Use tauri-plugin-updater to handle the download and installation. + #[cfg(feature = "desktop")] use tauri_plugin_updater::UpdaterExt; let mut builder = app.updater_builder(); diff --git a/src-tauri/src/window_decorations.rs b/src-tauri/src/window_decorations.rs index 767b7fad5..440b7c084 100644 --- a/src-tauri/src/window_decorations.rs +++ b/src-tauri/src/window_decorations.rs @@ -1,4 +1,5 @@ use crate::config::{get_cached_config, WindowDecorationsMode}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, Runtime}; #[cfg(target_os = "linux")] @@ -23,6 +24,7 @@ pub fn native_decorations_enabled() -> bool { }) } +#[cfg(feature = "desktop")] pub fn apply_to_all_windows(app: &AppHandle, mode: Option<&WindowDecorationsMode>) { let enabled = native_decorations_enabled_for_mode(mode, |name| std::env::var(name).ok()); diff --git a/src-tauri/src/window_placement.rs b/src-tauri/src/window_placement.rs index 26ed20a58..286c10ca3 100644 --- a/src-tauri/src/window_placement.rs +++ b/src-tauri/src/window_placement.rs @@ -5,6 +5,7 @@ use std::path::PathBuf; use std::sync::Mutex; use serde::{Deserialize, Serialize}; +#[cfg(feature = "desktop")] use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewWindow, Window}; const MIN_WIDTH: u32 = 480; @@ -26,6 +27,7 @@ fn placement_path() -> PathBuf { crate::paths::get_app_config_dir().join("main-window-placement.json") } +#[cfg(feature = "desktop")] fn overlaps_monitor( saved: WindowPlacement, monitor_position: PhysicalPosition, @@ -45,6 +47,7 @@ fn overlaps_monitor( overlap_x >= 80 && overlap_y >= 80 } +#[cfg(feature = "desktop")] /// Called before the existing start_maximized preference is applied. /// Missing/corrupt state falls back to Tauri's configured 1280x800 window. pub(crate) fn restore(window: &WebviewWindow) { @@ -92,6 +95,7 @@ pub(crate) fn restore(window: &WebviewWindow) { .unwrap() = Some(saved); } +#[cfg(feature = "desktop")] /// Update only in normal mode. Maximizing/minimizing must not overwrite the /// last non-maximized bounds with screen-sized or zero dimensions. pub(crate) fn remember(window: &Window) { @@ -122,6 +126,7 @@ pub(crate) fn remember(window: &Window) { .unwrap() = Some(placement); } +#[cfg(feature = "desktop")] /// Save the latest bounds captured by move/resize events. App exit and restart /// can bypass CloseRequested, so they persist the cache directly. pub(crate) fn persist_cached(app: &AppHandle) { @@ -140,6 +145,7 @@ pub(crate) fn persist_cached(app: &AppHandle) { } } +#[cfg(feature = "desktop")] /// Capture the final normal bounds when a window close event is available. pub(crate) fn persist(window: &Window) { remember(window); diff --git a/web-ui-project/docs/WEB_MODE_CONTAINERS.md b/web-ui-project/docs/WEB_MODE_CONTAINERS.md index dfc8c28aa..ed6bbefbe 100644 --- a/web-ui-project/docs/WEB_MODE_CONTAINERS.md +++ b/web-ui-project/docs/WEB_MODE_CONTAINERS.md @@ -2,9 +2,9 @@ The official image `ghcr.io/tabularisdb/tabularis` is published to the GitHub Container Registry for `linux/amd64` and `linux/arm64`, tagged `latest`, `0.30` and `0.30.0`. Prereleases get only their exact version tag (`0.30.0-beta.1`). -It is based on Debian slim, so registry driver plugins (built for glibc) run unchanged. It runs as UID `10001`, keeps all state in `/data`, and includes `ssh` for SSH tunnels. `kubectl` and the AWS CLI are not included; extend the image if you use Kubernetes or SSM tunnels. +It is based on Debian slim, so registry driver plugins (built for glibc) run unchanged, and is about 60 MB to pull. It runs as UID `10001`, keeps all state in `/data`, and includes `ssh` for SSH tunnels. `kubectl` and the AWS CLI are not included; extend the image if you use Kubernetes or SSM tunnels. -The server binary still links WebKitGTK because the desktop and Web modes ship as one executable, so the image is larger than a typical web service. `tabularis web` never opens a window and needs no display. +The image contains a server-only build (`cargo build --no-default-features`): it has no desktop app and links neither GTK nor WebKitGTK, and it only runs `tabularis web` and `tabularis --mcp`. ## Quick start on your machine @@ -83,4 +83,4 @@ docker build -f docker/Dockerfile -t tabularis . docker/smoke-test.sh tabularis ``` -The build compiles the frontend once on the build platform and the Rust server for the target platform. Release builds run on native `amd64` and `arm64` runners by `.github/workflows/docker.yml`, which also publishes the Helm chart. +The build compiles the frontend once on the build platform and the Rust server, without the `desktop` feature, for the target platform. Release builds run on native `amd64` and `arm64` runners by `.github/workflows/docker.yml`, which also publishes the Helm chart. From 123afafee3a84b2dac4f8b83c3053e57a484580a Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 14:43:20 +0200 Subject: [PATCH 2/6] refactor(desktop): route duplicated commands through the application layer Desktop commands that had their own copy of logic the web RPC already gets from `application/` now call the application layer, so both transports behave the same. The desktop app manages one `Arc`; its fields are `Arc`s so the per-field Tauri state shares the same instances. Desktop behaviour the application layer lacked moved into it first: - deleting a connection also removes its query history; a cascading group delete now cleans up secrets, plugin secrets, icons and history of every connection in the group (neither side did that before) - AWS IAM connections never fall back to a stored password, testing one without a token fails with the actionable message, and duplicates do not copy the token - a URI marked as stored in the keychain but missing fails a connect with a clear message - SSH secrets are only kept while the tunnel is enabled, and an empty passphrase field keeps the stored one - an unknown connection id in a test is treated as an ad-hoc connection; the dbConnect step shows host:port Web parity fixes found on the way: - `list_databases` had no RPC route; the connection dialog failed to load databases in the browser - the connection dialog treats a URI that only lives in the keychain as present, so editing a passthrough connection no longer fails with "Connection URI is required" - `create_sqlite_database` moved from the RPC handler into the application layer Also: theme package installs from a path read the archive inside the cancellable install again, `run_connections_backup` returns the same object on both transports, notebooks use the runtime paths, and kubectl calls no longer block the async runtime on desktop. --- packages/web-ui/src/api/contract.ts | 2 +- .../components/modals/NewConnectionModal.tsx | 14 +- .../src/components/settings/BackupTab.tsx | 14 +- packages/web-ui/src/i18n/locales/de.json | 1 + packages/web-ui/src/i18n/locales/en.json | 1 + packages/web-ui/src/i18n/locales/es.json | 1 + packages/web-ui/src/i18n/locales/fr.json | 1 + packages/web-ui/src/i18n/locales/it.json | 1 + packages/web-ui/src/i18n/locales/ja.json | 1 + packages/web-ui/src/i18n/locales/ko.json | 1 + packages/web-ui/src/i18n/locales/pt-BR.json | 1 + packages/web-ui/src/i18n/locales/ru.json | 1 + packages/web-ui/src/i18n/locales/tl.json | 1 + packages/web-ui/src/i18n/locales/zh.json | 1 + .../modals/NewConnectionModal.test.tsx | 27 + src-tauri/src/ai_commands.rs | 127 +- src-tauri/src/application/connections.rs | 246 +- .../src/application/connections_tests.rs | 329 +++ src-tauri/src/application/themes.rs | 24 +- src-tauri/src/backup/mod.rs | 14 +- src-tauri/src/commands.rs | 2461 ++++------------- src-tauri/src/connection_appearance.rs | 22 - src-tauri/src/connection_import_commands.rs | 8 +- src-tauri/src/connection_tags.rs | 67 - src-tauri/src/dump_commands.rs | 8 +- src-tauri/src/explain_import.rs | 6 +- src-tauri/src/export.rs | 4 +- src-tauri/src/json_viewer.rs | 8 +- src-tauri/src/lib.rs | 54 +- src-tauri/src/notebooks.rs | 42 +- src-tauri/src/plugins/deep_link.rs | 4 +- src-tauri/src/query_history.rs | 11 +- src-tauri/src/results_window.rs | 4 +- src-tauri/src/runtime/state.rs | 34 +- src-tauri/src/runtime/tests.rs | 19 +- src-tauri/src/sqlite_database.rs | 31 - src-tauri/src/theme_commands.rs | 276 +- src-tauri/src/theme_packages/commands.rs | 123 - src-tauri/src/transport/web/rpc.rs | 47 +- .../transport/web/rpc_connection_policy.rs | 12 +- src-tauri/src/transport/web/rpc_tests.rs | 3 +- 41 files changed, 1539 insertions(+), 2513 deletions(-) diff --git a/packages/web-ui/src/api/contract.ts b/packages/web-ui/src/api/contract.ts index 3a5db3008..d59bf2f53 100644 --- a/packages/web-ui/src/api/contract.ts +++ b/packages/web-ui/src/api/contract.ts @@ -806,7 +806,7 @@ export interface CommandMap { >; run_connections_backup: CommandDefinition< undefined, - string | BackupRunResult, + BackupRunResult, "sensitive" >; diff --git a/packages/web-ui/src/components/modals/NewConnectionModal.tsx b/packages/web-ui/src/components/modals/NewConnectionModal.tsx index 1ee447eda..8654e3e24 100644 --- a/packages/web-ui/src/components/modals/NewConnectionModal.tsx +++ b/packages/web-ui/src/components/modals/NewConnectionModal.tsx @@ -673,7 +673,13 @@ export const NewConnectionModal = ({ activeDriver?.capabilities?.no_connection_required === true; // A raw URI is self-contained: it carries the database (or deliberately omits // it, as Atlas URIs do) and the credentials, so it replaces those form fields. - const hasConnectionUri = !!formData.connection_uri?.trim(); + // The browser never receives a stored URI. The backend keeps it on save as + // long as the driver is unchanged, so it still counts as present. + const hasStoredConnectionUri = + formData.connection_uri_in_keychain === true && + initialConnection?.params.driver === driver; + const hasConnectionUri = + !!formData.connection_uri?.trim() || hasStoredConnectionUri; // Drivers with the `connection_uri` capability consume the raw URI verbatim: // host/port/username/database all derive from it, so the form only asks for // the connection string and an optional token (password) field. @@ -2902,7 +2908,11 @@ export const NewConnectionModal = ({ "flex-1 px-3 py-2 bg-base border rounded-md text-sm text-primary placeholder:text-muted placeholder:italic focus:border-focus focus:outline-none transition-colors", connectionStringError ? "border-accent-error" : "border-strong", )} - placeholder={connectionStringPlaceholder} + placeholder={ + hasStoredConnectionUri && !formData.connection_uri + ? t("newConnection.connectionUriStored") + : connectionStringPlaceholder + } /> {connectionString && !connectionStringError && (
diff --git a/packages/web-ui/src/components/settings/BackupTab.tsx b/packages/web-ui/src/components/settings/BackupTab.tsx index 997550e53..85eb7c8bc 100644 --- a/packages/web-ui/src/components/settings/BackupTab.tsx +++ b/packages/web-ui/src/components/settings/BackupTab.tsx @@ -119,16 +119,12 @@ export function BackupTab() { try { const result = await client.call("run_connections_backup", undefined); await refreshStatus(); - if (typeof result === "string") { - showAlert(t("settings.backup.backupDone", { path: result })); - } else { - if (result.download) { - await saveGeneratedFile(client, platform, result.download); - } - showAlert( - t("settings.backup.backupDone", { path: result.serverLocation }), - ); + if (result.download) { + await saveGeneratedFile(client, platform, result.download); } + showAlert( + t("settings.backup.backupDone", { path: result.serverLocation }), + ); } catch (e) { showAlert(toErrorMessage(e)); } finally { diff --git a/packages/web-ui/src/i18n/locales/de.json b/packages/web-ui/src/i18n/locales/de.json index 3967e2185..39b74271c 100644 --- a/packages/web-ui/src/i18n/locales/de.json +++ b/packages/web-ui/src/i18n/locales/de.json @@ -1153,6 +1153,7 @@ "dbNameRequired": "Datenbankname ist erforderlich", "connectionUriRequiresKeychain": "Verbindungs-URIs müssen im Keychain des Betriebssystems gespeichert werden. Aktiviere „Passwörter im Keychain speichern“, um fortzufahren.", "connectionUriRequired": "Verbindungs-URI ist erforderlich", + "connectionUriStored": "Im Schlüsselbund des Systems gespeichert. Füge einen neuen Verbindungs-String ein, um ihn zu ersetzen.", "connectionString": "Verbindungszeichenfolge", "connectionStringPlaceholder": "z. B. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Beispiel f?r eine Verbindungszeichenfolge", diff --git a/packages/web-ui/src/i18n/locales/en.json b/packages/web-ui/src/i18n/locales/en.json index 1052ffcd0..47a965518 100644 --- a/packages/web-ui/src/i18n/locales/en.json +++ b/packages/web-ui/src/i18n/locales/en.json @@ -1220,6 +1220,7 @@ "dbNameRequired": "Database name is required", "connectionUriRequiresKeychain": "Connection URIs must be saved in the OS keychain. Enable “Save passwords in Keychain” to continue.", "connectionUriRequired": "Connection URI is required", + "connectionUriStored": "Stored in the OS keychain. Paste a new connection string to replace it.", "connectionString": "Connection String", "connectionStringPlaceholder": "e.g. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Connection string example", diff --git a/packages/web-ui/src/i18n/locales/es.json b/packages/web-ui/src/i18n/locales/es.json index db7c68ecb..77b2f8003 100644 --- a/packages/web-ui/src/i18n/locales/es.json +++ b/packages/web-ui/src/i18n/locales/es.json @@ -1181,6 +1181,7 @@ "dbNameRequired": "El nombre de la base de datos es requerido", "connectionUriRequiresKeychain": "Las URI de conexión deben guardarse en el Llavero del sistema. Activa “Guardar contraseñas en el Llavero” para continuar.", "connectionUriRequired": "El URI de conexión es requerido", + "connectionUriStored": "Guardada en el llavero del sistema. Pega una nueva cadena de conexión para reemplazarla.", "connectionString": "Cadena de conexi?n", "connectionStringPlaceholder": "p. ej. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Ejemplo de cadena de conexi?n", diff --git a/packages/web-ui/src/i18n/locales/fr.json b/packages/web-ui/src/i18n/locales/fr.json index 3fdf5726e..c2bfe990a 100644 --- a/packages/web-ui/src/i18n/locales/fr.json +++ b/packages/web-ui/src/i18n/locales/fr.json @@ -1190,6 +1190,7 @@ "dbNameRequired": "Le nom de la base de données est requis", "connectionUriRequiresKeychain": "Les URI de connexion doivent être enregistrées dans le trousseau du système. Activez « Enregistrer les mots de passe dans le trousseau » pour continuer.", "connectionUriRequired": "L'URI de connexion est requise", + "connectionUriStored": "Enregistrée dans le trousseau du système. Collez une nouvelle chaîne de connexion pour la remplacer.", "connectionString": "Cha?ne de connexion", "connectionStringPlaceholder": "p. ex. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Exemple de cha?ne de connexion", diff --git a/packages/web-ui/src/i18n/locales/it.json b/packages/web-ui/src/i18n/locales/it.json index 303573b7b..958d5dffc 100644 --- a/packages/web-ui/src/i18n/locales/it.json +++ b/packages/web-ui/src/i18n/locales/it.json @@ -1216,6 +1216,7 @@ "dbNameRequired": "Il nome del database è richiesto", "connectionUriRequiresKeychain": "Gli URI di connessione devono essere salvati nel Portachiavi di sistema. Attiva “Salva password nel Portachiavi” per continuare.", "connectionUriRequired": "L'URI di connessione è richiesto", + "connectionUriStored": "Salvata nel portachiavi di sistema. Incolla una nuova stringa di connessione per sostituirla.", "connectionString": "Stringa di connessione", "connectionStringPlaceholder": "es. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Esempio di stringa di connessione", diff --git a/packages/web-ui/src/i18n/locales/ja.json b/packages/web-ui/src/i18n/locales/ja.json index 2a43a8ae4..576941b43 100644 --- a/packages/web-ui/src/i18n/locales/ja.json +++ b/packages/web-ui/src/i18n/locales/ja.json @@ -1167,6 +1167,7 @@ "dbNameRequired": "データベース名は必須です", "connectionUriRequiresKeychain": "接続 URI は OS のキーチェーンに保存する必要があります。「パスワードをキーチェーンに保存」を有効にしてください。", "connectionUriRequired": "接続 URI は必須です", + "connectionUriStored": "OS のキーチェーンに保存されています。置き換えるには新しい接続文字列を貼り付けてください。", "connectionString": "?????", "connectionStringPlaceholder": "?: mysql://user:pass@localhost:3306/db", "connectionStringExample": "???????", diff --git a/packages/web-ui/src/i18n/locales/ko.json b/packages/web-ui/src/i18n/locales/ko.json index a37902ed4..38211a8e3 100644 --- a/packages/web-ui/src/i18n/locales/ko.json +++ b/packages/web-ui/src/i18n/locales/ko.json @@ -1128,6 +1128,7 @@ "dbNameRequired": "데이터베이스 이름은 필수입니다", "connectionUriRequiresKeychain": "연결 URI는 OS 키체인에 저장해야 합니다. “키체인에 비밀번호 저장”을 활성화하세요.", "connectionUriRequired": "연결 URI는 필수입니다", + "connectionUriStored": "OS 키체인에 저장되어 있습니다. 바꾸려면 새 연결 문자열을 붙여 넣으세요.", "connectionString": "?? ???", "connectionStringPlaceholder": "?: mysql://user:pass@localhost:3306/db", "connectionStringExample": "?? ??? ??", diff --git a/packages/web-ui/src/i18n/locales/pt-BR.json b/packages/web-ui/src/i18n/locales/pt-BR.json index 68c2ad576..7e1ae84a7 100644 --- a/packages/web-ui/src/i18n/locales/pt-BR.json +++ b/packages/web-ui/src/i18n/locales/pt-BR.json @@ -1170,6 +1170,7 @@ "nameRequired": "O nome da conexão é obrigatório", "dbNameRequired": "O nome do banco de dados é obrigatório", "connectionUriRequired": "O URI da conexão é obrigatório", + "connectionUriStored": "Armazenada no chaveiro do sistema. Cole uma nova string de conexão para substituí-la.", "connectionString": "String de conex?o", "connectionStringPlaceholder": "ex.: mysql://user:pass@localhost:3306/db", "connectionStringExample": "Exemplo de string de conex?o", diff --git a/packages/web-ui/src/i18n/locales/ru.json b/packages/web-ui/src/i18n/locales/ru.json index 5e86a28bf..849667b71 100644 --- a/packages/web-ui/src/i18n/locales/ru.json +++ b/packages/web-ui/src/i18n/locales/ru.json @@ -1152,6 +1152,7 @@ "dbNameRequired": "Название базы данных обязательно", "connectionUriRequiresKeychain": "URI подключения должны храниться в системном хранилище ключей. Включите «Сохранять пароли в Keychain», чтобы продолжить.", "connectionUriRequired": "Требуется URI подключения", + "connectionUriStored": "Сохранено в системной связке ключей. Вставьте новую строку подключения, чтобы заменить её.", "connectionString": "?????? ???????????", "connectionStringPlaceholder": "????????, mysql://user:pass@localhost:3306/db", "connectionStringExample": "?????? ?????? ???????????", diff --git a/packages/web-ui/src/i18n/locales/tl.json b/packages/web-ui/src/i18n/locales/tl.json index 182b73c4d..0ca3707cb 100644 --- a/packages/web-ui/src/i18n/locales/tl.json +++ b/packages/web-ui/src/i18n/locales/tl.json @@ -1183,6 +1183,7 @@ "dbNameRequired": "Kailangan ang pangalan ng database", "connectionUriRequiresKeychain": "Dapat i-save ang mga connection URI sa OS keychain. I-enable ang “I-save ang mga password sa Keychain” para magpatuloy.", "connectionUriRequired": "Kailangan ang connection URI", + "connectionUriStored": "Naka-save sa keychain ng OS. Mag-paste ng bagong connection string para palitan ito.", "connectionString": "Connection string", "connectionStringPlaceholder": "hal. mysql://user:pass@localhost:3306/db", "connectionStringExample": "Halimbawa ng connection string", diff --git a/packages/web-ui/src/i18n/locales/zh.json b/packages/web-ui/src/i18n/locales/zh.json index 22f62452a..a2fc58e78 100644 --- a/packages/web-ui/src/i18n/locales/zh.json +++ b/packages/web-ui/src/i18n/locales/zh.json @@ -1129,6 +1129,7 @@ "dbNameRequired": "数据库名称是必需的", "connectionUriRequiresKeychain": "连接 URI 必须保存在操作系统密钥链中。请启用“在密钥链中保存密码”后继续。", "connectionUriRequired": "连接 URI 是必需的", + "connectionUriStored": "已保存在系统钥匙串中。粘贴新的连接字符串即可替换。", "connectionString": "?????", "connectionStringPlaceholder": "?? mysql://user:pass@localhost:3306/db", "connectionStringExample": "???????", diff --git a/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx b/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx index 47ca21554..2ece08680 100644 --- a/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx +++ b/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx @@ -34,6 +34,7 @@ interface MockSelectProps { const driverState = vi.hoisted(() => ({ defaultPort: 15432 as number | null, multiDatabase: false, + uriPassthrough: false, catalogueDriver: "mysql" as "mysql" | "sqlite", connectionFields: undefined as | Record @@ -136,6 +137,7 @@ vi.mock("../../../src/hooks/useDrivers", () => ({ file_based: false, folder_based: false, connection_string: true, + connection_uri: driverState.uriPassthrough, connection_string_examples: [ { label: "Local MySQL", @@ -194,6 +196,7 @@ vi.mock("../../../src/hooks/usePluginSlotRegistry", () => ({ afterEach(() => { driverState.connectionFields = undefined; + driverState.uriPassthrough = false; }); vi.mock("../../../src/hooks/useSettings", () => ({ @@ -525,6 +528,30 @@ describe("NewConnectionModal layout", () => { }); }); + it("saves a passthrough connection whose URI only lives in the keychain", async () => { + // The browser receives a redacted connection: the URI stays on the server. + driverState.uriPassthrough = true; + const stored = createInitialConnection({ + database: "", + save_in_keychain: true, + connection_uri_in_keychain: true, + }); + vi.mocked(invoke).mockImplementation(async (command) => + command === "get_connection_by_id" ? stored : "ok", + ); + renderModal(stored); + expect( + await screen.findByPlaceholderText("newConnection.connectionUriStored"), + ).toBeInTheDocument(); + fireEvent.click(screen.getByText("newConnection.save")); + await waitFor(() => expect(invoke).toHaveBeenCalledWith( + "update_connection", expect.objectContaining({ + params: expect.objectContaining({ connection_uri_in_keychain: true }), + }), + )); + expect(screen.queryByText("newConnection.connectionUriRequired")).toBeNull(); + }); + it("fills and parses a selected connection string example", async () => { vi.mocked(invoke).mockImplementation(async (command) => command === "list_databases" ? [] : "ok", diff --git a/src-tauri/src/ai_commands.rs b/src-tauri/src/ai_commands.rs index 0dedb54e8..d530a5954 100644 --- a/src-tauri/src/ai_commands.rs +++ b/src-tauri/src/ai_commands.rs @@ -2,82 +2,93 @@ //! and notebook export. The MCP subprocess writes the underlying files; the //! main app only reads and decides on them through these endpoints. -use crate::ai_activity::{self, AiActivityEvent, EventFilter, SessionSummary}; -use crate::ai_approval::{self, ApprovalDecision, PendingApproval}; +use crate::ai_activity::EventFilter; use crate::ai_notebook_export::NotebookExport; +use crate::application::ai::{self, AiCommand}; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use serde_json::Value; +use std::sync::Arc; +use tauri::{AppHandle, Manager}; -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn get_ai_activity(filter: Option) -> Result, String> { - let f = filter.unwrap_or_default(); - tokio::task::spawn_blocking(move || ai_activity::read_events(&f)) - .await - .map_err(|e| e.to_string())? +async fn execute(app: &AppHandle, command: AiCommand) -> Result { + let state = app.state::>(); + ai::execute(&app.state::(), &state, None, command).await } -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn get_ai_sessions() -> Result, String> { - tokio::task::spawn_blocking(ai_activity::read_sessions) - .await - .map_err(|e| e.to_string())? +#[tauri::command] +pub async fn get_ai_activity(app: AppHandle, filter: Option) -> Result { + execute(&app, AiCommand::GetActivity { filter }).await } -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn get_ai_session_events(session_id: String) -> Result, String> { - tokio::task::spawn_blocking(move || ai_activity::read_session_events(&session_id)) - .await - .map_err(|e| e.to_string())? +#[tauri::command] +pub async fn get_ai_sessions(app: AppHandle) -> Result { + execute(&app, AiCommand::GetSessions).await } -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn clear_ai_activity() -> Result<(), String> { - tokio::task::spawn_blocking(ai_activity::clear) - .await - .map_err(|e| e.to_string())? +#[tauri::command] +pub async fn get_ai_session_events(app: AppHandle, session_id: String) -> Result { + execute(&app, AiCommand::GetSessionEvents { session_id }).await } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] +pub async fn clear_ai_activity(app: AppHandle) -> Result { + execute(&app, AiCommand::ClearActivity).await +} + +#[tauri::command] +pub async fn list_pending_approvals(app: AppHandle) -> Result { + execute(&app, AiCommand::ListPendingApprovals).await +} + +#[tauri::command] +pub async fn decide_pending_approval( + app: AppHandle, + approval_id: String, + decision: String, + reason: Option, + edited_query: Option, +) -> Result { + execute( + &app, + AiCommand::DecidePendingApproval { + approval_id, + decision, + reason, + edited_query, + }, + ) + .await +} + +#[tauri::command] +pub async fn get_ai_schema_context( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result { + execute( + &app, + AiCommand::GetSchemaContext { + connection_id, + schema, + database, + }, + ) + .await +} + +#[tauri::command] pub async fn export_ai_activity_json() -> Result { crate::application::generic_exports::generate_ai_activity_json().await } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn export_ai_activity_csv() -> Result { crate::application::generic_exports::generate_ai_activity_csv().await } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn export_ai_session_as_notebook(session_id: String) -> Result { crate::application::generic_exports::generate_ai_session_notebook(session_id).await } - -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn list_pending_approvals() -> Result, String> { - tokio::task::spawn_blocking(ai_approval::list_pending) - .await - .map_err(|e| e.to_string())? -} - -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn decide_pending_approval( - approval_id: String, - decision: String, - reason: Option, - edited_query: Option, -) -> Result<(), String> { - if decision != "approve" && decision != "deny" { - return Err(format!( - "Invalid decision '{}': expected 'approve' or 'deny'", - decision - )); - } - let payload = ApprovalDecision { - approval_id, - decided_at: ai_activity::now_iso8601(), - decision, - reason, - edited_query, - }; - tokio::task::spawn_blocking(move || ai_approval::write_decision(&payload)) - .await - .map_err(|e| e.to_string())? -} diff --git a/src-tauri/src/application/connections.rs b/src-tauri/src/application/connections.rs index d6cf3ab68..0cad710a8 100644 --- a/src-tauri/src/application/connections.rs +++ b/src-tauri/src/application/connections.rs @@ -131,6 +131,12 @@ pub enum ConnectionCommand { TestConnection { request: TestConnectionRequest, }, + ListDatabases { + request: TestConnectionRequest, + }, + CreateSqliteDatabase { + path: String, + }, } pub async fn execute( @@ -342,6 +348,12 @@ pub async fn execute_for_session( ConnectionCommand::TestConnection { request } => { json(test_connection(runtime, session_id, request).await?) } + ConnectionCommand::ListDatabases { request } => { + json(list_databases(runtime, session_id, request).await?) + } + ConnectionCommand::CreateSqliteDatabase { path } => { + json(create_sqlite_database(runtime, state, path).await?) + } } } @@ -372,7 +384,7 @@ pub(crate) fn resolve_saved_connection_params( let driver_id = saved.params.driver.clone(); let plugin_secrets = load_plugin_secrets(runtime, &saved); let mut params = saved.params; - restore_secrets(runtime, connection_id, &mut params)?; + restore_secrets_for_connect(runtime, connection_id, &mut params)?; params.extra.extend(plugin_secrets); params.connection_id = Some(connection_id.to_string()); let params = @@ -483,6 +495,19 @@ fn validate_environment(environment: Option) -> Result, S } } +/// AWS IAM auth needs a fresh RDS token in the password field. +pub(crate) fn require_iam_token(iam_auth: bool, password: Option<&str>) -> Result<(), String> { + if iam_auth && password.unwrap_or("").is_empty() { + return Err( + "AWS IAM authentication is enabled but the password field is empty. \ + Paste the output of `aws rds generate-db-auth-token` into the \ + password field and try again. Tokens expire every 15 minutes." + .to_string(), + ); + } + Ok(()) +} + fn secret_account(connection_id: &str, suffix: &str) -> String { format!("{connection_id}:{suffix}") } @@ -491,12 +516,24 @@ fn non_empty(value: Option<&String>) -> Option<&str> { value.map(String::as_str).filter(|value| !value.is_empty()) } +fn non_empty_trimmed(value: Option<&String>) -> Option<&str> { + value + .map(String::as_str) + .filter(|value| !value.trim().is_empty()) +} + fn persist_secrets_for_create( runtime: &RuntimeContext, id: &str, params: &mut ConnectionParams, writes: &mut SecretWrites, ) -> Result<(), String> { + if !params.ssh_enabled.unwrap_or(false) { + params.ssh_password = None; + params.ssh_key_passphrase = None; + } else if non_empty_trimmed(params.ssh_key_passphrase.as_ref()).is_none() { + params.ssh_key_passphrase = None; + } if let Some(uri) = non_empty(params.connection_uri.as_ref()) { if !params.save_in_keychain.unwrap_or(false) { return Err("Connection URIs must be stored in the OS keychain".to_string()); @@ -573,6 +610,10 @@ fn merge_and_persist_update_secrets( } params.connection_uri = None; + // An empty passphrase field means "unchanged", like an omitted one. + if non_empty_trimmed(params.ssh_key_passphrase.as_ref()).is_none() { + params.ssh_key_passphrase = None; + } // Browser responses redact secrets; an omitted field must keep its saved value. for (field, previous, suffix) in [ (&mut params.password, &existing.password, DB_SECRET_SUFFIX), @@ -595,6 +636,11 @@ fn merge_and_persist_update_secrets( }; } } + if !params.ssh_enabled.unwrap_or(false) && keychain { + // Empty values delete the stored SSH secrets of a disabled tunnel. + params.ssh_password = Some(String::new()); + params.ssh_key_passphrase = Some(String::new()); + } persist_passwords(runtime, id, params, writes)?; Ok(()) } @@ -715,7 +761,10 @@ fn restore_secrets( params: &mut ConnectionParams, ) -> Result<(), String> { if params.save_in_keychain.unwrap_or(false) { - if params.password.as_deref().is_none_or(str::is_empty) { + // IAM tokens expire after 15 minutes, so a stored one is always stale. + if params.password.as_deref().is_none_or(str::is_empty) + && !params.use_iam_auth.unwrap_or(false) + { params.password = runtime.secrets.get(&secret_account(id, DB_SECRET_SUFFIX))?; } if params.ssh_password.as_deref().is_none_or(str::is_empty) { @@ -743,6 +792,22 @@ fn restore_secrets( Ok(()) } +/// Like `restore_secrets`, for opening a connection: a URI the file says is in +/// the keychain must be there, or the driver fails with a confusing error. +fn restore_secrets_for_connect( + runtime: &RuntimeContext, + id: &str, + params: &mut ConnectionParams, +) -> Result<(), String> { + restore_secrets(runtime, id, params)?; + if params.connection_uri_in_keychain.unwrap_or(false) + && params.connection_uri.as_deref().is_none_or(str::is_empty) + { + return Err("Stored connection URI is unavailable in the OS keychain".to_string()); + } + Ok(()) +} + fn save_connection( runtime: &RuntimeContext, state: &Arc, @@ -799,6 +864,38 @@ fn save_connection( result } +/// Creates an empty SQLite file and saves a connection to it. The file is +/// removed again when the connection cannot be saved. +async fn create_sqlite_database( + runtime: &RuntimeContext, + state: &Arc, + path: String, +) -> Result { + let database_path = crate::sqlite_database::create_sqlite_file(path).await?; + let path = PathBuf::from(&database_path); + let name = crate::sqlite_database::connection_name(&path)?; + let params = ConnectionParams { + driver: "sqlite".to_string(), + database: crate::models::DatabaseSelection::Single(database_path), + ..ConnectionParams::default() + }; + save_connection( + runtime, + state, + name, + params, + PluginSecretChanges::default(), + None, + None, + ) + .map_err(|error| match fs::remove_file(&path) { + Ok(()) => format!("Failed to save the SQLite connection: {error}"), + Err(cleanup_error) => format!( + "Failed to save the SQLite connection: {error}. The new database could not be removed: {cleanup_error}" + ), + }) +} + /// Drops cached plugin connection metadata for both the old and the new driver /// of an edited connection, and tells the frontend when any was dropped. async fn invalidate_connection_metadata( @@ -921,22 +1018,38 @@ fn delete_connection( .iter() .find(|connection| connection.id == id) .cloned(); - let appearance = removed - .as_ref() - .and_then(|connection| connection.appearance.clone()); file.connections.retain(|connection| connection.id != id); save_file(runtime, state, &file)?; - delete_connection_secrets(runtime, id)?; - if let Some(removed) = &removed { + clean_up_deleted_connection(runtime, state, id, removed.as_ref()); + Ok(()) +} + +/// Removes what a deleted connection leaves outside the connections file. The +/// connection is already gone at this point, so failures are only logged. +fn clean_up_deleted_connection( + runtime: &RuntimeContext, + state: &ApplicationState, + id: &str, + removed: Option<&SavedConnection>, +) { + if let Err(error) = delete_connection_secrets(runtime, id) { + log::warn!("Failed to remove credentials of deleted connection {id}: {error}"); + } + if let Some(removed) = removed { delete_plugin_secrets(runtime, removed); } crate::credential_cache::invalidate_all_for_connection(&state.credential_cache, id); - crate::connection_appearance::cascade_delete_if_image( + if let Err(error) = crate::connection_appearance::cascade_delete_if_image( runtime.paths.data_dir(), - appearance.as_ref(), - ) - .map_err(|error| error.to_string())?; - Ok(()) + removed.and_then(|connection| connection.appearance.as_ref()), + ) { + log::warn!("Failed to remove icon of deleted connection {id}: {error}"); + } + if let Err(error) = + super::productivity::remove_query_history_for_connection(runtime.paths.config_dir(), id) + { + log::warn!("Failed to remove query history of deleted connection {id}: {error}"); + } } fn duplicate_connection( @@ -958,6 +1071,10 @@ fn duplicate_connection( ] { let should_copy = if suffix == CONNECTION_URI_SUFFIX { original.params.connection_uri_in_keychain.unwrap_or(false) + } else if suffix == DB_SECRET_SUFFIX + && original.params.use_iam_auth.unwrap_or(false) + { + false } else { original.params.save_in_keychain.unwrap_or(false) }; @@ -1157,13 +1274,20 @@ fn delete_group( } let deleted = crate::models::collect_group_subtree(&file.groups, id); file.groups.retain(|group| !deleted.contains(&group.id)); - file.connections.retain(|connection| { - !connection - .group_id - .as_ref() - .is_some_and(|group_id| deleted.contains(group_id)) - }); - save_file(runtime, state, &file) + let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut file.connections) + .into_iter() + .partition(|connection| { + connection + .group_id + .as_ref() + .is_some_and(|group_id| deleted.contains(group_id)) + }); + file.connections = kept; + save_file(runtime, state, &file)?; + for connection in &removed { + clean_up_deleted_connection(runtime, state, &connection.id, Some(connection)); + } + Ok(()) } fn move_connection( @@ -1315,31 +1439,80 @@ pub async fn disconnect_connection( Ok(()) } -async fn test_connection( +/// Completes the connection form of the modal with what it omits: the saved +/// connection's secrets and the plugin secret changes. An id without a saved +/// connection is used as an ad-hoc connection. +fn prepare_connection_request( runtime: &RuntimeContext, - session_id: Option, - mut request: TestConnectionRequest, -) -> Result { - let progress_id = request.progress_id.clone(); + request: &mut TestConnectionRequest, +) -> Result<(), String> { + let iam_auth = request.params.use_iam_auth.unwrap_or(false); let mut stored_plugin_secrets = std::collections::HashMap::new(); - if let Some(connection_id) = request.connection_id.as_deref() { - let saved = find_connection(&load_file(runtime)?, connection_id)?; + let saved = match request.connection_id.as_deref() { + Some(connection_id) => find_connection(&load_file(runtime)?, connection_id).ok(), + None => None, + }; + if let Some(saved) = saved { // Stored plugin secrets apply only while the driver is unchanged, and // only for keys the pending modal changes do not set or clear. if saved.params.driver == request.params.driver { stored_plugin_secrets = load_plugin_secrets(runtime, &saved); stored_plugin_secrets.retain(|key, _| !request.plugin_secret_changes.contains_key(key)); } - if request.params.password.as_deref().is_none_or(str::is_empty) { + if request.params.password.as_deref().is_none_or(str::is_empty) && !iam_auth { request.params.password = saved.params.password; } - restore_secrets(runtime, connection_id, &mut request.params)?; + restore_secrets_for_connect(runtime, &saved.id, &mut request.params)?; } crate::plugin_secrets::apply_runtime_changes( &mut request.params, stored_plugin_secrets, &request.plugin_secret_changes, )?; + // Without a token the server only answers an opaque "Access denied". + require_iam_token(iam_auth, request.params.password.as_deref()) +} + +async fn list_databases( + runtime: &RuntimeContext, + session_id: Option, + mut request: TestConnectionRequest, +) -> Result, String> { + prepare_connection_request(runtime, &mut request)?; + let mut expanded = + crate::application::tunnels::expand_connection_params(runtime, &request.params)?; + expanded.connection_id = request.connection_id; + let runtime_for_tunnel = runtime.clone(); + let resolved = tokio::task::spawn_blocking(move || { + crate::application::tunnels::resolve_connection_params( + &runtime_for_tunnel, + &expanded, + session_id, + ) + }) + .await + .map_err(|error| error.to_string())??; + let driver = crate::drivers::registry::get_driver(&resolved.driver) + .await + .ok_or_else(|| format!("Driver not found: {}", resolved.driver))?; + driver.get_databases(&resolved).await +} + +async fn test_connection( + runtime: &RuntimeContext, + session_id: Option, + mut request: TestConnectionRequest, +) -> Result { + let progress_id = request.progress_id.clone(); + prepare_connection_request(runtime, &mut request).map_err(|error| { + emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + "resolve", + error, + ) + })?; let expanded = crate::application::tunnels::expand_connection_params(runtime, &request.params) .map_err(|error| { @@ -1419,14 +1592,27 @@ async fn test_connection( let driver = crate::drivers::registry::get_driver(&resolved.driver) .await - .ok_or_else(|| format!("Driver not found: {}", resolved.driver))?; + .ok_or_else(|| { + emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + "resolve", + format!("Driver not found: {}", resolved.driver), + ) + })?; + let db_target = match (expanded.host.as_deref(), expanded.port) { + (Some(host), Some(port)) => format!("{host}:{port}"), + (Some(host), None) => host.to_string(), + _ => expanded.database.to_string(), + }; emit_test_progress( runtime, session_id, progress_id.as_deref(), "dbConnect", "start", - request.params.host.clone(), + Some(db_target), ); let capabilities = &driver.manifest().capabilities; if capabilities.file_based diff --git a/src-tauri/src/application/connections_tests.rs b/src-tauri/src/application/connections_tests.rs index 76102676f..445c83591 100644 --- a/src-tauri/src/application/connections_tests.rs +++ b/src-tauri/src/application/connections_tests.rs @@ -414,6 +414,7 @@ fn keychain_failure_persists_passwords_and_reports_fallback_without_exposing_the secrets.clone(), ); let mut params = connection_params("db-secret"); + params.ssh_enabled = Some(true); params.ssh_password = Some("ssh-secret".into()); let saved = save_connection(&runtime, &state, "Fallback".into(), params, Default::default(), None, None).unwrap(); assert_eq!(saved.params.save_in_keychain, Some(false)); @@ -738,3 +739,331 @@ fn sql_builder_secrets_bind_stored_plugin_secrets_and_tolerate_missing_ones() { DatabaseSelection::Single("analytics".to_string()) ); } + +fn fixture_with_secrets() -> ( + tempfile::TempDir, + RuntimeContext, + Arc, + Arc, +) { + let temp = tempfile::tempdir().unwrap(); + let secrets = Arc::new(MemorySecrets::default()); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + secrets.clone(), + ); + ( + temp, + runtime, + Arc::new(ApplicationState::default()), + secrets, + ) +} + +fn stored_accounts(secrets: &MemorySecrets, connection_id: &str) -> Vec { + let mut accounts: Vec = secrets + .values + .lock() + .unwrap() + .keys() + .filter(|account| account.starts_with(connection_id)) + .cloned() + .collect(); + accounts.sort(); + accounts +} + +async fn add_history(runtime: &RuntimeContext, connection_id: &str) { + use super::super::productivity::{self, ProductivityCommand}; + productivity::execute( + runtime.paths.config_dir(), + ProductivityCommand::AddQueryHistoryEntry { + connection_id: connection_id.into(), + sql: "SELECT 1".into(), + executed_at: "2026-10-22".into(), + execution_time_ms: None, + status: "success".into(), + rows_affected: None, + error: None, + database: None, + }, + ) + .await + .unwrap(); +} + +async fn history_len(runtime: &RuntimeContext, connection_id: &str) -> usize { + use super::super::productivity::{self, ProductivityCommand}; + productivity::execute( + runtime.paths.config_dir(), + ProductivityCommand::GetQueryHistory { + connection_id: connection_id.into(), + }, + ) + .await + .unwrap()["entries"] + .as_array() + .unwrap() + .len() +} + +#[tokio::test] +async fn deleting_a_connection_removes_its_secrets_and_history() { + let (_temp, runtime, state, secrets) = fixture_with_secrets(); + let saved = save_connection( + &runtime, + &state, + "Doomed".into(), + connection_params("secret"), + Default::default(), + None, + None, + ) + .unwrap(); + add_history(&runtime, &saved.id).await; + assert!(!stored_accounts(&secrets, &saved.id).is_empty()); + + delete_connection(&runtime, &state, &saved.id).unwrap(); + + assert!(stored_accounts(&secrets, &saved.id).is_empty()); + assert_eq!(history_len(&runtime, &saved.id).await, 0); +} + +#[tokio::test] +async fn deleting_a_group_cleans_up_every_connection_in_it() { + let (_temp, runtime, state, secrets) = fixture_with_secrets(); + let group = execute( + &runtime, + &state, + ConnectionCommand::CreateConnectionGroup { + name: "Doomed".into(), + parent_id: None, + }, + ) + .await + .unwrap(); + let group_id = group["id"].as_str().unwrap().to_string(); + let saved = save_connection( + &runtime, + &state, + "Grouped".into(), + connection_params("secret"), + Default::default(), + None, + None, + ) + .unwrap(); + execute( + &runtime, + &state, + ConnectionCommand::MoveConnectionToGroup { + connection_id: saved.id.clone(), + group_id: Some(group_id.clone()), + sort_order: None, + }, + ) + .await + .unwrap(); + add_history(&runtime, &saved.id).await; + + execute( + &runtime, + &state, + ConnectionCommand::DeleteConnectionGroup { id: group_id }, + ) + .await + .unwrap(); + + assert!(load_file(&runtime).unwrap().connections.is_empty()); + assert!(stored_accounts(&secrets, &saved.id).is_empty()); + assert_eq!(history_len(&runtime, &saved.id).await, 0); +} + +#[test] +fn iam_guard_requires_a_token() { + let error = require_iam_token(true, None).unwrap_err(); + assert!(error.contains("AWS IAM authentication is enabled")); + assert!(error.contains("15 minutes")); + assert!(require_iam_token(true, Some("")).is_err()); + require_iam_token(true, Some("token")).unwrap(); + require_iam_token(false, None).unwrap(); +} + +#[tokio::test] +async fn testing_an_iam_connection_never_uses_the_stored_password() { + let (_temp, runtime, state, _secrets) = fixture_with_secrets(); + let mut params = connection_params("stale-token"); + params.use_iam_auth = Some(true); + let saved = save_connection( + &runtime, + &state, + "IAM".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + let mut request_params = saved.params.clone(); + request_params.password = None; + let error = execute( + &runtime, + &state, + ConnectionCommand::TestConnection { + request: TestConnectionRequest { + params: request_params, + connection_id: Some(saved.id.clone()), + progress_id: None, + plugin_secret_changes: Default::default(), + }, + }, + ) + .await + .unwrap_err(); + assert!( + error.contains("AWS IAM authentication is enabled"), + "{error}" + ); + + let mut restored = saved.params.clone(); + restore_secrets(&runtime, &saved.id, &mut restored).unwrap(); + assert_eq!(restored.password, None); +} + +#[test] +fn duplicating_an_iam_connection_does_not_copy_the_token() { + let (_temp, runtime, state, secrets) = fixture_with_secrets(); + let mut params = connection_params("stale-token"); + params.use_iam_auth = Some(true); + let saved = save_connection( + &runtime, + &state, + "IAM".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + let copy = duplicate_connection(&runtime, &state, &saved.id).unwrap(); + assert!(!stored_accounts(&secrets, ©.id).contains(&format!("{}:db", copy.id))); +} + +#[test] +fn a_missing_keychain_uri_fails_the_connection_with_a_clear_message() { + let (_temp, runtime, state, secrets) = fixture_with_secrets(); + let mut params = connection_params("secret"); + params.connection_uri = Some("postgres://user:secret@localhost/db".into()); + let saved = save_connection( + &runtime, + &state, + "URI".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + secrets + .values + .lock() + .unwrap() + .remove(&format!("{}:connection_uri", saved.id)); + let error = resolve_saved_connection_params(&runtime, None, &saved.id).unwrap_err(); + assert_eq!( + error, + "Stored connection URI is unavailable in the OS keychain" + ); +} + +#[test] +fn ssh_secrets_follow_the_tunnel_toggle() { + let (_temp, runtime, state, secrets) = fixture_with_secrets(); + let mut params = connection_params("secret"); + params.ssh_password = Some("ssh-secret".into()); + let without_ssh = save_connection( + &runtime, + &state, + "No tunnel".into(), + params.clone(), + Default::default(), + None, + None, + ) + .unwrap(); + assert_eq!( + stored_accounts(&secrets, &without_ssh.id), + vec![format!("{}:db", without_ssh.id)] + ); + + params.ssh_enabled = Some(true); + params.ssh_key_passphrase = Some("passphrase".into()); + let with_ssh = save_connection( + &runtime, + &state, + "Tunnel".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + let ssh_password = format!("{}:ssh", with_ssh.id); + let passphrase = format!("{}:ssh_passphrase", with_ssh.id); + + // An empty passphrase field keeps the stored one. + let mut edit = with_ssh.params.clone(); + edit.ssh_key_passphrase = Some(" ".into()); + update_connection( + &runtime, + &state, + with_ssh.id.clone(), + "Tunnel".into(), + edit.clone(), + Default::default(), + None, + None, + ) + .unwrap(); + assert!(stored_accounts(&secrets, &with_ssh.id).contains(&passphrase)); + + // Turning the tunnel off drops its secrets. + edit.ssh_enabled = Some(false); + update_connection( + &runtime, + &state, + with_ssh.id.clone(), + "Tunnel".into(), + edit, + Default::default(), + None, + None, + ) + .unwrap(); + let accounts = stored_accounts(&secrets, &with_ssh.id); + assert!(!accounts.contains(&ssh_password)); + assert!(!accounts.contains(&passphrase)); + assert!(accounts.contains(&format!("{}:db", with_ssh.id))); +} + +#[tokio::test] +async fn creating_a_sqlite_database_saves_a_connection_to_the_new_file() { + let (temp, runtime, state) = fixture(); + let path = temp.path().join("inventory.sqlite"); + let created = execute( + &runtime, + &state, + ConnectionCommand::CreateSqliteDatabase { + path: path.to_string_lossy().into_owned(), + }, + ) + .await + .unwrap(); + assert!(path.is_file()); + assert_eq!(created["params"]["driver"], "sqlite"); + assert_eq!(load_file(&runtime).unwrap().connections.len(), 1); +} diff --git a/src-tauri/src/application/themes.rs b/src-tauri/src/application/themes.rs index b9f5bc977..75bab12c5 100644 --- a/src-tauri/src/application/themes.rs +++ b/src-tauri/src/application/themes.rs @@ -187,10 +187,26 @@ pub async fn execute(runtime: &RuntimeContext, command: ThemeCommand) -> Result< package_name, expected_digest, } => { - let bytes = read_archive_now(runtime, archive).await?; - let result = - packages::install_local_package(move || Ok(bytes), package_name, expected_digest) - .await?; + let result = match archive { + // Read inside the install so a slow read stays cancellable. + LocalThemeArchive::Path(path) => { + packages::install_local_package( + move || packages::read_local_archive(&path), + package_name, + expected_digest, + ) + .await? + } + upload => { + let bytes = read_archive_now(runtime, upload).await?; + packages::install_local_package( + move || Ok(bytes), + package_name, + expected_digest, + ) + .await? + } + }; notify_catalog_changed(runtime); json(result) } diff --git a/src-tauri/src/backup/mod.rs b/src-tauri/src/backup/mod.rs index 1ee6113ff..84255f1fa 100644 --- a/src-tauri/src/backup/mod.rs +++ b/src-tauri/src/backup/mod.rs @@ -609,12 +609,16 @@ pub async fn set_connections_backup_target_password( #[cfg(feature = "desktop")] #[tauri::command] -pub async fn run_connections_backup(app: AppHandle) -> Result { - Ok( - run_backup_for_runtime(app.state::().inner(), "manual") - .await? - .location, +pub async fn run_connections_backup( + app: AppHandle, +) -> Result { + crate::application::connection_files::execute( + &app.state::(), + &app.state::>(), + None, + crate::application::connection_files::ConnectionFilesCommand::RunBackup, ) + .await } fn load_runtime_config(runtime: &RuntimeContext) -> crate::config::AppConfig { diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index d7a6e7c89..2929ab3fb 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -3,7 +3,7 @@ use std::fs; use std::path::PathBuf; use std::sync::{Arc, Mutex}; #[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter, Manager, Runtime, State}; +use tauri::{AppHandle, Manager, Runtime, State}; use tokio::task::AbortHandle; use urlencoding::encode; use uuid::Uuid; @@ -11,10 +11,10 @@ use uuid::Uuid; use crate::credential_cache; use crate::keychain_utils; use crate::models::{ - BatchStatementResult, ColumnDefinition, ConnectionGroup, ConnectionParams, ConnectionsFile, - ExplainQueryOutput, ExportPayload, ForeignKey, Index, K8sConnection, K8sConnectionInput, - QueryResult, RoutineInfo, RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, - SshTestParams, TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, + BatchStatementResult, ColumnDefinition, ConnectionGroup, ConnectionParams, ExplainQueryOutput, + ExportPayload, ForeignKey, Index, K8sConnection, K8sConnectionInput, QueryResult, RoutineInfo, + RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, SshTestParams, + TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, }; use crate::persistence; @@ -123,324 +123,461 @@ fn is_empty_or_whitespace(s: &Option) -> bool { s.as_ref().map(|p| p.trim().is_empty()).unwrap_or(true) } -/// Reject a connection attempt under AWS IAM auth when neither the raw form -/// payload nor the expanded params (after SSH/K8s expansion) carry an RDS -/// auth token. Both `test_connection` and `list_databases` run this guard -/// before any pool / driver work so the user gets an actionable message -/// instead of the opaque "Access denied" the server returns on an empty -/// password. -fn require_iam_token( - iam_auth: bool, - request_password: Option<&str>, - expanded_password: Option<&str>, -) -> Result<(), String> { - if iam_auth - && request_password.unwrap_or("").is_empty() - && expanded_password.unwrap_or("").is_empty() - { - return Err( - "AWS IAM authentication is enabled but the password field is empty. \ - Paste the output of `aws rds generate-db-auth-token` into the \ - password field and try again. Tokens expire every 15 minutes." - .to_string(), - ); - } - Ok(()) +#[cfg(feature = "desktop")] +async fn execute_connection_command( + app: &AppHandle, + command: crate::application::connections::ConnectionCommand, +) -> Result { + crate::application::connections::execute( + &app.state::(), + &app.state::>(), + command, + ) + .await } -#[cfg(test)] -mod require_iam_token_tests { - use super::require_iam_token; - - #[test] - fn rejects_iam_with_both_passwords_empty() { - // The primary case: ad-hoc connection, IAM enabled, nothing in the - // form and nothing from the keychain. - let err = require_iam_token(true, None, None).unwrap_err(); - assert!(err.contains("AWS IAM authentication is enabled")); - assert!(err.contains("15 minutes")); - } +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn get_connections(app: AppHandle) -> Result { + migrate_ssh_connections(&app).await.ok(); + migrate_postgres_ssl_mode_spelling(&app).await.ok(); + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnections, + ) + .await +} - #[test] - fn rejects_iam_with_empty_string_passwords() { - // Empty strings (rather than None) must also fail — sqlx stamps - // "" as a deliberate "user pressed Enter" password. - let err = require_iam_token(true, Some(""), Some("")).unwrap_err(); - assert!(err.contains("AWS IAM authentication is enabled")); - } +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn get_connections_with_groups( + app: AppHandle, +) -> Result { + migrate_ssh_connections(&app).await.ok(); + migrate_postgres_ssl_mode_spelling(&app).await.ok(); + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnectionsWithGroups, + ) + .await +} - #[test] - fn allows_iam_when_request_password_present() { - // A freshly pasted RDS auth token in the form is enough; the - // expanded (post-SSH/K8s) value is irrelevant. - require_iam_token(true, Some("fake-token"), None).unwrap(); - } +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn save_connection( + app: AppHandle, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SaveConnection { + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + }, + ) + .await +} - #[test] - fn allows_iam_when_expanded_password_present() { - // The expanded value can also satisfy the guard (e.g. an SSH tunnel - // wrapper injected it). - require_iam_token(true, None, Some("fake-token")).unwrap(); - } +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn update_connection( + app: AppHandle, + id: String, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnection { + id, + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + }, + ) + .await +} - #[test] - fn non_iam_always_passes() { - // Without IAM, an empty password is the caller's problem; the - // helper must never reject on its own. - require_iam_token(false, None, None).unwrap(); - require_iam_token(false, Some(""), Some("")).unwrap(); - } +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn duplicate_connection( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DuplicateConnection { id }, + ) + .await } -pub fn resolve_connection_params(params: &ConnectionParams) -> Result { - crate::application::tunnels::resolve_expanded_connection_params(params, None) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn delete_connection( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnection { id }, + ) + .await } -#[cfg(test)] -fn resolve_k8s_params(params: &ConnectionParams) -> Result { - crate::application::tunnels::resolve_k8s_params(params) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn test_connection( + app: AppHandle, + request: TestConnectionRequest, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::TestConnection { request }, + ) + .await } -#[cfg(test)] -fn resolve_ssm_params(params: &ConnectionParams) -> Result { - crate::application::tunnels::resolve_ssm_params(params) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn list_databases( + app: AppHandle, + request: TestConnectionRequest, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ListDatabases { request }, + ) + .await } -/// Resolve params for closing a pool without respawning tunnels. -/// -/// `build_connection_key` uses `connection_id` (plus driver/database/TLS), not -/// the tunnel's local port, so closing never needs a live SSH tunnel, SSM -/// session, or kubectl port-forward. Disabling all tunnel types here means a -/// dead bastion / unreachable cluster cannot prevent pool cleanup (#1065). -pub(crate) fn params_for_pool_close( - params: &ConnectionParams, - connection_id: &str, -) -> Result { - let mut for_close = params.clone(); - for_close.k8s_enabled = Some(false); - for_close.ssh_enabled = Some(false); - for_close.ssm_enabled = Some(false); - resolve_connection_params_with_id(&for_close, connection_id) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn get_connection_groups( + app: AppHandle, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnectionGroups, + ) + .await } -/// Resolve connection params and set connection_id for stable pooling -pub fn resolve_connection_params_with_id( - params: &ConnectionParams, - connection_id: &str, -) -> Result { - let mut with_id = params.clone(); - with_id.connection_id = Some(connection_id.to_string()); - resolve_connection_params(&with_id) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn create_connection_group( + app: AppHandle, + name: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateConnectionGroup { + name, + parent_id, + }, + ) + .await } #[cfg(feature = "desktop")] -pub fn get_config_path(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - Ok(crate::paths::resolve_connections_path(&config_dir)) +#[tauri::command] +pub async fn create_group_path( + app: AppHandle, + path: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateGroupPath { path, parent_id }, + ) + .await } #[cfg(feature = "desktop")] -pub fn get_ssh_config_path(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - Ok(config_dir.join("ssh_connections.json")) +#[tauri::command] +pub async fn update_connection_group( + app: AppHandle, + id: String, + name: Option, + collapsed: Option, + sort_order: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnectionGroup { + id, + name, + collapsed, + sort_order, + }, + ) + .await } -fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { - params - .connection_uri - .as_deref() - .filter(|value| !value.trim().is_empty()) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn move_group_to_parent( + app: AppHandle, + id: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::MoveGroupToParent { id, parent_id }, + ) + .await } -/// A connection URI embeds credentials, so it may only be persisted behind the -/// OS keychain. Refuse the save rather than silently downgrading to plaintext. -fn validate_connection_uri_persistence(params: &ConnectionParams) -> Result<(), String> { - if runtime_connection_uri(params).is_some() && !params.save_in_keychain.unwrap_or(false) { - return Err("Connection URIs must be stored in the OS keychain".to_string()); - } - Ok(()) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn delete_connection_group( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionGroup { id }, + ) + .await } -/// Write the secret first, then persist `connections.json`. If persistence -/// fails the secret is restored to its previous value so the keychain never -/// drifts from the file. -fn persist_secret_change( - apply: impl FnOnce() -> Result<(), String>, - persist: impl FnOnce() -> Result<(), String>, - rollback: impl FnOnce() -> Result<(), String>, -) -> Result<(), String> { - apply()?; - match persist() { - Ok(()) => Ok(()), - Err(error) => match rollback() { - Ok(()) => Err(error), - // Report both: the rollback error alone would hide why the save - // failed in the first place. - Err(rollback_error) => Err(format!("{error} ({rollback_error})")), +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn move_connection_to_group( + app: AppHandle, + connection_id: String, + group_id: Option, + sort_order: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::MoveConnectionToGroup { + connection_id, + group_id, + sort_order, }, - } + ) + .await } -/// The keychain URI to put back if persisting a change fails. A connection can -/// claim a keychain entry that was never written (duplicates used to copy the -/// flag but not the URI), so a missing entry means there is nothing to -/// restore. Only a genuine read failure aborts the change. -fn previous_keychain_connection_uri( - stored_in_keychain: bool, - read: impl FnOnce() -> Result, String>, -) -> Result, String> { - if !stored_in_keychain { - return Ok(None); - } - read().map_err(|_| "Failed to read the stored connection URI from the OS keychain".to_string()) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn reorder_groups( + app: AppHandle, + group_orders: Vec<(String, i32)>, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ReorderGroups { group_orders }, + ) + .await } -/// `change` is `None` to leave the stored URI untouched, `Some(Some(uri))` to -/// write it, and `Some(None)` to clear it. -fn persist_connection_uri_change( - cache: &credential_cache::CredentialCache, - connection_id: &str, - stored_in_keychain: bool, - change: Option>, - persist: impl FnOnce() -> Result<(), String>, -) -> Result<(), String> { - let Some(value) = change else { - return persist(); - }; - let previous_keychain = previous_keychain_connection_uri(stored_in_keychain, || { - keychain_utils::find_connection_uri(connection_id) - })?; - let previous_cache = cache - .connection_uris - .lock() - .unwrap() - .get(connection_id) - .cloned(); - - persist_secret_change( - || { - if let Some(value) = value { - keychain_utils::set_connection_uri(connection_id, value)?; - credential_cache::set_connection_uri_cached(cache, connection_id, value); - } else { - keychain_utils::delete_connection_uri(connection_id)?; - credential_cache::invalidate_connection_uri(cache, connection_id); - } - Ok(()) +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn reorder_connections_in_group( + app: AppHandle, + connection_orders: Vec<(String, i32)>, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ReorderConnectionsInGroup { + connection_orders, }, - persist, - || { - let keychain_result = match previous_keychain.as_deref() { - Some(value) => keychain_utils::set_connection_uri(connection_id, value), - None => keychain_utils::delete_connection_uri(connection_id), - }; - let mut entries = cache.connection_uris.lock().unwrap(); - match (&keychain_result, previous_cache) { - // Only re-pin the old value once the keychain actually holds it - // again. If the restore failed, drop the entry so the next read - // consults the keychain instead of trusting a stale copy. - (Ok(()), Some(entry)) => _ = entries.insert(connection_id.to_string(), entry), - (Ok(()), None) | (Err(_), _) => _ = entries.remove(connection_id), - } - keychain_result.map_err(|_| "Failed to roll back the stored connection URI".to_string()) + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn set_connection_appearance( + app: AppHandle, + id: String, + appearance: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SetConnectionAppearance { + id, + appearance, }, ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn list_connection_tags( + app: AppHandle, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ListConnectionTags, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn create_connection_tag( + app: AppHandle, + name: String, + color: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateConnectionTag { name, color }, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn update_connection_tag( + app: AppHandle, + id: String, + name: String, + color: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnectionTag { id, name, color }, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn delete_connection_tag( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionTag { id }, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn set_connection_tags( + app: AppHandle, + connection_id: String, + tag_ids: Vec, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SetConnectionTags { + connection_id, + tag_ids, + }, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn delete_connection_icon( + app: AppHandle, + relative_path: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionIcon { relative_path }, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn create_sqlite_database( + app: AppHandle, + path: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateSqliteDatabase { path }, + ) + .await +} + +pub fn resolve_connection_params(params: &ConnectionParams) -> Result { + crate::application::tunnels::resolve_expanded_connection_params(params, None) +} + +#[cfg(test)] +fn resolve_k8s_params(params: &ConnectionParams) -> Result { + crate::application::tunnels::resolve_k8s_params(params) +} + +#[cfg(test)] +fn resolve_ssm_params(params: &ConnectionParams) -> Result { + crate::application::tunnels::resolve_ssm_params(params) +} + +/// Resolve params for closing a pool without respawning tunnels. +/// +/// `build_connection_key` uses `connection_id` (plus driver/database/TLS), not +/// the tunnel's local port, so closing never needs a live SSH tunnel, SSM +/// session, or kubectl port-forward. Disabling all tunnel types here means a +/// dead bastion / unreachable cluster cannot prevent pool cleanup (#1065). +pub(crate) fn params_for_pool_close( + params: &ConnectionParams, + connection_id: &str, +) -> Result { + let mut for_close = params.clone(); + for_close.k8s_enabled = Some(false); + for_close.ssh_enabled = Some(false); + for_close.ssm_enabled = Some(false); + resolve_connection_params_with_id(&for_close, connection_id) } -/// Keychain secrets a connection save wrote, each with the value it held -/// before. If the config file write fails afterwards they are put back, so a -/// save that never landed doesn't leave secrets behind in the keychain. -#[derive(Default)] -struct KeychainSecretWrites { - db_password: Option>, - ssh_password: Option>, - ssh_key_passphrase: Option>, +/// Resolve connection params and set connection_id for stable pooling +pub fn resolve_connection_params_with_id( + params: &ConnectionParams, + connection_id: &str, +) -> Result { + let mut with_id = params.clone(); + with_id.connection_id = Some(connection_id.to_string()); + resolve_connection_params(&with_id) } -impl KeychainSecretWrites { - /// Delete every secret this save wrote to the keychain. Used once the - /// config file landed with the secrets inline because a later keychain - /// write failed, so nothing the config doesn't point at is left behind. - fn discard(self, cache: &credential_cache::CredentialCache, connection_id: &str) { - Self { - db_password: self.db_password.map(|_| None), - ssh_password: self.ssh_password.map(|_| None), - ssh_key_passphrase: self.ssh_key_passphrase.map(|_| None), - } - .roll_back(cache, connection_id); +#[cfg(feature = "desktop")] +pub fn get_config_path(_app: &AppHandle) -> Result { + let config_dir = crate::paths::get_app_config_dir(); + if !config_dir.exists() { + fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; } + Ok(crate::paths::resolve_connections_path(&config_dir)) +} - fn roll_back(self, cache: &credential_cache::CredentialCache, connection_id: &str) { - fn restore( - label: &str, - connection_id: &str, - previous: Option, - set: impl FnOnce(&str) -> Result<(), String>, - delete: impl FnOnce() -> Result<(), String>, - ) { - let result = match previous.as_deref() { - Some(value) => set(value), - None => delete(), - }; - if let Err(err) = result { - log::warn!( - "Failed to roll back the {} for {} after a failed save: {}", - label, - connection_id, - err - ); - } - } - - if let Some(previous) = self.db_password { - restore( - "DB password", - connection_id, - previous, - |value| keychain_utils::set_db_password(connection_id, value), - || keychain_utils::delete_db_password(connection_id), - ); - credential_cache::invalidate_db_password(cache, connection_id); - } - if let Some(previous) = self.ssh_password { - restore( - "SSH password", - connection_id, - previous, - |value| keychain_utils::set_ssh_password(connection_id, value), - || keychain_utils::delete_ssh_password(connection_id), - ); - credential_cache::invalidate_ssh_password(cache, connection_id); - } - if let Some(previous) = self.ssh_key_passphrase { - restore( - "SSH key passphrase", - connection_id, - previous, - |value| keychain_utils::set_ssh_key_passphrase(connection_id, value), - || keychain_utils::delete_ssh_key_passphrase(connection_id), - ); - credential_cache::invalidate_ssh_key_passphrase(cache, connection_id); - } +#[cfg(feature = "desktop")] +pub fn get_ssh_config_path(_app: &AppHandle) -> Result { + let config_dir = crate::paths::get_app_config_dir(); + if !config_dir.exists() { + fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; } + Ok(config_dir.join("ssh_connections.json")) } -/// Strip the URI out of the params that go to `connections.json`, leaving only -/// the marker that says a keychain entry exists. -fn params_for_persistence( - params: &ConnectionParams, - connection_uri_in_keychain: bool, -) -> ConnectionParams { - let mut persisted = params.clone(); - persisted.connection_uri = None; - persisted.connection_uri_in_keychain = connection_uri_in_keychain.then_some(true); - persisted +fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { + params + .connection_uri + .as_deref() + .filter(|value| !value.trim().is_empty()) } /// Re-attach the URI a saved connection needs at runtime, from the session @@ -587,18 +724,6 @@ pub(crate) fn merge_groups(existing: &mut Vec, incoming: Vec) -> Result, String> { - match env.as_deref() { - None | Some("") => Ok(None), - Some("development" | "staging" | "production") => Ok(env), - Some(other) => Err(format!("Invalid environment: {other}")), - } -} - #[cfg(feature = "desktop")] pub(crate) fn save_connections_and_invalidate( app: &AppHandle, @@ -831,766 +956,55 @@ pub async fn get_routine_edit_script( &app.state::(), None, &connection_id, - routine_name, - routine_type, - schema, - database, - identity_args, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_routine( - app: AppHandle, - connection_id: String, - routine_name: String, - routine_type: String, - schema: Option, - database: Option, - identity_args: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_routine( - &app.state::(), - None, - &connection_id, - routine_name, - routine_type, - schema, - database, - identity_args, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_schema_snapshot( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_schema_snapshot( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_ai_schema_context( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result { - let saved_conn = find_connection_by_id(&app, &connection_id)?; - let expanded_params = expand_ssh_connection_params(&app, &saved_conn.params).await?; - let expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; - let mut params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let driver = driver_for_params(¶ms).await?; - let identifier_quote = driver.manifest().capabilities.identifier_quote.as_str(); - let context = driver - .get_ai_schema_context( - ¶ms, - schema.as_deref(), - crate::ai_schema_context::DEFAULT_MAX_TABLES, - ) - .await?; - - Ok(crate::ai_schema_context::format_for_prompt( - &context, - identifier_quote, - )) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_connection( - app: AppHandle, - name: String, - params: ConnectionParams, - plugin_secret_changes: Option, - detect_json_in_text_columns: Option, - environment: Option, -) -> Result { - log::info!("Saving new connection: {}", name); - validate_connection_uri_persistence(¶ms)?; - - let path = get_config_path(&app)?; - let mut conn_file = persistence::load_connections_file(&path).unwrap_or_default(); - - let id = Uuid::new_v4().to_string(); - let cache = app.state::>(); - let plugin_secret_changes = plugin_secret_changes.unwrap_or_default(); - let plugin_secret_keys = - crate::plugin_secrets::next_secret_keys(&[], true, &plugin_secret_changes)?; - let connection_uri = runtime_connection_uri(¶ms).map(str::to_owned); - let mut params_to_save = params_for_persistence(¶ms, connection_uri.is_some()); - let mut keychain_writes = KeychainSecretWrites::default(); - for key in plugin_secret_changes.keys() { - params_to_save.extra.remove(key); - } - - if params.save_in_keychain.unwrap_or(false) { - log::debug!("Storing passwords in keychain for connection: {}", name); - let mut keychain_stored = true; - match keychain_utils::stored_password_change(params.password.as_deref()) { - keychain_utils::StoredPasswordChange::Store(pwd) => { - match keychain_utils::set_db_password(&id, pwd) { - Ok(()) => { - keychain_writes.db_password = Some(None); - credential_cache::set_db_password_cached(&cache, &id, pwd); - } - Err(err) => { - log::warn!( - "Keychain unavailable while saving connection {}; storing secrets in the config file: {}", - name, err - ); - keychain_stored = false; - } - } - } - // A fresh id has nothing to delete; an empty password is simply - // not stored (keyutils would reject it anyway). - keychain_utils::StoredPasswordChange::Keep - | keychain_utils::StoredPasswordChange::Delete => {} - } - if keychain_stored && params.ssh_enabled.unwrap_or(false) { - if let Some(ssh_pwd) = ¶ms.ssh_password { - match keychain_utils::set_ssh_password(&id, ssh_pwd) { - Ok(()) => { - keychain_writes.ssh_password = Some(None); - credential_cache::set_ssh_password_cached(&cache, &id, ssh_pwd); - } - Err(err) => { - log::warn!( - "Keychain unavailable while saving the SSH password for {}; storing secrets in the config file: {}", - name, err - ); - keychain_stored = false; - } - } - } - if keychain_stored { - if let Some(ssh_passphrase) = ¶ms.ssh_key_passphrase { - if !ssh_passphrase.trim().is_empty() { - match keychain_utils::set_ssh_key_passphrase(&id, ssh_passphrase) { - Ok(()) => { - keychain_writes.ssh_key_passphrase = Some(None); - credential_cache::set_ssh_key_passphrase_cached( - &cache, - &id, - ssh_passphrase, - ); - } - Err(err) => { - log::warn!( - "Keychain unavailable while saving the SSH key passphrase for {}; storing secrets in the config file: {}", - name, err - ); - keychain_stored = false; - } - } - } - } - } - } - persistence::apply_secret_persistence(&mut params_to_save, keychain_stored); - } - - let persisted_in_keychain = params_to_save.save_in_keychain.unwrap_or(false); - let new_conn = SavedConnection { - id: id.clone(), - name: name.clone(), - params: params_to_save, - plugin_secret_keys, - group_id: None, - sort_order: None, - detect_json_in_text_columns, - appearance: None, - tag_ids: None, - environment: validate_environment(environment)?, - }; - conn_file.connections.push(new_conn.clone()); - if let Err(err) = crate::plugin_secrets::persist_secret_changes( - &cache, - &id, - None, - &[], - ¶ms.driver, - &plugin_secret_changes, - || { - persist_connection_uri_change( - &cache, - &id, - false, - connection_uri.as_deref().map(Some), - || save_connections_and_invalidate(&app, &path, &conn_file), - ) - }, - ) { - keychain_writes.roll_back(&cache, &id); - return Err(err); - } - if !persisted_in_keychain { - // A later keychain write failed and the secrets went to the config - // file instead; drop the ones that did reach the keychain. - keychain_writes.discard(&cache, &id); - } - - log::info!("Connection saved successfully: {} (ID: {})", name, id); - - let requested_keychain = params.save_in_keychain.unwrap_or(false); - let mut returned_conn = new_conn; - returned_conn.params = params; // Return with password for frontend state - if requested_keychain && !persisted_in_keychain { - returned_conn.params.save_in_keychain = Some(false); - } - Ok(returned_conn) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection(app: AppHandle, id: String) -> Result<(), String> { - log::info!("Deleting connection: {}", id); - - let path = get_config_path(&app)?; - if !path.exists() { - return Ok(()); - } - - let mut conn_file = persistence::load_connections_file(&path)?; - - let cache = app.state::>(); - let uri_stored_in_keychain = conn_file - .connections - .iter() - .find(|c| c.id == id) - .and_then(|c| c.params.connection_uri_in_keychain) - .unwrap_or(false); - let plugin_secret_metadata = conn_file - .connections - .iter() - .find(|c| c.id == id) - .map(|c| (c.params.driver.clone(), c.plugin_secret_keys.clone())); - - // Capture the appearance before retain so we can cascade-delete the icon file. - let appearance_to_delete = conn_file - .connections - .iter() - .find(|c| c.id == id) - .and_then(|c| c.appearance.clone()); - - let initial_count = conn_file.connections.len(); - conn_file.connections.retain(|c| c.id != id); - let deleted = conn_file.connections.len() < initial_count; - - // Attempt to remove passwords from keychain (ignore if not found) - keychain_utils::delete_db_password(&id).ok(); - keychain_utils::delete_ssh_password(&id).ok(); - keychain_utils::delete_ssh_key_passphrase(&id).ok(); - persist_connection_uri_change(&cache, &id, uri_stored_in_keychain, Some(None), || { - save_connections_and_invalidate(&app, &path, &conn_file) - })?; - if let Some((driver, keys)) = plugin_secret_metadata { - crate::plugin_secrets::delete_connection_secrets(&cache, &id, &driver, &keys); - } - // Invalidate the in-memory cache for this connection - credential_cache::invalidate_all_for_connection(&cache, &id); - - // Cascade-delete the custom icon file if the connection used one. - { - let app_data = crate::paths::get_app_data_dir(); - let _ = crate::connection_appearance::cascade_delete_if_image( - &app_data, - appearance_to_delete.as_ref(), - ); - } - - // Clean up query history for this connection - if let Err(e) = crate::query_history::remove_history_for_connection(&app, &id).await { - log::warn!( - "Failed to remove query history for connection {}: {}", - id, - e - ); - } - - if deleted { - log::info!("Connection deleted successfully: {}", id); - } else { - log::warn!("Connection not found for deletion: {}", id); - } - - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection( - app: AppHandle, - id: String, - name: String, - params: ConnectionParams, - plugin_secret_changes: Option, - detect_json_in_text_columns: Option, - environment: Option, -) -> Result { - validate_connection_uri_persistence(¶ms)?; - let path = get_config_path(&app)?; - let mut conn_file = persistence::load_connections_file(&path)?; - - let conn_idx = conn_file - .connections - .iter() - .position(|c| c.id == id) - .ok_or("Connection not found")?; - - let existing_uri_in_keychain = conn_file.connections[conn_idx] - .params - .connection_uri_in_keychain - .unwrap_or(false); - // A stored URI belongs to the driver that produced it. Switching drivers - // must drop it rather than hand one driver's credentials to another. - let previous_driver_id = conn_file.connections[conn_idx].params.driver.clone(); - let same_driver = previous_driver_id == params.driver; - let original_plugin_secret_keys = conn_file.connections[conn_idx].plugin_secret_keys.clone(); - let plugin_secret_changes = plugin_secret_changes.unwrap_or_default(); - let plugin_secret_keys = crate::plugin_secrets::next_secret_keys( - &original_plugin_secret_keys, - same_driver, - &plugin_secret_changes, - )?; - let connection_uri = runtime_connection_uri(¶ms).map(str::to_owned); - // The frontend sends the URI back only when the user retyped it. An edit - // that leaves the field untouched must keep the stored secret; an edit that - // explicitly clears the marker must delete it. - let preserve_stored_uri = connection_uri.is_none() - && same_driver - && params.save_in_keychain.unwrap_or(false) - && existing_uri_in_keychain - && params.connection_uri_in_keychain != Some(false); - let uri_change = match connection_uri.as_deref() { - Some(value) => Some(Some(value)), - None if preserve_stored_uri => None, - None => Some(None), - }; - let mut params_to_save = - params_for_persistence(¶ms, connection_uri.is_some() || preserve_stored_uri); - for key in plugin_secret_changes.keys() { - params_to_save.extra.remove(key); - } - - let cache = app.state::>(); - let mut keychain_writes = KeychainSecretWrites::default(); - if params.save_in_keychain.unwrap_or(false) { - let mut keychain_stored = true; - match keychain_utils::stored_password_change(params.password.as_deref()) { - keychain_utils::StoredPasswordChange::Store(pwd) => { - let previous = keychain_utils::get_db_password(&id, "").ok(); - match keychain_utils::set_db_password(&id, pwd) { - Ok(()) => { - keychain_writes.db_password = Some(previous); - credential_cache::set_db_password_cached(&cache, &id, pwd); - } - Err(err) => { - log::warn!( - "Keychain unavailable while updating connection {}; storing secrets in the config file: {}", - id, err - ); - keychain_stored = false; - } - } - } - // The frontend sends an explicit empty password when a plugin hid - // the login inputs. The previous secret must not survive, or the - // next connect would hand a stale login to the driver. - keychain_utils::StoredPasswordChange::Delete => { - let previous = keychain_utils::get_db_password(&id, "").ok(); - keychain_utils::delete_db_password(&id)?; - keychain_writes.db_password = Some(previous); - credential_cache::invalidate_db_password(&cache, &id); - } - keychain_utils::StoredPasswordChange::Keep => {} - } - if keychain_stored && params.ssh_enabled.unwrap_or(false) { - if let Some(ssh_pwd) = ¶ms.ssh_password { - let previous = keychain_utils::get_ssh_password(&id, "").ok(); - match keychain_utils::set_ssh_password(&id, ssh_pwd) { - Ok(()) => { - keychain_writes.ssh_password = Some(previous); - credential_cache::set_ssh_password_cached(&cache, &id, ssh_pwd); - } - Err(err) => { - log::warn!( - "Keychain unavailable while updating the SSH password for {}; storing secrets in the config file: {}", - id, err - ); - keychain_stored = false; - } - } - } - if keychain_stored { - if let Some(ssh_passphrase) = ¶ms.ssh_key_passphrase { - if !ssh_passphrase.trim().is_empty() { - let previous = keychain_utils::get_ssh_key_passphrase(&id, "").ok(); - match keychain_utils::set_ssh_key_passphrase(&id, ssh_passphrase) { - Ok(()) => { - keychain_writes.ssh_key_passphrase = Some(previous); - credential_cache::set_ssh_key_passphrase_cached( - &cache, - &id, - ssh_passphrase, - ); - } - Err(err) => { - log::warn!( - "Keychain unavailable while updating the SSH key passphrase for {}; storing secrets in the config file: {}", - id, err - ); - keychain_stored = false; - } - } - } - } - } - } else if keychain_stored { - keychain_utils::delete_ssh_password(&id).ok(); - keychain_utils::delete_ssh_key_passphrase(&id).ok(); - credential_cache::invalidate_ssh_password(&cache, &id); - credential_cache::invalidate_ssh_key_passphrase(&cache, &id); - } - persistence::apply_secret_persistence(&mut params_to_save, keychain_stored); - } else { - keychain_utils::delete_db_password(&id).ok(); - keychain_utils::delete_ssh_password(&id).ok(); - keychain_utils::delete_ssh_key_passphrase(&id).ok(); - // The connection URI is cleared by its own transaction below, which - // needs the previous cache entry intact to roll back. - credential_cache::invalidate_db_password(&cache, &id); - credential_cache::invalidate_ssh_password(&cache, &id); - credential_cache::invalidate_ssh_key_passphrase(&cache, &id); - } - - // Preserve existing group_id and sort_order from the original connection - let original_group_id = conn_file.connections[conn_idx].group_id.clone(); - let original_sort_order = conn_file.connections[conn_idx].sort_order; - let original_db_selection = conn_file.connections[conn_idx].params.database.clone(); - // Preserve user's appearance customization across edits - let original_appearance = conn_file.connections[conn_idx].appearance.clone(); - // Tags are managed by set_connection_tags; preserve them across edits. - let original_tag_ids = conn_file.connections[conn_idx].tag_ids.clone(); - let persisted_in_keychain = params_to_save.save_in_keychain.unwrap_or(false); - - let updated = SavedConnection { - id: id.clone(), - name, - params: params_to_save, - plugin_secret_keys, - group_id: original_group_id, - sort_order: original_sort_order, - detect_json_in_text_columns, - appearance: original_appearance, - tag_ids: original_tag_ids, - environment: validate_environment(environment)?, - }; - - conn_file.connections[conn_idx] = updated.clone(); - - if let Err(err) = crate::plugin_secrets::persist_secret_changes( - &cache, - &id, - Some(&previous_driver_id), - &original_plugin_secret_keys, - ¶ms.driver, - &plugin_secret_changes, - || { - persist_connection_uri_change(&cache, &id, existing_uri_in_keychain, uri_change, || { - save_connections_and_invalidate(&app, &path, &conn_file) - }) - }, - ) { - keychain_writes.roll_back(&cache, &id); - return Err(err); - } - if !persisted_in_keychain { - // Same as save: the fallback put the secrets in the config file, so - // the keychain copies from this update are orphans. - keychain_writes.discard(&cache, &id); - } - - let mut metadata_changed = false; - for driver_id in [&previous_driver_id, &updated.params.driver] { - if let Some(driver) = crate::drivers::registry::get_driver(driver_id).await { - if driver.has_connection_metadata() { - driver.invalidate_connection_metadata(Some(&id)).await; - metadata_changed = true; - } - } - } - if metadata_changed { - let _ = app.emit( - "connection-metadata-invalidated", - serde_json::json!({"connectionId": id}), - ); - } - - // On single→multi transition, associate existing favorites/history (with no - // database set) to the original single database name. - if let Some(previous_db) = - crate::models::single_db_before_multi_transition(&original_db_selection, ¶ms.database) - { - if let Err(e) = - crate::saved_queries::backfill_missing_database_for_connection(&app, &id, &previous_db) - { - log::warn!("Failed to backfill saved query database for {}: {}", id, e); - } - if let Err(e) = - crate::query_history::backfill_missing_database_for_connection(&app, &id, &previous_db) - .await - { - log::warn!( - "Failed to backfill query history database for {}: {}", - id, - e - ); - } - } - - let requested_keychain = params.save_in_keychain.unwrap_or(false); - let mut returned_conn = updated; - returned_conn.params = params; - if requested_keychain && !persisted_in_keychain { - returned_conn.params.save_in_keychain = Some(false); - } - Ok(returned_conn) -} - -/// Pure, testable core of `set_connection_appearance`. -/// Mutates `file` in place; does not touch disk or Tauri state. -fn set_appearance_impl( - file: &mut ConnectionsFile, - id: &str, - appearance: Option, -) -> Result<(), String> { - let conn = file - .connections - .iter_mut() - .find(|c| c.id == id) - .ok_or("Connection not found")?; - conn.appearance = appearance; - Ok(()) + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] -pub async fn set_connection_appearance( +pub async fn drop_routine( app: AppHandle, - id: String, - appearance: Option, + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, ) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut conn_file = persistence::load_connections_file(&path)?; - set_appearance_impl(&mut conn_file, &id, appearance)?; - save_connections_and_invalidate(&app, &path, &conn_file)?; - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn duplicate_connection( - app: AppHandle, - id: String, -) -> Result { - let path = get_config_path(&app)?; - let mut conn_file = persistence::load_connections_file(&path)?; - - let original_idx = conn_file - .connections - .iter() - .position(|c| c.id == id) - .ok_or("Connection not found")?; - let mut original = conn_file.connections[original_idx].clone(); - - let cache = app.state::>(); - // Same tolerant read as a driver call: a secret missing from the keychain - // is not copied, and the duplicate does not list it. - let plugin_secret_changes = crate::plugin_secrets::duplicate_secret_changes( - &original.id, - &original.plugin_secret_keys, - |key| { - credential_cache::get_plugin_secret_cached( - &cache, - &original.id, - &original.params.driver, - key, - ) - }, - ); - let duplicate_plugin_secret_keys = - crate::plugin_secrets::next_secret_keys(&[], true, &plugin_secret_changes)?; - - // Same IAM-auth guard as `find_connection_by_id`: never copy a stale RDS - // auth token into a duplicated connection. - if original.params.save_in_keychain.unwrap_or(false) - && !original.params.use_iam_auth.unwrap_or(false) - { - if let Ok(pwd) = credential_cache::get_db_password_cached(&cache, &original.id) { - original.params.password = Some(pwd); - } - if original.params.ssh_enabled.unwrap_or(false) { - if let Ok(ssh_pwd) = credential_cache::get_ssh_password_cached(&cache, &original.id) { - if !ssh_pwd.trim().is_empty() { - original.params.ssh_password = Some(ssh_pwd); - } - } - if let Ok(ssh_passphrase) = - credential_cache::get_ssh_key_passphrase_cached(&cache, &original.id) - { - if !ssh_passphrase.trim().is_empty() { - original.params.ssh_key_passphrase = Some(ssh_passphrase); - } - } - } - } - - let new_id = Uuid::new_v4().to_string(); - let mut new_params = original.params.clone(); - - // Save passwords to new keychain entries if enabled - if new_params.save_in_keychain.unwrap_or(false) { - if let Some(pwd) = &new_params.password { - keychain_utils::set_db_password(&new_id, pwd)?; - credential_cache::set_db_password_cached(&cache, &new_id, pwd); - } - if new_params.ssh_enabled.unwrap_or(false) { - if let Some(ssh_pwd) = &new_params.ssh_password { - keychain_utils::set_ssh_password(&new_id, ssh_pwd)?; - credential_cache::set_ssh_password_cached(&cache, &new_id, ssh_pwd); - } - if let Some(ssh_passphrase) = &new_params.ssh_key_passphrase { - if !ssh_passphrase.trim().is_empty() { - keychain_utils::set_ssh_key_passphrase(&new_id, ssh_passphrase)?; - credential_cache::set_ssh_key_passphrase_cached( - &cache, - &new_id, - ssh_passphrase, - ); - } - } - } - new_params.password = None; - new_params.ssh_password = None; - new_params.ssh_key_passphrase = None; - } - - // A connection URI only lives in the keychain, under the original's id. - // Give the duplicate its own entry, or drop the marker if there is nothing - // to copy: a marker without an entry leaves a copy that can neither - // connect nor be deleted. - let original_uri = if original.params.connection_uri_in_keychain.unwrap_or(false) { - credential_cache::get_connection_uri_cached(&cache, &original.id, true) - .ok() - .flatten() - } else { - None - }; - if let Some(uri) = &original_uri { - keychain_utils::set_connection_uri(&new_id, uri)?; - credential_cache::set_connection_uri_cached(&cache, &new_id, uri); - } - new_params = params_for_persistence(&new_params, original_uri.is_some()); - - // Copy the icon file so the duplicate owns its own copy. - // If the original has an Image icon, the duplicate must not share the same file path — - // deleting either connection would otherwise cascade-delete the shared file and break - // the other connection's icon. We copy the file; on failure we drop the icon rather - // than sharing the path. - let new_appearance = { - let mut app_earance = original.appearance.clone(); - if let Some(ref mut a) = app_earance { - if let Some(crate::models::IconOverride::Image { ref path }) = a.icon.clone() { - let app_data = crate::paths::get_app_data_dir(); - match crate::connection_appearance::copy_icon_for_duplicate( - &app_data, path, &new_id, - ) { - Ok(new_path) => { - a.icon = Some(crate::models::IconOverride::Image { path: new_path }); - } - Err(_) => { - // Couldn't copy — drop the icon to avoid sharing - a.icon = None; - if a.accent_color.is_none() { - app_earance = None; - } - } - } - } - } - app_earance - }; - - let new_conn = SavedConnection { - id: new_id.clone(), - name: format!("{} (Copy)", original.name), - params: new_params, - plugin_secret_keys: duplicate_plugin_secret_keys, - group_id: original.group_id.clone(), // Copy to same group as original - sort_order: None, // Will be placed at end of group - detect_json_in_text_columns: original.detect_json_in_text_columns, - appearance: new_appearance, - tag_ids: original.tag_ids.clone(), - // Normalize rather than fail: an invalid on-disk value must not - // block duplication, the copy just becomes "unclassified". - environment: validate_environment(original.environment.clone()).unwrap_or(None), - }; - - conn_file.connections.push(new_conn.clone()); - - crate::plugin_secrets::persist_secret_changes( - &cache, - &new_id, + crate::application::database_objects::drop_routine( + &app.state::(), None, - &[], - &original.params.driver, - &plugin_secret_changes, - || save_connections_and_invalidate(&app, &path, &conn_file), - )?; - - let mut returned_conn = new_conn; - // Return with passwords for frontend consistency - if returned_conn.params.save_in_keychain.unwrap_or(false) { - // We can just use the values from `original.params` as they are identical (unless we cleared them in new_params) - // Actually original.params holds the clear text now. - returned_conn.params.password = original.params.password; - returned_conn.params.ssh_password = original.params.ssh_password; - returned_conn.params.ssh_key_passphrase = original.params.ssh_key_passphrase; - } - - Ok(returned_conn) + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] -pub async fn get_connections( +pub async fn get_schema_snapshot( app: AppHandle, -) -> Result, String> { - // Run migrations if needed - migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); - - let path = get_config_path(&app)?; - crate::application::connections::load_connections(&path) + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_schema_snapshot( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await } // ==================== SSH Connection Management ==================== @@ -1869,85 +1283,131 @@ pub async fn delete_k8s_connection( ) } +#[cfg(feature = "desktop")] +async fn execute_tunnel_command( + app: &AppHandle, + command: crate::application::tunnels::TunnelCommand, +) -> Result { + crate::application::tunnels::execute( + &app.state::(), + None, + command, + ) + .await +} + #[cfg(feature = "desktop")] #[tauri::command] pub async fn test_k8s_connection_cmd( - _app: AppHandle, + app: AppHandle, context: String, namespace: String, kubectl_path: Option, kubeconfig_path: Option, -) -> Result { +) -> Result { let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::test_k8s_connection(&context, &namespace, &options) + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::TestK8sConnection { + context, + namespace, + options, + }, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_contexts_cmd( - _app: AppHandle, + app: AppHandle, kubectl_path: Option, kubeconfig_path: Option, -) -> Result, String> { +) -> Result { let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_contexts(&options) + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sContexts { options }, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_namespaces_cmd( - _app: AppHandle, + app: AppHandle, context: String, kubectl_path: Option, kubeconfig_path: Option, -) -> Result, String> { +) -> Result { let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_namespaces(&context, &options) + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sNamespaces { context, options }, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_resources_cmd( - _app: AppHandle, + app: AppHandle, context: String, namespace: String, resource_type: String, kubectl_path: Option, kubeconfig_path: Option, -) -> Result, String> { +) -> Result { let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_resources(&context, &namespace, &resource_type, &options) + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sResources { + context, + namespace, + resource_type, + options, + }, + ) + .await } #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_k8s_resource_ports_cmd( - _app: AppHandle, + app: AppHandle, context: String, namespace: String, resource_type: String, resource_name: String, kubectl_path: Option, kubeconfig_path: Option, -) -> Result, String> { +) -> Result { let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_resource_ports( - &context, - &namespace, - &resource_type, - &resource_name, - &options, + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sResourcePorts { + context, + namespace, + resource_type, + resource_name, + options, + }, ) + .await } #[cfg(feature = "desktop")] #[tauri::command] pub async fn validate_k8s_path_cmd( - _app: AppHandle, + app: AppHandle, path: String, kind: String, -) -> Result<(), String> { - crate::k8s_tunnel::validate_k8s_path(&path, &kind) +) -> Result { + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::ValidateK8sPath { path, kind }, + ) + .await } // --------------------------------------------------------------------------- @@ -1963,10 +1423,9 @@ pub async fn test_ssm_connection_cmd( region: Option, host: String, port: u16, -) -> Result { - let result = crate::application::tunnels::execute( - &app.state::(), - None, +) -> Result { + execute_tunnel_command( + &app, crate::application::tunnels::TunnelCommand::TestSsmConnection { target, profile, @@ -1975,8 +1434,7 @@ pub async fn test_ssm_connection_cmd( port, }, ) - .await?; - serde_json::from_value(result).map_err(|e| e.to_string()) + .await } #[cfg(feature = "desktop")] @@ -1993,228 +1451,6 @@ pub async fn expand_k8s_connection_params( crate::application::tunnels::resolve_expanded_connection_params(&expanded, None) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn test_connection( - app: AppHandle, - request: TestConnectionRequest, -) -> Result { - log::info!( - "Testing connection to database: {}", - request.params.database - ); - let progress_id = request.progress_id.as_deref(); - // The saved connection, without plugin secrets: they are resolved below, - // after the pending changes from the modal are known. - let saved_conn = match &request.connection_id { - Some(id) => find_connection_metadata_by_id(&app, id).ok(), - None => None, - }; - - let mut expanded_params = expand_ssh_connection_params(&app, &request.params) - .await - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - expanded_params = expand_k8s_connection_params(&app, &expanded_params) - .await - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - - // AWS RDS IAM auth tokens are short-lived (15 min) and must come from the - // password field on every test/connect, never from the keychain. Skip the - // keychain fallback so a stale token can't be reused. - let iam_auth = expanded_params.use_iam_auth.unwrap_or(false); - - // IAM auth needs an RDS auth token right now. Without this guard the - // builder accepts an empty password, the server replies with the opaque - // "Access denied (using password: YES)", and the user can't tell whether - // the token is missing, wrong, or expired. - require_iam_token( - iam_auth, - request.params.password.as_deref(), - expanded_params.password.as_deref(), - ) - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - - if !iam_auth && request.params.password.is_none() && expanded_params.password.is_none() { - expanded_params.password = - resolve_test_connection_password(&request.params, saved_conn.as_ref(), |conn_id| { - keychain_utils::get_db_password(conn_id, "") - }); - } - - // Plugin-owned secrets: stored values of the saved connection, overridden - // by whatever the modal is about to set or clear. - { - let cache = app.state::>(); - crate::plugin_secrets::apply_request_secrets( - &cache, - saved_conn.as_ref(), - &mut expanded_params, - &request.plugin_secret_changes, - ) - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - } - - // Reconnecting to a saved connection sends the on-disk params, which never - // carry the URI — restore it the same way the password is restored above. - // An inline URI (the ephemeral Test Connection flow) always wins. - if runtime_connection_uri(&expanded_params).is_none() { - if let Some(conn_id) = &request.connection_id { - let cache = app.state::>(); - restore_runtime_connection_uri(&cache, conn_id, &mut expanded_params) - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - } - } - - let ssh_enabled = expanded_params.ssh_enabled.unwrap_or(false); - let k8s_enabled = expanded_params.k8s_enabled.unwrap_or(false); - let ssm_enabled = expanded_params.ssm_enabled.unwrap_or(false); - let tunnel_step = if ssh_enabled { - Some("sshTunnel") - } else if k8s_enabled { - Some("k8sForward") - } else if ssm_enabled { - Some("ssmForward") - } else { - None - }; - - if ssh_enabled { - emit_test_progress( - &app, - progress_id, - "sshTunnel", - "start", - Some(format!( - "{}@{}:{}", - expanded_params.ssh_user.as_deref().unwrap_or("?"), - expanded_params.ssh_host.as_deref().unwrap_or("?"), - expanded_params.ssh_port.unwrap_or(22) - )), - ); - } else if k8s_enabled { - emit_test_progress( - &app, - progress_id, - "k8sForward", - "start", - expanded_params.k8s_resource_name.clone(), - ); - } else if ssm_enabled { - emit_test_progress( - &app, - progress_id, - "ssmForward", - "start", - expanded_params.ssm_target.clone(), - ); - } - - let resolved_params = if let Some(conn_id) = &request.connection_id { - resolve_connection_params_with_id(&expanded_params, conn_id) - } else { - resolve_connection_params(&expanded_params) - } - .map_err(|e| emit_test_failure(&app, progress_id, tunnel_step.unwrap_or("resolve"), e))?; - log::debug!( - "Test connection params: Host={:?}, Port={:?}", - resolved_params.host, - resolved_params.port - ); - - if let Some(step) = tunnel_step { - emit_test_progress( - &app, - progress_id, - step, - "ok", - resolved_params.port.map(|port| format!("127.0.0.1:{port}")), - ); - } - - let drv = driver_for(&resolved_params.driver) - .await - .map_err(|e| emit_test_failure(&app, progress_id, "resolve", e))?; - - let db_target = match (expanded_params.host.as_deref(), expanded_params.port) { - (Some(host), Some(port)) => format!("{host}:{port}"), - (Some(host), None) => host.to_string(), - _ => expanded_params.database.to_string(), - }; - emit_test_progress(&app, progress_id, "dbConnect", "start", Some(db_target)); - - // For file-based drivers, verify the database file exists before attempting - // connection, unless the driver opens `:memory:` as a temporary database. - let capabilities = &drv.manifest().capabilities; - if capabilities.file_based - && crate::fs_path::requires_existing_database_file( - capabilities.in_memory, - resolved_params.database.primary(), - ) - { - let db_path = if resolved_params.driver == "sqlite" { - crate::sqlite_database::expand_sqlite_filename(resolved_params.database.primary()) - } else { - PathBuf::from(resolved_params.database.primary()) - }; - if !db_path.exists() { - let err = format!("Database file not found: {}", resolved_params.database); - return Err(emit_test_failure(&app, progress_id, "dbConnect", err)); - } - } - - drv.test_connection(&resolved_params).await.map_err(|e| { - log::warn!( - "Connection test failed for database {}: {e}", - request.params.database - ); - emit_test_failure(&app, progress_id, "dbConnect", e) - })?; - - drv.invalidate_connection_metadata(resolved_params.connection_id.as_deref()) - .await; - - emit_test_progress(&app, progress_id, "dbConnect", "ok", None); - log::info!( - "Connection test successful for database: {}", - request.params.database - ); - Ok("Connection successful!".to_string()) -} - -#[cfg(feature = "desktop")] -/// Emits one step of a connection test's live progress log. A no-op when the -/// caller did not request progress (no id). -fn emit_test_progress( - app: &AppHandle, - progress_id: Option<&str>, - step: &str, - status: &str, - detail: Option, -) { - let Some(id) = progress_id else { return }; - let _ = app.emit( - "connection-test-progress", - serde_json::json!({ - "id": id, - "step": step, - "status": status, - "detail": detail, - }), - ); -} - -#[cfg(feature = "desktop")] -/// Emits a failed step and passes the error through, for use in `map_err`. -fn emit_test_failure( - app: &AppHandle, - progress_id: Option<&str>, - step: &str, - error: String, -) -> String { - emit_test_progress(app, progress_id, step, "error", Some(error.clone())); - error -} - #[cfg(test)] mod tests { use super::*; @@ -2262,105 +1498,26 @@ mod tests { assert_eq!(resolved.ssh_enabled, Some(false)); assert_eq!(resolved.ssm_enabled, Some(false)); // connection_id is set for stable pool keying. - assert_eq!(resolved.connection_id.as_deref(), Some("conn-1")); - } - - #[test] - fn resolve_sanitizes_local_path_driver_databases() { - let driver = "__test_resolve_local_path_driver__"; - crate::drivers::registry::set_local_path_driver(driver, true); - let params = ConnectionParams { - driver: driver.to_string(), - host: None, - port: None, - database: DatabaseSelection::Single(r#""file:///tmp/my%20data.db""#.to_string()), - ..Default::default() - }; - - let resolved = resolve_connection_params(¶ms); - crate::drivers::registry::set_local_path_driver(driver, false); - assert_eq!( - resolved.expect("resolve").database.primary(), - "/tmp/my data.db" - ); - } - - #[test] - fn persisted_params_never_contain_the_connection_uri() { - let sentinel = "mongodb+srv://fixture-user:fixture-password@cluster.example.invalid/app"; - let params = ConnectionParams { - connection_uri: Some(sentinel.to_string()), - save_in_keychain: Some(true), - ..base_params() - }; - - let persisted = params_for_persistence(¶ms, true); - let json = serde_json::to_string(&persisted).expect("serialize persisted params"); - - assert_eq!(persisted.connection_uri, None); - assert_eq!(persisted.connection_uri_in_keychain, Some(true)); - assert!(!json.contains(sentinel)); - assert!(!json.contains("fixture-password")); - } - - #[test] - fn a_connection_uri_cannot_be_saved_outside_the_keychain() { - let params = ConnectionParams { - connection_uri: Some("mongodb+srv://cluster.example.invalid/app".to_string()), - save_in_keychain: Some(false), - ..base_params() - }; - - assert!(validate_connection_uri_persistence(¶ms).is_err()); - assert!(validate_connection_uri_persistence(&base_params()).is_ok()); - } - - #[test] - fn a_blank_connection_uri_is_treated_as_absent() { - let params = ConnectionParams { - connection_uri: Some(" ".to_string()), - save_in_keychain: Some(false), - ..base_params() - }; - - assert_eq!(runtime_connection_uri(¶ms), None); - assert!(validate_connection_uri_persistence(¶ms).is_ok()); - } - - #[test] - fn previous_uri_skips_the_keychain_when_none_is_stored() { - let previous = previous_keychain_connection_uri(false, || { - panic!("the keychain must not be read without a stored marker") - }); - - assert_eq!(previous, Ok(None)); - } - - #[test] - fn previous_uri_returns_the_stored_value() { - let uri = "mongodb+srv://cluster.example.invalid/app"; - let previous = previous_keychain_connection_uri(true, || Ok(Some(uri.to_string()))); - - assert_eq!(previous, Ok(Some(uri.to_string()))); - } - - #[test] - fn previous_uri_treats_a_missing_entry_as_nothing_to_restore() { - // A duplicate used to carry the marker without its own entry. Deleting - // it must not fail just because there is nothing to restore. - let previous = previous_keychain_connection_uri(true, || Ok(None)); - - assert_eq!(previous, Ok(None)); + assert_eq!(resolved.connection_id.as_deref(), Some("conn-1")); } #[test] - fn previous_uri_fails_on_a_genuine_keychain_error() { - let previous = - previous_keychain_connection_uri(true, || Err("securityd is not running".to_string())); + fn resolve_sanitizes_local_path_driver_databases() { + let driver = "__test_resolve_local_path_driver__"; + crate::drivers::registry::set_local_path_driver(driver, true); + let params = ConnectionParams { + driver: driver.to_string(), + host: None, + port: None, + database: DatabaseSelection::Single(r#""file:///tmp/my%20data.db""#.to_string()), + ..Default::default() + }; + let resolved = resolve_connection_params(¶ms); + crate::drivers::registry::set_local_path_driver(driver, false); assert_eq!( - previous, - Err("Failed to read the stored connection URI from the OS keychain".to_string()) + resolved.expect("resolve").database.primary(), + "/tmp/my data.db" ); } @@ -2407,24 +1564,6 @@ mod tests { ); } - #[test] - fn a_failed_persist_rolls_the_stored_uri_back() { - let rolled_back = std::cell::Cell::new(false); - - let error = persist_secret_change( - || Ok(()), - || Err("fictional connections.json failure".to_string()), - || { - rolled_back.set(true); - Ok(()) - }, - ) - .unwrap_err(); - - assert_eq!(error, "fictional connections.json failure"); - assert!(rolled_back.get()); - } - fn saved_conn(id: &str, password: Option<&str>, save_in_keychain: bool) -> SavedConnection { SavedConnection { id: id.to_string(), @@ -2501,114 +1640,6 @@ mod tests { assert!(matches!(&app.icon, Some(IconOverride::Emoji { value }) if value == "🐘")); } - /// Helper: build a minimal ConnectionsFile with one connection. - fn one_conn_file( - id: &str, - appearance: Option, - ) -> ConnectionsFile { - let conn = SavedConnection { - id: id.to_string(), - name: "Test".to_string(), - params: base_params(), - plugin_secret_keys: Vec::new(), - group_id: None, - sort_order: None, - detect_json_in_text_columns: None, - appearance, - tag_ids: None, - environment: None, - }; - ConnectionsFile { - groups: vec![], - connections: vec![conn], - tags: vec![], - } - } - - #[test] - fn set_connection_appearance_updates_existing() { - use crate::models::{ConnectionAppearance, IconOverride}; - - let mut file = one_conn_file("conn-1", None); - let new_appearance = ConnectionAppearance { - accent_color: Some("#00ff00".to_string()), - icon: Some(IconOverride::Emoji { - value: "🦀".to_string(), - }), - }; - - set_appearance_impl(&mut file, "conn-1", Some(new_appearance)).unwrap(); - - let app = file.connections[0] - .appearance - .as_ref() - .expect("appearance must be set"); - assert_eq!(app.accent_color.as_deref(), Some("#00ff00")); - assert!(matches!(&app.icon, Some(IconOverride::Emoji { value }) if value == "🦀")); - } - - #[test] - fn set_connection_appearance_clears_with_none() { - use crate::models::{ConnectionAppearance, IconOverride}; - - let existing_appearance = ConnectionAppearance { - accent_color: Some("#ff0000".to_string()), - icon: Some(IconOverride::Pack { - id: "server".to_string(), - }), - }; - let mut file = one_conn_file("conn-2", Some(existing_appearance)); - - set_appearance_impl(&mut file, "conn-2", None).unwrap(); - - assert!(file.connections[0].appearance.is_none()); - } - - #[test] - fn set_connection_appearance_errors_on_missing_id() { - let mut file = one_conn_file("conn-real", None); - - let result = set_appearance_impl(&mut file, "conn-does-not-exist", None); - - assert!(result.is_err()); - assert_eq!(result.unwrap_err(), "Connection not found"); - } - - #[test] - fn test_resolve_password_prefers_request() { - let mut params = base_params(); - params.password = Some("from_request".to_string()); - let result = resolve_test_connection_password(¶ms, None, |_| Ok("kc".to_string())); - assert_eq!(result, Some("from_request".to_string())); - } - - #[test] - fn test_resolve_password_from_keychain() { - let params = base_params(); - let saved = saved_conn("id1", None, true); - let result = - resolve_test_connection_password(¶ms, Some(&saved), |_| Ok("kc".to_string())); - assert_eq!(result, Some("kc".to_string())); - } - - #[test] - fn test_resolve_password_from_saved_when_not_keychain() { - let params = base_params(); - let saved = saved_conn("id1", Some("stored"), false); - let result = - resolve_test_connection_password(¶ms, Some(&saved), |_| Ok("kc".to_string())); - assert_eq!(result, Some("stored".to_string())); - } - - #[test] - fn test_resolve_password_fallback_to_saved_when_keychain_empty() { - let params = base_params(); - let saved = saved_conn("id1", Some("stored"), true); - let result = - resolve_test_connection_password(¶ms, Some(&saved), |_| Ok(" ".to_string())); - assert_eq!(result, Some("stored".to_string())); - } - mod build_connection_url_tests { use super::*; @@ -3677,76 +2708,6 @@ mod tests { } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn list_databases( - app: AppHandle, - request: TestConnectionRequest, -) -> Result, String> { - let mut expanded_params = expand_ssh_connection_params(&app, &request.params).await?; - expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; - - let iam_auth = expanded_params.use_iam_auth.unwrap_or(false); - - // IAM auth needs an RDS auth token right now; skip the keychain fallback - // so a stale token can't be reused, and fail fast with an actionable - // message if none was supplied. - require_iam_token( - iam_auth, - request.params.password.as_deref(), - expanded_params.password.as_deref(), - )?; - - let saved_conn = match &request.connection_id { - Some(id) => find_connection_metadata_by_id(&app, id).ok(), - None => None, - }; - if !iam_auth && request.params.password.is_none() && expanded_params.password.is_none() { - expanded_params.password = - resolve_test_connection_password(&request.params, saved_conn.as_ref(), |conn_id| { - keychain_utils::get_db_password(conn_id, "") - }); - } - - // Reconnecting to a saved connection sends the on-disk params, which never - // carry the URI — restore it the same way the password is restored above. - // An inline URI (the ephemeral Test Connection flow) always wins. - if runtime_connection_uri(&expanded_params).is_none() { - if let Some(conn_id) = &request.connection_id { - let cache = app.state::>(); - restore_runtime_connection_uri(&cache, conn_id, &mut expanded_params)?; - } - } - - // Plugin-owned secrets, resolved the same way as in `test_connection`. - { - let cache = app.state::>(); - crate::plugin_secrets::apply_request_secrets( - &cache, - saved_conn.as_ref(), - &mut expanded_params, - &request.plugin_secret_changes, - )?; - } - - let resolved_params = if let Some(conn_id) = &request.connection_id { - resolve_connection_params_with_id(&expanded_params, conn_id)? - } else { - resolve_connection_params(&expanded_params)? - }; - - #[cfg(debug_assertions)] - log::debug!( - "[List Databases] Resolved Params: Host={:?}, Port={:?}, Username={:?}", - resolved_params.host, - resolved_params.port, - resolved_params.username, - ); - - let drv = driver_for(&resolved_params.driver).await?; - drv.get_databases(&resolved_params).await -} - #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_tables( @@ -4126,7 +3087,7 @@ pub(crate) fn cancel_query_impl( #[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_query( - state: State<'_, QueryCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, ) -> Result<(), String> { crate::application::queries::cancel_query(&state, None, &connection_id, None) @@ -4136,7 +3097,7 @@ pub async fn cancel_query( #[tauri::command] pub async fn execute_query( app: AppHandle, - state: State<'_, QueryCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, query: String, limit: Option, @@ -4207,7 +3168,7 @@ pub async fn release_query_session( #[tauri::command] pub async fn execute_query_batch( app: AppHandle, - state: State<'_, QueryCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, queries: Vec, limit: Option, @@ -4240,7 +3201,7 @@ pub async fn execute_query_batch( #[tauri::command] pub async fn explain_query_plan( app: AppHandle, - state: State<'_, QueryCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, query: String, analyze: bool, @@ -4490,31 +3451,6 @@ pub async fn build_connection_url(params: &ConnectionParams) -> Result, - get_keychain_password: impl Fn(&str) -> Result, -) -> Option { - if let Some(pwd) = ¶ms.password { - return Some(pwd.clone()); - } - - let saved = saved_conn?; - - if saved.params.save_in_keychain.unwrap_or(false) { - if let Ok(pwd) = get_keychain_password(&saved.id) { - if !pwd.trim().is_empty() { - return Some(pwd); - } - } - } - - match &saved.params.password { - Some(pwd) if !pwd.trim().is_empty() => Some(pwd.clone()), - _ => None, - } -} - /// Resolves SSH credential (password or passphrase) for testing /// 1. Credential from request params (if provided, even if empty) /// 2. Credential from keychain (if save_in_keychain is enabled) @@ -5382,66 +4318,6 @@ pub async fn get_driver_manifest( // ==================== Connection Groups Management ==================== -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connection_groups( - app: AppHandle, -) -> Result, String> { - let path = get_config_path(&app)?; - persistence::load_groups(&path) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connections_with_groups( - app: AppHandle, -) -> Result { - // Run migrations if needed - migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); - - let path = get_config_path(&app)?; - persistence::load_connections_file(&path) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_connection_group( - app: AppHandle, - name: String, - parent_id: Option, -) -> Result { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path).unwrap_or_default(); - - if let Some(pid) = &parent_id { - if !file.groups.iter().any(|g| &g.id == pid) { - return Err(format!("Parent group with ID {} not found", pid)); - } - } - - let max_order = file - .groups - .iter() - .filter(|g| g.parent_id == parent_id) - .map(|g| g.sort_order) - .max() - .unwrap_or(-1); - - let group = ConnectionGroup { - id: Uuid::new_v4().to_string(), - name, - collapsed: false, - sort_order: max_order + 1, - parent_id, - }; - - file.groups.push(group.clone()); - save_connections_and_invalidate(&app, &path, &file)?; - - Ok(group) -} - /// Splits a `/`-separated group path into trimmed, non-empty segments. /// Returns an error if the result is empty. pub(crate) fn parse_group_path(path: &str) -> Result, String> { @@ -5469,135 +4345,6 @@ pub(crate) fn find_child_group<'a>( .find(|g| g.name.to_lowercase() == name_lower && g.parent_id == *parent_id) } -/// Creates a nested group hierarchy from a `/`-separated path. -/// -/// Each segment of `path` becomes one group. Existing segments are reused -/// (looked up case-insensitively among the children of the current parent); -/// missing segments are created in order. The final segment is returned. -/// The hierarchy is created atomically: either every missing segment is -/// persisted or none are. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_group_path( - app: AppHandle, - path: String, - parent_id: Option, -) -> Result { - let path_cfg = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path_cfg).unwrap_or_default(); - - if let Some(pid) = &parent_id { - if !file.groups.iter().any(|g| &g.id == pid) { - return Err(format!("Parent group with ID {} not found", pid)); - } - } - - let segments = parse_group_path(&path)?; - let mut current_parent = parent_id; - let mut last_created: Option = None; - - for seg in segments { - if let Some(g) = find_child_group(&file.groups, &seg, ¤t_parent).cloned() { - current_parent = Some(g.id.clone()); - last_created = Some(g); - continue; - } - let max_order = file - .groups - .iter() - .filter(|g| g.parent_id == current_parent) - .map(|g| g.sort_order) - .max() - .unwrap_or(-1); - let new_group = ConnectionGroup { - id: Uuid::new_v4().to_string(), - name: seg, - collapsed: false, - sort_order: max_order + 1, - parent_id: current_parent.clone(), - }; - current_parent = Some(new_group.id.clone()); - last_created = Some(new_group.clone()); - file.groups.push(new_group); - } - - save_connections_and_invalidate(&app, &path_cfg, &file)?; - - last_created.ok_or_else(|| "Group path resolved to an empty hierarchy".to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection_group( - app: AppHandle, - id: String, - name: Option, - collapsed: Option, - sort_order: Option, -) -> Result { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - let group = file - .groups - .iter_mut() - .find(|g| g.id == id) - .ok_or_else(|| format!("Group with ID {} not found", id))?; - - if let Some(n) = name { - group.name = n; - } - if let Some(c) = collapsed { - group.collapsed = c; - } - if let Some(o) = sort_order { - group.sort_order = o; - } - - let updated = group.clone(); - save_connections_and_invalidate(&app, &path, &file)?; - - Ok(updated) -} -/// Re-parent a group. Pass `Some(id)` to make it a child of that group, -/// or `None` to make it a top-level root. Cycles are rejected. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn move_group_to_parent( - app: AppHandle, - id: String, - parent_id: Option, -) -> Result { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - if !file.groups.iter().any(|g| g.id == id) { - return Err(format!("Group with ID {} not found", id)); - } - - if let Some(pid) = &parent_id { - if pid == &id { - return Err("A group cannot be its own parent".to_string()); - } - if !file.groups.iter().any(|g| &g.id == pid) { - return Err(format!("Parent group with ID {} not found", pid)); - } - } - - reject_if_would_create_cycle(&file.groups, &id, parent_id.as_deref())?; - - let group = file - .groups - .iter_mut() - .find(|g| g.id == id) - .expect("group existence checked above"); - group.parent_id = parent_id; - let updated = group.clone(); - - save_connections_and_invalidate(&app, &path, &file)?; - Ok(updated) -} - /// Reject re-parenting that would create a cycle: `target` must not be a /// descendant of `group_id`. Walks up from `target` looking for `group_id`. /// Bounded by `groups.len()` to fail-safe against pre-existing data cycles. @@ -5641,126 +4388,6 @@ pub(crate) fn reject_if_would_create_cycle( ) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_group( - app: AppHandle, - id: String, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - // Ensure the group exists before we walk the tree. - if !file.groups.iter().any(|g| g.id == id) { - return Err(format!("Group with ID {} not found", id)); - } - - // Cascade delete: collect the target group and all of its descendants - // (transitively) so the entire subtree is removed. The caller only - // needs to specify the top-level group — every nested child group is - // deleted along with it. Connections belonging to any group in the - // subtree are removed as well. - let to_delete = crate::models::collect_group_subtree(&file.groups, &id); - let deleted_plugin_secrets: Vec<(String, String, Vec)> = file - .connections - .iter() - .filter(|connection| { - connection - .group_id - .as_ref() - .is_some_and(|group_id| to_delete.contains(group_id)) - }) - .map(|connection| { - ( - connection.id.clone(), - connection.params.driver.clone(), - connection.plugin_secret_keys.clone(), - ) - }) - .collect(); - - file.groups.retain(|g| !to_delete.contains(&g.id)); - file.connections.retain(|c| { - !c.group_id - .as_ref() - .is_some_and(|gid| to_delete.contains(gid)) - }); - - save_connections_and_invalidate(&app, &path, &file)?; - let cache = app.state::>(); - for (connection_id, driver, keys) in deleted_plugin_secrets { - crate::plugin_secrets::delete_connection_secrets(&cache, &connection_id, &driver, &keys); - } - - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn move_connection_to_group( - app: AppHandle, - connection_id: String, - group_id: Option, - sort_order: Option, -) -> Result { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - let conn = file - .connections - .iter_mut() - .find(|c| c.id == connection_id) - .ok_or_else(|| format!("Connection with ID {} not found", connection_id))?; - - conn.group_id = group_id; - if let Some(order) = sort_order { - conn.sort_order = Some(order); - } - - let updated = conn.clone(); - save_connections_and_invalidate(&app, &path, &file)?; - - Ok(updated) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn reorder_groups( - app: AppHandle, - group_orders: Vec<(String, i32)>, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - for (group_id, order) in group_orders { - if let Some(group) = file.groups.iter_mut().find(|g| g.id == group_id) { - group.sort_order = order; - } - } - - save_connections_and_invalidate(&app, &path, &file)?; - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn reorder_connections_in_group( - app: AppHandle, - connection_orders: Vec<(String, i32)>, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - - for (conn_id, order) in connection_orders { - if let Some(conn) = file.connections.iter_mut().find(|c| c.id == conn_id) { - conn.sort_order = Some(order); - } - } - - save_connections_and_invalidate(&app, &path, &file)?; - Ok(()) -} - #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_server_now( diff --git a/src-tauri/src/connection_appearance.rs b/src-tauri/src/connection_appearance.rs index d404e14f4..bfccf5847 100644 --- a/src-tauri/src/connection_appearance.rs +++ b/src-tauri/src/connection_appearance.rs @@ -189,25 +189,3 @@ pub async fn save_connection_icon( .map_err(|e| e.to_string()) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_icon( - _app: AppHandle, - relative_path: String, -) -> Result<(), String> { - let data_dir = crate::paths::get_app_data_dir(); - let icons_dir = data_dir.join("connection-icons"); - let full = data_dir.join(&relative_path); - // If the file doesn't exist, treat as a no-op (don't canonicalize a non-existent path). - if !full.exists() { - return Ok(()); - } - let canon_icons = icons_dir.canonicalize().map_err(|e| e.to_string())?; - let canon_full = full.canonicalize().map_err(|e| e.to_string())?; - if !canon_full.starts_with(&canon_icons) { - return Err("path outside connection-icons".into()); - } - fs::remove_file(&canon_full).map_err(|e| e.to_string())?; - Ok(()) -} - diff --git a/src-tauri/src/connection_import_commands.rs b/src-tauri/src/connection_import_commands.rs index 6e620e60f..7d2833594 100644 --- a/src-tauri/src/connection_import_commands.rs +++ b/src-tauri/src/connection_import_commands.rs @@ -39,7 +39,7 @@ pub async fn list_connection_import_sources() -> Result, S #[tauri::command] pub async fn preview_connection_import( app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, source_id: String, include_passwords: bool, file: Option, @@ -59,7 +59,7 @@ pub async fn preview_connection_import( #[tauri::command] pub async fn apply_connection_import( app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, connection_cache: tauri::State<'_, std::sync::Arc>, credential_cache: tauri::State<'_, std::sync::Arc>, source_id: String, @@ -117,7 +117,7 @@ pub async fn apply_tabularis_import( #[tauri::command] pub async fn preview_tabularis_import_file( app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, file: ConnectionImportFile, password: Option, ) -> Result { @@ -135,7 +135,7 @@ pub async fn preview_tabularis_import_file( #[tauri::command] pub async fn apply_prepared_tabularis_import( app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, connection_cache: tauri::State<'_, std::sync::Arc>, credential_cache: tauri::State<'_, std::sync::Arc>, resolutions: Vec, diff --git a/src-tauri/src/connection_tags.rs b/src-tauri/src/connection_tags.rs index 6c2edcb64..93ba911f0 100644 --- a/src-tauri/src/connection_tags.rs +++ b/src-tauri/src/connection_tags.rs @@ -2,14 +2,9 @@ //! `connections.json` next to the groups. Tags are purely organizational; //! assignment lives on `SavedConnection.tag_ids`. -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Runtime}; use uuid::Uuid; -#[cfg(feature = "desktop")] -use crate::commands::{get_config_path, save_connections_and_invalidate}; use crate::models::{ConnectionTag, ConnectionsFile}; -use crate::persistence; /// Basic sanity check for a CSS hex color (`#rgb`, `#rrggbb` or `#rrggbbaa`), /// so a crafted connections.json entry can't inject arbitrary CSS. @@ -174,68 +169,6 @@ pub fn merge_imported_tags( // ---------- Tauri commands ---------- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn list_connection_tags( - app: AppHandle, -) -> Result, String> { - let path = get_config_path(&app)?; - Ok(persistence::load_connections_file(&path)?.tags) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_connection_tag( - app: AppHandle, - name: String, - color: String, -) -> Result { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - let tag = create_tag_impl(&mut file, &name, &color)?; - save_connections_and_invalidate(&app, &path, &file)?; - Ok(tag) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection_tag( - app: AppHandle, - id: String, - name: String, - color: String, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - update_tag_impl(&mut file, &id, &name, &color)?; - save_connections_and_invalidate(&app, &path, &file) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_tag( - app: AppHandle, - id: String, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - delete_tag_impl(&mut file, &id)?; - save_connections_and_invalidate(&app, &path, &file) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_connection_tags( - app: AppHandle, - connection_id: String, - tag_ids: Vec, -) -> Result<(), String> { - let path = get_config_path(&app)?; - let mut file = persistence::load_connections_file(&path)?; - set_connection_tags_impl(&mut file, &connection_id, &tag_ids)?; - save_connections_and_invalidate(&app, &path, &file) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/dump_commands.rs b/src-tauri/src/dump_commands.rs index 41c8b9f92..a0d43b5e8 100644 --- a/src-tauri/src/dump_commands.rs +++ b/src-tauri/src/dump_commands.rs @@ -9,7 +9,7 @@ use tauri::State; #[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_dump( - state: State<'_, DumpCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, ) -> Result<(), String> { database_transfers::cancel_job(state.inner(), None, JobKind::Dump, &connection_id) @@ -19,7 +19,7 @@ pub async fn cancel_dump( #[tauri::command] pub async fn dump_database( runtime: State<'_, RuntimeContext>, - state: State<'_, DumpCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, file_path: String, options: DumpOptions, @@ -42,7 +42,7 @@ pub async fn dump_database( #[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_import( - state: State<'_, DumpCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, ) -> Result<(), String> { database_transfers::cancel_job(state.inner(), None, JobKind::Import, &connection_id) @@ -52,7 +52,7 @@ pub async fn cancel_import( #[tauri::command] pub async fn import_database( runtime: State<'_, RuntimeContext>, - state: State<'_, DumpCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, file_path: String, schema: Option, diff --git a/src-tauri/src/explain_import.rs b/src-tauri/src/explain_import.rs index 1592a965f..27c2fb101 100644 --- a/src-tauri/src/explain_import.rs +++ b/src-tauri/src/explain_import.rs @@ -56,7 +56,9 @@ pub async fn load_explain_from_file(path: String) -> Result) -> Option { +pub fn get_pending_explain_file( + state: State<'_, std::sync::Arc>, +) -> Option { state.take() } @@ -73,7 +75,7 @@ pub fn spawn_visual_explain_window>( use tauri::{WebviewUrl, WebviewWindowBuilder}; if let Some(path) = file.as_ref() { - if let Some(state) = app.try_state::() { + if let Some(state) = app.try_state::>() { state.set(path.clone()); } } diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs index 6d9b9926f..6c033f7c4 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -38,7 +38,7 @@ impl Default for ExportCancellationState { #[cfg(feature = "desktop")] #[tauri::command] pub async fn cancel_export( - state: State<'_, ExportCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, ) -> Result<(), String> { crate::application::generic_exports::cancel_export(state.inner(), None, &connection_id) @@ -49,7 +49,7 @@ pub async fn cancel_export( #[allow(clippy::too_many_arguments)] pub async fn export_query_to_file( runtime: State<'_, RuntimeContext>, - state: State<'_, ExportCancellationState>, + state: State<'_, std::sync::Arc>, connection_id: String, query: String, file_path: String, diff --git a/src-tauri/src/json_viewer.rs b/src-tauri/src/json_viewer.rs index 91d90512f..336c14f14 100644 --- a/src-tauri/src/json_viewer.rs +++ b/src-tauri/src/json_viewer.rs @@ -41,7 +41,7 @@ pub struct JsonViewerStore { #[tauri::command] pub async fn open_json_viewer_window( app: AppHandle, - store: State<'_, JsonViewerStore>, + store: State<'_, std::sync::Arc>, value: serde_json::Value, original_value: Option, col_name: String, @@ -162,7 +162,7 @@ pub async fn open_json_viewer_window( if let WindowEvent::CloseRequested { .. } = event { if let Some(win) = app_handle.get_webview_window(&captured_label) { if let (Ok(pos), Ok(size)) = (win.outer_position(), win.outer_size()) { - let store = app_handle.state::(); + let store = app_handle.state::>(); let mut bounds = match store.last_bounds.lock() { Ok(g) => g, Err(_) => return, @@ -185,7 +185,7 @@ pub async fn open_json_viewer_window( #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_json_viewer_session( - store: State<'_, JsonViewerStore>, + store: State<'_, std::sync::Arc>, session_id: String, ) -> Result { let guard = store @@ -202,7 +202,7 @@ pub async fn get_json_viewer_session( #[tauri::command] pub async fn complete_json_viewer_session( app: AppHandle, - store: State<'_, JsonViewerStore>, + store: State<'_, std::sync::Arc>, session_id: String, value: serde_json::Value, ) -> Result<(), String> { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 951a309a2..38015baf7 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -310,7 +310,7 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { log::info!("Debug mode disabled - standard logging active"); } - let application_state = runtime::state::ApplicationState::default(); + let application_state = std::sync::Arc::new(runtime::state::ApplicationState::default()); let shutdown_hooks = runtime::lifecycle::ShutdownHooks::default(); shutdown_hooks.register(|| { log::info!("Application exiting, stopping all active tunnels..."); @@ -368,18 +368,18 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { } builder - .manage(application_state.pending_install) - .manage(application_state.query_cancellation) - .manage(application_state.export_cancellation) - .manage(application_state.dump_cancellation) + .manage(application_state.pending_install.clone()) + .manage(application_state.query_cancellation.clone()) + .manage(application_state.export_cancellation.clone()) + .manage(application_state.dump_cancellation.clone()) .manage(log_buffer) - .manage(application_state.credential_cache) - .manage(application_state.connection_cache) - .manage(application_state.import_envelope_cache) - .manage(application_state.pending_explain_file) - .manage(application_state.json_viewer_store) - .manage(application_state.results_window_store) - .manage(application_state.query_history_state) + .manage(application_state.credential_cache.clone()) + .manage(application_state.connection_cache.clone()) + .manage(application_state.import_envelope_cache.clone()) + .manage(application_state.pending_explain_file.clone()) + .manage(application_state.json_viewer_store.clone()) + .manage(application_state.results_window_store.clone()) + .manage(application_state.clone()) .manage(window_placement::WindowPlacementCache::default()) .setup(move |app| { #[cfg(target_os = "linux")] @@ -587,7 +587,7 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { commands::list_databases, commands::save_connection, sqlite_database::create_sqlite_file, - sqlite_database::create_sqlite_database, + commands::create_sqlite_database, commands::delete_connection, commands::update_connection, commands::duplicate_connection, @@ -629,11 +629,11 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { commands::move_connection_to_group, commands::reorder_groups, commands::reorder_connections_in_group, - connection_tags::list_connection_tags, - connection_tags::create_connection_tag, - connection_tags::update_connection_tag, - connection_tags::delete_connection_tag, - connection_tags::set_connection_tags, + commands::list_connection_tags, + commands::create_connection_tag, + commands::update_connection_tag, + commands::delete_connection_tag, + commands::set_connection_tags, commands::export_connections_payload, commands::encrypt_export_payload, connection_import_commands::export_connections_file, @@ -769,7 +769,7 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { chatgpt::open_chatgpt_usage, // Clipboard Import clipboard_import::execute_clipboard_import, - commands::get_ai_schema_context, + ai_commands::get_ai_schema_context, commands::get_schema_snapshot, // DDL generation commands::get_table_query_template, @@ -820,14 +820,14 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { // Themes theme_packages::commands::preview_theme_document, theme_packages::commands::preview_local_theme_package, - theme_packages::commands::install_local_theme_package, - theme_packages::commands::fetch_theme_registry, - theme_packages::commands::fetch_theme_package_detail, - theme_packages::commands::install_registry_theme, + theme_commands::install_local_theme_package, + theme_commands::fetch_theme_registry, + theme_commands::fetch_theme_package_detail, + theme_commands::install_registry_theme, theme_packages::commands::cancel_theme_install, - theme_packages::commands::set_theme_package_enabled, - theme_packages::commands::uninstall_theme_package, - theme_packages::commands::recover_theme_packages, + theme_commands::set_theme_package_enabled, + theme_commands::uninstall_theme_package, + theme_commands::recover_theme_packages, theme_commands::get_theme_catalog, theme_commands::create_personal_theme, theme_commands::create_personal_snapshot, @@ -904,7 +904,7 @@ fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { task_manager::open_task_manager_window, // Connection Appearance connection_appearance::save_connection_icon, - connection_appearance::delete_connection_icon, + commands::delete_connection_icon, commands::set_connection_appearance, ]) .build(tauri::generate_context!()) diff --git a/src-tauri/src/notebooks.rs b/src-tauri/src/notebooks.rs index f5f546f31..74c3d2564 100644 --- a/src-tauri/src/notebooks.rs +++ b/src-tauri/src/notebooks.rs @@ -1,16 +1,18 @@ use crate::application::notebooks::{execute, NotebookCommand}; -use crate::paths::get_app_config_dir; +use crate::runtime::RuntimeContext; +use tauri::{AppHandle, Manager}; pub use crate::application::notebooks::NotebookMetadata; -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn create_notebook( + app: AppHandle, connection_id: String, notebook_id: String, content: String, ) -> Result<(), String> { execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::Create { connection_id, notebook_id, @@ -20,14 +22,15 @@ pub async fn create_notebook( Ok(()) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn save_notebook( + app: AppHandle, connection_id: String, notebook_id: String, content: String, ) -> Result<(), String> { execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::Save { connection_id, notebook_id, @@ -37,13 +40,14 @@ pub async fn save_notebook( Ok(()) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn load_notebook( + app: AppHandle, connection_id: String, notebook_id: String, ) -> Result, String> { let value = execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::Load { connection_id, notebook_id, @@ -52,10 +56,14 @@ pub async fn load_notebook( serde_json::from_value(value).map_err(|error| error.to_string()) } -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Result<(), String> { +#[tauri::command] +pub async fn delete_notebook( + app: AppHandle, + connection_id: String, + notebook_id: String, +) -> Result<(), String> { execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::Delete { connection_id, notebook_id, @@ -64,14 +72,15 @@ pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Resu Ok(()) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] pub async fn rename_notebook( + app: AppHandle, connection_id: String, notebook_id: String, title: String, ) -> Result<(), String> { execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::Rename { connection_id, notebook_id, @@ -81,10 +90,13 @@ pub async fn rename_notebook( Ok(()) } -#[cfg_attr(feature = "desktop", tauri::command)] -pub async fn list_notebooks(connection_id: String) -> Result, String> { +#[tauri::command] +pub async fn list_notebooks( + app: AppHandle, + connection_id: String, +) -> Result, String> { let value = execute( - &get_app_config_dir(), + app.state::().paths.config_dir(), NotebookCommand::List { connection_id }, )?; serde_json::from_value(value).map_err(|error| error.to_string()) diff --git a/src-tauri/src/plugins/deep_link.rs b/src-tauri/src/plugins/deep_link.rs index 88e47e52c..5fd59a141 100644 --- a/src-tauri/src/plugins/deep_link.rs +++ b/src-tauri/src/plugins/deep_link.rs @@ -156,7 +156,7 @@ pub fn handle_url(app: &AppHandle, raw: &str) { // Stash for cold-start replay; the frontend pulls this on mount via // `consume_pending_deep_link_install`. - if let Some(state) = app.try_state::() { + if let Some(state) = app.try_state::>() { if let Ok(mut slot) = state.0.lock() { *slot = Some(req.clone()); } @@ -187,7 +187,7 @@ pub fn handle_url(app: &AppHandle, raw: &str) { #[cfg(feature = "desktop")] #[tauri::command] pub fn consume_pending_deep_link_install( - state: tauri::State<'_, PendingInstall>, + state: tauri::State<'_, std::sync::Arc>, ) -> Option { state.0.lock().ok().and_then(|mut slot| slot.take()) } diff --git a/src-tauri/src/query_history.rs b/src-tauri/src/query_history.rs index cf6330cbf..b5495c336 100644 --- a/src-tauri/src/query_history.rs +++ b/src-tauri/src/query_history.rs @@ -1,23 +1,17 @@ use crate::application::productivity::{self, ProductivityCommand}; use serde_json::from_value; #[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime, State}; +use tauri::{AppHandle, Manager, Runtime}; pub use crate::application::productivity::backfill_history_entries as backfill_missing_database; #[cfg(test)] pub(crate) use crate::application::productivity::{atomic_write, backup_corrupt_file}; pub use crate::application::productivity::{QueryHistoryEntry, QueryHistoryResponse}; -/// Kept as managed Tauri state for command signature compatibility. Storage -/// serialization is shared by desktop and web in the application service. -#[derive(Default)] -pub struct QueryHistoryState; - #[cfg(feature = "desktop")] #[tauri::command] pub async fn get_query_history( app: AppHandle, - _state: State<'_, QueryHistoryState>, connection_id: String, ) -> Result { let runtime = app.state::(); @@ -37,7 +31,6 @@ pub async fn get_query_history( #[allow(clippy::too_many_arguments)] pub async fn add_query_history_entry( app: AppHandle, - _state: State<'_, QueryHistoryState>, connection_id: String, sql: String, executed_at: String, @@ -72,7 +65,6 @@ pub async fn add_query_history_entry( #[tauri::command] pub async fn delete_query_history_entry( app: AppHandle, - _state: State<'_, QueryHistoryState>, connection_id: String, id: String, ) -> Result<(), String> { @@ -90,7 +82,6 @@ pub async fn delete_query_history_entry( #[tauri::command] pub async fn clear_query_history( app: AppHandle, - _state: State<'_, QueryHistoryState>, connection_id: String, ) -> Result<(), String> { let runtime = app.state::(); diff --git a/src-tauri/src/results_window.rs b/src-tauri/src/results_window.rs index 327ef73ae..d7a51ba4c 100644 --- a/src-tauri/src/results_window.rs +++ b/src-tauri/src/results_window.rs @@ -36,7 +36,7 @@ fn window_label(tab_id: &str) -> String { #[tauri::command] pub async fn open_results_window( app: AppHandle, - store: tauri::State<'_, ResultsWindowStore>, + store: tauri::State<'_, std::sync::Arc>, tab_id: String, title: Option, ) -> Result<(), String> { @@ -85,7 +85,7 @@ pub async fn open_results_window( // below, so saving `outer_size()` would grow the window by // the decoration height on each detach→close→reopen cycle. if let (Ok(pos), Ok(size)) = (win.outer_position(), win.inner_size()) { - let store = app_handle.state::(); + let store = app_handle.state::>(); if let Ok(mut bounds) = store.bounds.lock() { bounds.insert( captured_tab_id.clone(), diff --git a/src-tauri/src/runtime/state.rs b/src-tauri/src/runtime/state.rs index b4c7e5a5f..159ea166b 100644 --- a/src-tauri/src/runtime/state.rs +++ b/src-tauri/src/runtime/state.rs @@ -5,17 +5,16 @@ use std::sync::{Arc, Mutex}; use uuid::Uuid; pub struct ApplicationState { - pub pending_install: crate::plugins::deep_link::PendingInstall, - pub query_cancellation: crate::commands::QueryCancellationState, - pub export_cancellation: crate::export::ExportCancellationState, - pub dump_cancellation: crate::dump_commands::DumpCancellationState, + pub pending_install: Arc, + pub query_cancellation: Arc, + pub export_cancellation: Arc, + pub dump_cancellation: Arc, pub credential_cache: Arc, pub connection_cache: Arc, - pub import_envelope_cache: ImportEnvelopeCache, - pub pending_explain_file: crate::explain_import::PendingExplainFile, - pub json_viewer_store: crate::json_viewer::JsonViewerStore, - pub results_window_store: crate::results_window::ResultsWindowStore, - pub query_history_state: crate::query_history::QueryHistoryState, + pub import_envelope_cache: Arc, + pub pending_explain_file: Arc, + pub json_viewer_store: Arc, + pub results_window_store: Arc, pub web_active_connections: Mutex>>, pub web_approval_owners: Mutex>, pub web_preferences: @@ -47,17 +46,16 @@ fn abort_all(handles: &Arc>) { impl Default for ApplicationState { fn default() -> Self { Self { - pending_install: crate::plugins::deep_link::PendingInstall::default(), - query_cancellation: crate::commands::QueryCancellationState::default(), - export_cancellation: crate::export::ExportCancellationState::default(), - dump_cancellation: crate::dump_commands::DumpCancellationState::default(), + pending_install: Arc::new(crate::plugins::deep_link::PendingInstall::default()), + query_cancellation: Arc::new(crate::commands::QueryCancellationState::default()), + export_cancellation: Arc::new(crate::export::ExportCancellationState::default()), + dump_cancellation: Arc::new(crate::dump_commands::DumpCancellationState::default()), credential_cache: Arc::new(crate::credential_cache::CredentialCache::default()), connection_cache: Arc::new(crate::connection_cache::ConnectionCache::default()), - import_envelope_cache: ImportEnvelopeCache::default(), - pending_explain_file: crate::explain_import::PendingExplainFile::default(), - json_viewer_store: crate::json_viewer::JsonViewerStore::default(), - results_window_store: crate::results_window::ResultsWindowStore::default(), - query_history_state: crate::query_history::QueryHistoryState::default(), + import_envelope_cache: Arc::new(ImportEnvelopeCache::default()), + pending_explain_file: Arc::new(crate::explain_import::PendingExplainFile::default()), + json_viewer_store: Arc::new(crate::json_viewer::JsonViewerStore::default()), + results_window_store: Arc::new(crate::results_window::ResultsWindowStore::default()), web_active_connections: Mutex::new(HashMap::new()), web_approval_owners: Mutex::new(HashMap::new()), web_preferences: Mutex::new(HashMap::new()), diff --git a/src-tauri/src/runtime/tests.rs b/src-tauri/src/runtime/tests.rs index 688ac395e..fd080e678 100644 --- a/src-tauri/src/runtime/tests.rs +++ b/src-tauri/src/runtime/tests.rs @@ -157,8 +157,6 @@ fn shutdown_hooks_run_without_a_tauri_runtime() { #[tokio::test] async fn desktop_productivity_commands_use_the_managed_custom_config_directory() { use crate::{query_history, saved_queries}; - #[cfg(feature = "desktop")] - use tauri::Manager; let root = tempfile::tempdir().unwrap(); let config = root.path().join("custom-config"); let runtime = RuntimeContext::new( @@ -171,7 +169,6 @@ async fn desktop_productivity_commands_use_the_managed_custom_config_directory() ); let app = tauri::test::mock_builder() .manage(runtime) - .manage(query_history::QueryHistoryState) .build(tauri::test::mock_context(tauri::test::noop_assets())) .unwrap(); let handle = app.handle().clone(); @@ -248,7 +245,6 @@ async fn desktop_productivity_commands_use_the_managed_custom_config_directory() ); let entry = query_history::add_query_history_entry( handle.clone(), - handle.state(), connection.clone(), "SELECT 1".into(), "2026-10-15T00:00:00Z".into(), @@ -265,7 +261,7 @@ async fn desktop_productivity_commands_use_the_managed_custom_config_directory() "history must use the runtime config directory" ); assert_eq!( - query_history::get_query_history(handle.clone(), handle.state(), connection.clone()) + query_history::get_query_history(handle.clone(), connection.clone()) .await .unwrap() .entries @@ -278,15 +274,10 @@ async fn desktop_productivity_commands_use_the_managed_custom_config_directory() .unwrap(), 1 ); - query_history::delete_query_history_entry( - handle.clone(), - handle.state(), - connection.clone(), - entry.id, - ) - .await - .unwrap(); - query_history::clear_query_history(handle.clone(), handle.state(), connection.clone()) + query_history::delete_query_history_entry(handle.clone(), connection.clone(), entry.id) + .await + .unwrap(); + query_history::clear_query_history(handle.clone(), connection.clone()) .await .unwrap(); query_history::remove_history_for_connection(&handle, &connection) diff --git a/src-tauri/src/sqlite_database.rs b/src-tauri/src/sqlite_database.rs index 4370ef390..ac9e56951 100644 --- a/src-tauri/src/sqlite_database.rs +++ b/src-tauri/src/sqlite_database.rs @@ -1,10 +1,7 @@ -use crate::models::{ConnectionParams, DatabaseSelection, SavedConnection}; use sqlx::sqlite::SqliteConnectOptions; use sqlx::{Connection, Executor, SqliteConnection}; use std::fs::{self, OpenOptions}; use std::path::{Path, PathBuf}; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Runtime}; const SQLITE_EXTENSIONS: [&str; 3] = ["db", "sqlite", "sqlite3"]; @@ -111,31 +108,3 @@ pub async fn create_sqlite_file(path: String) -> Result { .map(str::to_owned) .ok_or_else(|| "The selected SQLite database path is not valid UTF-8.".to_string()) } - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_sqlite_database( - app: AppHandle, - path: String, -) -> Result { - let database_path = create_sqlite_file(path).await?; - let path = PathBuf::from(&database_path); - let name = connection_name(&path)?; - let params = ConnectionParams { - driver: "sqlite".to_string(), - database: DatabaseSelection::Single(database_path), - ..ConnectionParams::default() - }; - - match crate::commands::save_connection(app, name, params, None, None, None).await { - Ok(connection) => Ok(connection), - Err(error) => { - if let Err(cleanup_error) = fs::remove_file(&path) { - return Err(format!( - "Failed to save the SQLite connection: {error}. The new database could not be removed: {cleanup_error}" - )); - } - Err(format!("Failed to save the SQLite connection: {error}")) - } - } -} diff --git a/src-tauri/src/theme_commands.rs b/src-tauri/src/theme_commands.rs index 0551773f9..b4cc3b8b2 100644 --- a/src-tauri/src/theme_commands.rs +++ b/src-tauri/src/theme_commands.rs @@ -1,48 +1,28 @@ -use crate::paths::{get_app_config_dir, get_default_app_data_dir}; -use crate::theme_packages::{self, ThemeCatalog, ThemeContribution}; +use crate::application::themes::{self, LocalThemeArchive, ThemeCommand}; +use crate::runtime::RuntimeContext; +use crate::theme_packages::ThemeCatalog; use serde_json::Value; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter}; - -#[cfg(feature = "desktop")] -fn committed(app: &AppHandle, result: Result) -> Result { - let value = result?; - if let Err(error) = app.emit("theme-catalog-changed", ()) { - log::warn!("Personal theme change committed but refresh delivery failed: {error}"); - } - Ok(value) +use tauri::{AppHandle, Manager}; + +async fn execute(app: &AppHandle, command: ThemeCommand) -> Result { + themes::execute(&app.state::(), command).await } -#[cfg_attr(feature = "desktop", tauri::command)] -pub fn get_theme_catalog() -> ThemeCatalog { - theme_packages::read_theme_catalog( - &get_app_config_dir(), - &get_default_app_data_dir(), - env!("CARGO_PKG_VERSION"), - ) +#[tauri::command] +pub fn get_theme_catalog(app: AppHandle) -> ThemeCatalog { + themes::catalog(&app.state::()) } /// Legacy command names and argument names remain available. Raw metadata is /// retained instead of round-tripping files through the historical Rust model. -#[cfg_attr(feature = "desktop", tauri::command)] -pub fn get_all_themes() -> Result, String> { - get_theme_catalog() - .themes - .into_iter() - .filter(|entry| !entry.read_only && entry.format == "legacy" && entry.editor.is_none()) - .map(|entry| { - let mut value: Value = - serde_json::from_str(&entry.source).map_err(|e| e.to_string())?; - value["isPreset"] = Value::Bool(false); - value["isReadOnly"] = Value::Bool(false); - Ok(value) - }) - .collect() -} - -#[cfg_attr(feature = "desktop", tauri::command)] -pub fn get_theme(theme_id: String) -> Result { - let entry = get_theme_catalog() +#[tauri::command] +pub fn get_all_themes(app: AppHandle) -> Result, String> { + crate::application::persistence::get_all_themes(&app.state::()) +} + +#[tauri::command] +pub fn get_theme(app: AppHandle, theme_id: String) -> Result { + let entry = themes::catalog(&app.state::()) .themes .into_iter() .find(|entry| entry.id == theme_id) @@ -56,131 +36,215 @@ pub fn get_theme(theme_id: String) -> Result { Ok(value) } -#[cfg(feature = "desktop")] #[tauri::command] pub fn save_custom_theme(app: AppHandle, theme: Value) -> Result<(), String> { - committed( - &app, - theme_packages::save_legacy_theme(&get_app_config_dir(), theme), - ) + crate::application::persistence::save_custom_theme(&app.state::(), theme) } -#[cfg(feature = "desktop")] #[tauri::command] pub fn delete_custom_theme(app: AppHandle, theme_id: String) -> Result<(), String> { - committed( - &app, - theme_packages::remove_personal_theme(&get_app_config_dir(), &theme_id), - ) + crate::application::persistence::delete_custom_theme(&app.state::(), &theme_id) } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn import_theme( +pub async fn import_theme( app: AppHandle, theme_json: String, name: Option, ) -> Result { - let result = if let Some(name) = name { - theme_packages::import_legacy_theme_named(&get_app_config_dir(), &theme_json, &name) - } else { - theme_packages::import_legacy_theme(&get_app_config_dir(), &theme_json) - }; - committed(&app, result) + execute(&app, ThemeCommand::ImportTheme { theme_json, name }).await } -#[cfg_attr(feature = "desktop", tauri::command)] -pub fn export_theme(theme_id: String) -> Result { - theme_packages::export_personal_theme(&get_app_config_dir(), &theme_id) +#[tauri::command] +pub async fn export_theme(app: AppHandle, theme_id: String) -> Result { + execute(&app, ThemeCommand::ExportTheme { theme_id }).await } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn create_personal_theme( +pub async fn create_personal_theme( app: AppHandle, name: String, source: String, -) -> Result { - committed( - &app, - theme_packages::create_personal_definition(&get_app_config_dir(), &name, &source), - ) +) -> Result { + execute(&app, ThemeCommand::CreatePersonalTheme { name, source }).await } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn create_personal_snapshot( +pub async fn create_personal_snapshot( app: AppHandle, name: String, source: String, -) -> Result { - committed( - &app, - theme_packages::create_personal_snapshot(&get_app_config_dir(), &name, &source), - ) +) -> Result { + execute(&app, ThemeCommand::CreatePersonalSnapshot { name, source }).await } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn update_personal_theme( +pub async fn update_personal_theme( app: AppHandle, theme_id: String, name: String, source: String, expected_revision: String, -) -> Result { - committed( +) -> Result { + execute( &app, - theme_packages::update_personal_definition( - &get_app_config_dir(), - &theme_id, - &name, - &source, - &expected_revision, - ), + ThemeCommand::UpdatePersonalTheme { + theme_id, + name, + source, + expected_revision, + }, ) + .await } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn update_personal_snapshot( +pub async fn update_personal_snapshot( app: AppHandle, theme_id: String, name: String, source: String, editor: Value, expected_revision: String, -) -> Result { - committed( +) -> Result { + execute( &app, - theme_packages::update_personal_snapshot( - &get_app_config_dir(), - &theme_id, - &name, - &source, + ThemeCommand::UpdatePersonalSnapshot { + theme_id, + name, + source, editor, - &expected_revision, - ), + expected_revision, + }, ) + .await } -#[cfg(feature = "desktop")] #[tauri::command] -pub fn duplicate_personal_theme( +pub async fn duplicate_personal_theme( app: AppHandle, theme_id: String, name: String, editor: Option, -) -> Result { - committed( +) -> Result { + execute( &app, - theme_packages::duplicate_personal_theme( - &get_app_config_dir(), - &get_default_app_data_dir(), - env!("CARGO_PKG_VERSION"), - &theme_id, - &name, + ThemeCommand::DuplicatePersonalTheme { + theme_id, + name, editor, - ), + }, + ) + .await +} + +#[tauri::command] +pub async fn install_local_theme_package( + app: AppHandle, + path: String, + package_name: String, + expected_digest: String, +) -> Result { + execute( + &app, + ThemeCommand::InstallLocalPackage { + archive: LocalThemeArchive::Path(path.into()), + package_name, + expected_digest, + }, + ) + .await +} + +#[tauri::command] +pub async fn fetch_theme_registry( + app: AppHandle, + package_name: Option, + expected_registry_key: Option, +) -> Result { + execute( + &app, + ThemeCommand::FetchRegistry { + package_name, + expected_registry_key, + }, + ) + .await +} + +/// Read-only details: never resolve a tracked download during discovery. +#[tauri::command] +pub async fn fetch_theme_package_detail( + app: AppHandle, + package_name: String, + expected_registry_key: String, + requested_registry_url: Option, +) -> Result { + execute( + &app, + ThemeCommand::FetchPackageDetail { + package_name, + expected_registry_key, + requested_registry_url, + }, + ) + .await +} + +#[tauri::command] +pub async fn install_registry_theme( + app: AppHandle, + package_name: String, + expected_registry_key: String, + version: Option, +) -> Result { + execute( + &app, + ThemeCommand::InstallRegistryTheme { + package_name, + expected_registry_key, + version, + }, + ) + .await +} + +#[tauri::command] +pub async fn set_theme_package_enabled( + app: AppHandle, + registry_key: String, + package_name: String, + enabled: bool, +) -> Result { + execute( + &app, + ThemeCommand::SetPackageEnabled { + registry_key, + package_name, + enabled, + }, + ) + .await +} + +/// Recovery is an explicit action, never a catalog-read or hydration side effect. +#[tauri::command] +pub async fn recover_theme_packages(app: AppHandle) -> Result { + execute(&app, ThemeCommand::RecoverPackages).await +} + +#[tauri::command] +pub async fn uninstall_theme_package( + app: AppHandle, + registry_key: String, + package_name: String, +) -> Result { + execute( + &app, + ThemeCommand::UninstallPackage { + registry_key, + package_name, + }, ) + .await } diff --git a/src-tauri/src/theme_packages/commands.rs b/src-tauri/src/theme_packages/commands.rs index a03efa1bf..e4a746c9d 100644 --- a/src-tauri/src/theme_packages/commands.rs +++ b/src-tauri/src/theme_packages/commands.rs @@ -2,33 +2,11 @@ use super::{catalog::PACKAGES_DIR, lifecycle, *}; use crate::plugins::{install_cancellation, registry, tabularium}; use sha2::{Digest, Sha256}; use std::path::Path; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter}; - -#[cfg(feature = "desktop")] -fn registry_base(app: &AppHandle) -> Result { - let config = crate::config::load_config_internal(app); - let base = config - .tabularium_registry_url - .unwrap_or_else(|| registry::DEFAULT_TABULARIUM_URL.into()); - registry_key(&base)?; - Ok(base) -} fn operation_id(registry: &str, package: &str) -> String { format!("theme:{registry}:{package}") } -#[cfg(feature = "desktop")] -fn refresh(app: &AppHandle) { - if let Err(error) = app.emit("theme-catalog-changed", ()) { - log::warn!( - "Theme operation committed but refresh delivery failed: {}", - error - ); - } -} - /// Standalone import preview validates without creating a personal file. #[cfg_attr(feature = "desktop", tauri::command)] pub fn preview_theme_document(source: String, name: String) -> Result { @@ -126,24 +104,6 @@ pub async fn preview_local_theme_package( preview_local_package_bytes(bytes).await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn install_local_theme_package( - app: AppHandle, - path: String, - package_name: String, - expected_digest: String, -) -> Result { - let result = install_local_package( - move || lifecycle::read_local_archive(Path::new(&path)), - package_name, - expected_digest, - ) - .await?; - refresh(&app); - Ok(result) -} - #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ThemeRegistrySnapshot { @@ -152,16 +112,6 @@ pub struct ThemeRegistrySnapshot { pub plugins: Vec, } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_theme_registry( - app: AppHandle, - package_name: Option, - expected_registry_key: Option, -) -> Result { - fetch_registry(registry_base(&app)?, package_name, expected_registry_key).await -} - /// Lists theme packages from the configured registry `base`. pub async fn fetch_registry( base: String, @@ -195,24 +145,6 @@ pub async fn fetch_registry( }) } -/// Read-only details: never resolve a tracked download during discovery. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_theme_package_detail( - app: AppHandle, - package_name: String, - expected_registry_key: String, - requested_registry_url: Option, -) -> Result { - fetch_package_detail( - registry_base(&app)?, - package_name, - expected_registry_key, - requested_registry_url, - ) - .await -} - /// Read-only package details from the configured registry `base`. pub async fn fetch_package_detail( base: String, @@ -237,25 +169,6 @@ pub async fn fetch_package_detail( Ok(detail) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn install_registry_theme( - app: AppHandle, - package_name: String, - expected_registry_key: String, - version: Option, -) -> Result { - let result = install_registry( - registry_base(&app)?, - expected_registry_key, - package_name, - version, - ) - .await?; - refresh(&app); - Ok(result) -} - /// Downloads and installs one registry package from `base`. pub async fn install_registry( base: String, @@ -279,19 +192,6 @@ pub fn cancel_theme_install(registry_key: String, package_name: String) -> bool install_cancellation::cancel(&operation_id(®istry_key, &package_name)) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_theme_package_enabled( - app: AppHandle, - registry_key: String, - package_name: String, - enabled: bool, -) -> Result<(), String> { - set_package_enabled(®istry_key, &package_name, enabled)?; - refresh(&app); - Ok(()) -} - pub fn set_package_enabled( registry_key: &str, package_name: &str, @@ -305,17 +205,6 @@ pub fn set_package_enabled( ) } -/// Recovery is an explicit action, never a catalog-read or hydration side effect. -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn recover_theme_packages(app: AppHandle) -> Result, String> { - let failures = recover_packages(); - if failures.is_empty() { - refresh(&app); - } - Ok(failures) -} - /// Returns the recovery failures; an empty list means the catalog changed. pub fn recover_packages() -> Vec { let root = crate::paths::get_default_app_data_dir().join(PACKAGES_DIR); @@ -325,18 +214,6 @@ pub fn recover_packages() -> Vec { } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn uninstall_theme_package( - app: AppHandle, - registry_key: String, - package_name: String, -) -> Result { - let result = uninstall_package(®istry_key, &package_name)?; - refresh(&app); - Ok(result) -} - pub fn uninstall_package(registry_key: &str, package_name: &str) -> Result { lifecycle::remove_package( &crate::paths::get_default_app_data_dir(), diff --git a/src-tauri/src/transport/web/rpc.rs b/src-tauri/src/transport/web/rpc.rs index 52c175e8e..2f578f575 100644 --- a/src-tauri/src/transport/web/rpc.rs +++ b/src-tauri/src/transport/web/rpc.rs @@ -18,8 +18,8 @@ use crate::application::{ ApplicationApi, ApplicationError, ApplicationRequestContext, AuthorizationLevel, }; use crate::models::{ - ColumnDefinition, ConnectionAppearance, ConnectionParams, DatabaseSelection, - K8sConnectionInput, RoutineCallArg, SshConnectionInput, SshTestParams, TestConnectionRequest, + ColumnDefinition, ConnectionAppearance, ConnectionParams, K8sConnectionInput, RoutineCallArg, + SshConnectionInput, SshTestParams, TestConnectionRequest, }; use axum::body::Bytes; use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE}; @@ -471,6 +471,7 @@ enum ConnectionRpcCommand { RegisterActiveConnection, DisconnectConnection, TestConnection, + ListDatabases, } #[derive(Clone, Copy)] @@ -1735,38 +1736,21 @@ impl RpcDispatcher { &request.path, ) .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; - let database_path = crate::sqlite_database::create_sqlite_file(path) - .await - .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; if command == RpcCommand::CreateSqliteFile { + let database_path = crate::sqlite_database::create_sqlite_file(path) + .await + .map_err(|error| { + InvocationError::Application(ApplicationError::new(error)) + })?; return Ok(Value::String(database_path)); } - - let path = PathBuf::from(&database_path); - let name = crate::sqlite_database::connection_name(&path) - .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; - let params = ConnectionParams { - driver: "sqlite".to_string(), - database: DatabaseSelection::Single(database_path), - ..ConnectionParams::default() - }; - let result = self - .application + self.application .execute_connection_command( context, - ConnectionCommand::SaveConnection { - name, - params, - plugin_secret_changes: None, - detect_json_in_text_columns: None, - environment: None, - }, + ConnectionCommand::CreateSqliteDatabase { path }, ) - .await; - if result.is_err() { - let _ = std::fs::remove_file(&path); - } - result.map_err(InvocationError::Application) + .await + .map_err(InvocationError::Application) } RpcCommand::Query(command) => { let command = @@ -2603,6 +2587,7 @@ impl ConnectionRpcCommand { "register_active_connection" => Self::RegisterActiveConnection, "disconnect_connection" => Self::DisconnectConnection, "test_connection" => Self::TestConnection, + "list_databases" => Self::ListDatabases, _ => return None, }) } @@ -4208,6 +4193,12 @@ fn decode_connection_command( request: request.request, } } + ConnectionRpcCommand::ListDatabases => { + let request: TestRequest = decode_payload(body)?; + ConnectionCommand::ListDatabases { + request: request.request, + } + } }) } diff --git a/src-tauri/src/transport/web/rpc_connection_policy.rs b/src-tauri/src/transport/web/rpc_connection_policy.rs index 5ee66f476..8aa17806e 100644 --- a/src-tauri/src/transport/web/rpc_connection_policy.rs +++ b/src-tauri/src/transport/web/rpc_connection_policy.rs @@ -17,7 +17,8 @@ pub(super) fn authorize( let params = match command { ConnectionCommand::SaveConnection { params, .. } | ConnectionCommand::UpdateConnection { params, .. } => params, - ConnectionCommand::TestConnection { request } => &request.params, + ConnectionCommand::TestConnection { request } + | ConnectionCommand::ListDatabases { request } => &request.params, _ => return Ok(()), }; @@ -91,9 +92,9 @@ pub(super) async fn authorize_saved_access( | ConnectionRpcCommand::DuplicateConnection | ConnectionRpcCommand::SetConnectionAppearance, ) => &payload["id"], - RpcCommand::Connection(ConnectionRpcCommand::TestConnection) => { - &payload["request"]["connection_id"] - } + RpcCommand::Connection( + ConnectionRpcCommand::TestConnection | ConnectionRpcCommand::ListDatabases, + ) => &payload["request"]["connection_id"], RpcCommand::DatabaseObject(DatabaseObjectRpcCommand::ExecuteClipboardImport) => { &payload["req"]["connection_id"] } @@ -121,7 +122,8 @@ pub(super) async fn authorize_saved_credentials( return Ok(()); } let (id, params) = match command { - ConnectionCommand::TestConnection { request } => { + ConnectionCommand::TestConnection { request } + | ConnectionCommand::ListDatabases { request } => { let Some(id) = request.connection_id.as_deref() else { return Ok(()); }; diff --git a/src-tauri/src/transport/web/rpc_tests.rs b/src-tauri/src/transport/web/rpc_tests.rs index 56667f1fb..ed2190d41 100644 --- a/src-tauri/src/transport/web/rpc_tests.rs +++ b/src-tauri/src/transport/web/rpc_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::models::DatabaseSelection; use async_trait::async_trait; use axum::body::to_bytes; use axum::http::header::CONTENT_TYPE; @@ -819,8 +820,8 @@ async fn creates_sqlite_files_only_inside_configured_server_roots() { ) .await; + // The application layer creates the file; the fixture only records the call. assert_eq!(response.status(), StatusCode::OK); - assert!(database_path.exists()); } #[tokio::test] From 1d961a4d11dcc36acea84c21faf565a0d2b85fd5 Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 15:13:12 +0200 Subject: [PATCH 3/6] refactor(desktop): move all Tauri code into transport::desktop Tauri commands and everything that needs an AppHandle, a window or Tauri state now live in `src-tauri/src/transport/desktop/`, next to `transport/web`. It is the only module behind the `desktop` feature, so the rest of the crate no longer carries per-item `cfg(feature = "desktop")` or `cfg_attr(..., tauri::command)` attributes. - `transport/desktop/.rs` mirrors the module the code came from; commands the web RPC also calls stay plain functions and get a one-line Tauri wrapper there - `run()` moved from lib.rs with the handler list unchanged (308 commands) - the askpass bridge keeps the app's `RuntimeEvents` instead of a Tauri `AppHandle` - helpers the desktop code needs became `pub(crate)` No behaviour changes. `.rules/rust.md` documents the boundary and CI fails when Tauri shows up outside `transport/desktop`. --- .github/workflows/ci.yml | 8 + .rules/rust.md | 1 + src-tauri/src/ai.rs | 97 - src-tauri/src/ai_approval_watcher.rs | 97 +- src-tauri/src/application/plugins.rs | 2 +- src-tauri/src/askpass/mod.rs | 36 +- src-tauri/src/backup/mod.rs | 136 +- src-tauri/src/chatgpt/auth.rs | 146 +- src-tauri/src/chatgpt/mod.rs | 72 +- src-tauri/src/chatgpt/protocol.rs | 12 +- src-tauri/src/chatgpt/storage.rs | 10 +- src-tauri/src/clipboard_import.rs | 11 - src-tauri/src/commands.rs | 2599 +---------------- src-tauri/src/config.rs | 457 --- src-tauri/src/connection_appearance.rs | 15 - src-tauri/src/drivers/registry.rs | 2 +- src-tauri/src/dump_commands.rs | 69 - src-tauri/src/explain_import.rs | 66 - src-tauri/src/export.rs | 44 - src-tauri/src/health_check.rs | 215 +- src-tauri/src/json_viewer.rs | 200 +- src-tauri/src/lib.rs | 685 +---- src-tauri/src/log_commands.rs | 54 - src-tauri/src/mcp/install.rs | 17 - src-tauri/src/plugins/commands.rs | 119 +- src-tauri/src/plugins/connection_metadata.rs | 12 - src-tauri/src/plugins/deep_link.rs | 58 +- src-tauri/src/plugins/force_install.rs | 169 +- src-tauri/src/plugins/manager.rs | 16 - src-tauri/src/plugins/runtime_version.rs | 1 - src-tauri/src/preferences.rs | 70 - src-tauri/src/proxy/mod.rs | 3 - src-tauri/src/query_history.rs | 110 - src-tauri/src/results_window.rs | 100 +- src-tauri/src/runtime/events.rs | 22 - src-tauri/src/runtime/lifecycle.rs | 10 - src-tauri/src/runtime/tests.rs | 134 - src-tauri/src/saved_queries.rs | 194 -- src-tauri/src/sql_file.rs | 2 - src-tauri/src/sqlite_database.rs | 1 - src-tauri/src/storage_location.rs | 18 - src-tauri/src/theme_packages/catalog.rs | 2 +- src-tauri/src/theme_packages/commands.rs | 3 - src-tauri/src/theme_packages/mod.rs | 4 +- src-tauri/src/transport/desktop/ai.rs | 92 + .../transport/desktop/ai_approval_watcher.rs | 88 + .../{ => transport/desktop}/ai_commands.rs | 0 src-tauri/src/transport/desktop/askpass.rs | 6 + src-tauri/src/transport/desktop/backup.rs | 127 + src-tauri/src/transport/desktop/chatgpt.rs | 74 + .../src/transport/desktop/chatgpt/auth.rs | 140 + .../src/transport/desktop/clipboard_import.rs | 10 + src-tauri/src/transport/desktop/commands.rs | 2507 ++++++++++++++++ src-tauri/src/transport/desktop/config.rs | 433 +++ .../desktop/connection_appearance.rs | 14 + .../desktop}/connection_import_commands.rs | 0 .../desktop}/connection_window.rs | 4 +- .../desktop}/connection_window_tests.rs | 2 +- .../src/transport/desktop/dump_commands.rs | 66 + .../desktop}/e2e_dialog_mock.rs | 11 +- .../src/transport/desktop/explain_import.rs | 70 + src-tauri/src/transport/desktop/export.rs | 42 + .../src/transport/desktop/health_check.rs | 212 ++ .../src/transport/desktop/json_viewer.rs | 200 ++ .../src/transport/desktop/log_commands.rs | 59 + src-tauri/src/transport/desktop/mcp.rs | 1 + .../src/transport/desktop/mcp/install.rs | 16 + src-tauri/src/transport/desktop/mod.rs | 688 +++++ .../src/{ => transport/desktop}/notebooks.rs | 0 src-tauri/src/transport/desktop/plugins.rs | 6 + .../src/transport/desktop/plugins/commands.rs | 121 + .../desktop/plugins/connection_metadata.rs | 9 + .../transport/desktop/plugins/deep_link.rs | 55 + .../desktop/plugins/force_install.rs | 155 + .../src/transport/desktop/plugins/manager.rs | 19 + .../desktop/plugins/runtime_version.rs | 6 + .../src/transport/desktop/preferences.rs | 67 + src-tauri/src/transport/desktop/proxy.rs | 14 + .../src/transport/desktop/query_history.rs | 105 + .../src/transport/desktop/results_window.rs | 96 + src-tauri/src/transport/desktop/runtime.rs | 2 + .../src/transport/desktop/runtime/events.rs | 21 + .../transport/desktop/runtime/lifecycle.rs | 12 + .../src/transport/desktop/saved_queries.rs | 188 ++ src-tauri/src/transport/desktop/sql_file.rs | 9 + .../src/transport/desktop/sqlite_database.rs | 4 + .../src/transport/desktop/storage_location.rs | 45 + .../{ => transport/desktop}/system_theme.rs | 0 .../desktop}/system_theme/portal.rs | 0 .../desktop}/system_theme/portal/tests.rs | 0 .../{ => transport/desktop}/task_manager.rs | 2 +- src-tauri/src/transport/desktop/tests.rs | 155 + .../{ => transport/desktop}/theme_commands.rs | 0 .../src/transport/desktop/theme_packages.rs | 1 + .../desktop/theme_packages/commands.rs | 19 + .../desktop}/ui_state_commands.rs | 0 .../src/{ => transport/desktop}/updater.rs | 6 +- .../desktop}/updater/installation_source.rs | 0 .../updater/installation_source/tests.rs | 0 .../desktop}/window_decorations.rs | 0 .../desktop}/window_decorations_tests.rs | 0 .../desktop}/window_placement.rs | 0 src-tauri/src/transport/mod.rs | 2 + web-ui-project/docs/WEB_UI_PLAN.md | 2 +- web-ui-project/docs/web-ui-parity.json | 2 +- .../scripts/generate-web-ui-api-inventory.mjs | 2 +- 106 files changed, 6075 insertions(+), 6011 deletions(-) create mode 100644 src-tauri/src/transport/desktop/ai.rs create mode 100644 src-tauri/src/transport/desktop/ai_approval_watcher.rs rename src-tauri/src/{ => transport/desktop}/ai_commands.rs (100%) create mode 100644 src-tauri/src/transport/desktop/askpass.rs create mode 100644 src-tauri/src/transport/desktop/backup.rs create mode 100644 src-tauri/src/transport/desktop/chatgpt.rs create mode 100644 src-tauri/src/transport/desktop/chatgpt/auth.rs create mode 100644 src-tauri/src/transport/desktop/clipboard_import.rs create mode 100644 src-tauri/src/transport/desktop/commands.rs create mode 100644 src-tauri/src/transport/desktop/config.rs create mode 100644 src-tauri/src/transport/desktop/connection_appearance.rs rename src-tauri/src/{ => transport/desktop}/connection_import_commands.rs (100%) rename src-tauri/src/{ => transport/desktop}/connection_window.rs (94%) rename src-tauri/src/{ => transport/desktop}/connection_window_tests.rs (92%) create mode 100644 src-tauri/src/transport/desktop/dump_commands.rs rename src-tauri/src/{ => transport/desktop}/e2e_dialog_mock.rs (90%) create mode 100644 src-tauri/src/transport/desktop/explain_import.rs create mode 100644 src-tauri/src/transport/desktop/export.rs create mode 100644 src-tauri/src/transport/desktop/health_check.rs create mode 100644 src-tauri/src/transport/desktop/json_viewer.rs create mode 100644 src-tauri/src/transport/desktop/log_commands.rs create mode 100644 src-tauri/src/transport/desktop/mcp.rs create mode 100644 src-tauri/src/transport/desktop/mcp/install.rs create mode 100644 src-tauri/src/transport/desktop/mod.rs rename src-tauri/src/{ => transport/desktop}/notebooks.rs (100%) create mode 100644 src-tauri/src/transport/desktop/plugins.rs create mode 100644 src-tauri/src/transport/desktop/plugins/commands.rs create mode 100644 src-tauri/src/transport/desktop/plugins/connection_metadata.rs create mode 100644 src-tauri/src/transport/desktop/plugins/deep_link.rs create mode 100644 src-tauri/src/transport/desktop/plugins/force_install.rs create mode 100644 src-tauri/src/transport/desktop/plugins/manager.rs create mode 100644 src-tauri/src/transport/desktop/plugins/runtime_version.rs create mode 100644 src-tauri/src/transport/desktop/preferences.rs create mode 100644 src-tauri/src/transport/desktop/proxy.rs create mode 100644 src-tauri/src/transport/desktop/query_history.rs create mode 100644 src-tauri/src/transport/desktop/results_window.rs create mode 100644 src-tauri/src/transport/desktop/runtime.rs create mode 100644 src-tauri/src/transport/desktop/runtime/events.rs create mode 100644 src-tauri/src/transport/desktop/runtime/lifecycle.rs create mode 100644 src-tauri/src/transport/desktop/saved_queries.rs create mode 100644 src-tauri/src/transport/desktop/sql_file.rs create mode 100644 src-tauri/src/transport/desktop/sqlite_database.rs create mode 100644 src-tauri/src/transport/desktop/storage_location.rs rename src-tauri/src/{ => transport/desktop}/system_theme.rs (100%) rename src-tauri/src/{ => transport/desktop}/system_theme/portal.rs (100%) rename src-tauri/src/{ => transport/desktop}/system_theme/portal/tests.rs (100%) rename src-tauri/src/{ => transport/desktop}/task_manager.rs (95%) create mode 100644 src-tauri/src/transport/desktop/tests.rs rename src-tauri/src/{ => transport/desktop}/theme_commands.rs (100%) create mode 100644 src-tauri/src/transport/desktop/theme_packages.rs create mode 100644 src-tauri/src/transport/desktop/theme_packages/commands.rs rename src-tauri/src/{ => transport/desktop}/ui_state_commands.rs (100%) rename src-tauri/src/{ => transport/desktop}/updater.rs (98%) rename src-tauri/src/{ => transport/desktop}/updater/installation_source.rs (100%) rename src-tauri/src/{ => transport/desktop}/updater/installation_source/tests.rs (100%) rename src-tauri/src/{ => transport/desktop}/window_decorations.rs (100%) rename src-tauri/src/{ => transport/desktop}/window_decorations_tests.rs (100%) rename src-tauri/src/{ => transport/desktop}/window_placement.rs (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a0ecc4ca..cfb2e7324 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,6 +92,14 @@ jobs: working-directory: src-tauri run: cargo check --locked --no-default-features --bin tabularis + - name: Keep Tauri inside the desktop transport + run: | + if grep -rnE '(^|[^_[:alnum:]])tauri(::|_plugin)' src-tauri/src --include='*.rs' \ + --exclude-dir=desktop | grep -v 'tauri::mobile_entry_point\|async_runtime\|tauri::test::'; then + echo "::error::Tauri code belongs in src-tauri/src/transport/desktop/ (see .rules/rust.md)" + exit 1 + fi + web-e2e: runs-on: ubuntu-24.04 diff --git a/.rules/rust.md b/.rules/rust.md index f7a3ae356..b2245bbf1 100644 --- a/.rules/rust.md +++ b/.rules/rust.md @@ -6,3 +6,4 @@ 4. **Separate Rust tests from implementation:** When a module has non-trivial tests, place them in a sibling `tests.rs` file (or `tests/*.rs` when the module grows further) and load them with `#[cfg(test)] mod tests;`. 5. **Test extracted helpers directly:** Every extracted pure helper or parser should have unit tests covering nominal cases, edge cases, and unsupported inputs when relevant. 6. **Avoid behavioural refactors mixed with structural refactors:** When reorganizing Rust files, keep function signatures and runtime behaviour stable unless the task explicitly asks for behaviour changes. +7. **Keep Tauri in the desktop transport:** Tauri commands, plugins and anything that takes an `AppHandle`, `Window` or `State` live in `src-tauri/src/transport/desktop/`, which is the only module behind the `desktop` feature. Put the logic in `application/` (or a plain module) so the web RPC and the desktop command share it; the command stays a thin wrapper. diff --git a/src-tauri/src/ai.rs b/src-tauri/src/ai.rs index abbcc3cc7..029935f0c 100644 --- a/src-tauri/src/ai.rs +++ b/src-tauri/src/ai.rs @@ -8,8 +8,6 @@ use std::collections::{HashMap, HashSet}; use std::fs; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager}; // --- Data Structures --- @@ -385,12 +383,6 @@ async fn fetch_custom_openai_models(base_url: &str, api_key: &str) -> Vec Result<(), String> { - clear_models_cache(&app.state::()) -} - pub fn clear_models_cache(runtime: &RuntimeContext) -> Result<(), String> { let path = get_cache_path(runtime); if path.exists() { @@ -399,20 +391,6 @@ pub fn clear_models_cache(runtime: &RuntimeContext) -> Result<(), String> { Ok(()) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_ai_models( - app: AppHandle, - force_refresh: bool, -) -> Result>, String> { - get_models( - &app.state::(), - &app.state::>(), - force_refresh, - ) - .await -} - pub async fn get_models( runtime: &RuntimeContext, cache: &CredentialCache, @@ -583,53 +561,6 @@ pub async fn get_models( Ok(models) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result { - generate_query( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result { - explain_query( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn analyze_ai_explain_plan( - app: AppHandle, - req: AiExplainRequest, -) -> Result { - analyze_explain_plan( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn generate_cell_name(app: AppHandle, req: AiCellNameRequest) -> Result { - generate_cellname( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - // --- Shared helpers --- async fn resolve_model( @@ -900,20 +831,6 @@ pub async fn generate_cellname( .await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn suggest_table_name( - app: AppHandle, - req: AiSuggestTableNameRequest, -) -> Result { - suggest_table_name_with_runtime( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - pub async fn suggest_table_name_with_runtime( runtime: &RuntimeContext, cache: &CredentialCache, @@ -977,20 +894,6 @@ pub async fn suggest_table_name_with_runtime( } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn generate_tab_rename( - app: AppHandle, - req: AiTabRenameRequest, -) -> Result { - generate_tab_name( - &app.state::(), - &app.state::>(), - req, - ) - .await -} - pub async fn generate_tab_name( runtime: &RuntimeContext, cache: &CredentialCache, diff --git a/src-tauri/src/ai_approval_watcher.rs b/src-tauri/src/ai_approval_watcher.rs index 6d8881514..4ecd75aec 100644 --- a/src-tauri/src/ai_approval_watcher.rs +++ b/src-tauri/src/ai_approval_watcher.rs @@ -4,21 +4,18 @@ //! Also runs a periodic cleanup that removes stale pending/decision files //! left behind by crashed MCP processes. -use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use std::collections::{HashMap, HashSet}; -use std::sync::{mpsc, Arc}; +use std::sync::Arc; use std::time::Duration; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter, Runtime}; use crate::ai_approval; -const PENDING_APPROVAL_EVENT: &str = "ai://pending_approval"; +pub(crate) const PENDING_APPROVAL_EVENT: &str = "ai://pending_approval"; /// Stale pending+decision files older than this are deleted by the periodic /// cleanup task. 1 hour is comfortably longer than the maximum approval /// timeout (`mcp_approval_timeout_seconds` default: 120). -const CLEANUP_MAX_AGE_SECS: u64 = 3_600; -const CLEANUP_INTERVAL_SECS: u64 = 60; +pub(crate) const CLEANUP_MAX_AGE_SECS: u64 = 3_600; +pub(crate) const CLEANUP_INTERVAL_SECS: u64 = 60; const HEADLESS_POLL_INTERVAL_MS: u64 = 250; /// Poll the approval queue for headless Web mode and deliver each prompt to @@ -110,89 +107,3 @@ pub fn spawn_headless( }) } -#[cfg(feature = "desktop")] -/// Spawn the watcher + cleanup tasks. The watcher returns immediately if it -/// fails to initialise (e.g. unsupported filesystem); cleanup keeps running. -pub fn spawn(app: AppHandle) { - let app_for_watcher = app.clone(); - crate::async_rt::spawn_blocking(move || { - if let Err(e) = run_watcher(app_for_watcher) { - log::warn!("AI approval watcher disabled: {}", e); - } - }); - - let app_for_cleanup = app.clone(); - crate::async_rt::spawn(async move { - run_cleanup_loop(app_for_cleanup).await; - }); -} - -#[cfg(feature = "desktop")] -fn run_watcher(app: AppHandle) -> Result<(), String> { - let dir = ai_approval::approvals_dir_path(); - std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; - - let (tx, rx) = mpsc::channel::>(); - let mut watcher: RecommendedWatcher = - notify::recommended_watcher(tx).map_err(|e| e.to_string())?; - watcher - .watch(&dir, RecursiveMode::NonRecursive) - .map_err(|e| e.to_string())?; - - log::info!("AI approval watcher started on {}", dir.display()); - - // The watcher is dropped when this function returns; keep it alive for the - // process lifetime by looping forever. - for evt in rx { - match evt { - Ok(event) => handle_event(&app, &event), - Err(e) => log::warn!("approval watcher error: {}", e), - } - } - Ok(()) -} - -#[cfg(feature = "desktop")] -fn handle_event(app: &AppHandle, event: &Event) { - if !matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_)) { - return; - } - for path in &event.paths { - let name = match path.file_name().and_then(|s| s.to_str()) { - Some(n) => n, - None => continue, - }; - if !name.ends_with(".pending.json") { - continue; - } - let id = name.trim_end_matches(".pending.json").to_string(); - // The file may not yet be fully flushed when notify fires Create — - // try to read; if it fails this iteration we'll catch it on the - // next Modify event. - if let Ok(Some(pending)) = ai_approval::read_pending(&id) { - if let Err(e) = app.emit(PENDING_APPROVAL_EVENT, &pending) { - log::warn!("Failed to emit {}: {}", PENDING_APPROVAL_EVENT, e); - } - } - } -} - -#[cfg(feature = "desktop")] -async fn run_cleanup_loop(_app: AppHandle) { - let mut ticker = tokio::time::interval(Duration::from_secs(CLEANUP_INTERVAL_SECS)); - // Skip the immediate first tick. - ticker.tick().await; - loop { - ticker.tick().await; - let cleaned = tokio::task::spawn_blocking(|| { - ai_approval::cleanup_expired(CLEANUP_MAX_AGE_SECS) - }) - .await - .ok() - .and_then(|r| r.ok()) - .unwrap_or(0); - if cleaned > 0 { - log::info!("Cleaned {} stale approval file(s)", cleaned); - } - } -} diff --git a/src-tauri/src/application/plugins.rs b/src-tauri/src/application/plugins.rs index d5dc482be..140a4c8f3 100644 --- a/src-tauri/src/application/plugins.rs +++ b/src-tauri/src/application/plugins.rs @@ -382,7 +382,7 @@ pub async fn restart_plugin_process( } /// Tells the frontend that connection metadata derived from this driver may -/// have changed (see `crate::plugins::connection_metadata::notify_plugin_reload`). +/// have changed (see `crate::transport::desktop::plugins::connection_metadata::notify_plugin_reload`). fn notify_plugin_reload(runtime: &RuntimeContext, plugin_id: &str) { let _ = runtime.events.emit( "connection-metadata-invalidated", diff --git a/src-tauri/src/askpass/mod.rs b/src-tauri/src/askpass/mod.rs index 624f100a3..046581404 100644 --- a/src-tauri/src/askpass/mod.rs +++ b/src-tauri/src/askpass/mod.rs @@ -25,8 +25,7 @@ pub use protocol::PromptKind; pub use server::{AskpassOptions, AskpassServer, AskpassUi}; use crate::runtime::events::RuntimeEvents; -#[cfg(feature = "desktop")] -use crate::runtime::events::TauriRuntimeEvents; + use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{sync_channel, SyncSender}; @@ -34,8 +33,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use serde::Serialize; -#[cfg(feature = "desktop")] -use tauri::AppHandle; + use uuid::Uuid; /// Event emitted to the frontend when ssh needs user input. @@ -47,10 +45,9 @@ pub const DISMISS_EVENT: &str = "ssh-askpass://dismiss"; /// How long the user gets to answer a prompt before ssh receives a cancel. const RESPONSE_TIMEOUT_SECS: u64 = 300; -/// Global handle for code paths (the SSH tunnel module) that run without a -/// Tauri context. Set once during application setup. -#[cfg(feature = "desktop")] -static APP_HANDLE: OnceLock = OnceLock::new(); +/// Events of the app's own window, for code paths (the SSH tunnel module) that +/// run without a frontend session. Set once during desktop setup. +static FRONTEND_EVENTS: OnceLock> = OnceLock::new(); static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1); @@ -64,12 +61,6 @@ fn pending_responses() -> &'static Mutex> { PENDING.get_or_init(|| Mutex::new(HashMap::new())) } -#[cfg(feature = "desktop")] -/// Store the app handle so SSH tunnel code can reach the frontend. -pub fn set_app_handle(app: AppHandle) { - let _ = APP_HANDLE.set(app); -} - /// Start an askpass server bridged to the frontend. Fails when the app is not /// fully initialised (e.g. in unit tests). Callers must not then force OpenSSH /// to run its compiled-in askpass path: on macOS that is @@ -81,24 +72,22 @@ pub fn start_frontend_server() -> Result { /// Like [`start_frontend_server`], with stored credentials that answer matching /// prompts without opening the modal. pub fn start_frontend_server_with(options: AskpassOptions) -> Result { - #[cfg(not(feature = "desktop"))] - { - let _ = options; - Err("Askpass UI unavailable: application not initialised".to_string()) - } - #[cfg(feature = "desktop")] - let app = APP_HANDLE + let events = FRONTEND_EVENTS .get() .ok_or_else(|| "Askpass UI unavailable: application not initialised".to_string())?; - #[cfg(feature = "desktop")] start_scoped_server_with( - Arc::new(TauriRuntimeEvents::new(app.clone())), + events.clone(), None, Duration::from_secs(RESPONSE_TIMEOUT_SECS), options, ) } +/// Lets SSH tunnel code reach the app's own window. +pub fn set_frontend_events(events: Arc) { + let _ = FRONTEND_EVENTS.set(events); +} + pub fn start_scoped_server_with( events: Arc, session_id: Option, @@ -192,7 +181,6 @@ impl AskpassUi for FrontendUi { /// Frontend answer to an askpass prompt. `response = None` means the user /// cancelled. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn respond_ssh_askpass(id: u64, response: Option) { let _ = respond_for_session(None, id, response); } diff --git a/src-tauri/src/backup/mod.rs b/src-tauri/src/backup/mod.rs index 84255f1fa..12bf0ed87 100644 --- a/src-tauri/src/backup/mod.rs +++ b/src-tauri/src/backup/mod.rs @@ -11,8 +11,6 @@ use chrono::NaiveDateTime; use keyring::Entry; use std::fs; use std::path::PathBuf; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime}; use crate::runtime::RuntimeContext; @@ -326,7 +324,7 @@ fn backup_target(config: &crate::config::AppConfig) -> String { /// Timestamp of the newest existing backup on the configured target. Used /// for the due-check; a target that cannot be inspected yields `None`. -async fn newest_backup(config: &crate::config::AppConfig) -> Option { +pub(crate) async fn newest_backup(config: &crate::config::AppConfig) -> Option { newest_backup_on_target(target_from_config(config).ok()?).await } @@ -417,16 +415,7 @@ pub async fn run_backup_for_runtime( }) } -#[cfg(feature = "desktop")] -pub async fn run_backup(app: AppHandle, trigger: &str) -> Result { - Ok( - run_backup_for_runtime(app.state::().inner(), trigger) - .await? - .location, - ) -} - -fn backup_mode(config: &crate::config::AppConfig) -> String { +pub(crate) fn backup_mode(config: &crate::config::AppConfig) -> String { config .backup_mode .clone() @@ -434,84 +423,6 @@ fn backup_mode(config: &crate::config::AppConfig) -> String { .unwrap_or_else(|| "manual".to_string()) } -#[cfg(feature = "desktop")] -async fn run_and_log(app: &AppHandle, trigger: &str) { - if let Err(e) = run_backup(app.clone(), trigger).await { - log::warn!("Connections backup ({trigger}) failed: {e}"); - } -} - -#[cfg(feature = "desktop")] -/// Interval mode: runs one backup when the newest one is older than the -/// configured interval. -async fn run_if_due(app: &AppHandle) { - let config = crate::config::load_config_internal(app); - if backup_mode(&config) != "interval" { - return; - } - let interval = config - .backup_interval_minutes - .unwrap_or(DEFAULT_INTERVAL_MINUTES); - if is_backup_due( - newest_backup(&config).await, - chrono::Local::now().naive_local(), - interval, - ) { - run_and_log(app, "interval").await; - } -} - -#[cfg(feature = "desktop")] -/// Called from the `RunEvent::Exit` handler. In on-close mode every exit -/// writes a backup so the freshest state is what gets saved. Synchronous: -/// the process is about to end. -pub fn run_exit_backup(app: &AppHandle) { - let config = crate::config::load_config_internal(app); - if backup_mode(&config) == "onClose" { - // Bound the backup so a hung network operation can never prevent the - // process from exiting. - tauri::async_runtime::block_on(async { - if tokio::time::timeout( - std::time::Duration::from_secs(30), - run_and_log(app, "on close"), - ) - .await - .is_err() - { - log::error!("Exit backup timed out after 30s, exiting without it"); - } - }); - } -} - -#[cfg(feature = "desktop")] -/// Background task started at app launch. In on-launch mode it writes one -/// backup right away; in interval mode it checks periodically whether a -/// backup is due. Config is re-read on every tick so settings changes apply -/// without a restart (a switch to on-launch only takes effect at the next -/// start, like the mode's name says). -pub fn spawn_scheduler(app: AppHandle) { - crate::async_rt::spawn(async move { - if backup_mode(&crate::config::load_config_internal(&app)) == "onLaunch" { - run_and_log(&app, "on launch").await; - } - // Wake up every minute but only run the (possibly network-touching) - // due-check at the tick cadence, so interval changes in the settings - // take effect within a minute without hammering a WebDAV target. - let mut last_check = std::time::Instant::now(); - loop { - tokio::time::sleep(std::time::Duration::from_secs(60)).await; - let interval = crate::config::load_config_internal(&app) - .backup_interval_minutes - .unwrap_or(DEFAULT_INTERVAL_MINUTES); - if last_check.elapsed().as_secs() >= scheduler_tick_secs(interval) { - last_check = std::time::Instant::now(); - run_if_due(&app).await; - } - } - }); -} - // ---------- Tauri commands ---------- #[derive(serde::Serialize)] @@ -578,49 +489,6 @@ pub fn set_backup_target_password( } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connections_backup_status( - app: AppHandle, -) -> Result { - backup_status(app.state::().inner()).await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_connections_backup_password( - app: AppHandle, - password: String, -) -> Result<(), String> { - set_backup_password(app.state::().inner(), &password) -} - -/// Stores (or clears, with an empty password) the credential of one backup -/// target, keyed by its id (e.g. `"webdav"`). -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_connections_backup_target_password( - app: AppHandle, - target_id: String, - password: String, -) -> Result<(), String> { - set_backup_target_password(app.state::().inner(), &target_id, &password) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn run_connections_backup( - app: AppHandle, -) -> Result { - crate::application::connection_files::execute( - &app.state::(), - &app.state::>(), - None, - crate::application::connection_files::ConnectionFilesCommand::RunBackup, - ) - .await -} - fn load_runtime_config(runtime: &RuntimeContext) -> crate::config::AppConfig { fs::read_to_string(runtime.paths.config_dir().join("config.json")) .ok() diff --git a/src-tauri/src/chatgpt/auth.rs b/src-tauri/src/chatgpt/auth.rs index 9bdfab59b..0f04f1da6 100644 --- a/src-tauri/src/chatgpt/auth.rs +++ b/src-tauri/src/chatgpt/auth.rs @@ -15,7 +15,7 @@ use tokio::{ mod tests; #[derive(Deserialize)] -struct TokenResponse { +pub(crate) struct TokenResponse { access_token: String, refresh_token: String, id_token: Option, @@ -26,7 +26,7 @@ struct TokenResponse { } impl TokenResponse { - fn tokens(self, previous: Option<&Tokens>) -> Result { + pub(crate) fn tokens(self, previous: Option<&Tokens>) -> Result { if !self.token_type.eq_ignore_ascii_case("bearer") || self.access_token.is_empty() || self.refresh_token.is_empty() @@ -51,7 +51,7 @@ impl TokenResponse { } } -async fn token_request(params: &[(&str, &str)]) -> Result { +pub(crate) async fn token_request(params: &[(&str, &str)]) -> Result { let body = url::form_urlencoded::Serializer::new(String::new()) .extend_pairs(params.iter().copied()) .finish(); @@ -81,7 +81,7 @@ async fn token_request(params: &[(&str, &str)]) -> Result .map_err(|_| "ChatGPT returned an invalid token response.".into()) } -async fn callback( +pub(crate) async fn callback( listener: &TcpListener, state: &str, existing: Option<&str>, @@ -158,141 +158,7 @@ async fn callback( } } -#[cfg(feature = "desktop")] -pub(super) async fn sign_in( - app: &tauri::AppHandle, - store: Store, - profile_id: Option<&str>, -) -> Result { - #[cfg(feature = "desktop")] - use tauri_plugin_opener::OpenerExt; - let existing = profile_id - .map(|id| { - store - .profiles - .iter() - .find(|p| p.id == id) - .cloned() - .ok_or("ChatGPT account not found.") - }) - .transpose()?; - let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) - .await - .map_err(|_| "Could not start the local ChatGPT callback listener.")?; - let redirect_uri = format!( - "http://127.0.0.1:{}/auth/callback", - listener - .local_addr() - .map_err(|_| "Could not read callback port.")? - .port() - ); - let state = protocol::random()?; - let nonce = protocol::random()?; - let verifier = protocol::random()?; - let challenge = protocol::challenge(&verifier); - let client_id = existing - .as_ref() - .map(|p| p.client_id.as_str()) - .unwrap_or("dynamic_agent_client"); - let mut url = url::Url::parse(&format!("{ISSUER}/api/accounts/authorize")) - .map_err(|_| "Invalid ChatGPT authorization endpoint.")?; - url.query_pairs_mut().extend_pairs([ - ("client_id", client_id), - ("ext_agent_host_id", &store.host_id), - ("response_type", "code"), - ("redirect_uri", &redirect_uri), - ( - "scope", - "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct", - ), - ("resource", RESOURCE), - ("state", &state), - ("nonce", &nonce), - ("code_challenge_method", "S256"), - ("code_challenge", &challenge), - ]); - if let Some(profile) = &existing { - if let Some(tokens) = &profile.tokens { - url.query_pairs_mut() - .append_pair("id_token_hint", &tokens.id_token); - } - if let Some(email) = &profile.email { - url.query_pairs_mut().append_pair("login_hint", email); - } - } else { - url.query_pairs_mut() - .append_pair("agent_name_hint", "Tabularis"); - } - // Never include the authorization URL in errors or logs: it may contain an ID token. - app.opener() - .open_url(url.as_str(), None::<&str>) - .map_err(|_| "Could not open the browser for ChatGPT sign-in.")?; - let callback = callback( - &listener, - &state, - existing.as_ref().map(|p| p.client_id.as_str()), - ) - .await?; - let target_profile_id = { - let _guard = super::SESSION_LOCK.lock().await; - let disk = LockedStore::open()?; - let mut current = disk.load()?; - if current.host_id != store.host_id { - return Err("ChatGPT installation changed during sign-in. Please try again.".into()); - } - let id = register_profile(&mut current, existing.as_ref(), &callback)?; - // Retain the issued registration even when code exchange fails or is cancelled. - disk.save(¤t)?; - id - }; - let response = token_request(&[ - ("grant_type", "authorization_code"), - ("client_id", &callback.client_id), - ("code", &callback.code), - ("code_verifier", &verifier), - ("redirect_uri", &redirect_uri), - ("resource", RESOURCE), - ]) - .await?; - let tokens = response.tokens(None)?; - let response = super::http_client()? - .get(format!("{ISSUER}/.well-known/jwks.json")) - .timeout(std::time::Duration::from_secs(30)) - .send() - .await - .map_err(|_| "Could not retrieve ChatGPT identity verification keys.")?; - if !response.status().is_success() { - return Err("Could not retrieve ChatGPT identity verification keys.".into()); - } - let keys: Value = response - .json() - .await - .map_err(|_| "Invalid ChatGPT identity verification keys.")?; - let identity = protocol::verify_identity( - &tokens.id_token, - &keys, - &callback.client_id, - &nonce, - protocol::now(), - )?; - let _guard = super::SESSION_LOCK.lock().await; - let disk = LockedStore::open()?; - let mut current = disk.load()?; - if current.host_id != store.host_id { - return Err("ChatGPT installation changed during sign-in. Please try again.".into()); - } - complete_sign_in( - &mut current, - &target_profile_id, - &callback.client_id, - identity, - tokens, - )?; - disk.save(¤t)?; - Ok(current) -} - -fn register_profile( +pub(crate) fn register_profile( store: &mut Store, existing: Option<&Profile>, callback: &Callback, @@ -320,7 +186,7 @@ fn register_profile( Ok(id) } -fn complete_sign_in( +pub(crate) fn complete_sign_in( store: &mut Store, profile_id: &str, client_id: &str, diff --git a/src-tauri/src/chatgpt/mod.rs b/src-tauri/src/chatgpt/mod.rs index 5bd5e80a2..073de3ad3 100644 --- a/src-tauri/src/chatgpt/mod.rs +++ b/src-tauri/src/chatgpt/mod.rs @@ -1,9 +1,9 @@ //! ChatGPT plan usage for the local desktop app. Credentials never cross IPC. mod api_errors; -mod auth; -mod inference; -mod protocol; -mod storage; +pub(crate) mod auth; +pub(crate) mod inference; +pub(crate) mod protocol; +pub(crate) mod storage; #[cfg(test)] mod tests; @@ -13,12 +13,12 @@ use std::sync::Mutex; use storage::session; use tokio::sync::oneshot; -const ISSUER: &str = "https://auth.openai.com"; -const RESOURCE: &str = "https://api.openai.com/v1"; +pub(crate) const ISSUER: &str = "https://auth.openai.com"; +pub(crate) const RESOURCE: &str = "https://api.openai.com/v1"; const PLAN_SCOPE: &str = "chatgpt.tokens.use.direct"; -static SESSION_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); -static SIGN_IN_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); -static SIGN_IN_CANCEL: Mutex>> = Mutex::new(None); +pub(crate) static SESSION_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +pub(crate) static SIGN_IN_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +pub(crate) static SIGN_IN_CANCEL: Mutex>> = Mutex::new(None); #[derive(Serialize)] #[serde(rename_all = "camelCase")] @@ -37,55 +37,16 @@ pub struct ChatGptSession { profiles: Vec, } -fn http_client() -> Result { +pub(crate) fn http_client() -> Result { crate::proxy::ai_http_client("chatgpt") } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_chatgpt_session() -> Result { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; Ok(session(&disk.load()?)) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn sign_in_chatgpt( - app: tauri::AppHandle, - profile_id: Option, -) -> Result { - let _sign_in = SIGN_IN_LOCK - .try_lock() - .map_err(|_| "Another ChatGPT sign-in is running.")?; - let (cancel, cancelled) = oneshot::channel(); - *SIGN_IN_CANCEL - .lock() - .map_err(|_| "ChatGPT sign-in lock is unavailable.")? = Some(cancel); - let attempt = async { - let state = { - let _guard = SESSION_LOCK.lock().await; - let disk = storage::LockedStore::open()?; - let state = disk.load()?; - // Persist the installation ID before opening the browser. - disk.save(&state)?; - state - }; - auth::sign_in(&app, state, profile_id.as_deref()).await - }; - let result = tokio::select! { - result = tokio::time::timeout(std::time::Duration::from_secs(300), attempt) => { - result.map_err(|_| "ChatGPT sign-in timed out. Please try again.".to_string()).and_then(|r| r) - } - _ = cancelled => Err("ChatGPT sign-in cancelled.".to_string()), - }; - SIGN_IN_CANCEL - .lock() - .map_err(|_| "ChatGPT sign-in lock is unavailable.")? - .take(); - Ok(session(&result?)) -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_chatgpt_sign_in() { if let Ok(mut sender) = SIGN_IN_CANCEL.lock() { if let Some(sender) = sender.take() { @@ -94,7 +55,6 @@ pub fn cancel_chatgpt_sign_in() { } } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn select_chatgpt_profile(profile_id: String) -> Result { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; @@ -107,7 +67,6 @@ pub async fn select_chatgpt_profile(profile_id: String) -> Result Result, String> { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; @@ -131,19 +90,8 @@ pub async fn sign_out_chatgpt(profile_id: String) -> Result, Stri Ok(warning) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn open_chatgpt_usage(app: tauri::AppHandle) -> Result<(), String> { - #[cfg(feature = "desktop")] - use tauri_plugin_opener::OpenerExt; - app.opener() - .open_url("https://chatgpt.com/#settings/Usage", None::<&str>) - .map_err(|_| "Could not open ChatGPT usage settings.".into()) -} - pub use inference::{generate, list_models}; -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_chatgpt_models() -> Result, String> { list_models().await } diff --git a/src-tauri/src/chatgpt/protocol.rs b/src-tauri/src/chatgpt/protocol.rs index fc540cfea..61d4e37e7 100644 --- a/src-tauri/src/chatgpt/protocol.rs +++ b/src-tauri/src/chatgpt/protocol.rs @@ -4,25 +4,25 @@ use serde::Deserialize; use serde_json::Value; use sha2::{Digest, Sha256}; -pub(super) fn now() -> u64 { +pub(crate) fn now() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs() } -pub(super) fn random() -> Result { +pub(crate) fn random() -> Result { let mut bytes = [0u8; 32]; openssl::rand::rand_bytes(&mut bytes) .map_err(|_| "Could not prepare secure ChatGPT sign-in.")?; Ok(URL_SAFE_NO_PAD.encode(bytes)) } -pub(super) fn challenge(verifier: &str) -> String { +pub(crate) fn challenge(verifier: &str) -> String { URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) } -pub(super) struct Callback { +pub(crate) struct Callback { pub code: String, pub client_id: String, } @@ -76,7 +76,7 @@ pub(super) fn parse_callback( } #[derive(Deserialize)] -pub(super) struct Identity { +pub(crate) struct Identity { pub iss: String, pub sub: String, pub aud: Value, @@ -87,7 +87,7 @@ pub(super) struct Identity { pub azp: Option, } -pub(super) fn verify_identity( +pub(crate) fn verify_identity( token: &str, jwks: &Value, client_id: &str, diff --git a/src-tauri/src/chatgpt/storage.rs b/src-tauri/src/chatgpt/storage.rs index 4e65ac672..30528855d 100644 --- a/src-tauri/src/chatgpt/storage.rs +++ b/src-tauri/src/chatgpt/storage.rs @@ -12,7 +12,7 @@ use std::{ }; #[derive(Serialize, Deserialize)] -pub(super) struct Store { +pub(crate) struct Store { pub host_id: String, pub active_profile_id: Option, pub profiles: Vec, @@ -29,7 +29,7 @@ impl Default for Store { } #[derive(Clone, Serialize, Deserialize)] -pub(super) struct Profile { +pub(crate) struct Profile { pub id: String, pub label: String, pub client_id: String, @@ -39,7 +39,7 @@ pub(super) struct Profile { } #[derive(Clone, Serialize, Deserialize)] -pub(super) struct Tokens { +pub(crate) struct Tokens { pub access_token: String, pub refresh_token: String, pub id_token: String, @@ -56,12 +56,12 @@ impl Tokens { } } -pub(super) struct LockedStore { +pub(crate) struct LockedStore { path: PathBuf, _lock: File, } -pub(super) fn session(state: &Store) -> super::ChatGptSession { +pub(crate) fn session(state: &Store) -> super::ChatGptSession { super::ChatGptSession { active_profile_id: state.active_profile_id.clone(), profiles: state diff --git a/src-tauri/src/clipboard_import.rs b/src-tauri/src/clipboard_import.rs index 64c08a2ad..5f1ce2109 100644 --- a/src-tauri/src/clipboard_import.rs +++ b/src-tauri/src/clipboard_import.rs @@ -3,8 +3,6 @@ use crate::models::TableColumn; use crate::{drivers::driver_trait::DatabaseDriver, models::ColumnDefinition}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime}; #[derive(Deserialize, Debug)] pub struct ClipboardImportRequest { @@ -173,15 +171,6 @@ fn table_ref(table_name: &str, schema: Option<&str>, quote: &str) -> String { } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn execute_clipboard_import( - app: AppHandle, - req: ClipboardImportRequest, -) -> Result { - import_with_runtime(&app.state::(), None, req).await -} - pub async fn import_with_runtime( runtime: &crate::runtime::RuntimeContext, session_id: Option, diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 2929ab3fb..16c78034f 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,22 +1,14 @@ use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime, State}; + use tokio::task::AbortHandle; use urlencoding::encode; -use uuid::Uuid; use crate::credential_cache; -use crate::keychain_utils; use crate::models::{ - BatchStatementResult, ColumnDefinition, ConnectionGroup, ConnectionParams, ExplainQueryOutput, - ExportPayload, ForeignKey, Index, K8sConnection, K8sConnectionInput, QueryResult, RoutineInfo, - RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, SshTestParams, - TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, + BatchStatementResult, ConnectionGroup, ConnectionParams, + ExportPayload, QueryResult, SavedConnection, }; -use crate::persistence; // Constants /// Resolve the driver from the registry or return a descriptive error. @@ -28,26 +20,12 @@ async fn driver_for( .ok_or_else(|| format!("Unsupported driver: {}", id)) } -async fn driver_for_params( +pub(crate) async fn driver_for_params( params: &ConnectionParams, ) -> Result, String> { crate::drivers::registry::get_connection_driver(params).await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connection_metadata( - app: AppHandle, - connection_id: String, -) -> Result, String> { - crate::application::metadata::get_connection_metadata( - &app.state::(), - None, - &connection_id, - ) - .await -} - const DEFAULT_MYSQL_PORT: u16 = 3306; const DEFAULT_POSTGRES_PORT: u16 = 5432; @@ -105,17 +83,6 @@ pub(crate) fn unregister_abort_handle( // --- Persistence Helpers --- -#[cfg(feature = "desktop")] -pub async fn expand_ssh_connection_params( - app: &AppHandle, - params: &ConnectionParams, -) -> Result { - crate::application::tunnels::expand_connection_params( - &app.state::(), - params, - ) -} - /// Check if a string option is empty or contains only whitespace. #[inline] #[cfg(test)] @@ -123,397 +90,6 @@ fn is_empty_or_whitespace(s: &Option) -> bool { s.as_ref().map(|p| p.trim().is_empty()).unwrap_or(true) } -#[cfg(feature = "desktop")] -async fn execute_connection_command( - app: &AppHandle, - command: crate::application::connections::ConnectionCommand, -) -> Result { - crate::application::connections::execute( - &app.state::(), - &app.state::>(), - command, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connections(app: AppHandle) -> Result { - migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::GetConnections, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connections_with_groups( - app: AppHandle, -) -> Result { - migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::GetConnectionsWithGroups, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_connection( - app: AppHandle, - name: String, - params: ConnectionParams, - plugin_secret_changes: Option, - detect_json_in_text_columns: Option, - environment: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::SaveConnection { - name, - params, - plugin_secret_changes, - detect_json_in_text_columns, - environment, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection( - app: AppHandle, - id: String, - name: String, - params: ConnectionParams, - plugin_secret_changes: Option, - detect_json_in_text_columns: Option, - environment: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::UpdateConnection { - id, - name, - params, - plugin_secret_changes, - detect_json_in_text_columns, - environment, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn duplicate_connection( - app: AppHandle, - id: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::DuplicateConnection { id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection( - app: AppHandle, - id: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::DeleteConnection { id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn test_connection( - app: AppHandle, - request: TestConnectionRequest, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::TestConnection { request }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn list_databases( - app: AppHandle, - request: TestConnectionRequest, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::ListDatabases { request }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connection_groups( - app: AppHandle, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::GetConnectionGroups, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_connection_group( - app: AppHandle, - name: String, - parent_id: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::CreateConnectionGroup { - name, - parent_id, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_group_path( - app: AppHandle, - path: String, - parent_id: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::CreateGroupPath { path, parent_id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection_group( - app: AppHandle, - id: String, - name: Option, - collapsed: Option, - sort_order: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::UpdateConnectionGroup { - id, - name, - collapsed, - sort_order, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn move_group_to_parent( - app: AppHandle, - id: String, - parent_id: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::MoveGroupToParent { id, parent_id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_group( - app: AppHandle, - id: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::DeleteConnectionGroup { id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn move_connection_to_group( - app: AppHandle, - connection_id: String, - group_id: Option, - sort_order: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::MoveConnectionToGroup { - connection_id, - group_id, - sort_order, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn reorder_groups( - app: AppHandle, - group_orders: Vec<(String, i32)>, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::ReorderGroups { group_orders }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn reorder_connections_in_group( - app: AppHandle, - connection_orders: Vec<(String, i32)>, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::ReorderConnectionsInGroup { - connection_orders, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_connection_appearance( - app: AppHandle, - id: String, - appearance: Option, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::SetConnectionAppearance { - id, - appearance, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn list_connection_tags( - app: AppHandle, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::ListConnectionTags, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_connection_tag( - app: AppHandle, - name: String, - color: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::CreateConnectionTag { name, color }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_connection_tag( - app: AppHandle, - id: String, - name: String, - color: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::UpdateConnectionTag { id, name, color }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_tag( - app: AppHandle, - id: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::DeleteConnectionTag { id }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_connection_tags( - app: AppHandle, - connection_id: String, - tag_ids: Vec, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::SetConnectionTags { - connection_id, - tag_ids, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_connection_icon( - app: AppHandle, - relative_path: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::DeleteConnectionIcon { relative_path }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_sqlite_database( - app: AppHandle, - path: String, -) -> Result { - execute_connection_command( - &app, - crate::application::connections::ConnectionCommand::CreateSqliteDatabase { path }, - ) - .await -} - pub fn resolve_connection_params(params: &ConnectionParams) -> Result { crate::application::tunnels::resolve_expanded_connection_params(params, None) } @@ -555,24 +131,6 @@ pub fn resolve_connection_params_with_id( resolve_connection_params(&with_id) } -#[cfg(feature = "desktop")] -pub fn get_config_path(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - Ok(crate::paths::resolve_connections_path(&config_dir)) -} - -#[cfg(feature = "desktop")] -pub fn get_ssh_config_path(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - Ok(config_dir.join("ssh_connections.json")) -} - fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { params .connection_uri @@ -582,7 +140,7 @@ fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { /// Re-attach the URI a saved connection needs at runtime, from the session /// cache or the keychain. -fn restore_runtime_connection_uri( +pub(crate) fn restore_runtime_connection_uri( cache: &credential_cache::CredentialCache, connection_id: &str, params: &mut ConnectionParams, @@ -605,91 +163,6 @@ fn restore_runtime_connection_uri( } } -#[cfg(feature = "desktop")] -/// Saved connection as stored, without any keychain secret. -fn lookup_saved_connection( - app: &AppHandle, - id: &str, -) -> Result { - let conn_cache = app.state::>(); - - let conn = match conn_cache.lookup(id) { - crate::connection_cache::CacheLookup::Hit(c) => c, - crate::connection_cache::CacheLookup::Miss => { - return Err("Connection not found".to_string()) - } - crate::connection_cache::CacheLookup::Cold => { - let path = get_config_path(app)?; - let conn_file = persistence::load_connections_file(&path).unwrap_or_default(); - conn_cache.populate(&conn_file.connections); - conn_file - .connections - .into_iter() - .find(|c| c.id == id) - .ok_or_else(|| "Connection not found".to_string())? - } - }; - Ok(conn) -} - -#[cfg(feature = "desktop")] -/// Load a saved connection with its host-owned credentials (keychain password, -/// SSH secrets, connection URI) but without plugin-owned secrets. Used by the -/// edit modal and by the Test Connection / Load Databases flows, which resolve -/// plugin secrets themselves once the pending changes are known. -pub fn find_connection_metadata_by_id( - app: &AppHandle, - id: &str, -) -> Result { - let mut conn = lookup_saved_connection(app, id)?; - - let cache = app.state::>(); - restore_runtime_connection_uri(&cache, &conn.id, &mut conn.params)?; - - // Load passwords from keychain via the in-memory cache (warm hit = lookup, - // cold miss = keychain call + cache). Skip IAM-auth connections: their - // 15-min tokens must come from the `password` field, never the keychain, - // so a stale token from an older release can't be surfaced in the modal. - if conn.params.save_in_keychain.unwrap_or(false) && !conn.params.use_iam_auth.unwrap_or(false) { - match credential_cache::get_db_password_cached(&cache, &conn.id) { - Ok(pwd) => conn.params.password = Some(pwd), - Err(e) => eprintln!( - "[Keyring Error] Failed to get DB password for {}: {}", - conn.id, e - ), - } - if conn.params.ssh_enabled.unwrap_or(false) { - if let Ok(ssh_pwd) = credential_cache::get_ssh_password_cached(&cache, &conn.id) { - if !ssh_pwd.trim().is_empty() { - conn.params.ssh_password = Some(ssh_pwd); - } - } - if let Ok(ssh_passphrase) = - credential_cache::get_ssh_key_passphrase_cached(&cache, &conn.id) - { - if !ssh_passphrase.trim().is_empty() { - conn.params.ssh_key_passphrase = Some(ssh_passphrase); - } - } - } - } - - Ok(conn) -} - -#[cfg(feature = "desktop")] -/// Load a connection for driver execution. Unlike the metadata/edit path, -/// this resolves plugin-owned secrets into `params.extra` only in memory. -pub fn find_connection_by_id( - app: &AppHandle, - id: &str, -) -> Result { - let mut conn = find_connection_metadata_by_id(app, id)?; - let cache = app.state::>(); - crate::plugin_secrets::hydrate_connection(&cache, &mut conn); - Ok(conn) -} - /// Merge a list of incoming groups into an existing list, preserving hierarchy /// and repairing any `parent_id` that points to a group id not present in the /// union (i.e. neither in the existing list nor in the incoming batch). @@ -724,417 +197,10 @@ pub(crate) fn merge_groups(existing: &mut Vec, incoming: Vec( - app: &AppHandle, - path: &std::path::Path, - file: &crate::models::ConnectionsFile, -) -> Result<(), String> { - persistence::save_connections_file(path, file)?; - app.state::>() - .invalidate(); - Ok(()) -} - // --- Commands --- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_connection_by_id( - app: AppHandle, - id: String, -) -> Result { - find_connection_metadata_by_id(&app, &id) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_schemas( - app: AppHandle, - connection_id: String, - database: Option, -) -> Result, String> { - crate::application::metadata::get_schemas( - &app.state::(), - None, - &connection_id, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_available_databases( - app: AppHandle, - connection_id: String, -) -> Result, String> { - crate::application::metadata::get_available_databases( - &app.state::(), - None, - &connection_id, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_selected_databases( - app: AppHandle, - connection_id: String, - databases: Vec, -) -> Result<(), String> { - crate::application::connections::set_selected_databases( - &app.state::(), - &connection_id, - databases, - ) - .await?; - app.state::>() - .invalidate(); - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_routines( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_routines( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_routine_parameters( - app: AppHandle, - connection_id: String, - routine_name: String, - schema: Option, - database: Option, - /* The signature of the overload the user clicked, where the dialect has them (#893) */ - identity_args: Option, -) -> Result, String> { - crate::application::database_objects::get_routine_parameters( - &app.state::(), - None, - &connection_id, - routine_name, - schema, - database, - identity_args, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_routine_definition( - app: AppHandle, - connection_id: String, - routine_name: String, - routine_type: String, // "PROCEDURE" or "FUNCTION" - mainly for MySQL SHOW CREATE - schema: Option, - database: Option, - identity_args: Option, -) -> Result { - crate::application::database_objects::get_routine_definition( - &app.state::(), - None, - &connection_id, - routine_name, - routine_type, - schema, - database, - identity_args, - ) - .await -} - -/// Preview generation only; the returned SQL is never executed here. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_table_query_template( - app: AppHandle, - connection_id: String, - request: crate::models::TableQueryTemplateRequest, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_table_query_template( - &app.state::(), - None, - &connection_id, - request, - database, - ) - .await -} - -/// Column statistics through the optional plugin RPC (issue #1137). `None` -/// means the driver doesn't provide them; the frontend then falls back to its -/// generic SQL or hides the entry. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_column_stats( - app: AppHandle, - connection_id: String, - request: crate::models::ColumnStatsRequest, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_column_stats( - &app.state::(), - None, - &connection_id, - request, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn build_routine_call_sql( - app: AppHandle, - connection_id: String, - routine_name: String, - routine_type: String, - args: Vec, - schema: Option, -) -> Result { - crate::application::database_objects::build_routine_call_sql( - &app.state::(), - None, - &connection_id, - routine_name, - routine_type, - args, - schema, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_routine_create_template( - app: AppHandle, - connection_id: String, - routine_type: String, - schema: Option, - database: Option, -) -> Result { - crate::application::database_objects::get_routine_create_template( - &app.state::(), - &connection_id, - routine_type, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_routine_edit_script( - app: AppHandle, - connection_id: String, - routine_name: String, - routine_type: String, - schema: Option, - database: Option, - identity_args: Option, -) -> Result { - crate::application::database_objects::get_routine_edit_script( - &app.state::(), - None, - &connection_id, - routine_name, - routine_type, - schema, - database, - identity_args, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_routine( - app: AppHandle, - connection_id: String, - routine_name: String, - routine_type: String, - schema: Option, - database: Option, - identity_args: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_routine( - &app.state::(), - None, - &connection_id, - routine_name, - routine_type, - schema, - database, - identity_args, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_schema_snapshot( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_schema_snapshot( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - // ==================== SSH Connection Management ==================== -#[cfg(feature = "desktop")] -/// Migrates old embedded SSH connections to separate SSH connection entries -async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), String> { - let conn_path = get_config_path(app)?; - if !conn_path.exists() { - return Ok(()); // Nothing to migrate - } - - // Load connections using persistence (handles both old and new formats) - let mut conn_file = persistence::load_connections_file(&conn_path)?; - let connections = &conn_file.connections; - - // Check if any connections have old embedded SSH params - let needs_migration = connections - .iter() - .any(|c| c.params.ssh_enabled.unwrap_or(false) && c.params.ssh_connection_id.is_none()); - - if !needs_migration { - return Ok(()); // No migration needed - } - - eprintln!("[Migration] Starting SSH connections migration..."); - - let ssh_path = get_ssh_config_path(app)?; - let mut ssh_connections: Vec = if ssh_path.exists() { - let ssh_content = fs::read_to_string(&ssh_path).map_err(|e| e.to_string())?; - serde_json::from_str(&ssh_content).unwrap_or_default() - } else { - Vec::new() - }; - - let mut migrated_connections = Vec::new(); - let mut ssh_connection_map: HashMap = HashMap::new(); // (ssh_key -> ssh_id) - - for mut conn in conn_file.connections.clone() { - if conn.params.ssh_enabled.unwrap_or(false) && conn.params.ssh_connection_id.is_none() { - // Extract SSH params - if let (Some(host), Some(user)) = (&conn.params.ssh_host, &conn.params.ssh_user) { - let port = conn.params.ssh_port.unwrap_or(22); - let key_file = conn.params.ssh_key_file.clone().unwrap_or_default(); - - // Create unique key for this SSH config - let ssh_key = format!("{}:{}:{}:{}", host, port, user, key_file); - - // Check if we already created an SSH connection for this config - let ssh_id = if let Some(existing_id) = ssh_connection_map.get(&ssh_key) { - existing_id.clone() - } else { - // Create new SSH connection - let new_ssh_id = Uuid::new_v4().to_string(); - let ssh_name = format!("{}@{}", user, host); - - // Migrate credentials from connection keychain to SSH keychain - if conn.params.save_in_keychain.unwrap_or(false) { - if let Ok(ssh_pwd) = keychain_utils::get_ssh_password(&conn.id, &conn.name) - { - if !ssh_pwd.trim().is_empty() { - keychain_utils::set_ssh_password(&new_ssh_id, &ssh_pwd).ok(); - } - } - if let Ok(ssh_pass) = - keychain_utils::get_ssh_key_passphrase(&conn.id, &conn.name) - { - if !ssh_pass.trim().is_empty() { - keychain_utils::set_ssh_key_passphrase(&new_ssh_id, &ssh_pass).ok(); - } - } - } - - let new_ssh_conn = SshConnection { - id: new_ssh_id.clone(), - name: ssh_name, - host: host.clone(), - port, - user: user.clone(), - auth_type: Some(if !key_file.is_empty() { - "ssh_key".to_string() - } else { - "password".to_string() - }), - password: None, - key_file: if key_file.is_empty() { - None - } else { - Some(key_file.clone()) - }, - key_passphrase: None, - allow_passphrase_prompt: None, - save_in_keychain: conn.params.save_in_keychain, - }; - - ssh_connections.push(new_ssh_conn); - ssh_connection_map.insert(ssh_key, new_ssh_id.clone()); - new_ssh_id - }; - - // Update connection to reference the SSH connection - conn.params.ssh_connection_id = Some(ssh_id); - // Clear old embedded SSH params - conn.params.ssh_host = None; - conn.params.ssh_port = None; - conn.params.ssh_user = None; - conn.params.ssh_password = None; - conn.params.ssh_key_file = None; - conn.params.ssh_key_passphrase = None; - } - } - - migrated_connections.push(conn); - } - - // Save migrated SSH connections - let ssh_json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&ssh_path, ssh_json)?; - - // Save migrated connections using new format (preserving groups) - conn_file.connections = migrated_connections; - save_connections_and_invalidate(app, &conn_path, &conn_file)?; - - eprintln!( - "[Migration] Successfully migrated {} SSH connections", - ssh_connections.len() - ); - Ok(()) -} - // ==================== PostgreSQL Plugin SSL Mode Migration ==================== // // The shared, path-based migration logic lives in `connection_migrations` @@ -1143,314 +209,14 @@ async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), S // core, and invalidate the connection cache only if it actually rewrote // something. -#[cfg(feature = "desktop")] -/// Migrates already-persisted `ssl_mode` values on postgres-dialect -/// connections (driver id other than the builtin `"postgres"`) from the -/// stale MySQL-style spelling to the Postgres-style spelling the plugin -/// actually understands. Idempotent — a no-op once every affected -/// connection has been rewritten. See -/// `connection_migrations::migrate_postgres_ssl_mode_spelling_at_path` for -/// the full rationale, including the concurrency guard against a race with -/// the `--mcp` process's own call to the same function. -async fn migrate_postgres_ssl_mode_spelling(app: &AppHandle) -> Result<(), String> { - let conn_path = get_config_path(app)?; - let migrated = - crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path(&conn_path) - .await?; - if migrated { - app.state::>() - .invalidate(); - } - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_ssh_connections( - app: AppHandle, -) -> Result, String> { - crate::application::tunnels::get_ssh_connections( - &app.state::(), - true, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_ssh_connection( - app: AppHandle, - name: String, - ssh: SshConnectionInput, -) -> Result { - crate::application::tunnels::save_ssh_connection( - &app.state::(), - name, - ssh, - true, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_ssh_connection( - app: AppHandle, - id: String, - name: String, - ssh: SshConnectionInput, -) -> Result { - crate::application::tunnels::update_ssh_connection( - &app.state::(), - id, - name, - ssh, - true, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_ssh_connection( - app: AppHandle, - id: String, -) -> Result<(), String> { - crate::application::tunnels::delete_ssh_connection( - &app.state::(), - &id, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn test_ssh_connection( - app: AppHandle, - ssh: SshTestParams, -) -> Result { - crate::application::tunnels::test_ssh_connection( - &app.state::(), - ssh, - None, - ) - .await -} - // --------------------------------------------------------------------------- // Kubernetes Connections // --------------------------------------------------------------------------- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_k8s_connections( - app: AppHandle, -) -> Result, String> { - crate::application::tunnels::get_k8s_connections(&app.state::()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_k8s_connection( - app: AppHandle, - k8s: K8sConnectionInput, -) -> Result { - crate::application::tunnels::save_k8s_connection( - &app.state::(), - k8s, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_k8s_connection( - app: AppHandle, - id: String, - k8s: K8sConnectionInput, -) -> Result { - crate::application::tunnels::update_k8s_connection( - &app.state::(), - id, - k8s, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_k8s_connection( - app: AppHandle, - id: String, -) -> Result<(), String> { - crate::application::tunnels::delete_k8s_connection( - &app.state::(), - &id, - ) -} - -#[cfg(feature = "desktop")] -async fn execute_tunnel_command( - app: &AppHandle, - command: crate::application::tunnels::TunnelCommand, -) -> Result { - crate::application::tunnels::execute( - &app.state::(), - None, - command, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn test_k8s_connection_cmd( - app: AppHandle, - context: String, - namespace: String, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::TestK8sConnection { - context, - namespace, - options, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_k8s_contexts_cmd( - app: AppHandle, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::GetK8sContexts { options }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_k8s_namespaces_cmd( - app: AppHandle, - context: String, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::GetK8sNamespaces { context, options }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_k8s_resources_cmd( - app: AppHandle, - context: String, - namespace: String, - resource_type: String, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::GetK8sResources { - context, - namespace, - resource_type, - options, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_k8s_resource_ports_cmd( - app: AppHandle, - context: String, - namespace: String, - resource_type: String, - resource_name: String, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::GetK8sResourcePorts { - context, - namespace, - resource_type, - resource_name, - options, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn validate_k8s_path_cmd( - app: AppHandle, - path: String, - kind: String, -) -> Result { - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::ValidateK8sPath { path, kind }, - ) - .await -} - // --------------------------------------------------------------------------- // AWS SSM // --------------------------------------------------------------------------- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn test_ssm_connection_cmd( - app: AppHandle, - target: String, - profile: Option, - region: Option, - host: String, - port: u16, -) -> Result { - execute_tunnel_command( - &app, - crate::application::tunnels::TunnelCommand::TestSsmConnection { - target, - profile, - region, - host, - port, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -/// Expand K8s connection params by loading saved config and creating/reusing a tunnel. -pub async fn expand_k8s_connection_params( - app: &AppHandle, - params: &ConnectionParams, -) -> Result { - let runtime = app.state::(); - let expanded = crate::application::tunnels::expand_connection_params(&runtime, params)?; - if !expanded.k8s_enabled.unwrap_or(false) { - return Ok(expanded); - } - crate::application::tunnels::resolve_expanded_connection_params(&expanded, None) -} - #[cfg(test)] mod tests { use super::*; @@ -2708,287 +1474,22 @@ mod tests { } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_tables( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_tables( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_columns( - app: AppHandle, - connection_id: String, - table_name: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_columns( - &app.state::(), - None, - &connection_id, - table_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_foreign_keys( - app: AppHandle, - connection_id: String, - table_name: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_foreign_keys( - &app.state::(), - None, - &connection_id, - table_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_indexes( - app: AppHandle, - connection_id: String, - table_name: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_indexes( - &app.state::(), - None, - &connection_id, - table_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_record( - app: AppHandle, - connection_id: String, - table: String, - pk_map: std::collections::HashMap, - schema: Option, - database: Option, -) -> Result { - crate::application::records::delete_record( - &app.state::(), - None, - &connection_id, - table, - pk_map, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_record( - app: AppHandle, - connection_id: String, - table: String, - pk_map: std::collections::HashMap, - col_name: String, - new_val: serde_json::Value, - schema: Option, - database: Option, -) -> Result { - crate::application::records::update_record( - &app.state::(), - None, - &connection_id, - table, - pk_map, - col_name, - new_val, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_blob_to_file( - app: AppHandle, - connection_id: String, - table: String, - col_name: String, - pk_map: std::collections::HashMap, - file_path: String, - schema: Option, - database: Option, -) -> Result<(), String> { - let saved_conn = find_connection_by_id(&app, &connection_id)?; - let expanded_params = expand_ssh_connection_params(&app, &saved_conn.params).await?; - let expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; - let mut params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let drv = driver_for_params(¶ms).await?; - drv.save_blob_to_file( - ¶ms, - &table, - &col_name, - &pk_map, - schema.as_deref(), - &file_path, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_blob( - app: AppHandle, - connection_id: String, - table: String, - col_name: String, - pk_map: std::collections::HashMap, - schema: Option, - database: Option, -) -> Result { - crate::application::records::fetch_blob( - &app.state::(), - None, - &connection_id, - table, - col_name, - pk_map, - schema, - database, - crate::application::records::BlobFetchPolicy::Inline, - ) - .await -} - -/// Fetches a BLOB column from the database and returns it as a data: URL for image preview. -/// Same query logic as save_blob_to_file but returns the data in-memory instead of writing to disk. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_blob_as_data_url( - app: AppHandle, - connection_id: String, - table: String, - col_name: String, - pk_map: std::collections::HashMap, - schema: Option, - database: Option, -) -> Result { - crate::application::records::fetch_blob_as_data_url( - &app.state::(), - None, - &connection_id, - table, - col_name, - pk_map, - schema, - database, - ) - .await -} - /// Detects the MIME type of base64-encoded binary data using magic-byte analysis /// and returns the canonical blob wire format: "BLOB:::". /// Called by the frontend after the user selects a file to upload. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn detect_blob_mime(base64_data: String) -> Result { crate::application::records::detect_blob_mime(&base64_data) } -/// Prepares a file for BLOB upload by returning only metadata and a file reference. -/// The actual file content is NOT transferred over IPC, avoiding massive string allocations. -/// The file content will be read directly from disk when needed (e.g., during INSERT/UPDATE). -/// Returns a special "BLOB_FILE_REF" format that includes file path, size, and MIME type. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn load_blob_from_file( - app: AppHandle, - file_path: String, -) -> Result { - use std::io::Read; - - // Read max_blob_size from configuration - let max_blob_size = crate::config::get_max_blob_size(&app); - - tokio::task::spawn_blocking(move || -> Result { - let mut file = std::fs::File::open(&file_path) - .map_err(|e| format!("Failed to open file: {}", e))?; - - // Get file size - let metadata = file.metadata() - .map_err(|e| format!("Failed to get file metadata: {}", e))?; - let file_size = metadata.len(); - - // Validate file size against maximum allowed - if file_size > max_blob_size { - return Err(format!( - "File size ({} bytes / {:.2}MB) exceeds maximum allowed size ({} bytes / {}MB). Please choose a smaller file.", - file_size, - file_size as f64 / (1024.0 * 1024.0), - max_blob_size, - max_blob_size / (1024 * 1024) - )); - } - - // Read first chunk for MIME detection (only 8KB) - let header_size = std::cmp::min(8192, file_size as usize); - let mut header = vec![0u8; header_size]; - file.read_exact(&mut header) - .map_err(|e| format!("Failed to read file header: {}", e))?; - - // Detect MIME type - let mime = infer::get(&header) - .map(|k| k.mime_type()) - .unwrap_or("application/octet-stream"); - - // Return a file reference instead of actual content - // Format: "BLOB_FILE_REF:::" - Ok(format!("BLOB_FILE_REF:{}:{}:{}", file_size, mime, file_path)) - }) - .await - .map_err(|e| format!("Task join error: {}", e))? -} - /// Detects the MIME type from a small base64-encoded header (first ~8KB). /// Returns only the MIME type string — the frontend constructs the wire format /// locally, avoiding a full round-trip of the entire file over IPC. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn detect_mime_type(header_base64: String) -> Result { crate::application::records::detect_mime_type(&header_base64) } /// Gets file statistics (size and MIME type) without reading the entire file. /// Used after streaming upload to construct the final wire format. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_file_stats(file_path: String) -> Result { use std::io::Read; @@ -3019,7 +1520,6 @@ pub fn get_file_stats(file_path: String) -> Result { /// Reads a file from disk and returns it as a base64-encoded data URL. /// Used for image preview of BLOB_FILE_REF values without requiring frontend FS permissions. /// Only available for image files; returns an error for non-image MIME types. -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn read_file_as_data_url(file_path: String) -> Result { use base64::Engine; use std::io::Read; @@ -3048,179 +1548,22 @@ pub async fn read_file_as_data_url(file_path: String) -> Result } let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes); - Ok(format!("data:{};base64,{}", mime, b64)) - }) - .await - .map_err(|e| format!("Task join error: {}", e))? -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn insert_record( - app: AppHandle, - connection_id: String, - table: String, - data: std::collections::HashMap, - schema: Option, - database: Option, -) -> Result { - crate::application::records::insert_record( - &app.state::(), - None, - &connection_id, - table, - data, - schema, - database, - ) - .await -} - -#[cfg(test)] -pub(crate) fn cancel_query_impl( - state: &QueryCancellationState, - connection_id: &str, -) -> Result<(), String> { - crate::application::queries::cancel_registered_queries(state, None, connection_id, None) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn cancel_query( - state: State<'_, std::sync::Arc>, - connection_id: String, -) -> Result<(), String> { - crate::application::queries::cancel_query(&state, None, &connection_id, None) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn execute_query( - app: AppHandle, - state: State<'_, std::sync::Arc>, - connection_id: String, - query: String, - limit: Option, - page: Option, - schema: Option, - database: Option, - session_id: Option, -) -> Result { - crate::application::queries::execute_query( - &app.state::(), - &state, - crate::application::queries::QueryRequestScope::DESKTOP, - crate::application::queries::QueryResponsePolicy::Unbounded, - connection_id, - query, - limit, - page, - schema, - session_id, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -pub(crate) async fn release_connection_sessions( - app: &AppHandle, - connection_id: &str, - _params: Option<&ConnectionParams>, -) { - crate::application::query_sessions::release_connection( - &app.state::(), - None, - connection_id, - ) - .await; -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn release_query_session( - app: AppHandle, - connection_id: String, - session_id: String, -) -> Result<(), String> { - crate::application::query_sessions::release( - &app.state::(), - None, - &connection_id, - &session_id, - ) + Ok(format!("data:{};base64,{}", mime, b64)) + }) .await + .map_err(|e| format!("Task join error: {}", e))? } -/// Runs a sequence of statements that share a single physical database -/// connection. Use this — not multiple parallel `execute_query` calls — -/// whenever statements depend on connection-local session state -/// (`SET @var`, `LAST_INSERT_ID()` / `LASTVAL()`, `BEGIN`/`COMMIT`, -/// `TEMPORARY TABLE`, `PREPARE`/`EXECUTE`, `SET FOREIGN_KEY_CHECKS = 0`). -/// -/// The whole batch shares one cancellation handle so `cancel_query` -/// aborts the entire batch atomically. -/// -/// When `batch_id` is supplied, a `batch-statement-complete` event is emitted -/// after each statement so the UI updates result tabs progressively. The full -/// `Vec` is still returned at the end for final reconciliation / fallback. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn execute_query_batch( - app: AppHandle, - state: State<'_, std::sync::Arc>, - connection_id: String, - queries: Vec, - limit: Option, - page: Option, - schema: Option, - database: Option, - batch_id: Option, - session_id: Option, -) -> Result, String> { - crate::application::queries::execute_query_batch( - &app.state::(), - &state, - crate::application::queries::QueryRequestScope::DESKTOP, - crate::application::queries::QueryResponsePolicy::Unbounded, - connection_id, - queries, - limit, - page, - schema, - session_id, - batch_id, - database, - ) - .await +#[cfg(test)] +pub(crate) fn cancel_query_impl( + state: &QueryCancellationState, + connection_id: &str, +) -> Result<(), String> { + crate::application::queries::cancel_registered_queries(state, None, connection_id, None) } // --- Explain Query Plan --- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn explain_query_plan( - app: AppHandle, - state: State<'_, std::sync::Arc>, - connection_id: String, - query: String, - analyze: bool, - schema: Option, - database: Option, -) -> Result { - crate::application::queries::explain_query_plan( - &app.state::(), - &state, - crate::application::queries::QueryRequestScope::DESKTOP, - connection_id, - query, - analyze, - schema, - database, - ) - .await -} - /// Run a read on the connection pinned to `session_id`, inside its open /// transaction, so it sees the tab's uncommitted changes. A savepoint keeps a /// failing read from aborting the user's transaction. @@ -3255,171 +1598,8 @@ pub(crate) async fn read_in_open_transaction( // --- Count Query --- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn count_query( - app: AppHandle, - connection_id: String, - query: String, - schema: Option, - database: Option, - session_id: Option, -) -> Result { - crate::application::queries::count_query( - &app.state::(), - None, - connection_id, - query, - schema, - session_id, - database, - ) - .await -} - // --- Window Title Management --- -/// Sets the window title with Wayland workaround -/// -/// WORKAROUND: This is a temporary fix for tauri-apps/tauri#13749 -/// On Wayland (Linux), the standard `window.setTitle()` API doesn't properly update -/// the window title in the window manager's title bar due to an upstream dependency issue. -/// This command directly manipulates the GTK HeaderBar to ensure the title is visible. -/// -/// See: https://github.com/tauri-apps/tauri/issues/13749 -/// -/// This workaround should be removed once the upstream issue is resolved. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_window_title(app: AppHandle, title: String) -> Result<(), String> { - // Get the main window - let window = app - .get_webview_window("main") - .ok_or("Failed to get main window")?; - - // Set title using standard Tauri API (works on all platforms) - window - .set_title(&title) - .map_err(|e| format!("Failed to set window title: {}", e))?; - - // Apply Wayland-specific workaround on Linux - #[cfg(target_os = "linux")] - { - #[cfg(feature = "desktop")] - use gtk::prelude::{BinExt, Cast, GtkWindowExt, HeaderBarExt}; - #[cfg(feature = "desktop")] - use gtk::{EventBox, HeaderBar}; - - // Get the GTK window - let gtk_window = window - .gtk_window() - .map_err(|e| format!("Failed to get GTK window: {}", e))?; - - // Check if we have a custom titlebar (Wayland uses EventBox with HeaderBar) - if let Some(titlebar) = gtk_window.titlebar() { - // Try to downcast to EventBox (Wayland) - if let Ok(event_box) = titlebar.downcast::() { - // Get the HeaderBar child and set its title - if let Some(child) = event_box.child() { - if let Ok(header_bar) = child.downcast::() { - header_bar.set_title(Some(&title)); - } - } - } - } - } - - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn open_er_diagram_window( - app: AppHandle, - connection_id: String, - connection_name: String, - database_name: String, - focus_table: Option, - schema: Option, - database: Option, -) -> Result<(), String> { - #[cfg(feature = "desktop")] - use tauri::{WebviewUrl, WebviewWindowBuilder}; - use urlencoding::encode; - - let schema_suffix = schema - .as_deref() - .map(|s| format!("/{}", s)) - .unwrap_or_default(); - let title = format!( - "tabularis - {} ({}{})", - database_name, connection_name, schema_suffix - ); - let mut url = format!( - "/schema-diagram?connectionId={}&connectionName={}&databaseName={}", - encode(&connection_id), - encode(&connection_name), - encode(&database_name) - ); - - if let Some(table) = focus_table { - url.push_str(&format!("&focusTable={}", encode(&table))); - } - - if let Some(s) = &schema { - url.push_str(&format!("&schema={}", encode(s))); - } - - // `database` (distinct from the display-only `database_name` above) is only - // set for a schema-based multi-db connection (PostgreSQL browsing several - // databases) — it's the value the schema-diagram page actually routes its - // snapshot request with, alongside `schema`. Absent for the flat multi-db - // (MySQL) and plain single-database cases, which already resolve correctly - // through `schema` alone. - if let Some(db) = &database { - url.push_str(&format!("&database={}", encode(db))); - } - - // Derive a unique window label per (connection, database, schema) so that - // diagrams for different databases on the same connection do not collide on a - // shared label (which previously kept showing the first database's diagram). - // Tauri window labels only allow a limited character set, so sanitize anything - // else to '_'. - let raw_label = format!( - "er-diagram:{}:{}:{}", - connection_id, - database_name, - schema.as_deref().unwrap_or("") - ); - let label: String = raw_label - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || c == '-' || c == '_' { - c - } else { - '_' - } - }) - .collect(); - - // If a diagram window for this exact database already exists, just focus it - // instead of failing to build a second window with the same label. - if let Some(existing) = app.get_webview_window(&label) { - let _ = existing.set_focus(); - return Ok(()); - } - - let _webview = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) - .title(&title) - .inner_size(1200.0, 800.0) - .center() - .decorations(crate::window_decorations::native_decorations_enabled()) - .build() - .map_err(|e| format!("Failed to create ER Diagram window: {}", e))?; - - Ok(()) -} - /// Builds a connection URL for a database driver. pub async fn build_connection_url(params: &ConnectionParams) -> Result { let user = encode(params.username.as_deref().unwrap_or_default()); @@ -3455,6 +1635,9 @@ pub async fn build_connection_url(params: &ConnectionParams) -> Result, @@ -3530,476 +1713,16 @@ fn resolve_ssh_test_password( // ==================== View Management Commands ==================== -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_views( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_views( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_view_definition( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result { - crate::application::database_objects::get_view_definition( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_view( - app: AppHandle, - connection_id: String, - view_name: String, - definition: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::create_view( - &app.state::(), - None, - &connection_id, - view_name, - definition, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn alter_view( - app: AppHandle, - connection_id: String, - view_name: String, - definition: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::alter_view( - &app.state::(), - None, - &connection_id, - view_name, - definition, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_view( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_view( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_view_columns( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_view_columns( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_materialized_views( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_materialized_views( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_materialized_view_columns( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_materialized_view_columns( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_materialized_view_definition( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result { - crate::application::metadata::get_materialized_view_definition( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn refresh_materialized_view( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::refresh_materialized_view( - &app.state::(), - None, - &connection_id, - view_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_triggers( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::metadata::get_triggers( - &app.state::(), - None, - &connection_id, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_trigger_definition( - app: AppHandle, - connection_id: String, - trigger_name: String, - table_name: String, - schema: Option, - database: Option, -) -> Result { - crate::application::database_objects::get_trigger_definition( - &app.state::(), - None, - &connection_id, - trigger_name, - table_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_trigger( - app: AppHandle, - connection_id: String, - trigger_sql: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::create_trigger( - &app.state::(), - None, - &connection_id, - trigger_sql, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_trigger( - app: AppHandle, - connection_id: String, - trigger_name: String, - table_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_trigger( - &app.state::(), - None, - &connection_id, - trigger_name, - table_name, - schema, - database, - ) - .await -} - // --- User management (gated by `DriverCapabilities::user_management`) ------- -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_db_privilege_catalog( - app: AppHandle, - connection_id: String, -) -> Result { - crate::application::database_objects::get_db_privilege_catalog( - &app.state::(), - &connection_id, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_db_users( - app: AppHandle, - connection_id: String, -) -> Result, String> { - crate::application::database_objects::get_db_users( - &app.state::(), - None, - &connection_id, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_db_user_grants( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result, String> { - crate::application::database_objects::get_db_user_grants( - &app.state::(), - None, - &connection_id, - user, - host, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_db_user( - app: AppHandle, - connection_id: String, - user: String, - host: String, - password: String, -) -> Result<(), String> { - crate::application::database_objects::create_db_user( - &app.state::(), - None, - &connection_id, - user, - host, - password, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_db_user( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result<(), String> { - crate::application::database_objects::drop_db_user( - &app.state::(), - None, - &connection_id, - user, - host, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn set_db_user_password( - app: AppHandle, - connection_id: String, - user: String, - host: String, - password: String, -) -> Result<(), String> { - crate::application::database_objects::set_db_user_password( - &app.state::(), - None, - &connection_id, - user, - host, - password, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_db_user_privileges( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result, String> { - crate::application::database_objects::get_db_user_privileges( - &app.state::(), - None, - &connection_id, - user, - host, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn apply_db_user_privileges( - app: AppHandle, - connection_id: String, - user: String, - host: String, - database: Option, - table: Option, - privileges: Vec, - grant: bool, -) -> Result<(), String> { - crate::application::database_objects::apply_db_user_privileges( - &app.state::(), - None, - &connection_id, - user, - host, - database, - table, - privileges, - grant, - ) - .await -} - -/// Register a connection as active for health-check pinging. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn register_active_connection(app: AppHandle, connection_id: String) { - crate::application::connections::register_active_connection( - &app.state::(), - None, - None, - connection_id, - ) - .await; -} - /// Snapshot of connection ids currently open in the shared backend (across all /// windows). Used by each window to render cross-window connection status. -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_active_connections() -> Vec { crate::health_check::active_connections().await } -/// Disconnect from a database connection by closing all of its connection pools -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn disconnect_connection( - app: AppHandle, - connection_id: String, -) -> Result<(), String> { - crate::application::connections::disconnect_connection( - &app.state::(), - None, - None, - &connection_id, - ) - .await -} - // --- Type Registry --- -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_data_types(driver: String) -> Result { log::debug!("Fetching data types for driver: {}", driver); @@ -4009,26 +1732,6 @@ pub async fn get_data_types(driver: String) -> Result( - app: AppHandle, - driver: String, - kinds: Vec, - connection_id: Option, -) -> Result, String> { - crate::application::database_objects::map_inferred_column_types( - &app.state::(), - None, - driver, - kinds, - connection_id, - ) - .await -} - // --- DDL generation commands --- /// Point `params` at the database the user is browsing (multi-database @@ -4091,218 +1794,10 @@ pub(crate) fn sql_builder_params( params } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_create_table_sql( - app: AppHandle, - connection_id: String, - table_name: String, - columns: Vec, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_create_table_sql( - &app.state::(), - &connection_id, - table_name, - columns, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_add_column_sql( - app: AppHandle, - connection_id: String, - table: String, - column: ColumnDefinition, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_add_column_sql( - &app.state::(), - &connection_id, - table, - column, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_alter_column_sql( - app: AppHandle, - connection_id: String, - table: String, - old_column: ColumnDefinition, - new_column: ColumnDefinition, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_alter_column_sql( - &app.state::(), - &connection_id, - table, - old_column, - new_column, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_create_index_sql( - app: AppHandle, - connection_id: String, - table: String, - index_name: String, - columns: Vec, - is_unique: bool, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_create_index_sql( - &app.state::(), - &connection_id, - table, - index_name, - columns, - is_unique, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_create_foreign_key_sql( - app: AppHandle, - connection_id: String, - table: String, - fk_name: String, - column: String, - ref_table: String, - ref_column: String, - on_delete: Option, - on_update: Option, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_create_foreign_key_sql( - &app.state::(), - &connection_id, - table, - fk_name, - column, - ref_table, - ref_column, - on_delete, - on_update, - schema, - database, - ) - .await -} - -/// Plugin-provided statement for dropping a table, or `None` to let the -/// explorer build its generic `DROP TABLE`. Only plugins declaring -/// `capabilities.drop_table_sql` are asked; every other driver (built-ins -/// included) returns `None` without resolving credentials or params. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_drop_table_sql( - app: AppHandle, - connection_id: String, - table: String, - schema: Option, - database: Option, -) -> Result, String> { - crate::application::database_objects::get_drop_table_sql( - &app.state::(), - &connection_id, - table, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_index_action( - app: AppHandle, - connection_id: String, - table: String, - index_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_index( - &app.state::(), - None, - &connection_id, - table, - index_name, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn drop_foreign_key_action( - app: AppHandle, - connection_id: String, - table: String, - fk_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - crate::application::database_objects::drop_foreign_key( - &app.state::(), - None, - &connection_id, - table, - fk_name, - schema, - database, - ) - .await -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_registered_drivers() -> Vec { crate::drivers::registry::list_drivers().await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_keybindings(app: AppHandle) -> Result { - crate::application::persistence::get_keybindings(&app.state::()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_keybindings( - app: AppHandle, - keybindings: serde_json::Value, -) -> Result<(), String> { - crate::application::persistence::save_keybindings( - &app.state::(), - &keybindings, - ) -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn get_driver_manifest( driver_id: String, ) -> Option { @@ -4388,36 +1883,6 @@ pub(crate) fn reject_if_would_create_cycle( ) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_server_now( - app: AppHandle, - connection_id: String, -) -> Result { - crate::application::queries::get_server_now( - &app.state::(), - None, - connection_id, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn export_connections_payload( - app: AppHandle, - include_secrets: Option, - connection_ids: Option>, -) -> Result { - crate::application::connection_files::export_payload( - app.state::().inner(), - include_secrets.unwrap_or(true), - connection_ids, - ) - .await -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn encrypt_export_payload( payload: ExportPayload, password: String, @@ -4426,7 +1891,6 @@ pub async fn encrypt_export_payload( crate::export_crypto::encrypt(&plaintext, &password) } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn decrypt_export_payload( envelope: crate::export_crypto::EncryptedEnvelope, password: String, @@ -4435,32 +1899,3 @@ pub async fn decrypt_export_payload( serde_json::from_str(&plaintext).map_err(|e| format!("Invalid export payload: {e}")) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn import_connections_payload( - app: AppHandle, - payload: ExportPayload, -) -> Result<(), String> { - apply_export_payload(app, payload).await -} - -#[cfg(feature = "desktop")] -/// Merge an `ExportPayload` into the user's stored connections, groups, SSH and -/// K8s records, moving any inline secrets into the keychain. Shared by the JSON -/// import command above and the foreign-app import flow. -pub async fn apply_export_payload( - app: AppHandle, - payload: ExportPayload, -) -> Result<(), String> { - crate::application::connection_files::apply_export_payload( - app.state::().inner(), - app.state::>() - .inner() - .as_ref(), - app.state::>() - .inner() - .as_ref(), - payload, - ) - .await -} diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 1748c75f1..0fab2539b 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -1,12 +1,7 @@ use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use std::fs; -use std::path::PathBuf; use std::sync::RwLock; -#[cfg(feature = "desktop")] -use tauri::AppHandle; -#[cfg(feature = "desktop")] -use tauri::Manager; use std::collections::HashMap; @@ -308,11 +303,6 @@ pub enum MigrationMode { static CONFIG_CACHE: Lazy> = Lazy::new(|| RwLock::new(AppConfig::default())); -#[cfg(feature = "desktop")] -pub fn get_config_dir(_app: &AppHandle) -> Option { - Some(crate::paths::get_app_config_dir()) -} - pub(crate) fn cache_config(config: &AppConfig) { crate::plugins::call_timeout::apply_config(config); crate::plugins::shutdown_grace::apply_config(config); @@ -393,54 +383,6 @@ pub fn is_connection_readonly(config: &AppConfig, connection_id: &str) -> bool { } } -// Internal load -#[cfg(feature = "desktop")] -pub fn load_config_internal(app: &AppHandle) -> AppConfig { - if let Some(config_dir) = get_config_dir(app) { - let config_path = config_dir.join("config.json"); - if config_path.exists() { - if let Ok(content) = fs::read_to_string(config_path) { - if let Ok(mut config) = serde_json::from_str::(&content) { - crate::plugins::compat::migrate_legacy_config(&mut config); // COMPAT(registry-ga) - cache_config(&config); - return config; - } - } - } - } - let default_config = AppConfig::default(); - cache_config(&default_config); - default_config -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_config(app: AppHandle) -> AppConfig { - crate::application::persistence::load_config(&app.state::()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_config(app: AppHandle, config: AppConfig) -> Result<(), String> { - let runtime = app.state::(); - let previous = crate::application::persistence::load_config(&runtime); - let requested_ping_interval = config.ping_interval; - let window_decorations_changed = config.window_decorations.is_some() - && config.window_decorations != previous.window_decorations; - let saved = crate::application::persistence::save_config(&runtime, config)?; - - if window_decorations_changed { - crate::window_decorations::apply_to_all_windows(&app, saved.window_decorations.as_ref()); - } - if requested_ping_interval.is_some() && saved.ping_interval != previous.ping_interval { - let interval = saved - .ping_interval - .unwrap_or(crate::health_check::DEFAULT_PING_INTERVAL); - crate::async_rt::spawn(crate::health_check::restart_ping_loop(app, interval as u64)); - } - Ok(()) -} - /// Composes the config-storage key for per-connection schema selection/ /// preference. A non-empty `database` scopes the key to that database, so a /// nested multi-database driver (e.g. PostgreSQL browsing several databases @@ -477,172 +419,6 @@ pub(crate) fn resolve_schema_preference( None } -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_schema_preference( - app: AppHandle, - connection_id: String, - database: Option, -) -> Option { - crate::application::metadata::get_schema_preference( - &app.state::(), - &connection_id, - database, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_schema_preference( - app: AppHandle, - connection_id: String, - schema: String, - database: Option, -) -> Result<(), String> { - crate::application::metadata::set_schema_preference( - &app.state::(), - connection_id, - schema, - database, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_last_active_connection(app: AppHandle) -> Option { - crate::application::persistence::load_config(&app.state::()) - .last_active_connection_id -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_last_active_connection( - app: AppHandle, - connection_id: Option, -) -> Result<(), String> { - crate::application::persistence::set_last_active_connection_for_desktop( - &app.state::(), - connection_id, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_last_open_connections(app: AppHandle) -> Vec { - crate::application::persistence::load_config(&app.state::()) - .last_open_connection_ids - .unwrap_or_default() -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_last_open_connections( - app: AppHandle, - connection_ids: Vec, -) -> Result<(), String> { - crate::application::persistence::set_last_open_connections_for_desktop( - &app.state::(), - connection_ids, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_selected_schemas( - app: AppHandle, - connection_id: String, - database: Option, -) -> Vec { - crate::application::metadata::get_selected_schemas( - &app.state::(), - &connection_id, - database, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_selected_schemas( - app: AppHandle, - connection_id: String, - schemas: Vec, - database: Option, -) -> Result<(), String> { - crate::application::metadata::set_selected_schemas( - &app.state::(), - connection_id, - schemas, - database, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_ai_key(app: AppHandle, provider: String, key: String) -> Result<(), String> { - crate::application::ai::set_key( - &app.state::(), - &app.state::>(), - &provider, - &key, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn delete_ai_key(app: AppHandle, provider: String) -> Result<(), String> { - crate::application::ai::delete_key( - &app.state::(), - &app.state::>(), - &provider, - ) -} - -#[cfg(feature = "desktop")] -/// Get the configured maximum BLOB size in bytes, or DEFAULT_MAX_BLOB_SIZE if not set -pub fn get_max_blob_size(app: &AppHandle) -> u64 { - let config = load_config_internal(app); - config - .max_blob_size - .unwrap_or(crate::drivers::common::DEFAULT_MAX_BLOB_SIZE) -} - -#[cfg(feature = "desktop")] -pub fn get_ai_api_key(app: &AppHandle, provider: &str) -> Result { - // 1. Try Keychain First (Override) — via the in-memory credential cache so - // repeated lookups don't trigger a macOS Keychain authorization prompt - // each time. The keychain is read at most once per provider per session. - let cache = app.state::>(); - if let Ok(key) = crate::credential_cache::get_ai_key_cached(&cache, provider) { - if !key.is_empty() { - return Ok(key); - } - } - - // 2. Try Env Var - let env_var = match provider { - "openai" => "OPENAI_API_KEY", - "anthropic" => "ANTHROPIC_API_KEY", - "openrouter" => "OPENROUTER_API_KEY", - "requesty" => "REQUESTY_API_KEY", - "custom-openai" => "CUSTOM_OPENAI_API_KEY", - "minimax" => "MINIMAX_API_KEY", - _ => "", - }; - - if !env_var.is_empty() { - if let Ok(key) = std::env::var(env_var) { - if !key.is_empty() { - return Ok(key); - } - } - } - - Err(format!( - "API Key for {} not found in Keychain or Environment", - provider - )) -} - #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct AiKeyStatus { @@ -650,239 +426,6 @@ pub struct AiKeyStatus { pub from_env: bool, } -#[cfg(feature = "desktop")] -pub fn get_ai_api_key_status(app: &AppHandle, provider: &str) -> AiKeyStatus { - // 1. Check Keychain (through the cache to avoid repeated auth prompts) - let cache = app.state::>(); - let keychain_exists = crate::credential_cache::get_ai_key_cached(&cache, provider).is_ok(); - - // 2. Check Env Var - let env_var = match provider { - "openai" => "OPENAI_API_KEY", - "anthropic" => "ANTHROPIC_API_KEY", - "openrouter" => "OPENROUTER_API_KEY", - "requesty" => "REQUESTY_API_KEY", - "custom-openai" => "CUSTOM_OPENAI_API_KEY", - "minimax" => "MINIMAX_API_KEY", - _ => "", - }; - - let env_exists = if !env_var.is_empty() { - std::env::var(env_var) - .map(|k| !k.is_empty()) - .unwrap_or(false) - } else { - false - }; - - // Configured if either exists - // from_env is true ONLY if keychain is NOT present but env IS present - // because keychain overrides env now - - if keychain_exists { - AiKeyStatus { - configured: true, - from_env: false, // Even if env exists, we are using keychain - } - } else if env_exists { - AiKeyStatus { - configured: true, - from_env: true, - } - } else { - AiKeyStatus { - configured: false, - from_env: false, - } - } -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn check_ai_key(app: AppHandle, provider: String) -> bool { - crate::application::ai::get_api_key( - &app.state::(), - &app.state::>(), - &provider, - ) - .is_ok() -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn check_ai_key_status( - app: AppHandle, - provider: String, -) -> crate::application::ai::AiKeyStatus { - crate::application::ai::key_status( - &app.state::(), - &app.state::>(), - &provider, - ) -} - -#[cfg(feature = "desktop")] -fn prompt_kind(app: &AppHandle, kind: crate::application::persistence::PromptKind) -> String { - crate::application::persistence::get_prompt( - &app.state::(), - kind, - ) -} - -#[cfg(feature = "desktop")] -fn save_prompt_kind( - app: &AppHandle, - kind: crate::application::persistence::PromptKind, - prompt: &str, -) -> Result<(), String> { - crate::application::persistence::save_prompt( - &app.state::(), - kind, - prompt, - ) -} - -#[cfg(feature = "desktop")] -fn reset_prompt_kind( - app: &AppHandle, - kind: crate::application::persistence::PromptKind, -) -> Result { - crate::application::persistence::reset_prompt( - &app.state::(), - kind, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_system_prompt(app: AppHandle) -> String { - prompt_kind(&app, crate::application::persistence::PromptKind::System) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_system_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt_kind( - &app, - crate::application::persistence::PromptKind::System, - &prompt, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn reset_system_prompt(app: AppHandle) -> Result { - reset_prompt_kind(&app, crate::application::persistence::PromptKind::System) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_explain_prompt(app: AppHandle) -> String { - prompt_kind(&app, crate::application::persistence::PromptKind::Explain) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_explain_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt_kind( - &app, - crate::application::persistence::PromptKind::Explain, - &prompt, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn reset_explain_prompt(app: AppHandle) -> Result { - reset_prompt_kind(&app, crate::application::persistence::PromptKind::Explain) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_explainplan_prompt(app: AppHandle) -> String { - prompt_kind( - &app, - crate::application::persistence::PromptKind::ExplainPlan, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_explainplan_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt_kind( - &app, - crate::application::persistence::PromptKind::ExplainPlan, - &prompt, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn reset_explainplan_prompt(app: AppHandle) -> Result { - reset_prompt_kind( - &app, - crate::application::persistence::PromptKind::ExplainPlan, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_cellname_prompt(app: AppHandle) -> String { - prompt_kind(&app, crate::application::persistence::PromptKind::CellName) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_cellname_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt_kind( - &app, - crate::application::persistence::PromptKind::CellName, - &prompt, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn reset_cellname_prompt(app: AppHandle) -> Result { - reset_prompt_kind(&app, crate::application::persistence::PromptKind::CellName) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_tabrename_prompt(app: AppHandle) -> String { - prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_tabrename_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt_kind( - &app, - crate::application::persistence::PromptKind::TabRename, - &prompt, - ) -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn reset_tabrename_prompt(app: AppHandle) -> Result { - reset_prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_config_json(app: AppHandle) -> Result { - crate::application::persistence::get_config_json_for_desktop( - &app.state::(), - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn relaunch_app(app: AppHandle) { - crate::window_placement::persist_cached(&app); - app.restart(); -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn save_config_json(app: AppHandle, json: String) -> Result<(), String> { - crate::application::persistence::save_config_json_for_desktop( - &app.state::(), - &json, - ) -} - #[cfg(test)] #[path = "config/plugin_notification_tests.rs"] mod plugin_notification_tests; diff --git a/src-tauri/src/connection_appearance.rs b/src-tauri/src/connection_appearance.rs index bfccf5847..a541b9392 100644 --- a/src-tauri/src/connection_appearance.rs +++ b/src-tauri/src/connection_appearance.rs @@ -1,8 +1,6 @@ use std::fs; use std::path::Path; use sha2::{Digest, Sha256}; -#[cfg(feature = "desktop")] -use tauri::AppHandle; pub(crate) const MAX_ICON_BYTES: u64 = 512 * 1024; @@ -176,16 +174,3 @@ pub fn copy_icon_for_duplicate( Ok(format!("connection-icons/{filename}")) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_connection_icon( - _app: AppHandle, - connection_id: String, - source_path: String, -) -> Result { - let data_dir = crate::paths::get_app_data_dir(); - let dest = data_dir.join("connection-icons"); - save_icon_impl(&dest, &connection_id, Path::new(&source_path)) - .map_err(|e| e.to_string()) -} - diff --git a/src-tauri/src/drivers/registry.rs b/src-tauri/src/drivers/registry.rs index 7d2f4e284..49baf1e03 100644 --- a/src-tauri/src/drivers/registry.rs +++ b/src-tauri/src/drivers/registry.rs @@ -152,7 +152,7 @@ fn drivers_to_unregister(registered: &[(String, bool)], active_ids: &[String]) - /// stale driver keeps resolving successfully. /// /// `active_ids: None` means "no explicit preference saved" (see -/// [`crate::plugins::manager::load_plugins`]'s doc comment) — every +/// [`crate::transport::desktop::plugins::manager::load_plugins`]'s doc comment) — every /// installed plugin is implicitly active in that state, so nothing is /// unregistered. Builtins are never touched regardless of `active_ids`, /// since `active_external_drivers` only ever governs external plugins. diff --git a/src-tauri/src/dump_commands.rs b/src-tauri/src/dump_commands.rs index a0d43b5e8..35a37b605 100644 --- a/src-tauri/src/dump_commands.rs +++ b/src-tauri/src/dump_commands.rs @@ -1,71 +1,2 @@ -use crate::application::connection_files::GeneratedFile; -use crate::application::database_transfers::{self, DumpDestination, ImportSource, JobKind}; pub use crate::application::database_transfers::{DumpCancellationState, DumpOptions}; -use crate::runtime::RuntimeContext; -use std::path::PathBuf; -#[cfg(feature = "desktop")] -use tauri::State; -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn cancel_dump( - state: State<'_, std::sync::Arc>, - connection_id: String, -) -> Result<(), String> { - database_transfers::cancel_job(state.inner(), None, JobKind::Dump, &connection_id) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn dump_database( - runtime: State<'_, RuntimeContext>, - state: State<'_, std::sync::Arc>, - connection_id: String, - file_path: String, - options: DumpOptions, - schema: Option, - database: Option, -) -> Result, String> { - database_transfers::dump_database( - runtime.inner(), - state.inner(), - None, - connection_id, - DumpDestination::ServerPath(PathBuf::from(file_path)), - options, - schema, - database, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn cancel_import( - state: State<'_, std::sync::Arc>, - connection_id: String, -) -> Result<(), String> { - database_transfers::cancel_job(state.inner(), None, JobKind::Import, &connection_id) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn import_database( - runtime: State<'_, RuntimeContext>, - state: State<'_, std::sync::Arc>, - connection_id: String, - file_path: String, - schema: Option, - database: Option, -) -> Result<(), String> { - database_transfers::import_database( - runtime.inner(), - state.inner(), - None, - connection_id, - ImportSource::ServerPath(PathBuf::from(file_path)), - schema, - database, - ) - .await -} diff --git a/src-tauri/src/explain_import.rs b/src-tauri/src/explain_import.rs index 27c2fb101..0f7cf95ab 100644 --- a/src-tauri/src/explain_import.rs +++ b/src-tauri/src/explain_import.rs @@ -9,8 +9,6 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use serde::{Deserialize, Serialize}; -#[cfg(feature = "desktop")] -use tauri::{Manager, Runtime, State}; /// A plan file read from disk, parsed on the frontend by `@tabularis/explain`. #[derive(Debug, Serialize, Deserialize, Clone)] @@ -45,74 +43,10 @@ impl PendingExplainFile { /// /// The content comes back untouched; the frontend sniffs the format and /// parses it with `@tabularis/explain`. -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn load_explain_from_file(path: String) -> Result { load_from_file(&path).await } -/// Tauri command: pop the CLI-provided file path (if any). -/// -/// Returns `None` after the first successful read, allowing the window to -/// differentiate "cold start from CLI" from "opened manually". -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_pending_explain_file( - state: State<'_, std::sync::Arc>, -) -> Option { - state.take() -} - -#[cfg(feature = "desktop")] -/// Creates (or focuses) the standalone Visual Explain window. -/// -/// Runs fully synchronously so it can be invoked from the Tauri `setup` hook -/// without taking a detour through the async runtime. -pub fn spawn_visual_explain_window>( - app: &M, - file: Option, -) -> Result<(), String> { - #[cfg(feature = "desktop")] - use tauri::{WebviewUrl, WebviewWindowBuilder}; - - if let Some(path) = file.as_ref() { - if let Some(state) = app.try_state::>() { - state.set(path.clone()); - } - } - - if let Some(existing) = app.get_webview_window("visual-explain") { - existing - .set_focus() - .map_err(|e| format!("Failed to focus Visual Explain window: {e}"))?; - return Ok(()); - } - - WebviewWindowBuilder::new( - app, - "visual-explain", - WebviewUrl::App("/visual-explain".into()), - ) - .title("tabularis - Visual Explain") - .inner_size(1280.0, 820.0) - .min_inner_size(900.0, 600.0) - .center() - .decorations(crate::window_decorations::native_decorations_enabled()) - .build() - .map_err(|e| format!("Failed to create Visual Explain window: {e}"))?; - - Ok(()) -} - -/// Tauri command wrapper around [`spawn_visual_explain_window`]. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn open_visual_explain_window( - app: tauri::AppHandle, - file: Option, -) -> Result<(), String> { - spawn_visual_explain_window(&app, file) -} - /// Read a file from disk, returning its content plus the display name the UI /// shows as the plan's source label. /// diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs index 6c033f7c4..1225e5b05 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -11,17 +11,13 @@ pub use sink::{CsvSink, JsonSink, MarkdownSink, RowSink}; use std::collections::HashMap; use std::io::Write; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; use serde_json::Value; -#[cfg(feature = "desktop")] -use tauri::State; use crate::commands::AbortHandleMap; use crate::drivers::{mysql, postgres, sqlite}; use crate::models::ConnectionParams; -use crate::runtime::RuntimeContext; pub struct ExportCancellationState { pub handles: Arc>, @@ -35,46 +31,6 @@ impl Default for ExportCancellationState { } } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn cancel_export( - state: State<'_, std::sync::Arc>, - connection_id: String, -) -> Result<(), String> { - crate::application::generic_exports::cancel_export(state.inner(), None, &connection_id) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -#[allow(clippy::too_many_arguments)] -pub async fn export_query_to_file( - runtime: State<'_, RuntimeContext>, - state: State<'_, std::sync::Arc>, - connection_id: String, - query: String, - file_path: String, - format: String, - csv_delimiter: Option, - database: Option, - session_id: Option, -) -> Result, String> { - crate::application::generic_exports::export_query( - runtime.inner(), - state.inner(), - None, - connection_id, - query, - crate::application::generic_exports::ExportDestination::ServerPath(PathBuf::from( - file_path, - )), - format, - csv_delimiter, - database, - session_id, - ) - .await -} - /// Wires the driver stream, the row sink, and the progress emitter together. pub async fn run_export( driver: &str, diff --git a/src-tauri/src/health_check.rs b/src-tauri/src/health_check.rs index 891beb475..cdb4800ee 100644 --- a/src-tauri/src/health_check.rs +++ b/src-tauri/src/health_check.rs @@ -1,25 +1,24 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; use once_cell::sync::Lazy; -#[cfg(feature = "desktop")] -use tauri::Emitter; + use tokio::sync::{oneshot, Mutex, RwLock}; -static ACTIVE_CONNECTIONS: Lazy>>> = +pub(crate) static ACTIVE_CONNECTIONS: Lazy>>> = Lazy::new(|| Arc::new(RwLock::new(HashSet::new()))); -static PING_STOP_TX: Lazy>>> = Lazy::new(|| Mutex::new(None)); +pub(crate) static PING_STOP_TX: Lazy>>> = Lazy::new(|| Mutex::new(None)); /// Default ping interval in seconds. pub const DEFAULT_PING_INTERVAL: u32 = 30; /// Number of consecutive failures before disconnecting. -const FAILURE_THRESHOLD: u32 = 2; +pub(crate) const FAILURE_THRESHOLD: u32 = 2; /// Per-ping timeout. -const PING_TIMEOUT: Duration = Duration::from_secs(5); +pub(crate) const PING_TIMEOUT: Duration = Duration::from_secs(5); /// Register a connection ID as active (will be pinged). pub async fn register_connection(connection_id: String) { @@ -43,59 +42,6 @@ pub async fn active_connections() -> Vec { ACTIVE_CONNECTIONS.read().await.iter().cloned().collect() } -#[cfg(feature = "desktop")] -/// Broadcast the current active-connection set to all windows. -pub async fn emit_active_changed(app: &tauri::AppHandle) { - let ids = active_connections().await; - if let Err(e) = app.emit(ACTIVE_CONNECTIONS_CHANGED_EVENT, ids) { - log::error!( - "Health check: failed to emit {} event: {}", - ACTIVE_CONNECTIONS_CHANGED_EVENT, - e - ); - } -} - -#[cfg(feature = "desktop")] -/// Start the periodic ping loop. If a loop is already running it is stopped first. -pub async fn start_ping_loop(app: tauri::AppHandle, interval_secs: u64) { - // Stop any existing loop - stop_ping_loop().await; - - if interval_secs == 0 { - log::info!("Health check: disabled (interval = 0)"); - return; - } - - let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); - { - let mut guard = PING_STOP_TX.lock().await; - *guard = Some(stop_tx); - } - - log::info!( - "Health check: starting ping loop with interval {}s", - interval_secs - ); - - tokio::spawn(async move { - let mut interval = tokio::time::interval(Duration::from_secs(interval_secs)); - let mut failure_counts: HashMap = HashMap::new(); - - loop { - tokio::select! { - _ = &mut stop_rx => { - log::info!("Health check: ping loop stopped"); - break; - } - _ = interval.tick() => { - ping_all_connections(&app, &mut failure_counts).await; - } - } - } - }); -} - /// Stop the running ping loop, if any. pub async fn stop_ping_loop() { let mut guard = PING_STOP_TX.lock().await; @@ -104,152 +50,3 @@ pub async fn stop_ping_loop() { } } -#[cfg(feature = "desktop")] -/// Restart the ping loop with a new interval. -pub async fn restart_ping_loop(app: tauri::AppHandle, interval_secs: u64) { - stop_ping_loop().await; - start_ping_loop(app, interval_secs).await; -} - -#[cfg(feature = "desktop")] -/// Ping every registered connection. On failure beyond the threshold, -/// close the pool and emit an event to the frontend. -async fn ping_all_connections(app: &tauri::AppHandle, failure_counts: &mut HashMap) { - // Snapshot the active set so we don't hold the lock during I/O. - let active: Vec = ACTIVE_CONNECTIONS.read().await.iter().cloned().collect(); - - if active.is_empty() { - return; - } - - // Ping each connection concurrently. - let results = futures::future::join_all(active.iter().map(|conn_id| { - let app = app.clone(); - let conn_id = conn_id.clone(); - async move { - let result = ping_single_connection(&app, &conn_id).await; - (conn_id, result) - } - })) - .await; - - for (conn_id, result) in results { - match result { - Ok(()) => { - // Reset failure counter on success. - failure_counts.remove(&conn_id); - } - Err(err) => { - let count = failure_counts.entry(conn_id.clone()).or_insert(0); - *count += 1; - log::warn!( - "Health check: ping failed for {} ({}/{}): {}", - conn_id, - count, - FAILURE_THRESHOLD, - err - ); - - if *count >= FAILURE_THRESHOLD { - log::error!( - "Health check: connection {} exceeded failure threshold, disconnecting", - conn_id - ); - failure_counts.remove(&conn_id); - handle_connection_failure(app, &conn_id, &err).await; - } - } - } - } -} - -#[cfg(feature = "desktop")] -/// Ping a single connection by resolving its params and calling driver.ping(). -async fn ping_single_connection(app: &tauri::AppHandle, connection_id: &str) -> Result<(), String> { - let saved_conn = crate::commands::find_connection_by_id(app, connection_id)?; - - let expanded_params = - crate::commands::expand_ssh_connection_params(app, &saved_conn.params).await?; - let expanded_params = - crate::commands::expand_k8s_connection_params(app, &expanded_params).await?; - let params = - crate::commands::resolve_connection_params_with_id(&expanded_params, connection_id)?; - - // Check if pool exists before attempting ping (avoid creating new pools). - let is_builtin = matches!(params.driver.as_str(), "mysql" | "postgres" | "sqlite"); - if is_builtin && !crate::pool_manager::has_pool(¶ms, Some(connection_id)).await { - return Err("No active connection pool".into()); - } - - let driver = crate::drivers::registry::get_driver(¶ms.driver) - .await - .ok_or_else(|| format!("Driver not found: {}", params.driver))?; - - tokio::time::timeout(PING_TIMEOUT, driver.ping(¶ms)) - .await - .map_err(|_| "Ping timed out".to_string())? -} - -#[cfg(feature = "desktop")] -/// Close the pool, unregister the connection, and emit a failure event. -async fn handle_connection_failure(app: &tauri::AppHandle, connection_id: &str, error: &str) { - // Unregister first to prevent further pings. - unregister_connection(connection_id).await; - - // Close all pools for the connection before resolving SSH params. Pool - // keys depend only on connection_id (plus driver/database/TLS), not the - // tunnel's local port, so `close_pools_for_connection_id` matches by - // connection_id prefix — it subsumes the single-key close and closes - // per-database override pools too (#1063). A dead bastion / unreachable - // cluster must not prevent pool cleanup (#1065). - let mut params = None; - if let Ok(saved_conn) = crate::commands::find_connection_by_id(app, connection_id) { - crate::pool_manager::close_pools_for_connection_id( - &saved_conn.params.driver, - connection_id, - ) - .await; - - // release_connection_sessions only needs params.driver to look up the - // driver for rollback — the same driver regardless of tunnel expansion. - // Since params_for_pool_close already disabled all tunnel types, - // close_params has the right driver and connection_id, so re-expanding - // SSH would only add a redundant keychain lookup that produces the same - // result. If even tunnel-free resolution fails, fall back to the saved - // params with just the connection_id set. - let close_params = match crate::commands::params_for_pool_close( - &saved_conn.params, - connection_id, - ) { - Ok(p) => p, - Err(e) => { - log::warn!( - "Health check: failed to resolve tunnel-free params for session release on {connection_id}: {e}" - ); - let mut fallback = saved_conn.params.clone(); - fallback.connection_id = Some(connection_id.to_string()); - fallback - } - }; - params = Some(close_params); - } - // Release pinned transaction sessions after closing the pool. A checked-out - // pinned client survives pool.close() (which only blocks new checkouts), so - // ROLLBACK still runs; the connection is discarded when the client drops. - crate::commands::release_connection_sessions(app, connection_id, params.as_ref()).await; - - // Notify frontend. - let payload = serde_json::json!({ - "connectionId": connection_id, - "error": error, - }); - if let Err(e) = app.emit("connection-health-failed", payload) { - log::error!( - "Health check: failed to emit connection-health-failed event: {}", - e - ); - } - - // Broadcast the updated active-connection set so every window reconciles. - emit_active_changed(app).await; -} diff --git a/src-tauri/src/json_viewer.rs b/src-tauri/src/json_viewer.rs index 336c14f14..6ef51eee6 100644 --- a/src-tauri/src/json_viewer.rs +++ b/src-tauri/src/json_viewer.rs @@ -2,10 +2,7 @@ use std::collections::HashMap; use std::sync::Mutex; use serde::{Deserialize, Serialize}; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -use ulid::Ulid; -use urlencoding::encode; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JsonViewerSession { @@ -37,201 +34,6 @@ pub struct JsonViewerStore { pub last_bounds: Mutex>, } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn open_json_viewer_window( - app: AppHandle, - store: State<'_, std::sync::Arc>, - value: serde_json::Value, - original_value: Option, - col_name: String, - row_label: Option, - read_only: bool, - cell_key: Option, -) -> Result { - let original_value = original_value.unwrap_or_else(|| value.clone()); - if let Some(key) = cell_key.as_deref() { - let existing_id = { - let cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.get(key).cloned() - }; - if let Some(existing_id) = existing_id { - let existing_label = format!("json-viewer-{}", existing_id); - if let Some(window) = app.get_webview_window(&existing_label) { - let _ = window.unminimize(); - let _ = window.set_focus(); - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - if let Some(session) = sessions.get_mut(&existing_id) { - session.value = value; - } - return Ok(existing_id); - } - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.remove(key); - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - sessions.remove(&existing_id); - } - } - - let session_id = Ulid::new().to_string(); - let window_label = format!("json-viewer-{}", session_id); - - { - let mut guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard.insert( - session_id.clone(), - JsonViewerSession { - value, - original_value, - col_name: col_name.clone(), - read_only, - cell_key: cell_key.clone(), - }, - ); - } - if let Some(key) = cell_key.as_deref() { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.insert(key.to_string(), session_id.clone()); - } - - let url = format!("/json-viewer?session={}", encode(&session_id)); - let title = match row_label.as_deref().filter(|s| !s.is_empty()) { - Some(label) => format!("{} \u{00b7} {} \u{2014} JSON Viewer", col_name, label), - None => format!("{} \u{2014} JSON Viewer", col_name), - }; - - let remembered = store - .last_bounds - .lock() - .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? - .clone(); - - let mut builder = WebviewWindowBuilder::new(&app, &window_label, WebviewUrl::App(url.into())) - .title(&title) - .min_inner_size(600.0, 400.0) - .decorations(crate::window_decorations::native_decorations_enabled()) - .background_color(tauri::webview::Color(2, 6, 23, 255)); - - builder = match remembered { - Some(b) => builder - .inner_size(b.width as f64, b.height as f64) - .position(b.x as f64, b.y as f64), - None => builder.inner_size(900.0, 700.0).center(), - }; - - let build_result = builder.build(); - - match build_result { - Err(e) => { - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - sessions.remove(&session_id); - if let Some(key) = cell_key.as_deref() { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.remove(key); - } - Err(format!("Failed to create JSON viewer window: {}", e)) - } - Ok(window) => { - let app_handle = app.clone(); - let captured_label = window_label.clone(); - window.on_window_event(move |event| { - if let WindowEvent::CloseRequested { .. } = event { - if let Some(win) = app_handle.get_webview_window(&captured_label) { - if let (Ok(pos), Ok(size)) = (win.outer_position(), win.outer_size()) { - let store = app_handle.state::>(); - let mut bounds = match store.last_bounds.lock() { - Ok(g) => g, - Err(_) => return, - }; - *bounds = Some(WindowBounds { - x: pos.x, - y: pos.y, - width: size.width, - height: size.height, - }); - } - } - } - }); - Ok(session_id) - } - } -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_json_viewer_session( - store: State<'_, std::sync::Arc>, - session_id: String, -) -> Result { - let guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard - .get(&session_id) - .cloned() - .ok_or_else(|| format!("JSON viewer session '{}' not found", session_id)) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn complete_json_viewer_session( - app: AppHandle, - store: State<'_, std::sync::Arc>, - session_id: String, - value: serde_json::Value, -) -> Result<(), String> { - let cell_key = { - let mut guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard.remove(&session_id).and_then(|s| s.cell_key) - }; - if let Some(key) = cell_key { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - if cell_index.get(&key).map(|v| v == &session_id).unwrap_or(false) { - cell_index.remove(&key); - } - } - - app.emit( - "json-viewer:saved", - JsonViewerSavedPayload { session_id, value }, - ) - .map_err(|e| format!("Failed to emit json-viewer:saved: {}", e))?; - - Ok(()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 38015baf7..69855a9b3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,4 @@ -// ponytail: without `desktop`, helpers used only by Tauri command wrappers go +// ponytail: without `desktop`, helpers used only by `transport::desktop` go // unused; silenced here instead of gating each one. The desktop build still // reports real dead code. #![cfg_attr(not(feature = "desktop"), allow(unused_imports, dead_code))] @@ -13,8 +13,7 @@ pub mod ai_approval; #[cfg(test)] pub mod ai_approval_tests; pub mod ai_approval_watcher; -#[cfg(feature = "desktop")] -pub mod ai_commands; + pub mod ai_notebook_export; #[cfg(test)] pub mod ai_notebook_export_tests; @@ -36,16 +35,12 @@ pub mod connection_cache; #[cfg(test)] pub mod connection_cache_tests; pub mod connection_import; -#[cfg(feature = "desktop")] -pub mod connection_import_commands; + pub mod connection_migrations; #[cfg(test)] pub mod connection_migrations_tests; pub mod connection_tags; -#[cfg(feature = "desktop")] -pub mod connection_window; -#[cfg(test)] -pub mod connection_window_tests; + pub mod credential_cache; pub mod dump_commands; // Added #[cfg(test)] @@ -78,8 +73,7 @@ pub mod mcp; pub mod models; #[cfg(test)] pub mod models_tests; -#[cfg(feature = "desktop")] -pub mod notebooks; + pub mod paths; // Added #[cfg(test)] pub mod paths_tests; @@ -120,31 +114,18 @@ pub mod ssm_tunnel; pub mod storage_location; #[cfg(test)] pub mod storage_location_tests; -#[cfg(feature = "desktop")] -mod system_theme; -#[cfg(feature = "desktop")] -pub mod task_manager; + pub mod team_share; -#[cfg(feature = "desktop")] -pub mod theme_commands; + pub mod theme_models; pub mod theme_packages; pub mod transport; pub mod ui_state; -#[cfg(feature = "desktop")] -pub mod ui_state_commands; + #[cfg(test)] pub mod ui_state_tests; -#[cfg(feature = "desktop")] -pub mod updater; -#[cfg(feature = "desktop")] -pub mod window_decorations; -// E2E-only mock of the `dialog` plugin (auto-accepts ask/confirm, stubs -// open/save via env vars). Only compiled with --features e2e-testing. -#[cfg(feature = "e2e-testing")] -pub mod e2e_dialog_mock; -#[cfg(feature = "desktop")] -mod window_placement; + + /// Tauri's global runtime in the desktop app; the ambient Tokio runtime of /// `tabularis web` and `--mcp` otherwise. pub mod async_rt { @@ -170,30 +151,12 @@ pub mod drivers { pub mod sqlite; } -#[cfg(feature = "desktop")] -use tauri::Manager; - pub use runtime::bootstrap::get_log_buffer; -#[cfg_attr(feature = "desktop", tauri::command)] -fn is_debug_mode() -> bool { +pub(crate) fn is_debug_mode() -> bool { runtime::bootstrap::is_debug_mode() } -#[cfg(feature = "desktop")] -#[tauri::command] -fn open_devtools(window: tauri::WebviewWindow) { - window.open_devtools(); - log::info!("DevTools opened"); -} - -#[cfg(feature = "desktop")] -#[tauri::command] -fn close_devtools(window: tauri::WebviewWindow) { - window.close_devtools(); - log::info!("DevTools closed"); -} - #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { // When ssh re-executes this binary as its SSH_ASKPASS helper (see the @@ -291,7 +254,7 @@ pub fn run() { } #[cfg(feature = "desktop")] - run_desktop(args, log_buffer); + transport::desktop::run(args, log_buffer); #[cfg(not(feature = "desktop"))] { drop(log_buffer); @@ -300,627 +263,3 @@ pub fn run() { } } -#[cfg(feature = "desktop")] -fn run_desktop(args: cli::Args, log_buffer: logger::SharedLogBuffer) { - // Log startup message - log::info!("Tabularis application starting..."); - if args.debug { - log::info!("Debug mode enabled - verbose logging active"); - } else { - log::info!("Debug mode disabled - standard logging active"); - } - - let application_state = std::sync::Arc::new(runtime::state::ApplicationState::default()); - let shutdown_hooks = runtime::lifecycle::ShutdownHooks::default(); - shutdown_hooks.register(|| { - log::info!("Application exiting, stopping all active tunnels..."); - crate::ssh_tunnel::stop_all_tunnels(); - crate::proxy::stop_all_forwards(); - crate::ssm_tunnel::stop_all_tunnels(); - crate::k8s_tunnel::stop_all_tunnels(); - }); - let run_shutdown_hooks = shutdown_hooks.clone(); - - #[cfg_attr(not(feature = "e2e-testing"), allow(unused_mut))] - let mut builder = tauri::Builder::default() - // Singleton: a second launch (typically a `tabularis://...` URL - // clicked while the app is already running) hands its argv to the - // first instance and exits. With `features = ["deep-link"]` the plugin - // usually auto-routes those URLs through `on_open_url`, but on - // Linux/Windows the URL arrives as a plain argv entry on warm launch. - // We scan argv for it defensively and dispatch ourselves so the - // install modal fires even when auto-routing doesn't. - // - // Order matters: must be the FIRST plugin in the chain so it can - // intercept duplicate launches before any heavy initialisation. - .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| { - log::info!("Duplicate launch detected — forwarded to existing instance"); - if let Some(url) = argv.iter().find(|a| a.starts_with("tabularis:")) { - crate::plugins::deep_link::handle_url(app, url); - } - if let Some(win) = tauri::Manager::get_webview_window(app, "main") { - let _ = win.unminimize(); - let _ = win.set_focus(); - } - })) - .plugin(tauri_plugin_clipboard_manager::init()) - .plugin(tauri_plugin_opener::init()) - .plugin(tauri_plugin_fs::init()) - .plugin(tauri_plugin_notification::init()) - .plugin(tauri_plugin_updater::Builder::new().build()) - .plugin(tauri_plugin_deep_link::init()); - - // Dialog plugin: real in production, mocked under e2e-testing (the mock - // auto-accepts ask()/confirm() so native Tauri confirm dialogs — which - // WebDriverIO can't click — don't block the trigger-save flow). Registered - // as a same-named "dialog" plugin so it replaces the real one at Tauri's - // IPC dispatch layer (PluginStore::register retains only the last). - #[cfg(not(feature = "e2e-testing"))] - { - builder = builder.plugin(tauri_plugin_dialog::init()); - } - #[cfg(feature = "e2e-testing")] - { - builder = builder.plugin(crate::e2e_dialog_mock::init()); - // In-app WebDriver server. tauri-wd connects to drive the real WKWebView - // via the W3C WebDriver protocol on macOS, exercising real Tauri IPC. - builder = builder.plugin(tauri_plugin_webdriver_automation::init()); - } - - builder - .manage(application_state.pending_install.clone()) - .manage(application_state.query_cancellation.clone()) - .manage(application_state.export_cancellation.clone()) - .manage(application_state.dump_cancellation.clone()) - .manage(log_buffer) - .manage(application_state.credential_cache.clone()) - .manage(application_state.connection_cache.clone()) - .manage(application_state.import_envelope_cache.clone()) - .manage(application_state.pending_explain_file.clone()) - .manage(application_state.json_viewer_store.clone()) - .manage(application_state.results_window_store.clone()) - .manage(application_state.clone()) - .manage(window_placement::WindowPlacementCache::default()) - .setup(move |app| { - #[cfg(target_os = "linux")] - system_theme::watch(app.handle().clone()); - // The asset protocol scope in tauri.conf.json only covers the - // default data directory; when the user moved the storage folder - // the connection icons live there instead. - if crate::storage_location::active_override().is_some() { - let icons_dir = crate::paths::get_connection_icons_dir(); - let _ = std::fs::create_dir_all(&icons_dir); - if let Err(e) = app.asset_protocol_scope().allow_directory(&icons_dir, true) { - log::warn!("Failed to allow asset access to {:?}: {}", icons_dir, e); - } - log::info!( - "Using custom storage location: {}", - crate::paths::get_app_config_dir().display() - ); - } - - // Apply the persisted decoration policy as early as possible. The - // main window is created from tauri.conf.json before this hook. - let startup_config = crate::config::load_config_internal(&app.handle()); - crate::window_decorations::apply_to_all_windows( - &app.handle(), - startup_config.window_decorations.as_ref(), - ); - // Restore the main window's last normal size and position. - // The explicit start_maximized preference below still takes precedence. - if let Some(window) = app.get_webview_window("main") { - window_placement::restore(&window); - } - - // Allow the SSH tunnel code (which runs without a Tauri context) - // to bridge askpass prompts to the frontend. - askpass::set_app_handle(app.handle().clone()); - - let app_paths = runtime::paths::FixedRuntimePaths::system(); - let runtime_context = runtime::RuntimeContext::new( - std::sync::Arc::new(app_paths), - std::sync::Arc::new(runtime::events::TauriRuntimeEvents::new( - app.handle().clone(), - )), - std::sync::Arc::new(runtime::secrets::KeyringRuntimeSecrets), - ); - let bootstrapped = tauri::async_runtime::block_on( - runtime::bootstrap::bootstrap_application( - runtime_context, - runtime::bootstrap::BootstrapOptions { - load_external_plugins: true, - run_connection_migrations: false, - }, - ), - ) - .map_err(std::io::Error::other)?; - app.manage(runtime::lifecycle::start_approval_heartbeat(&bootstrapped.context)); - app.manage(bootstrapped.context); - - // Ensure replacement plugins are installed for any built-in - // driver a saved connection still depends on (e.g. install the - // `postgresql` plugin when a `postgres` connection exists). Spawned, - // not `block_on`, so a slow or failed registry fetch never delays - // window creation — same pattern as the health-check spawn below. - // See `.github/planning/postgres-plugin-force-install.md`. - for (builtin_id, plugin_id) in crate::plugins::force_install::MIGRATABLE_DRIVERS { - let handle = app.handle().clone(); - let builtin_id = builtin_id.to_string(); - let plugin_id = plugin_id.to_string(); - tauri::async_runtime::spawn(async move { - crate::plugins::force_install::ensure_plugin_installed_if_needed( - &handle, - &builtin_id, - &plugin_id, - ) - .await; - }); - } - - // Subscribe to `tabularis://` deep links so a registry's - // "Open in App" button can hand us a plugin slug + version. - // The handler emits a frontend event; the React side opens the - // install confirmation modal. See `plugins::deep_link`. - // - // On Linux/Windows the scheme is only auto-registered when the - // app is installed from a bundled package. Under `tauri dev` - // the binary lives in `target/debug/...`, so call - // `register("tabularis")` here — it writes the desktop / xdg-mime - // entry pointing at the current binary so Firefox & friends can - // route `tabularis://...` to us. The call is a no-op on macOS - // (handled by Info.plist) and idempotent across restarts. - // - // Inside Snap/Flatpak the exported `.desktop` entry already - // carries `MimeType=x-scheme-handler/tabularis`, and the sandbox - // has neither `xdg-mime` nor write access to the host's - // mimeapps.list — so skip the call instead of logging a failure. - { - #[cfg(feature = "desktop")] - use tauri_plugin_deep_link::DeepLinkExt; - let handle = app.handle().clone(); - let deep_link = app.deep_link(); - #[cfg(any(target_os = "linux", all(debug_assertions, target_os = "windows")))] - match crate::sandbox::current() { - Some(sandbox) => log::info!( - "Skipping tabularis:// scheme registration: handled by the {} desktop entry", - sandbox.name() - ), - None => { - if let Err(e) = deep_link.register("tabularis") { - log::warn!("Failed to register tabularis:// scheme: {}", e); - } - } - } - deep_link.on_open_url({ - let handle = handle.clone(); - move |event| { - for url in event.urls() { - crate::plugins::deep_link::handle_url(&handle, url.as_str()); - } - } - }); - // Cold-start path: when the OS launched us *because of* a - // tabularis:// URL, on_open_url won't fire — the URL is - // already consumed by the launch handshake. Pull it out via - // get_current() and route it through the same handler. - if let Ok(Some(urls)) = deep_link.get_current() { - for url in urls { - crate::plugins::deep_link::handle_url(&handle, url.as_str()); - } - } - } - - // Start desktop health checks, event watchers, and backups. - let ping_interval = crate::config::load_config_internal(&app.handle()) - .ping_interval - .unwrap_or(health_check::DEFAULT_PING_INTERVAL); - runtime::lifecycle::start_desktop_schedulers( - app.handle().clone(), - ping_interval as u64, - ); - - // Maximize the window on startup if the user enabled it. - if startup_config - .start_maximized - .unwrap_or(false) - { - if let Some(window) = app.get_webview_window("main") { - if let Err(e) = window.maximize() { - log::warn!("Failed to maximize window on startup: {e}"); - } - } - } - - // Open devtools automatically in debug mode - if args.debug { - if let Some(window) = app.get_webview_window("main") { - window.open_devtools(); - log::info!("DevTools opened (debug mode active)"); - } - } - - // If the user launched with `--explain `, spawn the Visual - // Explain window and hide the main app window: the CLI flag is - // meant to be a dedicated plan viewer, not a full app launch. - if let Some(path) = args.explain.clone() { - log::info!("CLI --explain received: {path}"); - if let Err(e) = - explain_import::spawn_visual_explain_window(app, Some(path)) - { - log::error!("Failed to open Visual Explain window: {e}"); - } - // Close the default main window only AFTER visual-explain is - // built — closing the last window would terminate the app. - if let Some(main) = app.get_webview_window("main") { - if let Err(e) = main.close() { - log::warn!("Failed to close main window: {e}"); - } - } - } - Ok(()) - }) - // Only the main window is persisted; utility windows retain their - // existing per-feature sizing and placement behavior. - .on_window_event(|window, event| { - if window.label() != "main" { return; } - match event { - tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => { - window_placement::remember(window); - } - tauri::WindowEvent::CloseRequested { .. } => { - window_placement::persist(window); - } - _ => {} - } - }) - .invoke_handler(tauri::generate_handler![ - system_theme::get_linux_system_theme, - is_debug_mode, - open_devtools, - close_devtools, - commands::get_registered_drivers, - commands::get_driver_manifest, - commands::get_connection_metadata, - commands::get_keybindings, - commands::save_keybindings, - commands::test_connection, - commands::list_databases, - commands::save_connection, - sqlite_database::create_sqlite_file, - commands::create_sqlite_database, - commands::delete_connection, - commands::update_connection, - commands::duplicate_connection, - commands::get_connections, - commands::get_connection_by_id, - commands::disconnect_connection, - commands::register_active_connection, - commands::get_active_connections, - commands::get_data_types, - commands::map_inferred_column_types, - // SSH Connections - commands::get_ssh_connections, - commands::save_ssh_connection, - commands::update_ssh_connection, - commands::delete_ssh_connection, - commands::test_ssh_connection, - askpass::respond_ssh_askpass, - // K8s Connections - commands::get_k8s_connections, - commands::save_k8s_connection, - commands::update_k8s_connection, - commands::delete_k8s_connection, - commands::test_k8s_connection_cmd, - commands::get_k8s_contexts_cmd, - commands::get_k8s_namespaces_cmd, - commands::get_k8s_resources_cmd, - commands::get_k8s_resource_ports_cmd, - commands::validate_k8s_path_cmd, - // AWS SSM - commands::test_ssm_connection_cmd, - // Connection Groups - commands::get_connection_groups, - commands::get_connections_with_groups, - commands::create_connection_group, - commands::create_group_path, - commands::update_connection_group, - commands::move_group_to_parent, - commands::delete_connection_group, - commands::move_connection_to_group, - commands::reorder_groups, - commands::reorder_connections_in_group, - commands::list_connection_tags, - commands::create_connection_tag, - commands::update_connection_tag, - commands::delete_connection_tag, - commands::set_connection_tags, - commands::export_connections_payload, - commands::encrypt_export_payload, - connection_import_commands::export_connections_file, - backup::get_connections_backup_status, - backup::set_connections_backup_password, - backup::set_connections_backup_target_password, - backup::run_connections_backup, - commands::decrypt_export_payload, - commands::import_connections_payload, - connection_import_commands::list_connection_import_sources, - connection_import_commands::preview_connection_import, - connection_import_commands::apply_connection_import, - connection_import_commands::preview_tabularis_import, - connection_import_commands::apply_tabularis_import, - connection_import_commands::preview_tabularis_import_file, - connection_import_commands::apply_prepared_tabularis_import, - commands::get_schemas, - commands::get_available_databases, - commands::set_selected_databases, - commands::get_tables, - commands::get_columns, - commands::get_foreign_keys, - commands::get_indexes, - commands::delete_record, - commands::update_record, - commands::insert_record, - commands::save_blob_to_file, - commands::fetch_blob, - commands::fetch_blob_as_data_url, - commands::load_blob_from_file, - commands::detect_blob_mime, - commands::detect_mime_type, - commands::get_file_stats, - commands::read_file_as_data_url, - commands::execute_query, - commands::execute_query_batch, - commands::release_query_session, - commands::get_server_now, - commands::explain_query_plan, - commands::count_query, - commands::cancel_query, - commands::get_views, - commands::get_view_definition, - commands::create_view, - commands::alter_view, - commands::drop_view, - commands::get_view_columns, - commands::get_materialized_views, - commands::get_materialized_view_columns, - commands::get_materialized_view_definition, - commands::refresh_materialized_view, - commands::set_window_title, - commands::open_er_diagram_window, - explain_import::load_explain_from_file, - explain_import::get_pending_explain_file, - explain_import::open_visual_explain_window, - export::export_query_to_file, - export::cancel_export, - sql_file::read_sql_file, - sql_file::write_sql_file, - saved_queries::get_saved_queries, - saved_queries::save_query, - saved_queries::update_saved_query, - saved_queries::delete_saved_query, - saved_queries::get_saved_query_folders, - saved_queries::create_saved_query_folder, - saved_queries::rename_saved_query_folder, - saved_queries::delete_saved_query_folder, - saved_queries::move_saved_query, - query_history::get_query_history, - query_history::add_query_history_entry, - query_history::delete_query_history_entry, - query_history::clear_query_history, - // Config - config::get_schema_preference, - config::set_schema_preference, - config::get_last_active_connection, - config::set_last_active_connection, - config::get_last_open_connections, - config::set_last_open_connections, - config::get_selected_schemas, - config::set_selected_schemas, - config::get_config, - config::save_config, - config::get_config_json, - config::save_config_json, - config::relaunch_app, - storage_location::get_storage_location, - storage_location::inspect_storage_location, - storage_location::set_storage_location, - storage_location::reset_storage_location, - storage_location::open_storage_location, - storage_location::get_app_data_dir, - ui_state_commands::get_ui_state, - ui_state_commands::set_ui_state, - ui_state_commands::delete_ui_state, - config::set_ai_key, - config::delete_ai_key, - config::check_ai_key, - config::check_ai_key_status, - proxy::set_proxy_password, - proxy::proxy_password_is_set, - proxy::delete_proxy_password, - config::get_system_prompt, - config::save_system_prompt, - config::reset_system_prompt, - config::get_explain_prompt, - config::save_explain_prompt, - config::reset_explain_prompt, - config::get_explainplan_prompt, - config::save_explainplan_prompt, - config::reset_explainplan_prompt, - config::get_cellname_prompt, - config::save_cellname_prompt, - config::reset_cellname_prompt, - config::get_tabrename_prompt, - config::save_tabrename_prompt, - config::reset_tabrename_prompt, - // AI - ai::generate_ai_query, - ai::explain_ai_query, - ai::analyze_ai_explain_plan, - ai::generate_cell_name, - ai::generate_tab_rename, - ai::suggest_table_name, - ai::get_ai_models, - chatgpt::get_chatgpt_session, - chatgpt::sign_in_chatgpt, - chatgpt::cancel_chatgpt_sign_in, - chatgpt::select_chatgpt_profile, - chatgpt::sign_out_chatgpt, - chatgpt::get_chatgpt_models, - chatgpt::open_chatgpt_usage, - // Clipboard Import - clipboard_import::execute_clipboard_import, - ai_commands::get_ai_schema_context, - commands::get_schema_snapshot, - // DDL generation - commands::get_table_query_template, - commands::get_column_stats, - commands::get_create_table_sql, - commands::get_add_column_sql, - commands::get_alter_column_sql, - commands::get_create_index_sql, - commands::get_create_foreign_key_sql, - commands::get_drop_table_sql, - commands::drop_index_action, - commands::drop_foreign_key_action, - // Routines - commands::get_routines, - commands::get_routine_parameters, - commands::get_routine_definition, - commands::build_routine_call_sql, - commands::get_routine_create_template, - commands::get_routine_edit_script, - commands::drop_routine, - // Triggers - commands::get_triggers, - commands::get_trigger_definition, - commands::create_trigger, - commands::drop_trigger, - // User management - commands::get_db_privilege_catalog, - commands::get_db_users, - commands::get_db_user_grants, - commands::get_db_user_privileges, - commands::create_db_user, - commands::drop_db_user, - commands::set_db_user_password, - commands::apply_db_user_privileges, - // MCP - mcp::install::get_mcp_status, - mcp::install::install_mcp_config, - // AI Activity / Approvals - ai_commands::get_ai_activity, - ai_commands::get_ai_sessions, - ai_commands::get_ai_session_events, - ai_commands::clear_ai_activity, - ai_commands::export_ai_activity_json, - ai_commands::export_ai_activity_csv, - ai_commands::export_ai_session_as_notebook, - ai_commands::list_pending_approvals, - ai_commands::decide_pending_approval, - // Themes - theme_packages::commands::preview_theme_document, - theme_packages::commands::preview_local_theme_package, - theme_commands::install_local_theme_package, - theme_commands::fetch_theme_registry, - theme_commands::fetch_theme_package_detail, - theme_commands::install_registry_theme, - theme_packages::commands::cancel_theme_install, - theme_commands::set_theme_package_enabled, - theme_commands::uninstall_theme_package, - theme_commands::recover_theme_packages, - theme_commands::get_theme_catalog, - theme_commands::create_personal_theme, - theme_commands::create_personal_snapshot, - theme_commands::update_personal_theme, - theme_commands::update_personal_snapshot, - theme_commands::duplicate_personal_theme, - theme_commands::get_all_themes, - theme_commands::get_theme, - theme_commands::save_custom_theme, - theme_commands::delete_custom_theme, - theme_commands::import_theme, - theme_commands::export_theme, - // Dump & Import - dump_commands::dump_database, - dump_commands::cancel_dump, - dump_commands::import_database, - dump_commands::cancel_import, - // Updater - updater::check_for_updates, - updater::download_and_install_update, - updater::get_installation_source, - // Logs - log_commands::get_logs, - log_commands::log_frontend_event, - log_commands::clear_logs, - log_commands::get_log_settings, - log_commands::set_log_enabled, - log_commands::set_log_max_size, - log_commands::export_logs, - log_commands::test_log, - // Preferences - preferences::save_editor_preferences, - preferences::load_editor_preferences, - preferences::delete_editor_preferences, - preferences::list_all_preferences, - // Notebooks - notebooks::create_notebook, - notebooks::save_notebook, - notebooks::load_notebook, - notebooks::delete_notebook, - notebooks::rename_notebook, - notebooks::list_notebooks, - // Plugin Registry - plugins::commands::fetch_plugin_registry, - plugins::commands::install_plugin, - plugins::commands::cancel_plugin_install, - plugins::commands::uninstall_plugin, - plugins::commands::get_installed_plugins, - plugins::commands::disable_plugin, - plugins::commands::enable_plugin, - plugins::commands::get_plugin_manifest, - plugins::commands::get_plugin_dir, - plugins::commands::open_plugins_dir, - plugins::commands::read_plugin_file, - plugins::commands::fetch_tabularium_plugin_preview, - plugins::commands::fetch_plugin_readme, - plugins::deep_link::consume_pending_deep_link_install, - plugins::manager::get_plugin_startup_errors, - plugins::runtime_version::get_plugin_runtime_warnings, - // JSON Viewer - json_viewer::open_json_viewer_window, - json_viewer::get_json_viewer_session, - json_viewer::complete_json_viewer_session, - results_window::open_results_window, - results_window::close_results_window, - // Connection Window - connection_window::open_connection_window, - // Task Manager - task_manager::get_process_list, - task_manager::get_system_stats, - task_manager::get_tabularis_children, - task_manager::kill_plugin_process, - task_manager::restart_plugin_process, - task_manager::open_task_manager_window, - // Connection Appearance - connection_appearance::save_connection_icon, - commands::delete_connection_icon, - commands::set_connection_appearance, - ]) - .build(tauri::generate_context!()) - .expect("error while building tauri application") - .run(move |app_handle, event| { - // Cmd+Q and relaunch paths can exit without CloseRequested. - if matches!(&event, tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit) { - window_placement::persist_cached(app_handle); - } - if let tauri::RunEvent::Exit = event { - app_handle.state::().stop(); - // Back up the freshest state before the process ends (no-op - // unless backups are enabled and due). - backup::run_exit_backup(app_handle); - tauri::async_runtime::block_on(runtime::lifecycle::release_pinned_sessions()); - run_shutdown_hooks.run(); - } - }); -} diff --git a/src-tauri/src/log_commands.rs b/src-tauri/src/log_commands.rs index 18b6de232..045b699ec 100644 --- a/src-tauri/src/log_commands.rs +++ b/src-tauri/src/log_commands.rs @@ -1,62 +1,9 @@ use crate::application::operations; -use crate::logger::{LogEntry, SharedLogBuffer}; -use std::path::PathBuf; -#[cfg(feature = "desktop")] -use tauri::State; pub use operations::{GetLogsRequest, LogSettings}; -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_logs(log_buffer: State, request: GetLogsRequest) -> Vec { - operations::get_logs(log_buffer.inner(), request) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn clear_logs(log_buffer: State) -> Result<(), String> { - operations::clear_logs(log_buffer.inner()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn get_log_settings(log_buffer: State) -> LogSettings { - operations::get_log_settings(log_buffer.inner()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_log_enabled(log_buffer: State, enabled: bool) -> Result<(), String> { - operations::set_log_enabled(log_buffer.inner(), enabled) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn set_log_max_size(log_buffer: State, max_size: usize) -> Result<(), String> { - operations::set_log_max_size(log_buffer.inner(), max_size) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn export_logs( - runtime: State<'_, crate::runtime::RuntimeContext>, - log_buffer: State<'_, SharedLogBuffer>, - file_path: String, -) -> Result, String> { - let path = PathBuf::from(file_path); - let result = crate::application::generic_exports::export_logs( - runtime.inner(), - log_buffer.inner().clone(), - crate::application::generic_exports::ExportDestination::ServerPath(path.clone()), - ) - .await?; - log::info!("Logs exported to: {:?}", path); - Ok(result) -} - /// Lets the frontend record user-relevant events (e.g. a database pruned from /// a connection's selection) in the activity log shown in Settings → Logs. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn log_frontend_event(level: String, message: String) { match level.as_str() { "error" => log::error!(target: "frontend", "{}", message), @@ -67,7 +14,6 @@ pub fn log_frontend_event(level: String, message: String) { } } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn test_log() -> Result<(), String> { log::info!("Test log message from frontend"); log::debug!("Debug test message: {}", 42); diff --git a/src-tauri/src/mcp/install.rs b/src-tauri/src/mcp/install.rs index 05ccd1b59..139597f9c 100644 --- a/src-tauri/src/mcp/install.rs +++ b/src-tauri/src/mcp/install.rs @@ -1,19 +1,2 @@ -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Runtime}; -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_mcp_status( - _app: AppHandle, -) -> Result, String> { - crate::application::mcp_host::get_status().await -} -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn install_mcp_config( - _app: AppHandle, - client_id: String, -) -> Result { - crate::application::mcp_host::install_config(client_id).await -} diff --git a/src-tauri/src/plugins/commands.rs b/src-tauri/src/plugins/commands.rs index 9785ad037..1f048c6ef 100644 --- a/src-tauri/src/plugins/commands.rs +++ b/src-tauri/src/plugins/commands.rs @@ -1,80 +1,15 @@ -use crate::drivers::driver_trait::PluginManifest; -use crate::plugins::installer::{self, InstalledPluginInfo}; -use crate::plugins::registry::{PluginReadme, RegistryPluginWithStatus}; -use crate::runtime::RuntimeContext; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, State}; +use crate::plugins::installer::{self}; -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_plugin_registry( - runtime: State<'_, RuntimeContext>, -) -> Result, String> { - crate::application::plugins::fetch_plugin_registry(runtime.inner()).await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn install_plugin( - runtime: State<'_, RuntimeContext>, - plugin_id: String, - version: Option, - registry_url: Option, -) -> Result<(), String> { - crate::application::plugins::install_plugin(runtime.inner(), plugin_id, version, registry_url) - .await -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_plugin_install(plugin_id: String) -> bool { crate::application::plugins::cancel_plugin_install(plugin_id).unwrap_or(false) } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn uninstall_plugin( - runtime: State<'_, RuntimeContext>, - plugin_id: String, -) -> Result<(), String> { - crate::application::plugins::uninstall_plugin(runtime.inner(), plugin_id).await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_installed_plugins( - runtime: State<'_, RuntimeContext>, -) -> Result, String> { - Ok(crate::application::plugins::get_installed_plugins( - runtime.inner(), - )) -} - -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn disable_plugin(plugin_id: String) -> Result<(), String> { crate::application::plugins::disable_plugin(plugin_id).await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn enable_plugin( - runtime: State<'_, RuntimeContext>, - plugin_id: String, -) -> Result<(), String> { - crate::application::plugins::enable_plugin(runtime.inner(), plugin_id).await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_plugin_manifest( - runtime: State<'_, RuntimeContext>, - plugin_id: String, -) -> Result { - crate::application::plugins::get_plugin_manifest(runtime.inner(), plugin_id) -} - /// Returns the absolute filesystem path of an installed plugin's directory. /// Desktop-only: browser RPC deliberately does not expose server filesystem paths. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_plugin_dir(plugin_id: String) -> Result { let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; plugin_dir @@ -83,55 +18,3 @@ pub fn get_plugin_dir(plugin_id: String) -> Result { .map(str::to_string) } -/// Opens the plugins directory in the desktop file manager. -/// Browser sessions never receive an equivalent server-path operation. -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn open_plugins_dir(app: AppHandle) -> Result<(), String> { - #[cfg(feature = "desktop")] - use tauri_plugin_opener::OpenerExt; - let plugins_dir = installer::get_plugins_dir()?; - app.opener() - .open_path(plugins_dir.to_string_lossy().to_string(), None::<&str>) - .map_err(|error| format!("Failed to open plugins directory: {error}")) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_tabularium_plugin_preview( - runtime: State<'_, RuntimeContext>, - slug: String, - registry_url: Option, - version: Option, -) -> Result { - crate::application::plugins::fetch_plugin_preview(runtime.inner(), slug, registry_url, version) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn fetch_plugin_readme( - runtime: State<'_, RuntimeContext>, - slug: String, - locale: Option, - registry_url: Option, -) -> Result { - crate::application::plugins::fetch_plugin_readme(runtime.inner(), slug, locale, registry_url) - .await -} - -/// Reads a file from an installed plugin's directory for the desktop UI loader. -/// Browser plugin assets use the authenticated asset route implemented separately. -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn read_plugin_file( - runtime: State<'_, RuntimeContext>, - plugin_id: String, - file_path: String, -) -> Result { - crate::application::plugin_assets::read_plugin_asset_text( - &runtime.paths.plugins_dir(), - &plugin_id, - &file_path, - ) -} diff --git a/src-tauri/src/plugins/connection_metadata.rs b/src-tauri/src/plugins/connection_metadata.rs index 783434cac..296d2076d 100644 --- a/src-tauri/src/plugins/connection_metadata.rs +++ b/src-tauri/src/plugins/connection_metadata.rs @@ -18,18 +18,6 @@ pub struct DriverManifestDetails { pub connection_metadata: Option, } -#[cfg(feature = "desktop")] -/// The UI invalidates only discovery-enabled contexts. Emitting for every -/// replacement also covers an update that removes a plugin's discovery opt-in. -pub async fn notify_plugin_reload(app: &tauri::AppHandle, driver_id: &str) { - #[cfg(feature = "desktop")] - use tauri::Emitter; - let _ = app.emit( - "connection-metadata-invalidated", - serde_json::json!({"driverId": driver_id}), - ); -} - /// Only connection-dependent fields belong here. Connection-form fields and /// plugin identity always come from the installed manifest. #[derive(Debug, Clone, Default, Deserialize)] diff --git a/src-tauri/src/plugins/deep_link.rs b/src-tauri/src/plugins/deep_link.rs index 5fd59a141..acda32dc7 100644 --- a/src-tauri/src/plugins/deep_link.rs +++ b/src-tauri/src/plugins/deep_link.rs @@ -24,8 +24,7 @@ use std::sync::Mutex; use serde::{Deserialize, Serialize}; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter, Manager}; + use url::Url; /// Tauri-managed state holding the most recent install request that has not @@ -137,61 +136,6 @@ fn is_valid_slug(s: &str) -> bool { bytes.iter().all(valid_char) && bytes.first().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) } -#[cfg(feature = "desktop")] -/// Dispatch a single URL to the frontend. Called from: -/// * the deep-link plugin's `on_open_url` handler (warm handoff), -/// * the cold-start `get_current()` path on app boot, -/// * the `single_instance` callback when a second launch forwards args. -/// -/// We both **emit** an event (so an already-mounted listener reacts -/// immediately) AND **stash** the request in `PendingInstall` so a fresh -/// React subscription can drain it on mount. Without the stash a cold-start -/// URL is delivered before the webview's event listener exists and silently -/// dropped. -pub fn handle_url(app: &AppHandle, raw: &str) { - let Some(req) = parse_install_url(raw) else { - log::info!("Ignoring tabularis:// URL: {}", raw); - return; - }; - - // Stash for cold-start replay; the frontend pulls this on mount via - // `consume_pending_deep_link_install`. - if let Some(state) = app.try_state::>() { - if let Ok(mut slot) = state.0.lock() { - *slot = Some(req.clone()); - } - } - - if let Err(err) = app.emit(PLUGIN_INSTALL_EVENT, &req) { - log::error!( - "Failed to emit {}: {} (request: {:?})", - PLUGIN_INSTALL_EVENT, - err, - req - ); - } else { - log::info!("Emitted {} for slug '{}'", PLUGIN_INSTALL_EVENT, req.slug); - } - - // Focus the main window so the user sees the confirmation modal — - // a second launch may otherwise leave Tabularis in the background. - if let Some(win) = app.get_webview_window("main") { - let _ = win.unminimize(); - let _ = win.set_focus(); - } -} - -/// Drains the pending deep-link install request, if any. Called from the -/// frontend immediately after the listener mounts to recover URLs that -/// arrived during cold-start before the event subscription existed. -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn consume_pending_deep_link_install( - state: tauri::State<'_, std::sync::Arc>, -) -> Option { - state.0.lock().ok().and_then(|mut slot| slot.take()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/plugins/force_install.rs b/src-tauri/src/plugins/force_install.rs index eb4103e72..93a30f494 100644 --- a/src-tauri/src/plugins/force_install.rs +++ b/src-tauri/src/plugins/force_install.rs @@ -15,11 +15,9 @@ //! [`MIGRATABLE_DRIVERS`] and a call site, not a new function. use serde::Serialize; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter}; -use crate::config::{self, AppConfig}; -use crate::plugins::{installer, registry, tabularium}; +use crate::config::AppConfig; +use crate::plugins::registry; /// Built-in driver id → replacement plugin id pairs that the app keeps /// installed automatically when a connection on the built-in exists. Adding @@ -28,7 +26,7 @@ pub const MIGRATABLE_DRIVERS: &[(&str, &str)] = &[("postgres", "postgresql")]; /// Log prefix shared by every message this module emits, so the force-install /// flow is greppable in logs at a glance. -const LOG_PREFIX: &str = "[force-install]"; +pub(crate) const LOG_PREFIX: &str = "[force-install]"; /// Emitted after a background force-install persists activation for /// `plugin_id`. This runs in a spawned task well after the frontend has @@ -43,112 +41,8 @@ pub const PLUGIN_ACTIVATED_EVENT: &str = "tabularis://plugin-activated"; #[derive(Serialize, Clone)] #[serde(rename_all = "camelCase")] -struct PluginActivatedPayload<'a> { - plugin_id: &'a str, -} - -#[cfg(feature = "desktop")] -/// Ensure the plugin for `builtin_id` is installed, but only when at least one -/// saved connection is still on the built-in driver. A user with no such -/// connection is left untouched — no plugin they don't need. -/// -/// Public entry point spawned from `setup()`. -pub async fn ensure_plugin_installed_if_needed(app: &AppHandle, builtin_id: &str, plugin_id: &str) { - match connections_use_driver(app, builtin_id) { - Ok(false) => return, // nothing on this built-in driver, nothing to do - Ok(true) => {} - Err(e) => { - log::warn!("{LOG_PREFIX} could not read connections: {e}"); - return; - } - } - ensure_plugin_installed(app, plugin_id).await; -} - -#[cfg(feature = "desktop")] -/// Install (and activate) `plugin_id` if it isn't already installed and the -/// latest release is compatible with this app build. Every failure path -/// logs and returns silently — there's no UI-visible error and no retry loop -/// within a single launch. The check re-runs from scratch on every launch, -/// so a transient failure self-heals next time; a persistent one (no network, -/// corporate proxy) is handled by the frontend nudge staying suppressed until -/// the plugin is actually present (see the design doc's connectivity section). -pub async fn ensure_plugin_installed(app: &AppHandle, plugin_id: &str) { - match installer::list_installed() { - Ok(installed) if installed.iter().any(|p| p.id == plugin_id) => return, - Ok(_) => {} - Err(e) => { - log::warn!("{LOG_PREFIX} could not list installed plugins: {e}"); - return; - } - } - if !plugin_compatible_with_this_app(app, plugin_id).await { - log::warn!("{LOG_PREFIX} {plugin_id} has no compatible release, skipping"); - return; - } - let runtime = tauri::Manager::state::(app); - if let Err(e) = - crate::application::plugins::install_plugin(&runtime, plugin_id.to_string(), None, None) - .await - { - log::warn!("{LOG_PREFIX} {plugin_id} install failed: {e}"); - return; - } - // `install_plugin` hot-registers for this session but does not persist - // activation — without this write the plugin vanishes on relaunch - // (`load_plugins` skips installed-but-unlisted drivers). Same effect as - // `NewConnectionModal`'s `updateSetting("activeExternalDrivers", ...)`, - // written from the backend because this runs in a spawned task. - if let Err(e) = persist_activation(app, plugin_id) { - log::warn!("{LOG_PREFIX} could not activate {plugin_id}: {e}"); - } - // Tell the already-running frontend the plugin is installed and - // (activation errors aside) registered — see `PLUGIN_ACTIVATED_EVENT`'s - // doc comment for why this can't wait for the next launch. Emitted even - // if `persist_activation` above failed: `install_plugin` still - // hot-registered the driver for this session, so `useDrivers`' - // `get_registered_drivers`/`get_installed_plugins` refetch has something - // new to report regardless of whether the config write landed. - if let Err(e) = app.emit(PLUGIN_ACTIVATED_EVENT, PluginActivatedPayload { plugin_id }) { - log::warn!("{LOG_PREFIX} could not emit {PLUGIN_ACTIVATED_EVENT}: {e}"); - } -} - -#[cfg(feature = "desktop")] -/// Persist `plugin_id` into `active_external_drivers` via the `save_config` -/// merge, leaving every other config field untouched. Idempotent: a no-op if -/// the id is already active. -/// -/// Reads the currently-installed plugin ids first: `merge_active_driver` needs -/// them to seed the list correctly when no preference has been saved yet (see -/// its doc comment). Bails without writing if that read fails — narrowing to -/// just `plugin_id` on a guess would be worse than not activating it this -/// launch, since it could silently deactivate every other installed plugin. -fn persist_activation(app: &AppHandle, plugin_id: &str) -> Result<(), String> { - let config = config::load_config_internal(app); - let installed_ids: Vec = installer::list_installed()? - .into_iter() - .map(|p| p.id) - .collect(); - let updated = merge_active_driver(&config, plugin_id, &installed_ids); - // Only write when something actually changed — avoids a pointless - // config.json rewrite (and cache invalidation) on every launch. - if updated.active_external_drivers == config.active_external_drivers { - return Ok(()); - } - // Pass save_config a config with only `active_external_drivers` set, - // not the full `updated` snapshot: save_config re-reads disk and - // overwrites every `Some` field, so writing back the stale snapshot - // taken above would silently revert any other setting the user changed - // in the meantime — the inverse of the race the frontend's - // `plugin-activated` listener already guards against. - config::save_config( - app.clone(), - AppConfig { - active_external_drivers: updated.active_external_drivers, - ..AppConfig::default() - }, - ) +pub(crate) struct PluginActivatedPayload<'a> { + pub(crate) plugin_id: &'a str, } /// Pure helper: return a copy of `config` with `plugin_id` added to @@ -189,57 +83,6 @@ pub(crate) fn merge_active_driver( } } -#[cfg(feature = "desktop")] -/// True when at least one saved connection has `params.driver == driver_id`. -/// Reads the connections file directly via `persistence::load_connections` -/// (the same path `get_connections` uses internally) rather than invoking the -/// Tauri command — the command wrapper runs per-call SSH/SSL migrations we -/// don't want firing on every launch just to detect a trigger. -fn connections_use_driver(app: &AppHandle, driver_id: &str) -> Result { - let path = crate::commands::get_config_path(app)?; - let connections = crate::persistence::load_connections(&path)?; - Ok(connections.iter().any(|c| c.params.driver == driver_id)) -} - -#[cfg(feature = "desktop")] -/// Check the latest release's `min_tabularis_version` against the running -/// app's own version. `install_plugin` doesn't gate on this itself, so without -/// this check an unattended install could silently install a release that -/// requires a newer Tabularis than the user is running, leaving them -/// installed-but-non-functional. Reuses the `semver::Version::parse` primitive -/// `classify_install` (`registry.rs:43`) already uses, applied to a different -/// comparison. -async fn plugin_compatible_with_this_app(app: &AppHandle, plugin_id: &str) -> bool { - let config = config::load_config_internal(app); - let base = registry_base_url(&config).trim_end_matches('/'); - let Ok(detail) = tabularium::fetch_plugin_detail(base, plugin_id).await else { - // Couldn't reach the registry — treat as compatible-by-default so a - // network blip doesn't permanently block an otherwise-fine install; - // the install itself will surface a real download error if it persists. - log::warn!("{LOG_PREFIX} could not fetch detail for {plugin_id}, assuming compatible"); - return true; - }; - // Find the release matching the registry's latest_version; fall back to - // the first release if the version string can't be matched. - let target = if detail.latest_version.is_empty() { - detail.releases.first() - } else { - detail - .releases - .iter() - .find(|r| r.version == detail.latest_version) - .or_else(|| detail.releases.first()) - }; - let Some(release) = target else { - log::warn!("{LOG_PREFIX} {plugin_id} has no releases on the registry"); - return false; - }; - let Some(min) = &release.min_tabularis_version else { - return true; // no minimum declared → compatible with any version - }; - is_version_compatible(min, env!("CARGO_PKG_VERSION")) -} - /// Pure semver check: is `app_version` >= `min_version`? Returns `true` when /// either string fails to parse (a malformed version string must not block an /// otherwise-fine install — the install itself surfaces real errors). Extracted @@ -270,7 +113,7 @@ pub(crate) fn is_version_compatible(min_version: &str, app_version: &str) -> boo /// Resolve the configured Tabularium registry base URL. Mirrors the private /// `registry_base_url` in `commands.rs` (same 3-line logic) rather than /// reaching across modules for it. -fn registry_base_url(config: &AppConfig) -> &str { +pub(crate) fn registry_base_url(config: &AppConfig) -> &str { config .tabularium_registry_url .as_deref() diff --git a/src-tauri/src/plugins/manager.rs b/src-tauri/src/plugins/manager.rs index a01dd407f..fce544113 100644 --- a/src-tauri/src/plugins/manager.rs +++ b/src-tauri/src/plugins/manager.rs @@ -4,8 +4,6 @@ use std::sync::Mutex; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; -#[cfg(feature = "desktop")] -use tauri::AppHandle; use crate::config::PluginConfig; use crate::drivers::driver_trait::{ @@ -42,7 +40,6 @@ pub struct PluginLoadError { pub error: String, } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_plugin_startup_errors() -> Vec { crate::application::plugins::get_plugin_startup_errors() } @@ -111,19 +108,6 @@ pub struct ConfigManifest { /// swallowed because the built-in of the same id is already registered. const BUILTIN_DRIVER_IDS: [&str; 3] = ["mysql", "postgres", "sqlite"]; -#[cfg(feature = "desktop")] -/// Load installed plugins at startup. -/// -/// `enabled_ids` controls which plugins are started: -/// - `None` → load all installed plugins (first-run or no preference saved). -/// - `Some(ids)` → load only the plugins whose directory name (= plugin ID) is in `ids`. -pub async fn load_plugins(app: &AppHandle, enabled_ids: Option<&[String]>) { - let plugin_configs = crate::config::load_config_internal(app) - .plugins - .unwrap_or_default(); - load_plugins_with_configs(plugin_configs, enabled_ids).await; -} - /// Re-scans installed plugins against the latest on-disk config and registers /// any that are missing from the driver registry. Idempotent — plugins /// already registered are skipped by `load_plugins_with_configs`, so this can diff --git a/src-tauri/src/plugins/runtime_version.rs b/src-tauri/src/plugins/runtime_version.rs index b65cf5a01..d000d9dd9 100644 --- a/src-tauri/src/plugins/runtime_version.rs +++ b/src-tauri/src/plugins/runtime_version.rs @@ -56,7 +56,6 @@ pub fn take_runtime_warnings() -> Vec { std::mem::take(&mut *guard) } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_plugin_runtime_warnings() -> Vec { take_runtime_warnings() } diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs index 4e241cdf2..faf636c5c 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -1,7 +1,4 @@ use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EditorPreferences { @@ -9,70 +6,3 @@ pub struct EditorPreferences { pub active_tab_id: Option, } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_editor_preferences( - app: AppHandle, - connection_id: String, - preferences: EditorPreferences, -) -> Result<(), String> { - crate::application::persistence::save_editor_preferences_for_desktop( - &app.state::(), - &connection_id, - &preferences, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn load_editor_preferences( - app: AppHandle, - connection_id: String, -) -> Result, String> { - crate::application::persistence::load_editor_preferences_for_desktop( - &app.state::(), - &connection_id, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_editor_preferences( - app: AppHandle, - connection_id: String, -) -> Result<(), String> { - crate::application::persistence::delete_editor_preferences_for_desktop( - &app.state::(), - &connection_id, - ) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn list_all_preferences( - app: AppHandle, -) -> Result, String> { - let preferences_dir = app - .state::() - .paths - .config_dir() - .join("preferences"); - if !preferences_dir.exists() { - return Ok(HashMap::new()); - } - - let mut preferences = HashMap::new(); - for entry in std::fs::read_dir(preferences_dir).map_err(|error| error.to_string())? { - let entry = entry.map_err(|error| error.to_string())?; - let Some(connection_id) = entry.file_name().to_str().map(str::to_string) else { - continue; - }; - if let Some(value) = crate::application::persistence::load_editor_preferences_for_desktop( - &app.state::(), - &connection_id, - )? { - preferences.insert(connection_id, value); - } - } - Ok(preferences) -} diff --git a/src-tauri/src/proxy/mod.rs b/src-tauri/src/proxy/mod.rs index 8ce27b0dd..7bca290e5 100644 --- a/src-tauri/src/proxy/mod.rs +++ b/src-tauri/src/proxy/mod.rs @@ -27,7 +27,6 @@ pub use types::{ use crate::keychain_utils; -#[cfg_attr(feature = "desktop", tauri::command)] pub fn set_proxy_password(slot: String, password: String) -> Result<(), String> { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); @@ -39,7 +38,6 @@ pub fn set_proxy_password(slot: String, password: String) -> Result<(), String> } } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn proxy_password_is_set(slot: String) -> Result { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); @@ -49,7 +47,6 @@ pub fn proxy_password_is_set(slot: String) -> Result { .unwrap_or(false)) } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn delete_proxy_password(slot: String) -> Result<(), String> { if !is_valid_proxy_slot(&slot) { return Err(format!("Invalid proxy password slot: {slot}")); diff --git a/src-tauri/src/query_history.rs b/src-tauri/src/query_history.rs index b5495c336..d6ebb6216 100644 --- a/src-tauri/src/query_history.rs +++ b/src-tauri/src/query_history.rs @@ -1,116 +1,6 @@ -use crate::application::productivity::{self, ProductivityCommand}; -use serde_json::from_value; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime}; pub use crate::application::productivity::backfill_history_entries as backfill_missing_database; #[cfg(test)] pub(crate) use crate::application::productivity::{atomic_write, backup_corrupt_file}; pub use crate::application::productivity::{QueryHistoryEntry, QueryHistoryResponse}; -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_query_history( - app: AppHandle, - connection_id: String, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - from_value( - productivity::execute( - config_dir, - ProductivityCommand::GetQueryHistory { connection_id }, - ) - .await?, - ) - .map_err(|error| error.to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -#[allow(clippy::too_many_arguments)] -pub async fn add_query_history_entry( - app: AppHandle, - connection_id: String, - sql: String, - executed_at: String, - execution_time_ms: Option, - status: String, - rows_affected: Option, - error: Option, - database: Option, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - from_value( - productivity::execute( - config_dir, - ProductivityCommand::AddQueryHistoryEntry { - connection_id, - sql, - executed_at, - execution_time_ms, - status, - rows_affected, - error, - database, - }, - ) - .await?, - ) - .map_err(|error| error.to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_query_history_entry( - app: AppHandle, - connection_id: String, - id: String, -) -> Result<(), String> { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::execute( - config_dir, - ProductivityCommand::DeleteQueryHistoryEntry { connection_id, id }, - ) - .await?; - Ok(()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn clear_query_history( - app: AppHandle, - connection_id: String, -) -> Result<(), String> { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::execute( - config_dir, - ProductivityCommand::ClearQueryHistory { connection_id }, - ) - .await?; - Ok(()) -} - -#[cfg(feature = "desktop")] -pub async fn backfill_missing_database_for_connection( - app: &AppHandle, - connection_id: &str, - database: &str, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::backfill_query_history_for_connection(config_dir, connection_id, database) -} - -#[cfg(feature = "desktop")] -pub async fn remove_history_for_connection( - app: &AppHandle, - connection_id: &str, -) -> Result<(), String> { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::remove_query_history_for_connection(config_dir, connection_id) -} diff --git a/src-tauri/src/results_window.rs b/src-tauri/src/results_window.rs index d7a51ba4c..c66eb6f04 100644 --- a/src-tauri/src/results_window.rs +++ b/src-tauri/src/results_window.rs @@ -1,9 +1,6 @@ use std::collections::HashMap; use std::sync::Mutex; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -use urlencoding::encode; /// Persisted geometry so a re-opened detached results window restores where the /// user last left it. Mirrors the pattern used by `json_viewer.rs`. @@ -25,105 +22,10 @@ pub struct ResultsWindowStore { /// One detached results window per editor tab. The frontend keeps each window's /// data in sync over Tauri events keyed by `tab_id`. -fn window_label(tab_id: &str) -> String { +pub(crate) fn window_label(tab_id: &str) -> String { format!("results-window-{}", tab_id) } -/// Open (or focus) the detached results window for a given tab. Result data is -/// streamed from the main window via `resultsSyncEvent(tabId)` in -/// `src/utils/resultsWindowSync.ts`, so no payload is passed here. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn open_results_window( - app: AppHandle, - store: tauri::State<'_, std::sync::Arc>, - tab_id: String, - title: Option, -) -> Result<(), String> { - let label = window_label(&tab_id); - - // If it already exists, just bring it to the front. - if let Some(window) = app.get_webview_window(&label) { - let _ = window.unminimize(); - let _ = window.set_focus(); - return Ok(()); - } - - let window_title = title.unwrap_or_else(|| "Query Results".to_string()); - - let remembered = store - .bounds - .lock() - .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? - .get(&tab_id) - .copied(); - - let url = format!("/results-window?tab={}", encode(&tab_id)); - let mut builder = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) - .title(&window_title) - .min_inner_size(500.0, 300.0) - .decorations(crate::window_decorations::native_decorations_enabled()) - .background_color(tauri::webview::Color(2, 6, 23, 255)); - - builder = match remembered { - Some(b) => builder - .inner_size(b.width as f64, b.height as f64) - .position(b.x as f64, b.y as f64), - None => builder.inner_size(900.0, 600.0).center(), - }; - - match builder.build() { - Err(e) => Err(format!("Failed to create results window: {}", e)), - Ok(window) => { - let app_handle = app.clone(); - let captured_label = label.clone(); - let captured_tab_id = tab_id.clone(); - window.on_window_event(move |event| { - if let WindowEvent::CloseRequested { .. } = event { - if let Some(win) = app_handle.get_webview_window(&captured_label) { - // Save the inner size: it is restored via `.inner_size(...)` - // below, so saving `outer_size()` would grow the window by - // the decoration height on each detach→close→reopen cycle. - if let (Ok(pos), Ok(size)) = (win.outer_position(), win.inner_size()) { - let store = app_handle.state::>(); - if let Ok(mut bounds) = store.bounds.lock() { - bounds.insert( - captured_tab_id.clone(), - WindowBounds { - x: pos.x, - y: pos.y, - width: size.width, - height: size.height, - }, - ); - }; - } - } - // Let the main window re-attach this tab's results panel. - let _ = app_handle.emit( - "results-window:closed", - serde_json::json!({ "tabId": captured_tab_id }), - ); - } - }); - Ok(()) - } - } -} - -/// Programmatically close a tab's detached results window (used by the -/// "Re-attach" button and when the bound tab is closed). -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn close_results_window(app: AppHandle, tab_id: String) -> Result<(), String> { - if let Some(window) = app.get_webview_window(&window_label(&tab_id)) { - window - .close() - .map_err(|e| format!("Failed to close results window: {}", e))?; - } - Ok(()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/runtime/events.rs b/src-tauri/src/runtime/events.rs index 87bd3b318..bf8d9965f 100644 --- a/src-tauri/src/runtime/events.rs +++ b/src-tauri/src/runtime/events.rs @@ -1,6 +1,4 @@ use serde_json::Value; -#[cfg(feature = "desktop")] -use tauri::Emitter; pub trait RuntimeEvents: Send + Sync { fn emit(&self, event: &str, payload: Value) -> Result<(), String>; @@ -19,23 +17,3 @@ impl RuntimeEvents for NoopRuntimeEvents { } } -#[cfg(feature = "desktop")] -pub struct TauriRuntimeEvents { - app: tauri::AppHandle, -} - -#[cfg(feature = "desktop")] -impl TauriRuntimeEvents { - pub fn new(app: tauri::AppHandle) -> Self { - Self { app } - } -} - -#[cfg(feature = "desktop")] -impl RuntimeEvents for TauriRuntimeEvents { - fn emit(&self, event: &str, payload: Value) -> Result<(), String> { - self.app - .emit(event, payload) - .map_err(|error| error.to_string()) - } -} diff --git a/src-tauri/src/runtime/lifecycle.rs b/src-tauri/src/runtime/lifecycle.rs index cba57fbdd..f2a953203 100644 --- a/src-tauri/src/runtime/lifecycle.rs +++ b/src-tauri/src/runtime/lifecycle.rs @@ -38,16 +38,6 @@ pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { crate::drivers::registry::shutdown_external_drivers().await; } -#[cfg(feature = "desktop")] -pub fn start_desktop_schedulers(app: tauri::AppHandle, ping_interval_secs: u64) { - let health_check_app = app.clone(); - crate::async_rt::spawn(async move { - crate::health_check::start_ping_loop(health_check_app, ping_interval_secs).await; - }); - crate::ai_approval_watcher::spawn(app.clone()); - crate::backup::spawn_scheduler(app); -} - pub async fn release_pinned_sessions() { if tokio::time::timeout( std::time::Duration::from_secs(3), diff --git a/src-tauri/src/runtime/tests.rs b/src-tauri/src/runtime/tests.rs index fd080e678..9aaf6f9ec 100644 --- a/src-tauri/src/runtime/tests.rs +++ b/src-tauri/src/runtime/tests.rs @@ -154,140 +154,6 @@ fn shutdown_hooks_run_without_a_tauri_runtime() { assert_eq!(calls.load(Ordering::Relaxed), 1); } -#[tokio::test] -async fn desktop_productivity_commands_use_the_managed_custom_config_directory() { - use crate::{query_history, saved_queries}; - let root = tempfile::tempdir().unwrap(); - let config = root.path().join("custom-config"); - let runtime = RuntimeContext::new( - Arc::new(super::paths::FixedRuntimePaths::new( - config.clone(), - root.path().join("data"), - )), - Arc::new(TestEvents::default()), - Arc::new(TestSecrets), - ); - let app = tauri::test::mock_builder() - .manage(runtime) - .build(tauri::test::mock_context(tauri::test::noop_assets())) - .unwrap(); - let handle = app.handle().clone(); - let connection = uuid::Uuid::new_v4().to_string(); - let seed = crate::application::productivity::execute( - &config, - crate::application::productivity::ProductivityCommand::SaveQuery { - connection_id: connection.clone(), - name: "Seed".into(), - sql: "SELECT 0".into(), - database: None, - }, - ) - .await - .unwrap(); - assert_eq!( - saved_queries::get_saved_queries(handle.clone(), connection.clone()) - .await - .unwrap() - .len(), - 1, - "desktop reads must use the managed runtime path" - ); - saved_queries::delete_saved_query( - handle.clone(), - Some(connection.clone()), - seed["id"].as_str().unwrap().into(), - ) - .await - .unwrap(); - let saved = saved_queries::save_query( - handle.clone(), - connection.clone(), - "Custom".into(), - "SELECT 1".into(), - None, - ) - .await - .unwrap(); - assert!( - config.join("saved_queries").exists(), - "saved queries must use the runtime config directory" - ); - assert_eq!( - saved_queries::get_saved_queries(handle.clone(), connection.clone()) - .await - .unwrap() - .len(), - 1 - ); - saved_queries::update_saved_query( - handle.clone(), - Some(connection.clone()), - saved.id.clone(), - "Updated".into(), - "SELECT 2".into(), - None, - ) - .await - .unwrap(); - assert_eq!( - saved_queries::backfill_missing_database_for_connection(&handle, &connection, "db") - .unwrap(), - 1 - ); - saved_queries::delete_saved_query(handle.clone(), Some(connection.clone()), saved.id) - .await - .unwrap(); - assert!( - saved_queries::get_saved_queries(handle.clone(), connection.clone()) - .await - .unwrap() - .is_empty() - ); - let entry = query_history::add_query_history_entry( - handle.clone(), - connection.clone(), - "SELECT 1".into(), - "2026-10-15T00:00:00Z".into(), - None, - "success".into(), - None, - None, - None, - ) - .await - .unwrap(); - assert!( - config.join("query_history").exists(), - "history must use the runtime config directory" - ); - assert_eq!( - query_history::get_query_history(handle.clone(), connection.clone()) - .await - .unwrap() - .entries - .len(), - 1 - ); - assert_eq!( - query_history::backfill_missing_database_for_connection(&handle, &connection, "db") - .await - .unwrap(), - 1 - ); - query_history::delete_query_history_entry(handle.clone(), connection.clone(), entry.id) - .await - .unwrap(); - query_history::clear_query_history(handle.clone(), connection.clone()) - .await - .unwrap(); - query_history::remove_history_for_connection(&handle, &connection) - .await - .unwrap(); - assert!(!config - .join("query_history") - .join(format!("{connection}.json")) - .exists()); -} #[test] fn approval_heartbeat_lives_only_for_its_runtime_lifecycle() { diff --git a/src-tauri/src/saved_queries.rs b/src-tauri/src/saved_queries.rs index e19b0bd3c..80132e1ed 100644 --- a/src-tauri/src/saved_queries.rs +++ b/src-tauri/src/saved_queries.rs @@ -1,199 +1,5 @@ -use crate::application::productivity::{self, ProductivityCommand}; -use serde_json::from_value; -#[cfg(feature = "desktop")] -use tauri::{AppHandle, Manager, Runtime}; pub use crate::application::productivity::{SavedQuery, SavedQueryMeta}; -use crate::saved_query_folders::SavedQueryFolder; - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_saved_queries( - app: AppHandle, - connection_id: String, -) -> Result, String> { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - from_value( - productivity::execute( - config_dir, - ProductivityCommand::GetSavedQueries { connection_id }, - ) - .await?, - ) - .map_err(|error| error.to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn save_query( - app: AppHandle, - connection_id: String, - name: String, - sql: String, - database: Option, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - from_value( - productivity::execute( - config_dir, - ProductivityCommand::SaveQuery { - connection_id, - name, - sql, - database, - }, - ) - .await?, - ) - .map_err(|error| error.to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn update_saved_query( - app: AppHandle, - connection_id: Option, - id: String, - name: String, - sql: String, - database: Option, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - from_value( - productivity::execute( - config_dir, - ProductivityCommand::UpdateSavedQuery { - connection_id, - id, - name, - sql, - database, - }, - ) - .await?, - ) - .map_err(|error| error.to_string()) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_saved_query( - app: AppHandle, - connection_id: Option, - id: String, -) -> Result<(), String> { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::execute( - config_dir, - ProductivityCommand::DeleteSavedQuery { connection_id, id }, - ) - .await?; - Ok(()) -} pub use crate::application::productivity::backfill_saved_query_metadata as backfill_missing_database; -#[cfg(feature = "desktop")] -pub fn backfill_missing_database_for_connection( - app: &AppHandle, - connection_id: &str, - database: &str, -) -> Result { - let runtime = app.state::(); - let config_dir = runtime.paths.config_dir(); - productivity::backfill_saved_queries_for_connection(config_dir, connection_id, database) -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn get_saved_query_folders( - app: AppHandle, - connection_id: String, -) -> Result, String> { - execute_typed(&app, ProductivityCommand::GetSavedQueryFolders { connection_id }).await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn create_saved_query_folder( - app: AppHandle, - connection_id: String, - name: String, -) -> Result { - execute_typed( - &app, - ProductivityCommand::CreateSavedQueryFolder { - connection_id, - name, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn rename_saved_query_folder( - app: AppHandle, - connection_id: Option, - id: String, - name: String, -) -> Result { - execute_typed( - &app, - ProductivityCommand::RenameSavedQueryFolder { - connection_id, - id, - name, - }, - ) - .await -} - -/// Only empty folders can be deleted; see `saved_query_folders::delete_folder`. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn delete_saved_query_folder( - app: AppHandle, - connection_id: Option, - id: String, -) -> Result<(), String> { - execute_typed( - &app, - ProductivityCommand::DeleteSavedQueryFolder { connection_id, id }, - ) - .await -} - -/// Moves a saved query into a folder, or to Unfiled when `folder_id` is null. -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn move_saved_query( - app: AppHandle, - connection_id: Option, - id: String, - folder_id: Option, -) -> Result<(), String> { - execute_typed( - &app, - ProductivityCommand::MoveSavedQuery { - connection_id, - id, - folder_id, - }, - ) - .await -} - -#[cfg(feature = "desktop")] -async fn execute_typed( - app: &AppHandle, - command: ProductivityCommand, -) -> Result { - let runtime = app.state::(); - from_value(productivity::execute(runtime.paths.config_dir(), command).await?) - .map_err(|error| error.to_string()) -} diff --git a/src-tauri/src/sql_file.rs b/src-tauri/src/sql_file.rs index f2133c87c..15b4f6dc9 100644 --- a/src-tauri/src/sql_file.rs +++ b/src-tauri/src/sql_file.rs @@ -50,7 +50,6 @@ pub fn write_sql_file_to_disk(path: &Path, content: &str) -> Result<(), String> .map_err(|e| format!("Failed to write SQL file {}: {}", path.display(), e)) } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn read_sql_file(path: String) -> Result { let path = validate_sql_file_path(&path)?; spawn_blocking(move || read_sql_file_from_disk(&path, MAX_SQL_FILE_BYTES)) @@ -58,7 +57,6 @@ pub async fn read_sql_file(path: String) -> Result { .map_err(|e| e.to_string())? } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn write_sql_file(path: String, content: String) -> Result<(), String> { let path = validate_sql_file_path(&path)?; spawn_blocking(move || write_sql_file_to_disk(&path, &content)) diff --git a/src-tauri/src/sqlite_database.rs b/src-tauri/src/sqlite_database.rs index ac9e56951..f389af57e 100644 --- a/src-tauri/src/sqlite_database.rs +++ b/src-tauri/src/sqlite_database.rs @@ -99,7 +99,6 @@ pub(crate) async fn initialize_sqlite_file(path: &Path) -> Result<(), String> { Ok(()) } -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn create_sqlite_file(path: String) -> Result { let path = normalize_sqlite_path(&path)?; initialize_sqlite_file(&path).await?; diff --git a/src-tauri/src/storage_location.rs b/src-tauri/src/storage_location.rs index 47524026d..26af8a7de 100644 --- a/src-tauri/src/storage_location.rs +++ b/src-tauri/src/storage_location.rs @@ -312,12 +312,10 @@ fn info() -> StorageLocationInfo { } } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_storage_location() -> StorageLocationInfo { info() } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn inspect_storage_location(path: String) -> Result { let target = PathBuf::from(path); validate_target(&target, &crate::paths::get_app_config_dir())?; @@ -326,7 +324,6 @@ pub fn inspect_storage_location(path: String) -> Result Result { let target = PathBuf::from(path); let current = crate::paths::get_app_config_dir(); @@ -352,30 +349,15 @@ pub fn set_storage_location(path: String, copy_data: bool) -> Result Result { clear_pointer(&crate::paths::get_default_app_config_dir())?; log::info!("[StorageLocation] Storage folder reset to default"); Ok(info()) } -/// Reveal the folder currently in use in the system file manager. -#[cfg(feature = "desktop")] -#[tauri::command] -pub fn open_storage_location(app: tauri::AppHandle) -> Result<(), String> { - #[cfg(feature = "desktop")] - use tauri_plugin_opener::OpenerExt; - let dir = crate::paths::get_app_config_dir(); - fs::create_dir_all(&dir).map_err(|e| e.to_string())?; - app.opener() - .open_path(dir.to_string_lossy().to_string(), None::<&str>) - .map_err(|e| format!("Failed to open storage folder: {e}")) -} - /// Absolute data directory, for the frontend to build `asset://` URLs of /// connection icons. Replaces `appDataDir()` from the Tauri JS API, which /// knows nothing about the custom location. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn get_app_data_dir() -> String { crate::paths::get_app_data_dir() .to_string_lossy() diff --git a/src-tauri/src/theme_packages/catalog.rs b/src-tauri/src/theme_packages/catalog.rs index 06f3ac451..f3b44ffc9 100644 --- a/src-tauri/src/theme_packages/catalog.rs +++ b/src-tauri/src/theme_packages/catalog.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; pub(super) const PERSONAL_DIR: &str = "theme-personal-v1"; /// Installed packages live in `plugins///`. Flat packages /// remain a read fallback; manifests keep declarative themes out of drivers. -pub(super) const PACKAGES_DIR: &str = "plugins"; +pub(crate) const PACKAGES_DIR: &str = "plugins"; const CATALOG_BYTES: usize = 32 * 1024 * 1024; pub(super) fn revision(source: &str) -> String { diff --git a/src-tauri/src/theme_packages/commands.rs b/src-tauri/src/theme_packages/commands.rs index e4a746c9d..fcecf286c 100644 --- a/src-tauri/src/theme_packages/commands.rs +++ b/src-tauri/src/theme_packages/commands.rs @@ -8,7 +8,6 @@ fn operation_id(registry: &str, package: &str) -> String { } /// Standalone import preview validates without creating a personal file. -#[cfg_attr(feature = "desktop", tauri::command)] pub fn preview_theme_document(source: String, name: String) -> Result { catalog::validate_name(&name)?; let value = parse_bounded_json(source.as_bytes(), legacy::LEGACY_BYTES * 2, 128, 262_144)?; @@ -92,7 +91,6 @@ pub fn read_local_archive(path: &Path) -> Result, String> { /// Largest accepted local theme archive. pub const MAX_LOCAL_ARCHIVE_BYTES: usize = lifecycle::ARCHIVE_BYTES; -#[cfg_attr(feature = "desktop", tauri::command)] pub async fn preview_local_theme_package( path: String, ) -> Result { @@ -187,7 +185,6 @@ pub async fn install_registry( .await } -#[cfg_attr(feature = "desktop", tauri::command)] pub fn cancel_theme_install(registry_key: String, package_name: String) -> bool { install_cancellation::cancel(&operation_id(®istry_key, &package_name)) } diff --git a/src-tauri/src/theme_packages/mod.rs b/src-tauri/src/theme_packages/mod.rs index 7c9781b2c..8cfa140e3 100644 --- a/src-tauri/src/theme_packages/mod.rs +++ b/src-tauri/src/theme_packages/mod.rs @@ -1,12 +1,12 @@ //! Declarative theme contracts. No executable plugin activation belongs here. mod archive; -mod catalog; +pub(crate) mod catalog; mod catalog_models; pub mod commands; mod files; mod json; mod legacy; -mod lifecycle; +pub(crate) mod lifecycle; mod locations; mod personal; pub(crate) use json::parse_bounded_json; diff --git a/src-tauri/src/transport/desktop/ai.rs b/src-tauri/src/transport/desktop/ai.rs new file mode 100644 index 000000000..cc545d631 --- /dev/null +++ b/src-tauri/src/transport/desktop/ai.rs @@ -0,0 +1,92 @@ +use crate::ai::*; +use crate::credential_cache::CredentialCache; +use crate::runtime::RuntimeContext; +use std::collections::HashMap; +use tauri::{AppHandle, Manager}; + +#[tauri::command] +pub fn clear_ai_models_cache(app: AppHandle) -> Result<(), String> { + clear_models_cache(&app.state::()) +} + +#[tauri::command] +pub async fn get_ai_models( + app: AppHandle, + force_refresh: bool, +) -> Result>, String> { + get_models( + &app.state::(), + &app.state::>(), + force_refresh, + ) + .await +} + +#[tauri::command] +pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result { + generate_query( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result { + explain_query( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn analyze_ai_explain_plan( + app: AppHandle, + req: AiExplainRequest, +) -> Result { + analyze_explain_plan( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn generate_cell_name(app: AppHandle, req: AiCellNameRequest) -> Result { + generate_cellname( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn suggest_table_name( + app: AppHandle, + req: AiSuggestTableNameRequest, +) -> Result { + suggest_table_name_with_runtime( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn generate_tab_rename( + app: AppHandle, + req: AiTabRenameRequest, +) -> Result { + generate_tab_name( + &app.state::(), + &app.state::>(), + req, + ) + .await +} diff --git a/src-tauri/src/transport/desktop/ai_approval_watcher.rs b/src-tauri/src/transport/desktop/ai_approval_watcher.rs new file mode 100644 index 000000000..0c4b93a34 --- /dev/null +++ b/src-tauri/src/transport/desktop/ai_approval_watcher.rs @@ -0,0 +1,88 @@ +use crate::ai_approval; +use crate::ai_approval_watcher::*; +use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; +use std::sync::mpsc; +use std::time::Duration; +use tauri::{AppHandle, Emitter, Runtime}; + +/// Spawn the watcher + cleanup tasks. The watcher returns immediately if it +/// fails to initialise (e.g. unsupported filesystem); cleanup keeps running. +pub fn spawn(app: AppHandle) { + let app_for_watcher = app.clone(); + crate::async_rt::spawn_blocking(move || { + if let Err(e) = run_watcher(app_for_watcher) { + log::warn!("AI approval watcher disabled: {}", e); + } + }); + + let app_for_cleanup = app.clone(); + crate::async_rt::spawn(async move { + run_cleanup_loop(app_for_cleanup).await; + }); +} + +fn run_watcher(app: AppHandle) -> Result<(), String> { + let dir = ai_approval::approvals_dir_path(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + + let (tx, rx) = mpsc::channel::>(); + let mut watcher: RecommendedWatcher = + notify::recommended_watcher(tx).map_err(|e| e.to_string())?; + watcher + .watch(&dir, RecursiveMode::NonRecursive) + .map_err(|e| e.to_string())?; + + log::info!("AI approval watcher started on {}", dir.display()); + + // The watcher is dropped when this function returns; keep it alive for the + // process lifetime by looping forever. + for evt in rx { + match evt { + Ok(event) => handle_event(&app, &event), + Err(e) => log::warn!("approval watcher error: {}", e), + } + } + Ok(()) +} + +fn handle_event(app: &AppHandle, event: &Event) { + if !matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_)) { + return; + } + for path in &event.paths { + let name = match path.file_name().and_then(|s| s.to_str()) { + Some(n) => n, + None => continue, + }; + if !name.ends_with(".pending.json") { + continue; + } + let id = name.trim_end_matches(".pending.json").to_string(); + // The file may not yet be fully flushed when notify fires Create — + // try to read; if it fails this iteration we'll catch it on the + // next Modify event. + if let Ok(Some(pending)) = ai_approval::read_pending(&id) { + if let Err(e) = app.emit(PENDING_APPROVAL_EVENT, &pending) { + log::warn!("Failed to emit {}: {}", PENDING_APPROVAL_EVENT, e); + } + } + } +} + +async fn run_cleanup_loop(_app: AppHandle) { + let mut ticker = tokio::time::interval(Duration::from_secs(CLEANUP_INTERVAL_SECS)); + // Skip the immediate first tick. + ticker.tick().await; + loop { + ticker.tick().await; + let cleaned = + tokio::task::spawn_blocking(|| ai_approval::cleanup_expired(CLEANUP_MAX_AGE_SECS)) + .await + .ok() + .and_then(|r| r.ok()) + .unwrap_or(0); + if cleaned > 0 { + log::info!("Cleaned {} stale approval file(s)", cleaned); + } + } +} diff --git a/src-tauri/src/ai_commands.rs b/src-tauri/src/transport/desktop/ai_commands.rs similarity index 100% rename from src-tauri/src/ai_commands.rs rename to src-tauri/src/transport/desktop/ai_commands.rs diff --git a/src-tauri/src/transport/desktop/askpass.rs b/src-tauri/src/transport/desktop/askpass.rs new file mode 100644 index 000000000..fab9b6bf4 --- /dev/null +++ b/src-tauri/src/transport/desktop/askpass.rs @@ -0,0 +1,6 @@ +/// Frontend answer to an askpass prompt. `response = None` means the user +/// cancelled. +#[tauri::command] +pub fn respond_ssh_askpass(id: u64, response: Option) { + crate::askpass::respond_ssh_askpass(id, response) +} diff --git a/src-tauri/src/transport/desktop/backup.rs b/src-tauri/src/transport/desktop/backup.rs new file mode 100644 index 000000000..17b6634fb --- /dev/null +++ b/src-tauri/src/transport/desktop/backup.rs @@ -0,0 +1,127 @@ +use crate::backup::*; +use crate::runtime::RuntimeContext; +use tauri::{AppHandle, Manager, Runtime}; + +pub async fn run_backup(app: AppHandle, trigger: &str) -> Result { + Ok( + run_backup_for_runtime(app.state::().inner(), trigger) + .await? + .location, + ) +} + +async fn run_and_log(app: &AppHandle, trigger: &str) { + if let Err(e) = run_backup(app.clone(), trigger).await { + log::warn!("Connections backup ({trigger}) failed: {e}"); + } +} + +/// Interval mode: runs one backup when the newest one is older than the +/// configured interval. +async fn run_if_due(app: &AppHandle) { + let config = crate::transport::desktop::config::load_config_internal(app); + if backup_mode(&config) != "interval" { + return; + } + let interval = config + .backup_interval_minutes + .unwrap_or(DEFAULT_INTERVAL_MINUTES); + if is_backup_due( + newest_backup(&config).await, + chrono::Local::now().naive_local(), + interval, + ) { + run_and_log(app, "interval").await; + } +} + +/// Called from the `RunEvent::Exit` handler. In on-close mode every exit +/// writes a backup so the freshest state is what gets saved. Synchronous: +/// the process is about to end. +pub fn run_exit_backup(app: &AppHandle) { + let config = crate::transport::desktop::config::load_config_internal(app); + if backup_mode(&config) == "onClose" { + // Bound the backup so a hung network operation can never prevent the + // process from exiting. + tauri::async_runtime::block_on(async { + if tokio::time::timeout( + std::time::Duration::from_secs(30), + run_and_log(app, "on close"), + ) + .await + .is_err() + { + log::error!("Exit backup timed out after 30s, exiting without it"); + } + }); + } +} + +/// Background task started at app launch. In on-launch mode it writes one +/// backup right away; in interval mode it checks periodically whether a +/// backup is due. Config is re-read on every tick so settings changes apply +/// without a restart (a switch to on-launch only takes effect at the next +/// start, like the mode's name says). +pub fn spawn_scheduler(app: AppHandle) { + crate::async_rt::spawn(async move { + if backup_mode(&crate::transport::desktop::config::load_config_internal( + &app, + )) == "onLaunch" + { + run_and_log(&app, "on launch").await; + } + // Wake up every minute but only run the (possibly network-touching) + // due-check at the tick cadence, so interval changes in the settings + // take effect within a minute without hammering a WebDAV target. + let mut last_check = std::time::Instant::now(); + loop { + tokio::time::sleep(std::time::Duration::from_secs(60)).await; + let interval = crate::transport::desktop::config::load_config_internal(&app) + .backup_interval_minutes + .unwrap_or(DEFAULT_INTERVAL_MINUTES); + if last_check.elapsed().as_secs() >= scheduler_tick_secs(interval) { + last_check = std::time::Instant::now(); + run_if_due(&app).await; + } + } + }); +} + +#[tauri::command] +pub async fn get_connections_backup_status( + app: AppHandle, +) -> Result { + backup_status(app.state::().inner()).await +} + +#[tauri::command] +pub async fn set_connections_backup_password( + app: AppHandle, + password: String, +) -> Result<(), String> { + set_backup_password(app.state::().inner(), &password) +} + +/// Stores (or clears, with an empty password) the credential of one backup +/// target, keyed by its id (e.g. `"webdav"`). +#[tauri::command] +pub async fn set_connections_backup_target_password( + app: AppHandle, + target_id: String, + password: String, +) -> Result<(), String> { + set_backup_target_password(app.state::().inner(), &target_id, &password) +} + +#[tauri::command] +pub async fn run_connections_backup( + app: AppHandle, +) -> Result { + crate::application::connection_files::execute( + &app.state::(), + &app.state::>(), + None, + crate::application::connection_files::ConnectionFilesCommand::RunBackup, + ) + .await +} diff --git a/src-tauri/src/transport/desktop/chatgpt.rs b/src-tauri/src/transport/desktop/chatgpt.rs new file mode 100644 index 000000000..ae221764f --- /dev/null +++ b/src-tauri/src/transport/desktop/chatgpt.rs @@ -0,0 +1,74 @@ +pub mod auth; + +use crate::chatgpt::storage::session; +use crate::chatgpt::*; +use tokio::sync::oneshot; + +#[tauri::command] +pub async fn sign_in_chatgpt( + app: tauri::AppHandle, + profile_id: Option, +) -> Result { + let _sign_in = SIGN_IN_LOCK + .try_lock() + .map_err(|_| "Another ChatGPT sign-in is running.")?; + let (cancel, cancelled) = oneshot::channel(); + *SIGN_IN_CANCEL + .lock() + .map_err(|_| "ChatGPT sign-in lock is unavailable.")? = Some(cancel); + let attempt = async { + let state = { + let _guard = SESSION_LOCK.lock().await; + let disk = storage::LockedStore::open()?; + let state = disk.load()?; + // Persist the installation ID before opening the browser. + disk.save(&state)?; + state + }; + auth::sign_in(&app, state, profile_id.as_deref()).await + }; + let result = tokio::select! { + result = tokio::time::timeout(std::time::Duration::from_secs(300), attempt) => { + result.map_err(|_| "ChatGPT sign-in timed out. Please try again.".to_string()).and_then(|r| r) + } + _ = cancelled => Err("ChatGPT sign-in cancelled.".to_string()), + }; + SIGN_IN_CANCEL + .lock() + .map_err(|_| "ChatGPT sign-in lock is unavailable.")? + .take(); + Ok(session(&result?)) +} + +#[tauri::command] +pub fn open_chatgpt_usage(app: tauri::AppHandle) -> Result<(), String> { + use tauri_plugin_opener::OpenerExt; + app.opener() + .open_url("https://chatgpt.com/#settings/Usage", None::<&str>) + .map_err(|_| "Could not open ChatGPT usage settings.".into()) +} + +#[tauri::command] +pub async fn get_chatgpt_session() -> Result { + crate::chatgpt::get_chatgpt_session().await +} + +#[tauri::command] +pub fn cancel_chatgpt_sign_in() { + crate::chatgpt::cancel_chatgpt_sign_in() +} + +#[tauri::command] +pub async fn select_chatgpt_profile(profile_id: String) -> Result { + crate::chatgpt::select_chatgpt_profile(profile_id).await +} + +#[tauri::command] +pub async fn sign_out_chatgpt(profile_id: String) -> Result, String> { + crate::chatgpt::sign_out_chatgpt(profile_id).await +} + +#[tauri::command] +pub async fn get_chatgpt_models() -> Result, String> { + crate::chatgpt::get_chatgpt_models().await +} diff --git a/src-tauri/src/transport/desktop/chatgpt/auth.rs b/src-tauri/src/transport/desktop/chatgpt/auth.rs new file mode 100644 index 000000000..d79f0e5eb --- /dev/null +++ b/src-tauri/src/transport/desktop/chatgpt/auth.rs @@ -0,0 +1,140 @@ +use crate::chatgpt::auth::*; +use crate::chatgpt::{ + protocol::{self}, + storage::{LockedStore, Store}, + ISSUER, RESOURCE, +}; +use serde_json::Value; +use tokio::net::TcpListener; + +pub(super) async fn sign_in( + app: &tauri::AppHandle, + store: Store, + profile_id: Option<&str>, +) -> Result { + use tauri_plugin_opener::OpenerExt; + let existing = profile_id + .map(|id| { + store + .profiles + .iter() + .find(|p| p.id == id) + .cloned() + .ok_or("ChatGPT account not found.") + }) + .transpose()?; + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .map_err(|_| "Could not start the local ChatGPT callback listener.")?; + let redirect_uri = format!( + "http://127.0.0.1:{}/auth/callback", + listener + .local_addr() + .map_err(|_| "Could not read callback port.")? + .port() + ); + let state = protocol::random()?; + let nonce = protocol::random()?; + let verifier = protocol::random()?; + let challenge = protocol::challenge(&verifier); + let client_id = existing + .as_ref() + .map(|p| p.client_id.as_str()) + .unwrap_or("dynamic_agent_client"); + let mut url = url::Url::parse(&format!("{ISSUER}/api/accounts/authorize")) + .map_err(|_| "Invalid ChatGPT authorization endpoint.")?; + url.query_pairs_mut().extend_pairs([ + ("client_id", client_id), + ("ext_agent_host_id", &store.host_id), + ("response_type", "code"), + ("redirect_uri", &redirect_uri), + ( + "scope", + "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct", + ), + ("resource", RESOURCE), + ("state", &state), + ("nonce", &nonce), + ("code_challenge_method", "S256"), + ("code_challenge", &challenge), + ]); + if let Some(profile) = &existing { + if let Some(tokens) = &profile.tokens { + url.query_pairs_mut() + .append_pair("id_token_hint", &tokens.id_token); + } + if let Some(email) = &profile.email { + url.query_pairs_mut().append_pair("login_hint", email); + } + } else { + url.query_pairs_mut() + .append_pair("agent_name_hint", "Tabularis"); + } + // Never include the authorization URL in errors or logs: it may contain an ID token. + app.opener() + .open_url(url.as_str(), None::<&str>) + .map_err(|_| "Could not open the browser for ChatGPT sign-in.")?; + let callback = callback( + &listener, + &state, + existing.as_ref().map(|p| p.client_id.as_str()), + ) + .await?; + let target_profile_id = { + let _guard = crate::chatgpt::SESSION_LOCK.lock().await; + let disk = LockedStore::open()?; + let mut current = disk.load()?; + if current.host_id != store.host_id { + return Err("ChatGPT installation changed during sign-in. Please try again.".into()); + } + let id = register_profile(&mut current, existing.as_ref(), &callback)?; + // Retain the issued registration even when code exchange fails or is cancelled. + disk.save(¤t)?; + id + }; + let response = token_request(&[ + ("grant_type", "authorization_code"), + ("client_id", &callback.client_id), + ("code", &callback.code), + ("code_verifier", &verifier), + ("redirect_uri", &redirect_uri), + ("resource", RESOURCE), + ]) + .await?; + let tokens = response.tokens(None)?; + let response = crate::chatgpt::http_client()? + .get(format!("{ISSUER}/.well-known/jwks.json")) + .timeout(std::time::Duration::from_secs(30)) + .send() + .await + .map_err(|_| "Could not retrieve ChatGPT identity verification keys.")?; + if !response.status().is_success() { + return Err("Could not retrieve ChatGPT identity verification keys.".into()); + } + let keys: Value = response + .json() + .await + .map_err(|_| "Invalid ChatGPT identity verification keys.")?; + let identity = protocol::verify_identity( + &tokens.id_token, + &keys, + &callback.client_id, + &nonce, + protocol::now(), + )?; + let _guard = crate::chatgpt::SESSION_LOCK.lock().await; + let disk = LockedStore::open()?; + let mut current = disk.load()?; + if current.host_id != store.host_id { + return Err("ChatGPT installation changed during sign-in. Please try again.".into()); + } + complete_sign_in( + &mut current, + &target_profile_id, + &callback.client_id, + identity, + tokens, + )?; + disk.save(¤t)?; + Ok(current) +} diff --git a/src-tauri/src/transport/desktop/clipboard_import.rs b/src-tauri/src/transport/desktop/clipboard_import.rs new file mode 100644 index 000000000..f9586d799 --- /dev/null +++ b/src-tauri/src/transport/desktop/clipboard_import.rs @@ -0,0 +1,10 @@ +use crate::clipboard_import::*; +use tauri::{AppHandle, Manager, Runtime}; + +#[tauri::command] +pub async fn execute_clipboard_import( + app: AppHandle, + req: ClipboardImportRequest, +) -> Result { + import_with_runtime(&app.state::(), None, req).await +} diff --git a/src-tauri/src/transport/desktop/commands.rs b/src-tauri/src/transport/desktop/commands.rs new file mode 100644 index 000000000..c60a4491e --- /dev/null +++ b/src-tauri/src/transport/desktop/commands.rs @@ -0,0 +1,2507 @@ +use crate::commands::*; +use crate::credential_cache; +use crate::keychain_utils; +use crate::models::{ + BatchStatementResult, ColumnDefinition, ConnectionParams, ExplainQueryOutput, ExportPayload, + ForeignKey, Index, K8sConnection, K8sConnectionInput, QueryResult, RoutineInfo, + RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, SshTestParams, + TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, +}; +use crate::persistence; +use std::collections::HashMap; +use std::fs; +use std::path::PathBuf; +use tauri::{AppHandle, Manager, Runtime, State}; +use uuid::Uuid; + +#[tauri::command] +pub async fn get_connection_metadata( + app: AppHandle, + connection_id: String, +) -> Result, String> { + crate::application::metadata::get_connection_metadata( + &app.state::(), + None, + &connection_id, + ) + .await +} + +pub async fn expand_ssh_connection_params( + app: &AppHandle, + params: &ConnectionParams, +) -> Result { + crate::application::tunnels::expand_connection_params( + &app.state::(), + params, + ) +} + +async fn execute_connection_command( + app: &AppHandle, + command: crate::application::connections::ConnectionCommand, +) -> Result { + crate::application::connections::execute( + &app.state::(), + &app.state::>(), + command, + ) + .await +} + +#[tauri::command] +pub async fn get_connections(app: AppHandle) -> Result { + migrate_ssh_connections(&app).await.ok(); + migrate_postgres_ssl_mode_spelling(&app).await.ok(); + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnections, + ) + .await +} + +#[tauri::command] +pub async fn get_connections_with_groups( + app: AppHandle, +) -> Result { + migrate_ssh_connections(&app).await.ok(); + migrate_postgres_ssl_mode_spelling(&app).await.ok(); + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnectionsWithGroups, + ) + .await +} + +#[tauri::command] +pub async fn save_connection( + app: AppHandle, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SaveConnection { + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + }, + ) + .await +} + +#[tauri::command] +pub async fn update_connection( + app: AppHandle, + id: String, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnection { + id, + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + }, + ) + .await +} + +#[tauri::command] +pub async fn duplicate_connection( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DuplicateConnection { id }, + ) + .await +} + +#[tauri::command] +pub async fn delete_connection( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnection { id }, + ) + .await +} + +#[tauri::command] +pub async fn test_connection( + app: AppHandle, + request: TestConnectionRequest, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::TestConnection { request }, + ) + .await +} + +#[tauri::command] +pub async fn list_databases( + app: AppHandle, + request: TestConnectionRequest, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ListDatabases { request }, + ) + .await +} + +#[tauri::command] +pub async fn get_connection_groups( + app: AppHandle, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::GetConnectionGroups, + ) + .await +} + +#[tauri::command] +pub async fn create_connection_group( + app: AppHandle, + name: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateConnectionGroup { + name, + parent_id, + }, + ) + .await +} + +#[tauri::command] +pub async fn create_group_path( + app: AppHandle, + path: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateGroupPath { path, parent_id }, + ) + .await +} + +#[tauri::command] +pub async fn update_connection_group( + app: AppHandle, + id: String, + name: Option, + collapsed: Option, + sort_order: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnectionGroup { + id, + name, + collapsed, + sort_order, + }, + ) + .await +} + +#[tauri::command] +pub async fn move_group_to_parent( + app: AppHandle, + id: String, + parent_id: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::MoveGroupToParent { id, parent_id }, + ) + .await +} + +#[tauri::command] +pub async fn delete_connection_group( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionGroup { id }, + ) + .await +} + +#[tauri::command] +pub async fn move_connection_to_group( + app: AppHandle, + connection_id: String, + group_id: Option, + sort_order: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::MoveConnectionToGroup { + connection_id, + group_id, + sort_order, + }, + ) + .await +} + +#[tauri::command] +pub async fn reorder_groups( + app: AppHandle, + group_orders: Vec<(String, i32)>, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ReorderGroups { group_orders }, + ) + .await +} + +#[tauri::command] +pub async fn reorder_connections_in_group( + app: AppHandle, + connection_orders: Vec<(String, i32)>, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ReorderConnectionsInGroup { + connection_orders, + }, + ) + .await +} + +#[tauri::command] +pub async fn set_connection_appearance( + app: AppHandle, + id: String, + appearance: Option, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SetConnectionAppearance { + id, + appearance, + }, + ) + .await +} + +#[tauri::command] +pub async fn list_connection_tags( + app: AppHandle, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::ListConnectionTags, + ) + .await +} + +#[tauri::command] +pub async fn create_connection_tag( + app: AppHandle, + name: String, + color: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateConnectionTag { name, color }, + ) + .await +} + +#[tauri::command] +pub async fn update_connection_tag( + app: AppHandle, + id: String, + name: String, + color: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::UpdateConnectionTag { id, name, color }, + ) + .await +} + +#[tauri::command] +pub async fn delete_connection_tag( + app: AppHandle, + id: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionTag { id }, + ) + .await +} + +#[tauri::command] +pub async fn set_connection_tags( + app: AppHandle, + connection_id: String, + tag_ids: Vec, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::SetConnectionTags { + connection_id, + tag_ids, + }, + ) + .await +} + +#[tauri::command] +pub async fn delete_connection_icon( + app: AppHandle, + relative_path: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::DeleteConnectionIcon { relative_path }, + ) + .await +} + +#[tauri::command] +pub async fn create_sqlite_database( + app: AppHandle, + path: String, +) -> Result { + execute_connection_command( + &app, + crate::application::connections::ConnectionCommand::CreateSqliteDatabase { path }, + ) + .await +} + +pub fn get_config_path(_app: &AppHandle) -> Result { + let config_dir = crate::paths::get_app_config_dir(); + if !config_dir.exists() { + fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; + } + Ok(crate::paths::resolve_connections_path(&config_dir)) +} + +pub fn get_ssh_config_path(_app: &AppHandle) -> Result { + let config_dir = crate::paths::get_app_config_dir(); + if !config_dir.exists() { + fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; + } + Ok(config_dir.join("ssh_connections.json")) +} + +/// Saved connection as stored, without any keychain secret. +fn lookup_saved_connection( + app: &AppHandle, + id: &str, +) -> Result { + let conn_cache = app.state::>(); + + let conn = match conn_cache.lookup(id) { + crate::connection_cache::CacheLookup::Hit(c) => c, + crate::connection_cache::CacheLookup::Miss => { + return Err("Connection not found".to_string()) + } + crate::connection_cache::CacheLookup::Cold => { + let path = get_config_path(app)?; + let conn_file = persistence::load_connections_file(&path).unwrap_or_default(); + conn_cache.populate(&conn_file.connections); + conn_file + .connections + .into_iter() + .find(|c| c.id == id) + .ok_or_else(|| "Connection not found".to_string())? + } + }; + Ok(conn) +} + +/// Load a saved connection with its host-owned credentials (keychain password, +/// SSH secrets, connection URI) but without plugin-owned secrets. Used by the +/// edit modal and by the Test Connection / Load Databases flows, which resolve +/// plugin secrets themselves once the pending changes are known. +pub fn find_connection_metadata_by_id( + app: &AppHandle, + id: &str, +) -> Result { + let mut conn = lookup_saved_connection(app, id)?; + + let cache = app.state::>(); + restore_runtime_connection_uri(&cache, &conn.id, &mut conn.params)?; + + // Load passwords from keychain via the in-memory cache (warm hit = lookup, + // cold miss = keychain call + cache). Skip IAM-auth connections: their + // 15-min tokens must come from the `password` field, never the keychain, + // so a stale token from an older release can't be surfaced in the modal. + if conn.params.save_in_keychain.unwrap_or(false) && !conn.params.use_iam_auth.unwrap_or(false) { + match credential_cache::get_db_password_cached(&cache, &conn.id) { + Ok(pwd) => conn.params.password = Some(pwd), + Err(e) => eprintln!( + "[Keyring Error] Failed to get DB password for {}: {}", + conn.id, e + ), + } + if conn.params.ssh_enabled.unwrap_or(false) { + if let Ok(ssh_pwd) = credential_cache::get_ssh_password_cached(&cache, &conn.id) { + if !ssh_pwd.trim().is_empty() { + conn.params.ssh_password = Some(ssh_pwd); + } + } + if let Ok(ssh_passphrase) = + credential_cache::get_ssh_key_passphrase_cached(&cache, &conn.id) + { + if !ssh_passphrase.trim().is_empty() { + conn.params.ssh_key_passphrase = Some(ssh_passphrase); + } + } + } + } + + Ok(conn) +} + +/// Load a connection for driver execution. Unlike the metadata/edit path, +/// this resolves plugin-owned secrets into `params.extra` only in memory. +pub fn find_connection_by_id( + app: &AppHandle, + id: &str, +) -> Result { + let mut conn = find_connection_metadata_by_id(app, id)?; + let cache = app.state::>(); + crate::plugin_secrets::hydrate_connection(&cache, &mut conn); + Ok(conn) +} + +pub(crate) fn save_connections_and_invalidate( + app: &AppHandle, + path: &std::path::Path, + file: &crate::models::ConnectionsFile, +) -> Result<(), String> { + persistence::save_connections_file(path, file)?; + app.state::>() + .invalidate(); + Ok(()) +} + +#[tauri::command] +pub async fn get_connection_by_id( + app: AppHandle, + id: String, +) -> Result { + find_connection_metadata_by_id(&app, &id) +} + +#[tauri::command] +pub async fn get_schemas( + app: AppHandle, + connection_id: String, + database: Option, +) -> Result, String> { + crate::application::metadata::get_schemas( + &app.state::(), + None, + &connection_id, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_available_databases( + app: AppHandle, + connection_id: String, +) -> Result, String> { + crate::application::metadata::get_available_databases( + &app.state::(), + None, + &connection_id, + ) + .await +} + +#[tauri::command] +pub async fn set_selected_databases( + app: AppHandle, + connection_id: String, + databases: Vec, +) -> Result<(), String> { + crate::application::connections::set_selected_databases( + &app.state::(), + &connection_id, + databases, + ) + .await?; + app.state::>() + .invalidate(); + Ok(()) +} + +#[tauri::command] +pub async fn get_routines( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_routines( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_routine_parameters( + app: AppHandle, + connection_id: String, + routine_name: String, + schema: Option, + database: Option, + /* The signature of the overload the user clicked, where the dialect has them (#893) */ + identity_args: Option, +) -> Result, String> { + crate::application::database_objects::get_routine_parameters( + &app.state::(), + None, + &connection_id, + routine_name, + schema, + database, + identity_args, + ) + .await +} + +#[tauri::command] +pub async fn get_routine_definition( + app: AppHandle, + connection_id: String, + routine_name: String, + routine_type: String, // "PROCEDURE" or "FUNCTION" - mainly for MySQL SHOW CREATE + schema: Option, + database: Option, + identity_args: Option, +) -> Result { + crate::application::database_objects::get_routine_definition( + &app.state::(), + None, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await +} + +/// Preview generation only; the returned SQL is never executed here. +#[tauri::command] +pub async fn get_table_query_template( + app: AppHandle, + connection_id: String, + request: crate::models::TableQueryTemplateRequest, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_table_query_template( + &app.state::(), + None, + &connection_id, + request, + database, + ) + .await +} + +/// Column statistics through the optional plugin RPC (issue #1137). `None` +/// means the driver doesn't provide them; the frontend then falls back to its +/// generic SQL or hides the entry. +#[tauri::command] +pub async fn get_column_stats( + app: AppHandle, + connection_id: String, + request: crate::models::ColumnStatsRequest, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_column_stats( + &app.state::(), + None, + &connection_id, + request, + database, + ) + .await +} + +#[tauri::command] +pub async fn build_routine_call_sql( + app: AppHandle, + connection_id: String, + routine_name: String, + routine_type: String, + args: Vec, + schema: Option, +) -> Result { + crate::application::database_objects::build_routine_call_sql( + &app.state::(), + None, + &connection_id, + routine_name, + routine_type, + args, + schema, + ) + .await +} + +#[tauri::command] +pub async fn get_routine_create_template( + app: AppHandle, + connection_id: String, + routine_type: String, + schema: Option, + database: Option, +) -> Result { + crate::application::database_objects::get_routine_create_template( + &app.state::(), + &connection_id, + routine_type, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_routine_edit_script( + app: AppHandle, + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result { + crate::application::database_objects::get_routine_edit_script( + &app.state::(), + None, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await +} + +#[tauri::command] +pub async fn drop_routine( + app: AppHandle, + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result<(), String> { + crate::application::database_objects::drop_routine( + &app.state::(), + None, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await +} + +#[tauri::command] +pub async fn get_schema_snapshot( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_schema_snapshot( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +/// Migrates old embedded SSH connections to separate SSH connection entries +async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), String> { + let conn_path = get_config_path(app)?; + if !conn_path.exists() { + return Ok(()); // Nothing to migrate + } + + // Load connections using persistence (handles both old and new formats) + let mut conn_file = persistence::load_connections_file(&conn_path)?; + let connections = &conn_file.connections; + + // Check if any connections have old embedded SSH params + let needs_migration = connections + .iter() + .any(|c| c.params.ssh_enabled.unwrap_or(false) && c.params.ssh_connection_id.is_none()); + + if !needs_migration { + return Ok(()); // No migration needed + } + + eprintln!("[Migration] Starting SSH connections migration..."); + + let ssh_path = get_ssh_config_path(app)?; + let mut ssh_connections: Vec = if ssh_path.exists() { + let ssh_content = fs::read_to_string(&ssh_path).map_err(|e| e.to_string())?; + serde_json::from_str(&ssh_content).unwrap_or_default() + } else { + Vec::new() + }; + + let mut migrated_connections = Vec::new(); + let mut ssh_connection_map: HashMap = HashMap::new(); // (ssh_key -> ssh_id) + + for mut conn in conn_file.connections.clone() { + if conn.params.ssh_enabled.unwrap_or(false) && conn.params.ssh_connection_id.is_none() { + // Extract SSH params + if let (Some(host), Some(user)) = (&conn.params.ssh_host, &conn.params.ssh_user) { + let port = conn.params.ssh_port.unwrap_or(22); + let key_file = conn.params.ssh_key_file.clone().unwrap_or_default(); + + // Create unique key for this SSH config + let ssh_key = format!("{}:{}:{}:{}", host, port, user, key_file); + + // Check if we already created an SSH connection for this config + let ssh_id = if let Some(existing_id) = ssh_connection_map.get(&ssh_key) { + existing_id.clone() + } else { + // Create new SSH connection + let new_ssh_id = Uuid::new_v4().to_string(); + let ssh_name = format!("{}@{}", user, host); + + // Migrate credentials from connection keychain to SSH keychain + if conn.params.save_in_keychain.unwrap_or(false) { + if let Ok(ssh_pwd) = keychain_utils::get_ssh_password(&conn.id, &conn.name) + { + if !ssh_pwd.trim().is_empty() { + keychain_utils::set_ssh_password(&new_ssh_id, &ssh_pwd).ok(); + } + } + if let Ok(ssh_pass) = + keychain_utils::get_ssh_key_passphrase(&conn.id, &conn.name) + { + if !ssh_pass.trim().is_empty() { + keychain_utils::set_ssh_key_passphrase(&new_ssh_id, &ssh_pass).ok(); + } + } + } + + let new_ssh_conn = SshConnection { + id: new_ssh_id.clone(), + name: ssh_name, + host: host.clone(), + port, + user: user.clone(), + auth_type: Some(if !key_file.is_empty() { + "ssh_key".to_string() + } else { + "password".to_string() + }), + password: None, + key_file: if key_file.is_empty() { + None + } else { + Some(key_file.clone()) + }, + key_passphrase: None, + allow_passphrase_prompt: None, + save_in_keychain: conn.params.save_in_keychain, + }; + + ssh_connections.push(new_ssh_conn); + ssh_connection_map.insert(ssh_key, new_ssh_id.clone()); + new_ssh_id + }; + + // Update connection to reference the SSH connection + conn.params.ssh_connection_id = Some(ssh_id); + // Clear old embedded SSH params + conn.params.ssh_host = None; + conn.params.ssh_port = None; + conn.params.ssh_user = None; + conn.params.ssh_password = None; + conn.params.ssh_key_file = None; + conn.params.ssh_key_passphrase = None; + } + } + + migrated_connections.push(conn); + } + + // Save migrated SSH connections + let ssh_json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; + persistence::write_private_file(&ssh_path, ssh_json)?; + + // Save migrated connections using new format (preserving groups) + conn_file.connections = migrated_connections; + save_connections_and_invalidate(app, &conn_path, &conn_file)?; + + eprintln!( + "[Migration] Successfully migrated {} SSH connections", + ssh_connections.len() + ); + Ok(()) +} + +/// Migrates already-persisted `ssl_mode` values on postgres-dialect +/// connections (driver id other than the builtin `"postgres"`) from the +/// stale MySQL-style spelling to the Postgres-style spelling the plugin +/// actually understands. Idempotent — a no-op once every affected +/// connection has been rewritten. See +/// `connection_migrations::migrate_postgres_ssl_mode_spelling_at_path` for +/// the full rationale, including the concurrency guard against a race with +/// the `--mcp` process's own call to the same function. +async fn migrate_postgres_ssl_mode_spelling(app: &AppHandle) -> Result<(), String> { + let conn_path = get_config_path(app)?; + let migrated = + crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path(&conn_path) + .await?; + if migrated { + app.state::>() + .invalidate(); + } + Ok(()) +} + +#[tauri::command] +pub async fn get_ssh_connections( + app: AppHandle, +) -> Result, String> { + crate::application::tunnels::get_ssh_connections( + &app.state::(), + true, + ) +} + +#[tauri::command] +pub async fn save_ssh_connection( + app: AppHandle, + name: String, + ssh: SshConnectionInput, +) -> Result { + crate::application::tunnels::save_ssh_connection( + &app.state::(), + name, + ssh, + true, + ) +} + +#[tauri::command] +pub async fn update_ssh_connection( + app: AppHandle, + id: String, + name: String, + ssh: SshConnectionInput, +) -> Result { + crate::application::tunnels::update_ssh_connection( + &app.state::(), + id, + name, + ssh, + true, + ) +} + +#[tauri::command] +pub async fn delete_ssh_connection( + app: AppHandle, + id: String, +) -> Result<(), String> { + crate::application::tunnels::delete_ssh_connection( + &app.state::(), + &id, + ) +} + +#[tauri::command] +pub async fn test_ssh_connection( + app: AppHandle, + ssh: SshTestParams, +) -> Result { + crate::application::tunnels::test_ssh_connection( + &app.state::(), + ssh, + None, + ) + .await +} + +#[tauri::command] +pub async fn get_k8s_connections( + app: AppHandle, +) -> Result, String> { + crate::application::tunnels::get_k8s_connections(&app.state::()) +} + +#[tauri::command] +pub async fn save_k8s_connection( + app: AppHandle, + k8s: K8sConnectionInput, +) -> Result { + crate::application::tunnels::save_k8s_connection( + &app.state::(), + k8s, + ) +} + +#[tauri::command] +pub async fn update_k8s_connection( + app: AppHandle, + id: String, + k8s: K8sConnectionInput, +) -> Result { + crate::application::tunnels::update_k8s_connection( + &app.state::(), + id, + k8s, + ) +} + +#[tauri::command] +pub async fn delete_k8s_connection( + app: AppHandle, + id: String, +) -> Result<(), String> { + crate::application::tunnels::delete_k8s_connection( + &app.state::(), + &id, + ) +} + +async fn execute_tunnel_command( + app: &AppHandle, + command: crate::application::tunnels::TunnelCommand, +) -> Result { + crate::application::tunnels::execute( + &app.state::(), + None, + command, + ) + .await +} + +#[tauri::command] +pub async fn test_k8s_connection_cmd( + app: AppHandle, + context: String, + namespace: String, + kubectl_path: Option, + kubeconfig_path: Option, +) -> Result { + let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::TestK8sConnection { + context, + namespace, + options, + }, + ) + .await +} + +#[tauri::command] +pub async fn get_k8s_contexts_cmd( + app: AppHandle, + kubectl_path: Option, + kubeconfig_path: Option, +) -> Result { + let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sContexts { options }, + ) + .await +} + +#[tauri::command] +pub async fn get_k8s_namespaces_cmd( + app: AppHandle, + context: String, + kubectl_path: Option, + kubeconfig_path: Option, +) -> Result { + let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sNamespaces { context, options }, + ) + .await +} + +#[tauri::command] +pub async fn get_k8s_resources_cmd( + app: AppHandle, + context: String, + namespace: String, + resource_type: String, + kubectl_path: Option, + kubeconfig_path: Option, +) -> Result { + let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sResources { + context, + namespace, + resource_type, + options, + }, + ) + .await +} + +#[tauri::command] +pub async fn get_k8s_resource_ports_cmd( + app: AppHandle, + context: String, + namespace: String, + resource_type: String, + resource_name: String, + kubectl_path: Option, + kubeconfig_path: Option, +) -> Result { + let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::GetK8sResourcePorts { + context, + namespace, + resource_type, + resource_name, + options, + }, + ) + .await +} + +#[tauri::command] +pub async fn validate_k8s_path_cmd( + app: AppHandle, + path: String, + kind: String, +) -> Result { + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::ValidateK8sPath { path, kind }, + ) + .await +} + +#[tauri::command] +pub async fn test_ssm_connection_cmd( + app: AppHandle, + target: String, + profile: Option, + region: Option, + host: String, + port: u16, +) -> Result { + execute_tunnel_command( + &app, + crate::application::tunnels::TunnelCommand::TestSsmConnection { + target, + profile, + region, + host, + port, + }, + ) + .await +} + +/// Expand K8s connection params by loading saved config and creating/reusing a tunnel. +pub async fn expand_k8s_connection_params( + app: &AppHandle, + params: &ConnectionParams, +) -> Result { + let runtime = app.state::(); + let expanded = crate::application::tunnels::expand_connection_params(&runtime, params)?; + if !expanded.k8s_enabled.unwrap_or(false) { + return Ok(expanded); + } + crate::application::tunnels::resolve_expanded_connection_params(&expanded, None) +} + +#[tauri::command] +pub async fn get_tables( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_tables( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_columns( + app: AppHandle, + connection_id: String, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_columns( + &app.state::(), + None, + &connection_id, + table_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_foreign_keys( + app: AppHandle, + connection_id: String, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_foreign_keys( + &app.state::(), + None, + &connection_id, + table_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_indexes( + app: AppHandle, + connection_id: String, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_indexes( + &app.state::(), + None, + &connection_id, + table_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn delete_record( + app: AppHandle, + connection_id: String, + table: String, + pk_map: std::collections::HashMap, + schema: Option, + database: Option, +) -> Result { + crate::application::records::delete_record( + &app.state::(), + None, + &connection_id, + table, + pk_map, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn update_record( + app: AppHandle, + connection_id: String, + table: String, + pk_map: std::collections::HashMap, + col_name: String, + new_val: serde_json::Value, + schema: Option, + database: Option, +) -> Result { + crate::application::records::update_record( + &app.state::(), + None, + &connection_id, + table, + pk_map, + col_name, + new_val, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn save_blob_to_file( + app: AppHandle, + connection_id: String, + table: String, + col_name: String, + pk_map: std::collections::HashMap, + file_path: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let saved_conn = find_connection_by_id(&app, &connection_id)?; + let expanded_params = expand_ssh_connection_params(&app, &saved_conn.params).await?; + let expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; + let mut params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; + if let Some(db) = database.filter(|d| !d.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(db); + } + let drv = driver_for_params(¶ms).await?; + drv.save_blob_to_file( + ¶ms, + &table, + &col_name, + &pk_map, + schema.as_deref(), + &file_path, + ) + .await +} + +#[tauri::command] +pub async fn fetch_blob( + app: AppHandle, + connection_id: String, + table: String, + col_name: String, + pk_map: std::collections::HashMap, + schema: Option, + database: Option, +) -> Result { + crate::application::records::fetch_blob( + &app.state::(), + None, + &connection_id, + table, + col_name, + pk_map, + schema, + database, + crate::application::records::BlobFetchPolicy::Inline, + ) + .await +} + +/// Fetches a BLOB column from the database and returns it as a data: URL for image preview. +/// Same query logic as save_blob_to_file but returns the data in-memory instead of writing to disk. +#[tauri::command] +pub async fn fetch_blob_as_data_url( + app: AppHandle, + connection_id: String, + table: String, + col_name: String, + pk_map: std::collections::HashMap, + schema: Option, + database: Option, +) -> Result { + crate::application::records::fetch_blob_as_data_url( + &app.state::(), + None, + &connection_id, + table, + col_name, + pk_map, + schema, + database, + ) + .await +} + +/// Prepares a file for BLOB upload by returning only metadata and a file reference. +/// The actual file content is NOT transferred over IPC, avoiding massive string allocations. +/// The file content will be read directly from disk when needed (e.g., during INSERT/UPDATE). +/// Returns a special "BLOB_FILE_REF" format that includes file path, size, and MIME type. +#[tauri::command] +pub async fn load_blob_from_file( + app: AppHandle, + file_path: String, +) -> Result { + use std::io::Read; + + // Read max_blob_size from configuration + let max_blob_size = crate::transport::desktop::config::get_max_blob_size(&app); + + tokio::task::spawn_blocking(move || -> Result { + let mut file = std::fs::File::open(&file_path) + .map_err(|e| format!("Failed to open file: {}", e))?; + + // Get file size + let metadata = file.metadata() + .map_err(|e| format!("Failed to get file metadata: {}", e))?; + let file_size = metadata.len(); + + // Validate file size against maximum allowed + if file_size > max_blob_size { + return Err(format!( + "File size ({} bytes / {:.2}MB) exceeds maximum allowed size ({} bytes / {}MB). Please choose a smaller file.", + file_size, + file_size as f64 / (1024.0 * 1024.0), + max_blob_size, + max_blob_size / (1024 * 1024) + )); + } + + // Read first chunk for MIME detection (only 8KB) + let header_size = std::cmp::min(8192, file_size as usize); + let mut header = vec![0u8; header_size]; + file.read_exact(&mut header) + .map_err(|e| format!("Failed to read file header: {}", e))?; + + // Detect MIME type + let mime = infer::get(&header) + .map(|k| k.mime_type()) + .unwrap_or("application/octet-stream"); + + // Return a file reference instead of actual content + // Format: "BLOB_FILE_REF:::" + Ok(format!("BLOB_FILE_REF:{}:{}:{}", file_size, mime, file_path)) + }) + .await + .map_err(|e| format!("Task join error: {}", e))? +} + +#[tauri::command] +pub async fn insert_record( + app: AppHandle, + connection_id: String, + table: String, + data: std::collections::HashMap, + schema: Option, + database: Option, +) -> Result { + crate::application::records::insert_record( + &app.state::(), + None, + &connection_id, + table, + data, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn cancel_query( + state: State<'_, std::sync::Arc>, + connection_id: String, +) -> Result<(), String> { + crate::application::queries::cancel_query(&state, None, &connection_id, None) +} + +#[tauri::command] +pub async fn execute_query( + app: AppHandle, + state: State<'_, std::sync::Arc>, + connection_id: String, + query: String, + limit: Option, + page: Option, + schema: Option, + database: Option, + session_id: Option, +) -> Result { + crate::application::queries::execute_query( + &app.state::(), + &state, + crate::application::queries::QueryRequestScope::DESKTOP, + crate::application::queries::QueryResponsePolicy::Unbounded, + connection_id, + query, + limit, + page, + schema, + session_id, + database, + ) + .await +} + +pub(crate) async fn release_connection_sessions( + app: &AppHandle, + connection_id: &str, + _params: Option<&ConnectionParams>, +) { + crate::application::query_sessions::release_connection( + &app.state::(), + None, + connection_id, + ) + .await; +} + +#[tauri::command] +pub async fn release_query_session( + app: AppHandle, + connection_id: String, + session_id: String, +) -> Result<(), String> { + crate::application::query_sessions::release( + &app.state::(), + None, + &connection_id, + &session_id, + ) + .await +} + +/// Runs a sequence of statements that share a single physical database +/// connection. Use this — not multiple parallel `execute_query` calls — +/// whenever statements depend on connection-local session state +/// (`SET @var`, `LAST_INSERT_ID()` / `LASTVAL()`, `BEGIN`/`COMMIT`, +/// `TEMPORARY TABLE`, `PREPARE`/`EXECUTE`, `SET FOREIGN_KEY_CHECKS = 0`). +/// +/// The whole batch shares one cancellation handle so `cancel_query` +/// aborts the entire batch atomically. +/// +/// When `batch_id` is supplied, a `batch-statement-complete` event is emitted +/// after each statement so the UI updates result tabs progressively. The full +/// `Vec` is still returned at the end for final reconciliation / fallback. +#[tauri::command] +pub async fn execute_query_batch( + app: AppHandle, + state: State<'_, std::sync::Arc>, + connection_id: String, + queries: Vec, + limit: Option, + page: Option, + schema: Option, + database: Option, + batch_id: Option, + session_id: Option, +) -> Result, String> { + crate::application::queries::execute_query_batch( + &app.state::(), + &state, + crate::application::queries::QueryRequestScope::DESKTOP, + crate::application::queries::QueryResponsePolicy::Unbounded, + connection_id, + queries, + limit, + page, + schema, + session_id, + batch_id, + database, + ) + .await +} + +#[tauri::command] +pub async fn explain_query_plan( + app: AppHandle, + state: State<'_, std::sync::Arc>, + connection_id: String, + query: String, + analyze: bool, + schema: Option, + database: Option, +) -> Result { + crate::application::queries::explain_query_plan( + &app.state::(), + &state, + crate::application::queries::QueryRequestScope::DESKTOP, + connection_id, + query, + analyze, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn count_query( + app: AppHandle, + connection_id: String, + query: String, + schema: Option, + database: Option, + session_id: Option, +) -> Result { + crate::application::queries::count_query( + &app.state::(), + None, + connection_id, + query, + schema, + session_id, + database, + ) + .await +} + +/// Sets the window title with Wayland workaround +/// +/// WORKAROUND: This is a temporary fix for tauri-apps/tauri#13749 +/// On Wayland (Linux), the standard `window.setTitle()` API doesn't properly update +/// the window title in the window manager's title bar due to an upstream dependency issue. +/// This command directly manipulates the GTK HeaderBar to ensure the title is visible. +/// +/// See: https://github.com/tauri-apps/tauri/issues/13749 +/// +/// This workaround should be removed once the upstream issue is resolved. +#[tauri::command] +pub async fn set_window_title(app: AppHandle, title: String) -> Result<(), String> { + // Get the main window + let window = app + .get_webview_window("main") + .ok_or("Failed to get main window")?; + + // Set title using standard Tauri API (works on all platforms) + window + .set_title(&title) + .map_err(|e| format!("Failed to set window title: {}", e))?; + + // Apply Wayland-specific workaround on Linux + #[cfg(target_os = "linux")] + { + use gtk::prelude::{BinExt, Cast, GtkWindowExt, HeaderBarExt}; + use gtk::{EventBox, HeaderBar}; + + // Get the GTK window + let gtk_window = window + .gtk_window() + .map_err(|e| format!("Failed to get GTK window: {}", e))?; + + // Check if we have a custom titlebar (Wayland uses EventBox with HeaderBar) + if let Some(titlebar) = gtk_window.titlebar() { + // Try to downcast to EventBox (Wayland) + if let Ok(event_box) = titlebar.downcast::() { + // Get the HeaderBar child and set its title + if let Some(child) = event_box.child() { + if let Ok(header_bar) = child.downcast::() { + header_bar.set_title(Some(&title)); + } + } + } + } + } + + Ok(()) +} + +#[tauri::command] +pub async fn open_er_diagram_window( + app: AppHandle, + connection_id: String, + connection_name: String, + database_name: String, + focus_table: Option, + schema: Option, + database: Option, +) -> Result<(), String> { + use tauri::{WebviewUrl, WebviewWindowBuilder}; + use urlencoding::encode; + + let schema_suffix = schema + .as_deref() + .map(|s| format!("/{}", s)) + .unwrap_or_default(); + let title = format!( + "tabularis - {} ({}{})", + database_name, connection_name, schema_suffix + ); + let mut url = format!( + "/schema-diagram?connectionId={}&connectionName={}&databaseName={}", + encode(&connection_id), + encode(&connection_name), + encode(&database_name) + ); + + if let Some(table) = focus_table { + url.push_str(&format!("&focusTable={}", encode(&table))); + } + + if let Some(s) = &schema { + url.push_str(&format!("&schema={}", encode(s))); + } + + // `database` (distinct from the display-only `database_name` above) is only + // set for a schema-based multi-db connection (PostgreSQL browsing several + // databases) — it's the value the schema-diagram page actually routes its + // snapshot request with, alongside `schema`. Absent for the flat multi-db + // (MySQL) and plain single-database cases, which already resolve correctly + // through `schema` alone. + if let Some(db) = &database { + url.push_str(&format!("&database={}", encode(db))); + } + + // Derive a unique window label per (connection, database, schema) so that + // diagrams for different databases on the same connection do not collide on a + // shared label (which previously kept showing the first database's diagram). + // Tauri window labels only allow a limited character set, so sanitize anything + // else to '_'. + let raw_label = format!( + "er-diagram:{}:{}:{}", + connection_id, + database_name, + schema.as_deref().unwrap_or("") + ); + let label: String = raw_label + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect(); + + // If a diagram window for this exact database already exists, just focus it + // instead of failing to build a second window with the same label. + if let Some(existing) = app.get_webview_window(&label) { + let _ = existing.set_focus(); + return Ok(()); + } + + let _webview = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) + .title(&title) + .inner_size(1200.0, 800.0) + .center() + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) + .build() + .map_err(|e| format!("Failed to create ER Diagram window: {}", e))?; + + Ok(()) +} + +#[tauri::command] +pub async fn get_views( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_views( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_view_definition( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result { + crate::application::database_objects::get_view_definition( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn create_view( + app: AppHandle, + connection_id: String, + view_name: String, + definition: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::create_view( + &app.state::(), + None, + &connection_id, + view_name, + definition, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn alter_view( + app: AppHandle, + connection_id: String, + view_name: String, + definition: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::alter_view( + &app.state::(), + None, + &connection_id, + view_name, + definition, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn drop_view( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::drop_view( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_view_columns( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_view_columns( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_materialized_views( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_materialized_views( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_materialized_view_columns( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_materialized_view_columns( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_materialized_view_definition( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result { + crate::application::metadata::get_materialized_view_definition( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn refresh_materialized_view( + app: AppHandle, + connection_id: String, + view_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::refresh_materialized_view( + &app.state::(), + None, + &connection_id, + view_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_triggers( + app: AppHandle, + connection_id: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::metadata::get_triggers( + &app.state::(), + None, + &connection_id, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_trigger_definition( + app: AppHandle, + connection_id: String, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, +) -> Result { + crate::application::database_objects::get_trigger_definition( + &app.state::(), + None, + &connection_id, + trigger_name, + table_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn create_trigger( + app: AppHandle, + connection_id: String, + trigger_sql: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::create_trigger( + &app.state::(), + None, + &connection_id, + trigger_sql, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn drop_trigger( + app: AppHandle, + connection_id: String, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::drop_trigger( + &app.state::(), + None, + &connection_id, + trigger_name, + table_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_db_privilege_catalog( + app: AppHandle, + connection_id: String, +) -> Result { + crate::application::database_objects::get_db_privilege_catalog( + &app.state::(), + &connection_id, + ) + .await +} + +#[tauri::command] +pub async fn get_db_users( + app: AppHandle, + connection_id: String, +) -> Result, String> { + crate::application::database_objects::get_db_users( + &app.state::(), + None, + &connection_id, + ) + .await +} + +#[tauri::command] +pub async fn get_db_user_grants( + app: AppHandle, + connection_id: String, + user: String, + host: String, +) -> Result, String> { + crate::application::database_objects::get_db_user_grants( + &app.state::(), + None, + &connection_id, + user, + host, + ) + .await +} + +#[tauri::command] +pub async fn create_db_user( + app: AppHandle, + connection_id: String, + user: String, + host: String, + password: String, +) -> Result<(), String> { + crate::application::database_objects::create_db_user( + &app.state::(), + None, + &connection_id, + user, + host, + password, + ) + .await +} + +#[tauri::command] +pub async fn drop_db_user( + app: AppHandle, + connection_id: String, + user: String, + host: String, +) -> Result<(), String> { + crate::application::database_objects::drop_db_user( + &app.state::(), + None, + &connection_id, + user, + host, + ) + .await +} + +#[tauri::command] +pub async fn set_db_user_password( + app: AppHandle, + connection_id: String, + user: String, + host: String, + password: String, +) -> Result<(), String> { + crate::application::database_objects::set_db_user_password( + &app.state::(), + None, + &connection_id, + user, + host, + password, + ) + .await +} + +#[tauri::command] +pub async fn get_db_user_privileges( + app: AppHandle, + connection_id: String, + user: String, + host: String, +) -> Result, String> { + crate::application::database_objects::get_db_user_privileges( + &app.state::(), + None, + &connection_id, + user, + host, + ) + .await +} + +#[tauri::command] +pub async fn apply_db_user_privileges( + app: AppHandle, + connection_id: String, + user: String, + host: String, + database: Option, + table: Option, + privileges: Vec, + grant: bool, +) -> Result<(), String> { + crate::application::database_objects::apply_db_user_privileges( + &app.state::(), + None, + &connection_id, + user, + host, + database, + table, + privileges, + grant, + ) + .await +} + +/// Register a connection as active for health-check pinging. +#[tauri::command] +pub async fn register_active_connection(app: AppHandle, connection_id: String) { + crate::application::connections::register_active_connection( + &app.state::(), + None, + None, + connection_id, + ) + .await; +} + +/// Disconnect from a database connection by closing all of its connection pools +#[tauri::command] +pub async fn disconnect_connection( + app: AppHandle, + connection_id: String, +) -> Result<(), String> { + crate::application::connections::disconnect_connection( + &app.state::(), + None, + None, + &connection_id, + ) + .await +} + +/// Maps generic inferred types (emitted by the clipboard parser) to +/// driver-specific type names. Returns names in the same order as `kinds`. +#[tauri::command] +pub async fn map_inferred_column_types( + app: AppHandle, + driver: String, + kinds: Vec, + connection_id: Option, +) -> Result, String> { + crate::application::database_objects::map_inferred_column_types( + &app.state::(), + None, + driver, + kinds, + connection_id, + ) + .await +} + +#[tauri::command] +pub async fn get_create_table_sql( + app: AppHandle, + connection_id: String, + table_name: String, + columns: Vec, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_create_table_sql( + &app.state::(), + &connection_id, + table_name, + columns, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_add_column_sql( + app: AppHandle, + connection_id: String, + table: String, + column: ColumnDefinition, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_add_column_sql( + &app.state::(), + &connection_id, + table, + column, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_alter_column_sql( + app: AppHandle, + connection_id: String, + table: String, + old_column: ColumnDefinition, + new_column: ColumnDefinition, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_alter_column_sql( + &app.state::(), + &connection_id, + table, + old_column, + new_column, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_create_index_sql( + app: AppHandle, + connection_id: String, + table: String, + index_name: String, + columns: Vec, + is_unique: bool, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_create_index_sql( + &app.state::(), + &connection_id, + table, + index_name, + columns, + is_unique, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_create_foreign_key_sql( + app: AppHandle, + connection_id: String, + table: String, + fk_name: String, + column: String, + ref_table: String, + ref_column: String, + on_delete: Option, + on_update: Option, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_create_foreign_key_sql( + &app.state::(), + &connection_id, + table, + fk_name, + column, + ref_table, + ref_column, + on_delete, + on_update, + schema, + database, + ) + .await +} + +/// Plugin-provided statement for dropping a table, or `None` to let the +/// explorer build its generic `DROP TABLE`. Only plugins declaring +/// `capabilities.drop_table_sql` are asked; every other driver (built-ins +/// included) returns `None` without resolving credentials or params. +#[tauri::command] +pub async fn get_drop_table_sql( + app: AppHandle, + connection_id: String, + table: String, + schema: Option, + database: Option, +) -> Result, String> { + crate::application::database_objects::get_drop_table_sql( + &app.state::(), + &connection_id, + table, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn drop_index_action( + app: AppHandle, + connection_id: String, + table: String, + index_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::drop_index( + &app.state::(), + None, + &connection_id, + table, + index_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn drop_foreign_key_action( + app: AppHandle, + connection_id: String, + table: String, + fk_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + crate::application::database_objects::drop_foreign_key( + &app.state::(), + None, + &connection_id, + table, + fk_name, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn get_keybindings(app: AppHandle) -> Result { + crate::application::persistence::get_keybindings(&app.state::()) +} + +#[tauri::command] +pub async fn save_keybindings( + app: AppHandle, + keybindings: serde_json::Value, +) -> Result<(), String> { + crate::application::persistence::save_keybindings( + &app.state::(), + &keybindings, + ) +} + +#[tauri::command] +pub async fn get_server_now( + app: AppHandle, + connection_id: String, +) -> Result { + crate::application::queries::get_server_now( + &app.state::(), + None, + connection_id, + ) + .await +} + +#[tauri::command] +pub async fn export_connections_payload( + app: AppHandle, + include_secrets: Option, + connection_ids: Option>, +) -> Result { + crate::application::connection_files::export_payload( + app.state::().inner(), + include_secrets.unwrap_or(true), + connection_ids, + ) + .await +} + +#[tauri::command] +pub async fn import_connections_payload( + app: AppHandle, + payload: ExportPayload, +) -> Result<(), String> { + apply_export_payload(app, payload).await +} + +/// Merge an `ExportPayload` into the user's stored connections, groups, SSH and +/// K8s records, moving any inline secrets into the keychain. Shared by the JSON +/// import command above and the foreign-app import flow. +pub async fn apply_export_payload( + app: AppHandle, + payload: ExportPayload, +) -> Result<(), String> { + crate::application::connection_files::apply_export_payload( + app.state::().inner(), + app.state::>() + .inner() + .as_ref(), + app.state::>() + .inner() + .as_ref(), + payload, + ) + .await +} + +/// Detects the MIME type of base64-encoded binary data using magic-byte analysis +/// and returns the canonical blob wire format: "BLOB:::". +/// Called by the frontend after the user selects a file to upload. +#[tauri::command] +pub fn detect_blob_mime(base64_data: String) -> Result { + crate::commands::detect_blob_mime(base64_data) +} + +/// Detects the MIME type from a small base64-encoded header (first ~8KB). +/// Returns only the MIME type string — the frontend constructs the wire format +/// locally, avoiding a full round-trip of the entire file over IPC. +#[tauri::command] +pub fn detect_mime_type(header_base64: String) -> Result { + crate::commands::detect_mime_type(header_base64) +} + +/// Gets file statistics (size and MIME type) without reading the entire file. +/// Used after streaming upload to construct the final wire format. +#[tauri::command] +pub fn get_file_stats(file_path: String) -> Result { + crate::commands::get_file_stats(file_path) +} + +/// Reads a file from disk and returns it as a base64-encoded data URL. +/// Used for image preview of BLOB_FILE_REF values without requiring frontend FS permissions. +/// Only available for image files; returns an error for non-image MIME types. +#[tauri::command] +pub async fn read_file_as_data_url(file_path: String) -> Result { + crate::commands::read_file_as_data_url(file_path).await +} + +/// Snapshot of connection ids currently open in the shared backend (across all +/// windows). Used by each window to render cross-window connection status. +#[tauri::command] +pub async fn get_active_connections() -> Vec { + crate::commands::get_active_connections().await +} + +#[tauri::command] +pub async fn get_data_types(driver: String) -> Result { + crate::commands::get_data_types(driver).await +} + +#[tauri::command] +pub async fn get_registered_drivers() -> Vec { + crate::commands::get_registered_drivers().await +} + +#[tauri::command] +pub async fn get_driver_manifest( + driver_id: String, +) -> Option { + crate::commands::get_driver_manifest(driver_id).await +} + +#[tauri::command] +pub async fn encrypt_export_payload( + payload: ExportPayload, + password: String, +) -> Result { + crate::commands::encrypt_export_payload(payload, password).await +} + +#[tauri::command] +pub async fn decrypt_export_payload( + envelope: crate::export_crypto::EncryptedEnvelope, + password: String, +) -> Result { + crate::commands::decrypt_export_payload(envelope, password).await +} diff --git a/src-tauri/src/transport/desktop/config.rs b/src-tauri/src/transport/desktop/config.rs new file mode 100644 index 000000000..7acfa61a2 --- /dev/null +++ b/src-tauri/src/transport/desktop/config.rs @@ -0,0 +1,433 @@ +use crate::config::*; +use std::fs; +use std::path::PathBuf; +use tauri::AppHandle; +use tauri::Manager; + +pub fn get_config_dir(_app: &AppHandle) -> Option { + Some(crate::paths::get_app_config_dir()) +} + +// Internal load +pub fn load_config_internal(app: &AppHandle) -> AppConfig { + if let Some(config_dir) = get_config_dir(app) { + let config_path = config_dir.join("config.json"); + if config_path.exists() { + if let Ok(content) = fs::read_to_string(config_path) { + if let Ok(mut config) = serde_json::from_str::(&content) { + crate::plugins::compat::migrate_legacy_config(&mut config); // COMPAT(registry-ga) + cache_config(&config); + return config; + } + } + } + } + let default_config = AppConfig::default(); + cache_config(&default_config); + default_config +} + +#[tauri::command] +pub fn get_config(app: AppHandle) -> AppConfig { + crate::application::persistence::load_config(&app.state::()) +} + +#[tauri::command] +pub fn save_config(app: AppHandle, config: AppConfig) -> Result<(), String> { + let runtime = app.state::(); + let previous = crate::application::persistence::load_config(&runtime); + let requested_ping_interval = config.ping_interval; + let window_decorations_changed = config.window_decorations.is_some() + && config.window_decorations != previous.window_decorations; + let saved = crate::application::persistence::save_config(&runtime, config)?; + + if window_decorations_changed { + crate::transport::desktop::window_decorations::apply_to_all_windows( + &app, + saved.window_decorations.as_ref(), + ); + } + if requested_ping_interval.is_some() && saved.ping_interval != previous.ping_interval { + let interval = saved + .ping_interval + .unwrap_or(crate::health_check::DEFAULT_PING_INTERVAL); + crate::async_rt::spawn(crate::transport::desktop::health_check::restart_ping_loop( + app, + interval as u64, + )); + } + Ok(()) +} + +#[tauri::command] +pub fn get_schema_preference( + app: AppHandle, + connection_id: String, + database: Option, +) -> Option { + crate::application::metadata::get_schema_preference( + &app.state::(), + &connection_id, + database, + ) +} + +#[tauri::command] +pub fn set_schema_preference( + app: AppHandle, + connection_id: String, + schema: String, + database: Option, +) -> Result<(), String> { + crate::application::metadata::set_schema_preference( + &app.state::(), + connection_id, + schema, + database, + ) +} + +#[tauri::command] +pub fn get_last_active_connection(app: AppHandle) -> Option { + crate::application::persistence::load_config(&app.state::()) + .last_active_connection_id +} + +#[tauri::command] +pub fn set_last_active_connection( + app: AppHandle, + connection_id: Option, +) -> Result<(), String> { + crate::application::persistence::set_last_active_connection_for_desktop( + &app.state::(), + connection_id, + ) +} + +#[tauri::command] +pub fn get_last_open_connections(app: AppHandle) -> Vec { + crate::application::persistence::load_config(&app.state::()) + .last_open_connection_ids + .unwrap_or_default() +} + +#[tauri::command] +pub fn set_last_open_connections( + app: AppHandle, + connection_ids: Vec, +) -> Result<(), String> { + crate::application::persistence::set_last_open_connections_for_desktop( + &app.state::(), + connection_ids, + ) +} + +#[tauri::command] +pub fn get_selected_schemas( + app: AppHandle, + connection_id: String, + database: Option, +) -> Vec { + crate::application::metadata::get_selected_schemas( + &app.state::(), + &connection_id, + database, + ) +} + +#[tauri::command] +pub fn set_selected_schemas( + app: AppHandle, + connection_id: String, + schemas: Vec, + database: Option, +) -> Result<(), String> { + crate::application::metadata::set_selected_schemas( + &app.state::(), + connection_id, + schemas, + database, + ) +} + +#[tauri::command] +pub fn set_ai_key(app: AppHandle, provider: String, key: String) -> Result<(), String> { + crate::application::ai::set_key( + &app.state::(), + &app.state::>(), + &provider, + &key, + ) +} + +#[tauri::command] +pub fn delete_ai_key(app: AppHandle, provider: String) -> Result<(), String> { + crate::application::ai::delete_key( + &app.state::(), + &app.state::>(), + &provider, + ) +} + +/// Get the configured maximum BLOB size in bytes, or DEFAULT_MAX_BLOB_SIZE if not set +pub fn get_max_blob_size(app: &AppHandle) -> u64 { + let config = load_config_internal(app); + config + .max_blob_size + .unwrap_or(crate::drivers::common::DEFAULT_MAX_BLOB_SIZE) +} + +pub fn get_ai_api_key(app: &AppHandle, provider: &str) -> Result { + // 1. Try Keychain First (Override) — via the in-memory credential cache so + // repeated lookups don't trigger a macOS Keychain authorization prompt + // each time. The keychain is read at most once per provider per session. + let cache = app.state::>(); + if let Ok(key) = crate::credential_cache::get_ai_key_cached(&cache, provider) { + if !key.is_empty() { + return Ok(key); + } + } + + // 2. Try Env Var + let env_var = match provider { + "openai" => "OPENAI_API_KEY", + "anthropic" => "ANTHROPIC_API_KEY", + "openrouter" => "OPENROUTER_API_KEY", + "requesty" => "REQUESTY_API_KEY", + "custom-openai" => "CUSTOM_OPENAI_API_KEY", + "minimax" => "MINIMAX_API_KEY", + _ => "", + }; + + if !env_var.is_empty() { + if let Ok(key) = std::env::var(env_var) { + if !key.is_empty() { + return Ok(key); + } + } + } + + Err(format!( + "API Key for {} not found in Keychain or Environment", + provider + )) +} + +pub fn get_ai_api_key_status(app: &AppHandle, provider: &str) -> AiKeyStatus { + // 1. Check Keychain (through the cache to avoid repeated auth prompts) + let cache = app.state::>(); + let keychain_exists = crate::credential_cache::get_ai_key_cached(&cache, provider).is_ok(); + + // 2. Check Env Var + let env_var = match provider { + "openai" => "OPENAI_API_KEY", + "anthropic" => "ANTHROPIC_API_KEY", + "openrouter" => "OPENROUTER_API_KEY", + "requesty" => "REQUESTY_API_KEY", + "custom-openai" => "CUSTOM_OPENAI_API_KEY", + "minimax" => "MINIMAX_API_KEY", + _ => "", + }; + + let env_exists = if !env_var.is_empty() { + std::env::var(env_var) + .map(|k| !k.is_empty()) + .unwrap_or(false) + } else { + false + }; + + // Configured if either exists + // from_env is true ONLY if keychain is NOT present but env IS present + // because keychain overrides env now + + if keychain_exists { + AiKeyStatus { + configured: true, + from_env: false, // Even if env exists, we are using keychain + } + } else if env_exists { + AiKeyStatus { + configured: true, + from_env: true, + } + } else { + AiKeyStatus { + configured: false, + from_env: false, + } + } +} + +#[tauri::command] +pub fn check_ai_key(app: AppHandle, provider: String) -> bool { + crate::application::ai::get_api_key( + &app.state::(), + &app.state::>(), + &provider, + ) + .is_ok() +} + +#[tauri::command] +pub fn check_ai_key_status( + app: AppHandle, + provider: String, +) -> crate::application::ai::AiKeyStatus { + crate::application::ai::key_status( + &app.state::(), + &app.state::>(), + &provider, + ) +} + +fn prompt_kind(app: &AppHandle, kind: crate::application::persistence::PromptKind) -> String { + crate::application::persistence::get_prompt( + &app.state::(), + kind, + ) +} + +fn save_prompt_kind( + app: &AppHandle, + kind: crate::application::persistence::PromptKind, + prompt: &str, +) -> Result<(), String> { + crate::application::persistence::save_prompt( + &app.state::(), + kind, + prompt, + ) +} + +fn reset_prompt_kind( + app: &AppHandle, + kind: crate::application::persistence::PromptKind, +) -> Result { + crate::application::persistence::reset_prompt( + &app.state::(), + kind, + ) +} + +#[tauri::command] +pub fn get_system_prompt(app: AppHandle) -> String { + prompt_kind(&app, crate::application::persistence::PromptKind::System) +} + +#[tauri::command] +pub fn save_system_prompt(app: AppHandle, prompt: String) -> Result<(), String> { + save_prompt_kind( + &app, + crate::application::persistence::PromptKind::System, + &prompt, + ) +} + +#[tauri::command] +pub fn reset_system_prompt(app: AppHandle) -> Result { + reset_prompt_kind(&app, crate::application::persistence::PromptKind::System) +} + +#[tauri::command] +pub fn get_explain_prompt(app: AppHandle) -> String { + prompt_kind(&app, crate::application::persistence::PromptKind::Explain) +} + +#[tauri::command] +pub fn save_explain_prompt(app: AppHandle, prompt: String) -> Result<(), String> { + save_prompt_kind( + &app, + crate::application::persistence::PromptKind::Explain, + &prompt, + ) +} + +#[tauri::command] +pub fn reset_explain_prompt(app: AppHandle) -> Result { + reset_prompt_kind(&app, crate::application::persistence::PromptKind::Explain) +} + +#[tauri::command] +pub fn get_explainplan_prompt(app: AppHandle) -> String { + prompt_kind( + &app, + crate::application::persistence::PromptKind::ExplainPlan, + ) +} + +#[tauri::command] +pub fn save_explainplan_prompt(app: AppHandle, prompt: String) -> Result<(), String> { + save_prompt_kind( + &app, + crate::application::persistence::PromptKind::ExplainPlan, + &prompt, + ) +} + +#[tauri::command] +pub fn reset_explainplan_prompt(app: AppHandle) -> Result { + reset_prompt_kind( + &app, + crate::application::persistence::PromptKind::ExplainPlan, + ) +} + +#[tauri::command] +pub fn get_cellname_prompt(app: AppHandle) -> String { + prompt_kind(&app, crate::application::persistence::PromptKind::CellName) +} + +#[tauri::command] +pub fn save_cellname_prompt(app: AppHandle, prompt: String) -> Result<(), String> { + save_prompt_kind( + &app, + crate::application::persistence::PromptKind::CellName, + &prompt, + ) +} + +#[tauri::command] +pub fn reset_cellname_prompt(app: AppHandle) -> Result { + reset_prompt_kind(&app, crate::application::persistence::PromptKind::CellName) +} + +#[tauri::command] +pub fn get_tabrename_prompt(app: AppHandle) -> String { + prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) +} + +#[tauri::command] +pub fn save_tabrename_prompt(app: AppHandle, prompt: String) -> Result<(), String> { + save_prompt_kind( + &app, + crate::application::persistence::PromptKind::TabRename, + &prompt, + ) +} + +#[tauri::command] +pub fn reset_tabrename_prompt(app: AppHandle) -> Result { + reset_prompt_kind(&app, crate::application::persistence::PromptKind::TabRename) +} + +#[tauri::command] +pub fn get_config_json(app: AppHandle) -> Result { + crate::application::persistence::get_config_json_for_desktop( + &app.state::(), + ) +} + +#[tauri::command] +pub fn relaunch_app(app: AppHandle) { + crate::transport::desktop::window_placement::persist_cached(&app); + app.restart(); +} + +#[tauri::command] +pub fn save_config_json(app: AppHandle, json: String) -> Result<(), String> { + crate::application::persistence::save_config_json_for_desktop( + &app.state::(), + &json, + ) +} diff --git a/src-tauri/src/transport/desktop/connection_appearance.rs b/src-tauri/src/transport/desktop/connection_appearance.rs new file mode 100644 index 000000000..7c2d96c86 --- /dev/null +++ b/src-tauri/src/transport/desktop/connection_appearance.rs @@ -0,0 +1,14 @@ +use crate::connection_appearance::*; +use std::path::Path; +use tauri::AppHandle; + +#[tauri::command] +pub async fn save_connection_icon( + _app: AppHandle, + connection_id: String, + source_path: String, +) -> Result { + let data_dir = crate::paths::get_app_data_dir(); + let dest = data_dir.join("connection-icons"); + save_icon_impl(&dest, &connection_id, Path::new(&source_path)).map_err(|e| e.to_string()) +} diff --git a/src-tauri/src/connection_import_commands.rs b/src-tauri/src/transport/desktop/connection_import_commands.rs similarity index 100% rename from src-tauri/src/connection_import_commands.rs rename to src-tauri/src/transport/desktop/connection_import_commands.rs diff --git a/src-tauri/src/connection_window.rs b/src-tauri/src/transport/desktop/connection_window.rs similarity index 94% rename from src-tauri/src/connection_window.rs rename to src-tauri/src/transport/desktop/connection_window.rs index 7858b4b76..132f1c001 100644 --- a/src-tauri/src/connection_window.rs +++ b/src-tauri/src/transport/desktop/connection_window.rs @@ -58,7 +58,7 @@ pub async fn open_connection_window( .inner_size(1280.0, 800.0) .min_inner_size(800.0, 500.0) .center() - .decorations(crate::window_decorations::native_decorations_enabled()) + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) .background_color(tauri::webview::Color(2, 6, 23, 255)) // The native drag-drop handler swallows DOM drag events (sidebar // reorder, split panel moves), see dragDropEnabled in tauri.conf.json @@ -78,7 +78,7 @@ pub async fn open_connection_window( let connection_id = close_connection_id.clone(); crate::async_rt::spawn(async move { if let Err(e) = - crate::commands::disconnect_connection(app, connection_id.clone()).await + crate::transport::desktop::commands::disconnect_connection(app, connection_id.clone()).await { log::warn!( "Failed to disconnect '{}' on connection window close: {}", diff --git a/src-tauri/src/connection_window_tests.rs b/src-tauri/src/transport/desktop/connection_window_tests.rs similarity index 92% rename from src-tauri/src/connection_window_tests.rs rename to src-tauri/src/transport/desktop/connection_window_tests.rs index 3c55c3791..d56f23eab 100644 --- a/src-tauri/src/connection_window_tests.rs +++ b/src-tauri/src/transport/desktop/connection_window_tests.rs @@ -1,6 +1,6 @@ #[cfg(test)] mod tests { - use crate::connection_window::{connection_route, window_label}; + use crate::transport::desktop::connection_window::{connection_route, window_label}; #[test] fn uuid_like_id_is_preserved() { diff --git a/src-tauri/src/transport/desktop/dump_commands.rs b/src-tauri/src/transport/desktop/dump_commands.rs new file mode 100644 index 000000000..251c351f7 --- /dev/null +++ b/src-tauri/src/transport/desktop/dump_commands.rs @@ -0,0 +1,66 @@ +use crate::application::connection_files::GeneratedFile; +use crate::application::database_transfers::{self, DumpDestination, ImportSource, JobKind}; +use crate::dump_commands::*; +use crate::runtime::RuntimeContext; +use std::path::PathBuf; +use tauri::State; + +#[tauri::command] +pub async fn cancel_dump( + state: State<'_, std::sync::Arc>, + connection_id: String, +) -> Result<(), String> { + database_transfers::cancel_job(state.inner(), None, JobKind::Dump, &connection_id) +} + +#[tauri::command] +pub async fn dump_database( + runtime: State<'_, RuntimeContext>, + state: State<'_, std::sync::Arc>, + connection_id: String, + file_path: String, + options: DumpOptions, + schema: Option, + database: Option, +) -> Result, String> { + database_transfers::dump_database( + runtime.inner(), + state.inner(), + None, + connection_id, + DumpDestination::ServerPath(PathBuf::from(file_path)), + options, + schema, + database, + ) + .await +} + +#[tauri::command] +pub async fn cancel_import( + state: State<'_, std::sync::Arc>, + connection_id: String, +) -> Result<(), String> { + database_transfers::cancel_job(state.inner(), None, JobKind::Import, &connection_id) +} + +#[tauri::command] +pub async fn import_database( + runtime: State<'_, RuntimeContext>, + state: State<'_, std::sync::Arc>, + connection_id: String, + file_path: String, + schema: Option, + database: Option, +) -> Result<(), String> { + database_transfers::import_database( + runtime.inner(), + state.inner(), + None, + connection_id, + ImportSource::ServerPath(PathBuf::from(file_path)), + schema, + database, + ) + .await +} diff --git a/src-tauri/src/e2e_dialog_mock.rs b/src-tauri/src/transport/desktop/e2e_dialog_mock.rs similarity index 90% rename from src-tauri/src/e2e_dialog_mock.rs rename to src-tauri/src/transport/desktop/e2e_dialog_mock.rs index 0eed11fe8..955ad0c85 100644 --- a/src-tauri/src/e2e_dialog_mock.rs +++ b/src-tauri/src/transport/desktop/e2e_dialog_mock.rs @@ -22,7 +22,6 @@ //! / `Value::Null` satisfy. use serde_json::{json, Value}; -#[cfg(feature = "desktop")] use tauri::{plugin::{Builder, TauriPlugin}, Runtime}; fn env_path(var: &str) -> Value { @@ -32,27 +31,27 @@ fn env_path(var: &str) -> Value { } } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] async fn ask(_message: Value, _title: Option, _kind: Option, _yes_button_label: Option, _no_button_label: Option) -> Result { Ok(json!(true)) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] async fn confirm(_message: Value, _title: Option, _kind: Option, _ok_button_label: Option, _cancel_button_label: Option) -> Result { Ok(json!(true)) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] async fn message(_message: Value, _title: Option, _kind: Option, _ok_button_label: Option, _buttons: Option) -> Result { Ok(Value::Null) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] async fn open(_options: Value) -> Result { Ok(env_path("E2E_DIALOG_OPEN_PATH")) } -#[cfg_attr(feature = "desktop", tauri::command)] +#[tauri::command] async fn save(_options: Value) -> Result { Ok(env_path("E2E_DIALOG_SAVE_PATH")) } diff --git a/src-tauri/src/transport/desktop/explain_import.rs b/src-tauri/src/transport/desktop/explain_import.rs new file mode 100644 index 000000000..09c6fc16d --- /dev/null +++ b/src-tauri/src/transport/desktop/explain_import.rs @@ -0,0 +1,70 @@ +use crate::explain_import::*; +use tauri::{Manager, Runtime, State}; + +/// Tauri command: pop the CLI-provided file path (if any). +/// +/// Returns `None` after the first successful read, allowing the window to +/// differentiate "cold start from CLI" from "opened manually". +#[tauri::command] +pub fn get_pending_explain_file( + state: State<'_, std::sync::Arc>, +) -> Option { + state.take() +} + +/// Creates (or focuses) the standalone Visual Explain window. +/// +/// Runs fully synchronously so it can be invoked from the Tauri `setup` hook +/// without taking a detour through the async runtime. +pub fn spawn_visual_explain_window>( + app: &M, + file: Option, +) -> Result<(), String> { + use tauri::{WebviewUrl, WebviewWindowBuilder}; + + if let Some(path) = file.as_ref() { + if let Some(state) = app.try_state::>() { + state.set(path.clone()); + } + } + + if let Some(existing) = app.get_webview_window("visual-explain") { + existing + .set_focus() + .map_err(|e| format!("Failed to focus Visual Explain window: {e}"))?; + return Ok(()); + } + + WebviewWindowBuilder::new( + app, + "visual-explain", + WebviewUrl::App("/visual-explain".into()), + ) + .title("tabularis - Visual Explain") + .inner_size(1280.0, 820.0) + .min_inner_size(900.0, 600.0) + .center() + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) + .build() + .map_err(|e| format!("Failed to create Visual Explain window: {e}"))?; + + Ok(()) +} + +/// Tauri command wrapper around [`spawn_visual_explain_window`]. +#[tauri::command] +pub async fn open_visual_explain_window( + app: tauri::AppHandle, + file: Option, +) -> Result<(), String> { + spawn_visual_explain_window(&app, file) +} + +/// Tauri command: read an EXPLAIN file from disk. +/// +/// The content comes back untouched; the frontend sniffs the format and +/// parses it with `@tabularis/explain`. +#[tauri::command] +pub async fn load_explain_from_file(path: String) -> Result { + crate::explain_import::load_explain_from_file(path).await +} diff --git a/src-tauri/src/transport/desktop/export.rs b/src-tauri/src/transport/desktop/export.rs new file mode 100644 index 000000000..1d30fad21 --- /dev/null +++ b/src-tauri/src/transport/desktop/export.rs @@ -0,0 +1,42 @@ +use crate::export::*; +use crate::runtime::RuntimeContext; +use std::path::PathBuf; +use tauri::State; + +#[tauri::command] +pub async fn cancel_export( + state: State<'_, std::sync::Arc>, + connection_id: String, +) -> Result<(), String> { + crate::application::generic_exports::cancel_export(state.inner(), None, &connection_id) +} + +#[tauri::command] +#[allow(clippy::too_many_arguments)] +pub async fn export_query_to_file( + runtime: State<'_, RuntimeContext>, + state: State<'_, std::sync::Arc>, + connection_id: String, + query: String, + file_path: String, + format: String, + csv_delimiter: Option, + database: Option, + session_id: Option, +) -> Result, String> { + crate::application::generic_exports::export_query( + runtime.inner(), + state.inner(), + None, + connection_id, + query, + crate::application::generic_exports::ExportDestination::ServerPath(PathBuf::from( + file_path, + )), + format, + csv_delimiter, + database, + session_id, + ) + .await +} diff --git a/src-tauri/src/transport/desktop/health_check.rs b/src-tauri/src/transport/desktop/health_check.rs new file mode 100644 index 000000000..d165595e5 --- /dev/null +++ b/src-tauri/src/transport/desktop/health_check.rs @@ -0,0 +1,212 @@ +pub(crate) use crate::health_check::*; +use std::collections::HashMap; +use std::time::Duration; +use tauri::Emitter; +use tokio::sync::oneshot; + +/// Broadcast the current active-connection set to all windows. +pub async fn emit_active_changed(app: &tauri::AppHandle) { + let ids = active_connections().await; + if let Err(e) = app.emit(ACTIVE_CONNECTIONS_CHANGED_EVENT, ids) { + log::error!( + "Health check: failed to emit {} event: {}", + ACTIVE_CONNECTIONS_CHANGED_EVENT, + e + ); + } +} + +/// Start the periodic ping loop. If a loop is already running it is stopped first. +pub async fn start_ping_loop(app: tauri::AppHandle, interval_secs: u64) { + // Stop any existing loop + stop_ping_loop().await; + + if interval_secs == 0 { + log::info!("Health check: disabled (interval = 0)"); + return; + } + + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + { + let mut guard = PING_STOP_TX.lock().await; + *guard = Some(stop_tx); + } + + log::info!( + "Health check: starting ping loop with interval {}s", + interval_secs + ); + + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(interval_secs)); + let mut failure_counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + _ = &mut stop_rx => { + log::info!("Health check: ping loop stopped"); + break; + } + _ = interval.tick() => { + ping_all_connections(&app, &mut failure_counts).await; + } + } + } + }); +} + +/// Restart the ping loop with a new interval. +pub async fn restart_ping_loop(app: tauri::AppHandle, interval_secs: u64) { + stop_ping_loop().await; + start_ping_loop(app, interval_secs).await; +} + +/// Ping every registered connection. On failure beyond the threshold, +/// close the pool and emit an event to the frontend. +async fn ping_all_connections(app: &tauri::AppHandle, failure_counts: &mut HashMap) { + // Snapshot the active set so we don't hold the lock during I/O. + let active: Vec = ACTIVE_CONNECTIONS.read().await.iter().cloned().collect(); + + if active.is_empty() { + return; + } + + // Ping each connection concurrently. + let results = futures::future::join_all(active.iter().map(|conn_id| { + let app = app.clone(); + let conn_id = conn_id.clone(); + async move { + let result = ping_single_connection(&app, &conn_id).await; + (conn_id, result) + } + })) + .await; + + for (conn_id, result) in results { + match result { + Ok(()) => { + // Reset failure counter on success. + failure_counts.remove(&conn_id); + } + Err(err) => { + let count = failure_counts.entry(conn_id.clone()).or_insert(0); + *count += 1; + log::warn!( + "Health check: ping failed for {} ({}/{}): {}", + conn_id, + count, + FAILURE_THRESHOLD, + err + ); + + if *count >= FAILURE_THRESHOLD { + log::error!( + "Health check: connection {} exceeded failure threshold, disconnecting", + conn_id + ); + failure_counts.remove(&conn_id); + handle_connection_failure(app, &conn_id, &err).await; + } + } + } + } +} + +/// Ping a single connection by resolving its params and calling driver.ping(). +async fn ping_single_connection(app: &tauri::AppHandle, connection_id: &str) -> Result<(), String> { + let saved_conn = + crate::transport::desktop::commands::find_connection_by_id(app, connection_id)?; + + let expanded_params = + crate::transport::desktop::commands::expand_ssh_connection_params(app, &saved_conn.params) + .await?; + let expanded_params = + crate::transport::desktop::commands::expand_k8s_connection_params(app, &expanded_params) + .await?; + let params = + crate::commands::resolve_connection_params_with_id(&expanded_params, connection_id)?; + + // Check if pool exists before attempting ping (avoid creating new pools). + let is_builtin = matches!(params.driver.as_str(), "mysql" | "postgres" | "sqlite"); + if is_builtin && !crate::pool_manager::has_pool(¶ms, Some(connection_id)).await { + return Err("No active connection pool".into()); + } + + let driver = crate::drivers::registry::get_driver(¶ms.driver) + .await + .ok_or_else(|| format!("Driver not found: {}", params.driver))?; + + tokio::time::timeout(PING_TIMEOUT, driver.ping(¶ms)) + .await + .map_err(|_| "Ping timed out".to_string())? +} + +/// Close the pool, unregister the connection, and emit a failure event. +async fn handle_connection_failure(app: &tauri::AppHandle, connection_id: &str, error: &str) { + // Unregister first to prevent further pings. + unregister_connection(connection_id).await; + + // Close all pools for the connection before resolving SSH params. Pool + // keys depend only on connection_id (plus driver/database/TLS), not the + // tunnel's local port, so `close_pools_for_connection_id` matches by + // connection_id prefix — it subsumes the single-key close and closes + // per-database override pools too (#1063). A dead bastion / unreachable + // cluster must not prevent pool cleanup (#1065). + let mut params = None; + if let Ok(saved_conn) = + crate::transport::desktop::commands::find_connection_by_id(app, connection_id) + { + crate::pool_manager::close_pools_for_connection_id( + &saved_conn.params.driver, + connection_id, + ) + .await; + + // release_connection_sessions only needs params.driver to look up the + // driver for rollback — the same driver regardless of tunnel expansion. + // Since params_for_pool_close already disabled all tunnel types, + // close_params has the right driver and connection_id, so re-expanding + // SSH would only add a redundant keychain lookup that produces the same + // result. If even tunnel-free resolution fails, fall back to the saved + // params with just the connection_id set. + let close_params = match crate::commands::params_for_pool_close( + &saved_conn.params, + connection_id, + ) { + Ok(p) => p, + Err(e) => { + log::warn!( + "Health check: failed to resolve tunnel-free params for session release on {connection_id}: {e}" + ); + let mut fallback = saved_conn.params.clone(); + fallback.connection_id = Some(connection_id.to_string()); + fallback + } + }; + params = Some(close_params); + } + // Release pinned transaction sessions after closing the pool. A checked-out + // pinned client survives pool.close() (which only blocks new checkouts), so + // ROLLBACK still runs; the connection is discarded when the client drops. + crate::transport::desktop::commands::release_connection_sessions( + app, + connection_id, + params.as_ref(), + ) + .await; + + // Notify frontend. + let payload = serde_json::json!({ + "connectionId": connection_id, + "error": error, + }); + if let Err(e) = app.emit("connection-health-failed", payload) { + log::error!( + "Health check: failed to emit connection-health-failed event: {}", + e + ); + } + + // Broadcast the updated active-connection set so every window reconciles. + emit_active_changed(app).await; +} diff --git a/src-tauri/src/transport/desktop/json_viewer.rs b/src-tauri/src/transport/desktop/json_viewer.rs new file mode 100644 index 000000000..d79177c3c --- /dev/null +++ b/src-tauri/src/transport/desktop/json_viewer.rs @@ -0,0 +1,200 @@ +use crate::json_viewer::*; +use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent}; +use ulid::Ulid; +use urlencoding::encode; + +#[tauri::command] +pub async fn open_json_viewer_window( + app: AppHandle, + store: State<'_, std::sync::Arc>, + value: serde_json::Value, + original_value: Option, + col_name: String, + row_label: Option, + read_only: bool, + cell_key: Option, +) -> Result { + let original_value = original_value.unwrap_or_else(|| value.clone()); + if let Some(key) = cell_key.as_deref() { + let existing_id = { + let cell_index = store + .cell_index + .lock() + .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; + cell_index.get(key).cloned() + }; + if let Some(existing_id) = existing_id { + let existing_label = format!("json-viewer-{}", existing_id); + if let Some(window) = app.get_webview_window(&existing_label) { + let _ = window.unminimize(); + let _ = window.set_focus(); + let mut sessions = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + if let Some(session) = sessions.get_mut(&existing_id) { + session.value = value; + } + return Ok(existing_id); + } + let mut cell_index = store + .cell_index + .lock() + .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; + cell_index.remove(key); + let mut sessions = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + sessions.remove(&existing_id); + } + } + + let session_id = Ulid::new().to_string(); + let window_label = format!("json-viewer-{}", session_id); + + { + let mut guard = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + guard.insert( + session_id.clone(), + JsonViewerSession { + value, + original_value, + col_name: col_name.clone(), + read_only, + cell_key: cell_key.clone(), + }, + ); + } + if let Some(key) = cell_key.as_deref() { + let mut cell_index = store + .cell_index + .lock() + .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; + cell_index.insert(key.to_string(), session_id.clone()); + } + + let url = format!("/json-viewer?session={}", encode(&session_id)); + let title = match row_label.as_deref().filter(|s| !s.is_empty()) { + Some(label) => format!("{} \u{00b7} {} \u{2014} JSON Viewer", col_name, label), + None => format!("{} \u{2014} JSON Viewer", col_name), + }; + + let remembered = store + .last_bounds + .lock() + .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? + .clone(); + + let mut builder = WebviewWindowBuilder::new(&app, &window_label, WebviewUrl::App(url.into())) + .title(&title) + .min_inner_size(600.0, 400.0) + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) + .background_color(tauri::webview::Color(2, 6, 23, 255)); + + builder = match remembered { + Some(b) => builder + .inner_size(b.width as f64, b.height as f64) + .position(b.x as f64, b.y as f64), + None => builder.inner_size(900.0, 700.0).center(), + }; + + let build_result = builder.build(); + + match build_result { + Err(e) => { + let mut sessions = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + sessions.remove(&session_id); + if let Some(key) = cell_key.as_deref() { + let mut cell_index = store + .cell_index + .lock() + .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; + cell_index.remove(key); + } + Err(format!("Failed to create JSON viewer window: {}", e)) + } + Ok(window) => { + let app_handle = app.clone(); + let captured_label = window_label.clone(); + window.on_window_event(move |event| { + if let WindowEvent::CloseRequested { .. } = event { + if let Some(win) = app_handle.get_webview_window(&captured_label) { + if let (Ok(pos), Ok(size)) = (win.outer_position(), win.outer_size()) { + let store = app_handle.state::>(); + let mut bounds = match store.last_bounds.lock() { + Ok(g) => g, + Err(_) => return, + }; + *bounds = Some(WindowBounds { + x: pos.x, + y: pos.y, + width: size.width, + height: size.height, + }); + } + } + } + }); + Ok(session_id) + } + } +} + +#[tauri::command] +pub async fn get_json_viewer_session( + store: State<'_, std::sync::Arc>, + session_id: String, +) -> Result { + let guard = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + guard + .get(&session_id) + .cloned() + .ok_or_else(|| format!("JSON viewer session '{}' not found", session_id)) +} + +#[tauri::command] +pub async fn complete_json_viewer_session( + app: AppHandle, + store: State<'_, std::sync::Arc>, + session_id: String, + value: serde_json::Value, +) -> Result<(), String> { + let cell_key = { + let mut guard = store + .sessions + .lock() + .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; + guard.remove(&session_id).and_then(|s| s.cell_key) + }; + if let Some(key) = cell_key { + let mut cell_index = store + .cell_index + .lock() + .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; + if cell_index + .get(&key) + .map(|v| v == &session_id) + .unwrap_or(false) + { + cell_index.remove(&key); + } + } + + app.emit( + "json-viewer:saved", + JsonViewerSavedPayload { session_id, value }, + ) + .map_err(|e| format!("Failed to emit json-viewer:saved: {}", e))?; + + Ok(()) +} diff --git a/src-tauri/src/transport/desktop/log_commands.rs b/src-tauri/src/transport/desktop/log_commands.rs new file mode 100644 index 000000000..037f8e053 --- /dev/null +++ b/src-tauri/src/transport/desktop/log_commands.rs @@ -0,0 +1,59 @@ +use crate::application::operations; +use crate::log_commands::*; +use crate::logger::{LogEntry, SharedLogBuffer}; +use std::path::PathBuf; +use tauri::State; + +#[tauri::command] +pub fn get_logs(log_buffer: State, request: GetLogsRequest) -> Vec { + operations::get_logs(log_buffer.inner(), request) +} + +#[tauri::command] +pub fn clear_logs(log_buffer: State) -> Result<(), String> { + operations::clear_logs(log_buffer.inner()) +} + +#[tauri::command] +pub fn get_log_settings(log_buffer: State) -> LogSettings { + operations::get_log_settings(log_buffer.inner()) +} + +#[tauri::command] +pub fn set_log_enabled(log_buffer: State, enabled: bool) -> Result<(), String> { + operations::set_log_enabled(log_buffer.inner(), enabled) +} + +#[tauri::command] +pub fn set_log_max_size(log_buffer: State, max_size: usize) -> Result<(), String> { + operations::set_log_max_size(log_buffer.inner(), max_size) +} + +#[tauri::command] +pub async fn export_logs( + runtime: State<'_, crate::runtime::RuntimeContext>, + log_buffer: State<'_, SharedLogBuffer>, + file_path: String, +) -> Result, String> { + let path = PathBuf::from(file_path); + let result = crate::application::generic_exports::export_logs( + runtime.inner(), + log_buffer.inner().clone(), + crate::application::generic_exports::ExportDestination::ServerPath(path.clone()), + ) + .await?; + log::info!("Logs exported to: {:?}", path); + Ok(result) +} + +/// Lets the frontend record user-relevant events (e.g. a database pruned from +/// a connection's selection) in the activity log shown in Settings → Logs. +#[tauri::command] +pub fn log_frontend_event(level: String, message: String) { + crate::log_commands::log_frontend_event(level, message) +} + +#[tauri::command] +pub fn test_log() -> Result<(), String> { + crate::log_commands::test_log() +} diff --git a/src-tauri/src/transport/desktop/mcp.rs b/src-tauri/src/transport/desktop/mcp.rs new file mode 100644 index 000000000..e5b1d65b7 --- /dev/null +++ b/src-tauri/src/transport/desktop/mcp.rs @@ -0,0 +1 @@ +pub mod install; diff --git a/src-tauri/src/transport/desktop/mcp/install.rs b/src-tauri/src/transport/desktop/mcp/install.rs new file mode 100644 index 000000000..2ba1948fd --- /dev/null +++ b/src-tauri/src/transport/desktop/mcp/install.rs @@ -0,0 +1,16 @@ +use tauri::{AppHandle, Runtime}; + +#[tauri::command] +pub async fn get_mcp_status( + _app: AppHandle, +) -> Result, String> { + crate::application::mcp_host::get_status().await +} + +#[tauri::command] +pub async fn install_mcp_config( + _app: AppHandle, + client_id: String, +) -> Result { + crate::application::mcp_host::install_config(client_id).await +} diff --git a/src-tauri/src/transport/desktop/mod.rs b/src-tauri/src/transport/desktop/mod.rs new file mode 100644 index 000000000..e56d42ea8 --- /dev/null +++ b/src-tauri/src/transport/desktop/mod.rs @@ -0,0 +1,688 @@ +//! The Tauri desktop app: every Tauri command and the code that needs a +//! Tauri handle. Nothing outside this module depends on Tauri. + +pub mod ai; +pub mod ai_approval_watcher; +pub mod ai_commands; +pub mod askpass; +pub mod backup; +pub mod chatgpt; +pub mod clipboard_import; +pub mod commands; +pub mod config; +pub mod connection_appearance; +pub mod connection_import_commands; +pub mod connection_window; +pub mod dump_commands; +#[cfg(feature = "e2e-testing")] +pub mod e2e_dialog_mock; +pub mod explain_import; +pub mod export; +pub mod health_check; +pub mod json_viewer; +pub mod log_commands; +pub mod mcp; +pub mod notebooks; +pub mod plugins; +pub mod preferences; +pub mod proxy; +pub mod query_history; +pub mod results_window; +pub mod runtime; +pub mod saved_queries; +pub mod sql_file; +pub mod sqlite_database; +pub mod storage_location; +pub mod system_theme; +pub mod task_manager; +pub mod theme_commands; +pub mod theme_packages; +pub mod ui_state_commands; +pub mod updater; +pub mod window_decorations; +pub mod window_placement; +#[cfg(test)] +mod connection_window_tests; +#[cfg(test)] +mod tests; + +use tauri::Manager; + +#[tauri::command] +fn open_devtools(window: tauri::WebviewWindow) { + window.open_devtools(); + log::info!("DevTools opened"); +} + +#[tauri::command] +fn close_devtools(window: tauri::WebviewWindow) { + window.close_devtools(); + log::info!("DevTools closed"); +} + +pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { + // Log startup message + log::info!("Tabularis application starting..."); + if args.debug { + log::info!("Debug mode enabled - verbose logging active"); + } else { + log::info!("Debug mode disabled - standard logging active"); + } + + let application_state = std::sync::Arc::new(crate::runtime::state::ApplicationState::default()); + let shutdown_hooks = crate::runtime::lifecycle::ShutdownHooks::default(); + shutdown_hooks.register(|| { + log::info!("Application exiting, stopping all active tunnels..."); + crate::ssh_tunnel::stop_all_tunnels(); + crate::proxy::stop_all_forwards(); + crate::ssm_tunnel::stop_all_tunnels(); + crate::k8s_tunnel::stop_all_tunnels(); + }); + let run_shutdown_hooks = shutdown_hooks.clone(); + + #[cfg_attr(not(feature = "e2e-testing"), allow(unused_mut))] + let mut builder = tauri::Builder::default() + // Singleton: a second launch (typically a `tabularis://...` URL + // clicked while the app is already running) hands its argv to the + // first instance and exits. With `features = ["deep-link"]` the plugin + // usually auto-routes those URLs through `on_open_url`, but on + // Linux/Windows the URL arrives as a plain argv entry on warm launch. + // We scan argv for it defensively and dispatch ourselves so the + // install modal fires even when auto-routing doesn't. + // + // Order matters: must be the FIRST plugin in the chain so it can + // intercept duplicate launches before any heavy initialisation. + .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| { + log::info!("Duplicate launch detected — forwarded to existing instance"); + if let Some(url) = argv.iter().find(|a| a.starts_with("tabularis:")) { + crate::transport::desktop::plugins::deep_link::handle_url(app, url); + } + if let Some(win) = tauri::Manager::get_webview_window(app, "main") { + let _ = win.unminimize(); + let _ = win.set_focus(); + } + })) + .plugin(tauri_plugin_clipboard_manager::init()) + .plugin(tauri_plugin_opener::init()) + .plugin(tauri_plugin_fs::init()) + .plugin(tauri_plugin_notification::init()) + .plugin(tauri_plugin_updater::Builder::new().build()) + .plugin(tauri_plugin_deep_link::init()); + + // Dialog plugin: real in production, mocked under e2e-testing (the mock + // auto-accepts ask()/confirm() so native Tauri confirm dialogs — which + // WebDriverIO can't click — don't block the trigger-save flow). Registered + // as a same-named "dialog" plugin so it replaces the real one at Tauri's + // IPC dispatch layer (PluginStore::register retains only the last). + #[cfg(not(feature = "e2e-testing"))] + { + builder = builder.plugin(tauri_plugin_dialog::init()); + } + #[cfg(feature = "e2e-testing")] + { + builder = builder.plugin(e2e_dialog_mock::init()); + // In-app WebDriver server. tauri-wd connects to drive the real WKWebView + // via the W3C WebDriver protocol on macOS, exercising real Tauri IPC. + builder = builder.plugin(tauri_plugin_webdriver_automation::init()); + } + + builder + .manage(application_state.pending_install.clone()) + .manage(application_state.query_cancellation.clone()) + .manage(application_state.export_cancellation.clone()) + .manage(application_state.dump_cancellation.clone()) + .manage(log_buffer) + .manage(application_state.credential_cache.clone()) + .manage(application_state.connection_cache.clone()) + .manage(application_state.import_envelope_cache.clone()) + .manage(application_state.pending_explain_file.clone()) + .manage(application_state.json_viewer_store.clone()) + .manage(application_state.results_window_store.clone()) + .manage(application_state.clone()) + .manage(window_placement::WindowPlacementCache::default()) + .setup(move |app| { + #[cfg(target_os = "linux")] + system_theme::watch(app.handle().clone()); + // The asset protocol scope in tauri.conf.json only covers the + // default data directory; when the user moved the storage folder + // the connection icons live there instead. + if crate::storage_location::active_override().is_some() { + let icons_dir = crate::paths::get_connection_icons_dir(); + let _ = std::fs::create_dir_all(&icons_dir); + if let Err(e) = app.asset_protocol_scope().allow_directory(&icons_dir, true) { + log::warn!("Failed to allow asset access to {:?}: {}", icons_dir, e); + } + log::info!( + "Using custom storage location: {}", + crate::paths::get_app_config_dir().display() + ); + } + + // Apply the persisted decoration policy as early as possible. The + // main window is created from tauri.conf.json before this hook. + let startup_config = crate::transport::desktop::config::load_config_internal(&app.handle()); + crate::transport::desktop::window_decorations::apply_to_all_windows( + &app.handle(), + startup_config.window_decorations.as_ref(), + ); + // Restore the main window's last normal size and position. + // The explicit start_maximized preference below still takes precedence. + if let Some(window) = app.get_webview_window("main") { + window_placement::restore(&window); + } + + let app_paths = crate::runtime::paths::FixedRuntimePaths::system(); + let runtime_context = crate::runtime::RuntimeContext::new( + std::sync::Arc::new(app_paths), + std::sync::Arc::new(runtime::events::TauriRuntimeEvents::new( + app.handle().clone(), + )), + std::sync::Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), + ); + // Allow the SSH tunnel code (which runs without a Tauri context) + // to bridge askpass prompts to the frontend. + crate::askpass::set_frontend_events(runtime_context.events.clone()); + let bootstrapped = tauri::async_runtime::block_on( + crate::runtime::bootstrap::bootstrap_application( + runtime_context, + crate::runtime::bootstrap::BootstrapOptions { + load_external_plugins: true, + run_connection_migrations: false, + }, + ), + ) + .map_err(std::io::Error::other)?; + app.manage(crate::runtime::lifecycle::start_approval_heartbeat(&bootstrapped.context)); + app.manage(bootstrapped.context); + + // Ensure replacement plugins are installed for any built-in + // driver a saved connection still depends on (e.g. install the + // `postgresql` plugin when a `postgres` connection exists). Spawned, + // not `block_on`, so a slow or failed registry fetch never delays + // window creation — same pattern as the health-check spawn below. + // See `.github/planning/postgres-plugin-force-install.md`. + for (builtin_id, plugin_id) in crate::plugins::force_install::MIGRATABLE_DRIVERS { + let handle = app.handle().clone(); + let builtin_id = builtin_id.to_string(); + let plugin_id = plugin_id.to_string(); + tauri::async_runtime::spawn(async move { + crate::transport::desktop::plugins::force_install::ensure_plugin_installed_if_needed( + &handle, + &builtin_id, + &plugin_id, + ) + .await; + }); + } + + // Subscribe to `tabularis://` deep links so a registry's + // "Open in App" button can hand us a plugin slug + version. + // The handler emits a frontend event; the React side opens the + // install confirmation modal. See `plugins::deep_link`. + // + // On Linux/Windows the scheme is only auto-registered when the + // app is installed from a bundled package. Under `tauri dev` + // the binary lives in `target/debug/...`, so call + // `register("tabularis")` here — it writes the desktop / xdg-mime + // entry pointing at the current binary so Firefox & friends can + // route `tabularis://...` to us. The call is a no-op on macOS + // (handled by Info.plist) and idempotent across restarts. + // + // Inside Snap/Flatpak the exported `.desktop` entry already + // carries `MimeType=x-scheme-handler/tabularis`, and the sandbox + // has neither `xdg-mime` nor write access to the host's + // mimeapps.list — so skip the call instead of logging a failure. + { + use tauri_plugin_deep_link::DeepLinkExt; + let handle = app.handle().clone(); + let deep_link = app.deep_link(); + #[cfg(any(target_os = "linux", all(debug_assertions, target_os = "windows")))] + match crate::sandbox::current() { + Some(sandbox) => log::info!( + "Skipping tabularis:// scheme registration: handled by the {} desktop entry", + sandbox.name() + ), + None => { + if let Err(e) = deep_link.register("tabularis") { + log::warn!("Failed to register tabularis:// scheme: {}", e); + } + } + } + deep_link.on_open_url({ + let handle = handle.clone(); + move |event| { + for url in event.urls() { + crate::transport::desktop::plugins::deep_link::handle_url(&handle, url.as_str()); + } + } + }); + // Cold-start path: when the OS launched us *because of* a + // tabularis:// URL, on_open_url won't fire — the URL is + // already consumed by the launch handshake. Pull it out via + // get_current() and route it through the same handler. + if let Ok(Some(urls)) = deep_link.get_current() { + for url in urls { + crate::transport::desktop::plugins::deep_link::handle_url(&handle, url.as_str()); + } + } + } + + // Start desktop health checks, event watchers, and backups. + let ping_interval = crate::transport::desktop::config::load_config_internal(&app.handle()) + .ping_interval + .unwrap_or(crate::health_check::DEFAULT_PING_INTERVAL); + runtime::lifecycle::start_desktop_schedulers( + app.handle().clone(), + ping_interval as u64, + ); + + // Maximize the window on startup if the user enabled it. + if startup_config + .start_maximized + .unwrap_or(false) + { + if let Some(window) = app.get_webview_window("main") { + if let Err(e) = window.maximize() { + log::warn!("Failed to maximize window on startup: {e}"); + } + } + } + + // Open devtools automatically in debug mode + if args.debug { + if let Some(window) = app.get_webview_window("main") { + window.open_devtools(); + log::info!("DevTools opened (debug mode active)"); + } + } + + // If the user launched with `--explain `, spawn the Visual + // Explain window and hide the main app window: the CLI flag is + // meant to be a dedicated plan viewer, not a full app launch. + if let Some(path) = args.explain.clone() { + log::info!("CLI --explain received: {path}"); + if let Err(e) = + explain_import::spawn_visual_explain_window(app, Some(path)) + { + log::error!("Failed to open Visual Explain window: {e}"); + } + // Close the default main window only AFTER visual-explain is + // built — closing the last window would terminate the app. + if let Some(main) = app.get_webview_window("main") { + if let Err(e) = main.close() { + log::warn!("Failed to close main window: {e}"); + } + } + } + Ok(()) + }) + // Only the main window is persisted; utility windows retain their + // existing per-feature sizing and placement behavior. + .on_window_event(|window, event| { + if window.label() != "main" { return; } + match event { + tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => { + window_placement::remember(window); + } + tauri::WindowEvent::CloseRequested { .. } => { + window_placement::persist(window); + } + _ => {} + } + }) + .invoke_handler(tauri::generate_handler![ + system_theme::get_linux_system_theme, + is_debug_mode, + open_devtools, + close_devtools, + commands::get_registered_drivers, + commands::get_driver_manifest, + commands::get_connection_metadata, + commands::get_keybindings, + commands::save_keybindings, + commands::test_connection, + commands::list_databases, + commands::save_connection, + sqlite_database::create_sqlite_file, + commands::create_sqlite_database, + commands::delete_connection, + commands::update_connection, + commands::duplicate_connection, + commands::get_connections, + commands::get_connection_by_id, + commands::disconnect_connection, + commands::register_active_connection, + commands::get_active_connections, + commands::get_data_types, + commands::map_inferred_column_types, + // SSH Connections + commands::get_ssh_connections, + commands::save_ssh_connection, + commands::update_ssh_connection, + commands::delete_ssh_connection, + commands::test_ssh_connection, + askpass::respond_ssh_askpass, + // K8s Connections + commands::get_k8s_connections, + commands::save_k8s_connection, + commands::update_k8s_connection, + commands::delete_k8s_connection, + commands::test_k8s_connection_cmd, + commands::get_k8s_contexts_cmd, + commands::get_k8s_namespaces_cmd, + commands::get_k8s_resources_cmd, + commands::get_k8s_resource_ports_cmd, + commands::validate_k8s_path_cmd, + // AWS SSM + commands::test_ssm_connection_cmd, + // Connection Groups + commands::get_connection_groups, + commands::get_connections_with_groups, + commands::create_connection_group, + commands::create_group_path, + commands::update_connection_group, + commands::move_group_to_parent, + commands::delete_connection_group, + commands::move_connection_to_group, + commands::reorder_groups, + commands::reorder_connections_in_group, + commands::list_connection_tags, + commands::create_connection_tag, + commands::update_connection_tag, + commands::delete_connection_tag, + commands::set_connection_tags, + commands::export_connections_payload, + commands::encrypt_export_payload, + connection_import_commands::export_connections_file, + backup::get_connections_backup_status, + backup::set_connections_backup_password, + backup::set_connections_backup_target_password, + backup::run_connections_backup, + commands::decrypt_export_payload, + commands::import_connections_payload, + connection_import_commands::list_connection_import_sources, + connection_import_commands::preview_connection_import, + connection_import_commands::apply_connection_import, + connection_import_commands::preview_tabularis_import, + connection_import_commands::apply_tabularis_import, + connection_import_commands::preview_tabularis_import_file, + connection_import_commands::apply_prepared_tabularis_import, + commands::get_schemas, + commands::get_available_databases, + commands::set_selected_databases, + commands::get_tables, + commands::get_columns, + commands::get_foreign_keys, + commands::get_indexes, + commands::delete_record, + commands::update_record, + commands::insert_record, + commands::save_blob_to_file, + commands::fetch_blob, + commands::fetch_blob_as_data_url, + commands::load_blob_from_file, + commands::detect_blob_mime, + commands::detect_mime_type, + commands::get_file_stats, + commands::read_file_as_data_url, + commands::execute_query, + commands::execute_query_batch, + commands::release_query_session, + commands::get_server_now, + commands::explain_query_plan, + commands::count_query, + commands::cancel_query, + commands::get_views, + commands::get_view_definition, + commands::create_view, + commands::alter_view, + commands::drop_view, + commands::get_view_columns, + commands::get_materialized_views, + commands::get_materialized_view_columns, + commands::get_materialized_view_definition, + commands::refresh_materialized_view, + commands::set_window_title, + commands::open_er_diagram_window, + explain_import::load_explain_from_file, + explain_import::get_pending_explain_file, + explain_import::open_visual_explain_window, + export::export_query_to_file, + export::cancel_export, + sql_file::read_sql_file, + sql_file::write_sql_file, + saved_queries::get_saved_queries, + saved_queries::save_query, + saved_queries::update_saved_query, + saved_queries::delete_saved_query, + saved_queries::get_saved_query_folders, + saved_queries::create_saved_query_folder, + saved_queries::rename_saved_query_folder, + saved_queries::delete_saved_query_folder, + saved_queries::move_saved_query, + query_history::get_query_history, + query_history::add_query_history_entry, + query_history::delete_query_history_entry, + query_history::clear_query_history, + // Config + config::get_schema_preference, + config::set_schema_preference, + config::get_last_active_connection, + config::set_last_active_connection, + config::get_last_open_connections, + config::set_last_open_connections, + config::get_selected_schemas, + config::set_selected_schemas, + config::get_config, + config::save_config, + config::get_config_json, + config::save_config_json, + config::relaunch_app, + storage_location::get_storage_location, + storage_location::inspect_storage_location, + storage_location::set_storage_location, + storage_location::reset_storage_location, + storage_location::open_storage_location, + storage_location::get_app_data_dir, + ui_state_commands::get_ui_state, + ui_state_commands::set_ui_state, + ui_state_commands::delete_ui_state, + config::set_ai_key, + config::delete_ai_key, + config::check_ai_key, + config::check_ai_key_status, + proxy::set_proxy_password, + proxy::proxy_password_is_set, + proxy::delete_proxy_password, + config::get_system_prompt, + config::save_system_prompt, + config::reset_system_prompt, + config::get_explain_prompt, + config::save_explain_prompt, + config::reset_explain_prompt, + config::get_explainplan_prompt, + config::save_explainplan_prompt, + config::reset_explainplan_prompt, + config::get_cellname_prompt, + config::save_cellname_prompt, + config::reset_cellname_prompt, + config::get_tabrename_prompt, + config::save_tabrename_prompt, + config::reset_tabrename_prompt, + // AI + ai::generate_ai_query, + ai::explain_ai_query, + ai::analyze_ai_explain_plan, + ai::generate_cell_name, + ai::generate_tab_rename, + ai::suggest_table_name, + ai::get_ai_models, + chatgpt::get_chatgpt_session, + chatgpt::sign_in_chatgpt, + chatgpt::cancel_chatgpt_sign_in, + chatgpt::select_chatgpt_profile, + chatgpt::sign_out_chatgpt, + chatgpt::get_chatgpt_models, + chatgpt::open_chatgpt_usage, + // Clipboard Import + clipboard_import::execute_clipboard_import, + ai_commands::get_ai_schema_context, + commands::get_schema_snapshot, + // DDL generation + commands::get_table_query_template, + commands::get_column_stats, + commands::get_create_table_sql, + commands::get_add_column_sql, + commands::get_alter_column_sql, + commands::get_create_index_sql, + commands::get_create_foreign_key_sql, + commands::get_drop_table_sql, + commands::drop_index_action, + commands::drop_foreign_key_action, + // Routines + commands::get_routines, + commands::get_routine_parameters, + commands::get_routine_definition, + commands::build_routine_call_sql, + commands::get_routine_create_template, + commands::get_routine_edit_script, + commands::drop_routine, + // Triggers + commands::get_triggers, + commands::get_trigger_definition, + commands::create_trigger, + commands::drop_trigger, + // User management + commands::get_db_privilege_catalog, + commands::get_db_users, + commands::get_db_user_grants, + commands::get_db_user_privileges, + commands::create_db_user, + commands::drop_db_user, + commands::set_db_user_password, + commands::apply_db_user_privileges, + // MCP + mcp::install::get_mcp_status, + mcp::install::install_mcp_config, + // AI Activity / Approvals + ai_commands::get_ai_activity, + ai_commands::get_ai_sessions, + ai_commands::get_ai_session_events, + ai_commands::clear_ai_activity, + ai_commands::export_ai_activity_json, + ai_commands::export_ai_activity_csv, + ai_commands::export_ai_session_as_notebook, + ai_commands::list_pending_approvals, + ai_commands::decide_pending_approval, + // Themes + theme_packages::commands::preview_theme_document, + theme_packages::commands::preview_local_theme_package, + theme_commands::install_local_theme_package, + theme_commands::fetch_theme_registry, + theme_commands::fetch_theme_package_detail, + theme_commands::install_registry_theme, + theme_packages::commands::cancel_theme_install, + theme_commands::set_theme_package_enabled, + theme_commands::uninstall_theme_package, + theme_commands::recover_theme_packages, + theme_commands::get_theme_catalog, + theme_commands::create_personal_theme, + theme_commands::create_personal_snapshot, + theme_commands::update_personal_theme, + theme_commands::update_personal_snapshot, + theme_commands::duplicate_personal_theme, + theme_commands::get_all_themes, + theme_commands::get_theme, + theme_commands::save_custom_theme, + theme_commands::delete_custom_theme, + theme_commands::import_theme, + theme_commands::export_theme, + // Dump & Import + dump_commands::dump_database, + dump_commands::cancel_dump, + dump_commands::import_database, + dump_commands::cancel_import, + // Updater + updater::check_for_updates, + updater::download_and_install_update, + updater::get_installation_source, + // Logs + log_commands::get_logs, + log_commands::log_frontend_event, + log_commands::clear_logs, + log_commands::get_log_settings, + log_commands::set_log_enabled, + log_commands::set_log_max_size, + log_commands::export_logs, + log_commands::test_log, + // Preferences + preferences::save_editor_preferences, + preferences::load_editor_preferences, + preferences::delete_editor_preferences, + preferences::list_all_preferences, + // Notebooks + notebooks::create_notebook, + notebooks::save_notebook, + notebooks::load_notebook, + notebooks::delete_notebook, + notebooks::rename_notebook, + notebooks::list_notebooks, + // Plugin Registry + plugins::commands::fetch_plugin_registry, + plugins::commands::install_plugin, + plugins::commands::cancel_plugin_install, + plugins::commands::uninstall_plugin, + plugins::commands::get_installed_plugins, + plugins::commands::disable_plugin, + plugins::commands::enable_plugin, + plugins::commands::get_plugin_manifest, + plugins::commands::get_plugin_dir, + plugins::commands::open_plugins_dir, + plugins::commands::read_plugin_file, + plugins::commands::fetch_tabularium_plugin_preview, + plugins::commands::fetch_plugin_readme, + plugins::deep_link::consume_pending_deep_link_install, + plugins::manager::get_plugin_startup_errors, + plugins::runtime_version::get_plugin_runtime_warnings, + // JSON Viewer + json_viewer::open_json_viewer_window, + json_viewer::get_json_viewer_session, + json_viewer::complete_json_viewer_session, + results_window::open_results_window, + results_window::close_results_window, + // Connection Window + connection_window::open_connection_window, + // Task Manager + task_manager::get_process_list, + task_manager::get_system_stats, + task_manager::get_tabularis_children, + task_manager::kill_plugin_process, + task_manager::restart_plugin_process, + task_manager::open_task_manager_window, + // Connection Appearance + connection_appearance::save_connection_icon, + commands::delete_connection_icon, + commands::set_connection_appearance, + ]) + .build(tauri::generate_context!()) + .expect("error while building tauri application") + .run(move |app_handle, event| { + // Cmd+Q and relaunch paths can exit without CloseRequested. + if matches!(&event, tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit) { + window_placement::persist_cached(app_handle); + } + if let tauri::RunEvent::Exit = event { + app_handle.state::().stop(); + // Back up the freshest state before the process ends (no-op + // unless backups are enabled and due). + backup::run_exit_backup(app_handle); + tauri::async_runtime::block_on(crate::runtime::lifecycle::release_pinned_sessions()); + run_shutdown_hooks.run(); + } + }); +} + +#[tauri::command] +fn is_debug_mode() -> bool { + crate::is_debug_mode() +} diff --git a/src-tauri/src/notebooks.rs b/src-tauri/src/transport/desktop/notebooks.rs similarity index 100% rename from src-tauri/src/notebooks.rs rename to src-tauri/src/transport/desktop/notebooks.rs diff --git a/src-tauri/src/transport/desktop/plugins.rs b/src-tauri/src/transport/desktop/plugins.rs new file mode 100644 index 000000000..5b1d302ab --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins.rs @@ -0,0 +1,6 @@ +pub mod commands; +pub mod connection_metadata; +pub mod deep_link; +pub mod force_install; +pub mod manager; +pub mod runtime_version; diff --git a/src-tauri/src/transport/desktop/plugins/commands.rs b/src-tauri/src/transport/desktop/plugins/commands.rs new file mode 100644 index 000000000..7845b1b87 --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/commands.rs @@ -0,0 +1,121 @@ +use crate::drivers::driver_trait::PluginManifest; +use crate::plugins::installer::{self, InstalledPluginInfo}; +use crate::plugins::registry::{PluginReadme, RegistryPluginWithStatus}; +use crate::runtime::RuntimeContext; +use tauri::{AppHandle, State}; + +#[tauri::command] +pub async fn fetch_plugin_registry( + runtime: State<'_, RuntimeContext>, +) -> Result, String> { + crate::application::plugins::fetch_plugin_registry(runtime.inner()).await +} + +#[tauri::command] +pub async fn install_plugin( + runtime: State<'_, RuntimeContext>, + plugin_id: String, + version: Option, + registry_url: Option, +) -> Result<(), String> { + crate::application::plugins::install_plugin(runtime.inner(), plugin_id, version, registry_url) + .await +} + +#[tauri::command] +pub async fn uninstall_plugin( + runtime: State<'_, RuntimeContext>, + plugin_id: String, +) -> Result<(), String> { + crate::application::plugins::uninstall_plugin(runtime.inner(), plugin_id).await +} + +#[tauri::command] +pub async fn get_installed_plugins( + runtime: State<'_, RuntimeContext>, +) -> Result, String> { + Ok(crate::application::plugins::get_installed_plugins( + runtime.inner(), + )) +} + +#[tauri::command] +pub async fn enable_plugin( + runtime: State<'_, RuntimeContext>, + plugin_id: String, +) -> Result<(), String> { + crate::application::plugins::enable_plugin(runtime.inner(), plugin_id).await +} + +#[tauri::command] +pub async fn get_plugin_manifest( + runtime: State<'_, RuntimeContext>, + plugin_id: String, +) -> Result { + crate::application::plugins::get_plugin_manifest(runtime.inner(), plugin_id) +} + +/// Opens the plugins directory in the desktop file manager. +/// Browser sessions never receive an equivalent server-path operation. +#[tauri::command] +pub fn open_plugins_dir(app: AppHandle) -> Result<(), String> { + use tauri_plugin_opener::OpenerExt; + let plugins_dir = installer::get_plugins_dir()?; + app.opener() + .open_path(plugins_dir.to_string_lossy().to_string(), None::<&str>) + .map_err(|error| format!("Failed to open plugins directory: {error}")) +} + +#[tauri::command] +pub async fn fetch_tabularium_plugin_preview( + runtime: State<'_, RuntimeContext>, + slug: String, + registry_url: Option, + version: Option, +) -> Result { + crate::application::plugins::fetch_plugin_preview(runtime.inner(), slug, registry_url, version) + .await +} + +#[tauri::command] +pub async fn fetch_plugin_readme( + runtime: State<'_, RuntimeContext>, + slug: String, + locale: Option, + registry_url: Option, +) -> Result { + crate::application::plugins::fetch_plugin_readme(runtime.inner(), slug, locale, registry_url) + .await +} + +/// Reads a file from an installed plugin's directory for the desktop UI loader. +/// Browser plugin assets use the authenticated asset route implemented separately. +#[tauri::command] +pub fn read_plugin_file( + runtime: State<'_, RuntimeContext>, + plugin_id: String, + file_path: String, +) -> Result { + crate::application::plugin_assets::read_plugin_asset_text( + &runtime.paths.plugins_dir(), + &plugin_id, + &file_path, + ) +} + +#[tauri::command] +pub fn cancel_plugin_install(plugin_id: String) -> bool { + crate::plugins::commands::cancel_plugin_install(plugin_id) +} + +#[tauri::command] +pub async fn disable_plugin(plugin_id: String) -> Result<(), String> { + crate::plugins::commands::disable_plugin(plugin_id).await +} + +/// Returns the absolute filesystem path of an installed plugin's directory. +/// Desktop-only: browser RPC deliberately does not expose server filesystem paths. +#[tauri::command] +pub fn get_plugin_dir(plugin_id: String) -> Result { + crate::plugins::commands::get_plugin_dir(plugin_id) +} diff --git a/src-tauri/src/transport/desktop/plugins/connection_metadata.rs b/src-tauri/src/transport/desktop/plugins/connection_metadata.rs new file mode 100644 index 000000000..027fcca6d --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/connection_metadata.rs @@ -0,0 +1,9 @@ +/// The UI invalidates only discovery-enabled contexts. Emitting for every +/// replacement also covers an update that removes a plugin's discovery opt-in. +pub async fn notify_plugin_reload(app: &tauri::AppHandle, driver_id: &str) { + use tauri::Emitter; + let _ = app.emit( + "connection-metadata-invalidated", + serde_json::json!({"driverId": driver_id}), + ); +} diff --git a/src-tauri/src/transport/desktop/plugins/deep_link.rs b/src-tauri/src/transport/desktop/plugins/deep_link.rs new file mode 100644 index 000000000..9c76596ef --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/deep_link.rs @@ -0,0 +1,55 @@ +use crate::plugins::deep_link::*; +use tauri::{AppHandle, Emitter, Manager}; + +/// Dispatch a single URL to the frontend. Called from: +/// * the deep-link plugin's `on_open_url` handler (warm handoff), +/// * the cold-start `get_current()` path on app boot, +/// * the `single_instance` callback when a second launch forwards args. +/// +/// We both **emit** an event (so an already-mounted listener reacts +/// immediately) AND **stash** the request in `PendingInstall` so a fresh +/// React subscription can drain it on mount. Without the stash a cold-start +/// URL is delivered before the webview's event listener exists and silently +/// dropped. +pub fn handle_url(app: &AppHandle, raw: &str) { + let Some(req) = parse_install_url(raw) else { + log::info!("Ignoring tabularis:// URL: {}", raw); + return; + }; + + // Stash for cold-start replay; the frontend pulls this on mount via + // `consume_pending_deep_link_install`. + if let Some(state) = app.try_state::>() { + if let Ok(mut slot) = state.0.lock() { + *slot = Some(req.clone()); + } + } + + if let Err(err) = app.emit(PLUGIN_INSTALL_EVENT, &req) { + log::error!( + "Failed to emit {}: {} (request: {:?})", + PLUGIN_INSTALL_EVENT, + err, + req + ); + } else { + log::info!("Emitted {} for slug '{}'", PLUGIN_INSTALL_EVENT, req.slug); + } + + // Focus the main window so the user sees the confirmation modal — + // a second launch may otherwise leave Tabularis in the background. + if let Some(win) = app.get_webview_window("main") { + let _ = win.unminimize(); + let _ = win.set_focus(); + } +} + +/// Drains the pending deep-link install request, if any. Called from the +/// frontend immediately after the listener mounts to recover URLs that +/// arrived during cold-start before the event subscription existed. +#[tauri::command] +pub fn consume_pending_deep_link_install( + state: tauri::State<'_, std::sync::Arc>, +) -> Option { + state.0.lock().ok().and_then(|mut slot| slot.take()) +} diff --git a/src-tauri/src/transport/desktop/plugins/force_install.rs b/src-tauri/src/transport/desktop/plugins/force_install.rs new file mode 100644 index 000000000..bc455c8e0 --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/force_install.rs @@ -0,0 +1,155 @@ +use crate::config::AppConfig; +use crate::plugins::force_install::*; +use crate::plugins::{installer, tabularium}; +use crate::transport::desktop::config; +use tauri::{AppHandle, Emitter}; + +/// Ensure the plugin for `builtin_id` is installed, but only when at least one +/// saved connection is still on the built-in driver. A user with no such +/// connection is left untouched — no plugin they don't need. +/// +/// Public entry point spawned from `setup()`. +pub async fn ensure_plugin_installed_if_needed(app: &AppHandle, builtin_id: &str, plugin_id: &str) { + match connections_use_driver(app, builtin_id) { + Ok(false) => return, // nothing on this built-in driver, nothing to do + Ok(true) => {} + Err(e) => { + log::warn!("{LOG_PREFIX} could not read connections: {e}"); + return; + } + } + ensure_plugin_installed(app, plugin_id).await; +} + +/// Install (and activate) `plugin_id` if it isn't already installed and the +/// latest release is compatible with this app build. Every failure path +/// logs and returns silently — there's no UI-visible error and no retry loop +/// within a single launch. The check re-runs from scratch on every launch, +/// so a transient failure self-heals next time; a persistent one (no network, +/// corporate proxy) is handled by the frontend nudge staying suppressed until +/// the plugin is actually present (see the design doc's connectivity section). +pub async fn ensure_plugin_installed(app: &AppHandle, plugin_id: &str) { + match installer::list_installed() { + Ok(installed) if installed.iter().any(|p| p.id == plugin_id) => return, + Ok(_) => {} + Err(e) => { + log::warn!("{LOG_PREFIX} could not list installed plugins: {e}"); + return; + } + } + if !plugin_compatible_with_this_app(app, plugin_id).await { + log::warn!("{LOG_PREFIX} {plugin_id} has no compatible release, skipping"); + return; + } + let runtime = tauri::Manager::state::(app); + if let Err(e) = + crate::application::plugins::install_plugin(&runtime, plugin_id.to_string(), None, None) + .await + { + log::warn!("{LOG_PREFIX} {plugin_id} install failed: {e}"); + return; + } + // `install_plugin` hot-registers for this session but does not persist + // activation — without this write the plugin vanishes on relaunch + // (`load_plugins` skips installed-but-unlisted drivers). Same effect as + // `NewConnectionModal`'s `updateSetting("activeExternalDrivers", ...)`, + // written from the backend because this runs in a spawned task. + if let Err(e) = persist_activation(app, plugin_id) { + log::warn!("{LOG_PREFIX} could not activate {plugin_id}: {e}"); + } + // Tell the already-running frontend the plugin is installed and + // (activation errors aside) registered — see `PLUGIN_ACTIVATED_EVENT`'s + // doc comment for why this can't wait for the next launch. Emitted even + // if `persist_activation` above failed: `install_plugin` still + // hot-registered the driver for this session, so `useDrivers`' + // `get_registered_drivers`/`get_installed_plugins` refetch has something + // new to report regardless of whether the config write landed. + if let Err(e) = app.emit(PLUGIN_ACTIVATED_EVENT, PluginActivatedPayload { plugin_id }) { + log::warn!("{LOG_PREFIX} could not emit {PLUGIN_ACTIVATED_EVENT}: {e}"); + } +} + +/// Persist `plugin_id` into `active_external_drivers` via the `save_config` +/// merge, leaving every other config field untouched. Idempotent: a no-op if +/// the id is already active. +/// +/// Reads the currently-installed plugin ids first: `merge_active_driver` needs +/// them to seed the list correctly when no preference has been saved yet (see +/// its doc comment). Bails without writing if that read fails — narrowing to +/// just `plugin_id` on a guess would be worse than not activating it this +/// launch, since it could silently deactivate every other installed plugin. +fn persist_activation(app: &AppHandle, plugin_id: &str) -> Result<(), String> { + let config = config::load_config_internal(app); + let installed_ids: Vec = installer::list_installed()? + .into_iter() + .map(|p| p.id) + .collect(); + let updated = merge_active_driver(&config, plugin_id, &installed_ids); + // Only write when something actually changed — avoids a pointless + // config.json rewrite (and cache invalidation) on every launch. + if updated.active_external_drivers == config.active_external_drivers { + return Ok(()); + } + // Pass save_config a config with only `active_external_drivers` set, + // not the full `updated` snapshot: save_config re-reads disk and + // overwrites every `Some` field, so writing back the stale snapshot + // taken above would silently revert any other setting the user changed + // in the meantime — the inverse of the race the frontend's + // `plugin-activated` listener already guards against. + config::save_config( + app.clone(), + AppConfig { + active_external_drivers: updated.active_external_drivers, + ..AppConfig::default() + }, + ) +} + +/// True when at least one saved connection has `params.driver == driver_id`. +/// Reads the connections file directly via `persistence::load_connections` +/// (the same path `get_connections` uses internally) rather than invoking the +/// Tauri command — the command wrapper runs per-call SSH/SSL migrations we +/// don't want firing on every launch just to detect a trigger. +fn connections_use_driver(app: &AppHandle, driver_id: &str) -> Result { + let path = crate::transport::desktop::commands::get_config_path(app)?; + let connections = crate::persistence::load_connections(&path)?; + Ok(connections.iter().any(|c| c.params.driver == driver_id)) +} + +/// Check the latest release's `min_tabularis_version` against the running +/// app's own version. `install_plugin` doesn't gate on this itself, so without +/// this check an unattended install could silently install a release that +/// requires a newer Tabularis than the user is running, leaving them +/// installed-but-non-functional. Reuses the `semver::Version::parse` primitive +/// `classify_install` (`registry.rs:43`) already uses, applied to a different +/// comparison. +async fn plugin_compatible_with_this_app(app: &AppHandle, plugin_id: &str) -> bool { + let config = config::load_config_internal(app); + let base = registry_base_url(&config).trim_end_matches('/'); + let Ok(detail) = tabularium::fetch_plugin_detail(base, plugin_id).await else { + // Couldn't reach the registry — treat as compatible-by-default so a + // network blip doesn't permanently block an otherwise-fine install; + // the install itself will surface a real download error if it persists. + log::warn!("{LOG_PREFIX} could not fetch detail for {plugin_id}, assuming compatible"); + return true; + }; + // Find the release matching the registry's latest_version; fall back to + // the first release if the version string can't be matched. + let target = if detail.latest_version.is_empty() { + detail.releases.first() + } else { + detail + .releases + .iter() + .find(|r| r.version == detail.latest_version) + .or_else(|| detail.releases.first()) + }; + let Some(release) = target else { + log::warn!("{LOG_PREFIX} {plugin_id} has no releases on the registry"); + return false; + }; + let Some(min) = &release.min_tabularis_version else { + return true; // no minimum declared → compatible with any version + }; + is_version_compatible(min, env!("CARGO_PKG_VERSION")) +} diff --git a/src-tauri/src/transport/desktop/plugins/manager.rs b/src-tauri/src/transport/desktop/plugins/manager.rs new file mode 100644 index 000000000..b9eea3b91 --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/manager.rs @@ -0,0 +1,19 @@ +use crate::plugins::manager::*; +use tauri::AppHandle; + +/// Load installed plugins at startup. +/// +/// `enabled_ids` controls which plugins are started: +/// - `None` → load all installed plugins (first-run or no preference saved). +/// - `Some(ids)` → load only the plugins whose directory name (= plugin ID) is in `ids`. +pub async fn load_plugins(app: &AppHandle, enabled_ids: Option<&[String]>) { + let plugin_configs = crate::transport::desktop::config::load_config_internal(app) + .plugins + .unwrap_or_default(); + load_plugins_with_configs(plugin_configs, enabled_ids).await; +} + +#[tauri::command] +pub fn get_plugin_startup_errors() -> Vec { + crate::plugins::manager::get_plugin_startup_errors() +} diff --git a/src-tauri/src/transport/desktop/plugins/runtime_version.rs b/src-tauri/src/transport/desktop/plugins/runtime_version.rs new file mode 100644 index 000000000..f5e0777ab --- /dev/null +++ b/src-tauri/src/transport/desktop/plugins/runtime_version.rs @@ -0,0 +1,6 @@ +use crate::plugins::runtime_version::*; + +#[tauri::command] +pub fn get_plugin_runtime_warnings() -> Vec { + crate::plugins::runtime_version::get_plugin_runtime_warnings() +} diff --git a/src-tauri/src/transport/desktop/preferences.rs b/src-tauri/src/transport/desktop/preferences.rs new file mode 100644 index 000000000..29c2cc2fb --- /dev/null +++ b/src-tauri/src/transport/desktop/preferences.rs @@ -0,0 +1,67 @@ +use crate::preferences::*; +use std::collections::HashMap; +use tauri::{AppHandle, Manager}; + +#[tauri::command] +pub async fn save_editor_preferences( + app: AppHandle, + connection_id: String, + preferences: EditorPreferences, +) -> Result<(), String> { + crate::application::persistence::save_editor_preferences_for_desktop( + &app.state::(), + &connection_id, + &preferences, + ) +} + +#[tauri::command] +pub async fn load_editor_preferences( + app: AppHandle, + connection_id: String, +) -> Result, String> { + crate::application::persistence::load_editor_preferences_for_desktop( + &app.state::(), + &connection_id, + ) +} + +#[tauri::command] +pub async fn delete_editor_preferences( + app: AppHandle, + connection_id: String, +) -> Result<(), String> { + crate::application::persistence::delete_editor_preferences_for_desktop( + &app.state::(), + &connection_id, + ) +} + +#[tauri::command] +pub async fn list_all_preferences( + app: AppHandle, +) -> Result, String> { + let preferences_dir = app + .state::() + .paths + .config_dir() + .join("preferences"); + if !preferences_dir.exists() { + return Ok(HashMap::new()); + } + + let mut preferences = HashMap::new(); + for entry in std::fs::read_dir(preferences_dir).map_err(|error| error.to_string())? { + let entry = entry.map_err(|error| error.to_string())?; + let Some(connection_id) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + if let Some(value) = crate::application::persistence::load_editor_preferences_for_desktop( + &app.state::(), + &connection_id, + )? { + preferences.insert(connection_id, value); + } + } + Ok(preferences) +} diff --git a/src-tauri/src/transport/desktop/proxy.rs b/src-tauri/src/transport/desktop/proxy.rs new file mode 100644 index 000000000..b5ba689e4 --- /dev/null +++ b/src-tauri/src/transport/desktop/proxy.rs @@ -0,0 +1,14 @@ +#[tauri::command] +pub fn set_proxy_password(slot: String, password: String) -> Result<(), String> { + crate::proxy::set_proxy_password(slot, password) +} + +#[tauri::command] +pub fn proxy_password_is_set(slot: String) -> Result { + crate::proxy::proxy_password_is_set(slot) +} + +#[tauri::command] +pub fn delete_proxy_password(slot: String) -> Result<(), String> { + crate::proxy::delete_proxy_password(slot) +} diff --git a/src-tauri/src/transport/desktop/query_history.rs b/src-tauri/src/transport/desktop/query_history.rs new file mode 100644 index 000000000..723108058 --- /dev/null +++ b/src-tauri/src/transport/desktop/query_history.rs @@ -0,0 +1,105 @@ +use crate::application::productivity::{self, ProductivityCommand}; +use crate::query_history::*; +use serde_json::from_value; +use tauri::{AppHandle, Manager, Runtime}; + +#[tauri::command] +pub async fn get_query_history( + app: AppHandle, + connection_id: String, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + from_value( + productivity::execute( + config_dir, + ProductivityCommand::GetQueryHistory { connection_id }, + ) + .await?, + ) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +#[allow(clippy::too_many_arguments)] +pub async fn add_query_history_entry( + app: AppHandle, + connection_id: String, + sql: String, + executed_at: String, + execution_time_ms: Option, + status: String, + rows_affected: Option, + error: Option, + database: Option, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + from_value( + productivity::execute( + config_dir, + ProductivityCommand::AddQueryHistoryEntry { + connection_id, + sql, + executed_at, + execution_time_ms, + status, + rows_affected, + error, + database, + }, + ) + .await?, + ) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn delete_query_history_entry( + app: AppHandle, + connection_id: String, + id: String, +) -> Result<(), String> { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::execute( + config_dir, + ProductivityCommand::DeleteQueryHistoryEntry { connection_id, id }, + ) + .await?; + Ok(()) +} + +#[tauri::command] +pub async fn clear_query_history( + app: AppHandle, + connection_id: String, +) -> Result<(), String> { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::execute( + config_dir, + ProductivityCommand::ClearQueryHistory { connection_id }, + ) + .await?; + Ok(()) +} + +pub async fn backfill_missing_database_for_connection( + app: &AppHandle, + connection_id: &str, + database: &str, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::backfill_query_history_for_connection(config_dir, connection_id, database) +} + +pub async fn remove_history_for_connection( + app: &AppHandle, + connection_id: &str, +) -> Result<(), String> { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::remove_query_history_for_connection(config_dir, connection_id) +} diff --git a/src-tauri/src/transport/desktop/results_window.rs b/src-tauri/src/transport/desktop/results_window.rs new file mode 100644 index 000000000..758411bf0 --- /dev/null +++ b/src-tauri/src/transport/desktop/results_window.rs @@ -0,0 +1,96 @@ +use crate::results_window::*; +use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent}; +use urlencoding::encode; + +/// Open (or focus) the detached results window for a given tab. Result data is +/// streamed from the main window via `resultsSyncEvent(tabId)` in +/// `src/utils/resultsWindowSync.ts`, so no payload is passed here. +#[tauri::command] +pub async fn open_results_window( + app: AppHandle, + store: tauri::State<'_, std::sync::Arc>, + tab_id: String, + title: Option, +) -> Result<(), String> { + let label = window_label(&tab_id); + + // If it already exists, just bring it to the front. + if let Some(window) = app.get_webview_window(&label) { + let _ = window.unminimize(); + let _ = window.set_focus(); + return Ok(()); + } + + let window_title = title.unwrap_or_else(|| "Query Results".to_string()); + + let remembered = store + .bounds + .lock() + .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? + .get(&tab_id) + .copied(); + + let url = format!("/results-window?tab={}", encode(&tab_id)); + let mut builder = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) + .title(&window_title) + .min_inner_size(500.0, 300.0) + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) + .background_color(tauri::webview::Color(2, 6, 23, 255)); + + builder = match remembered { + Some(b) => builder + .inner_size(b.width as f64, b.height as f64) + .position(b.x as f64, b.y as f64), + None => builder.inner_size(900.0, 600.0).center(), + }; + + match builder.build() { + Err(e) => Err(format!("Failed to create results window: {}", e)), + Ok(window) => { + let app_handle = app.clone(); + let captured_label = label.clone(); + let captured_tab_id = tab_id.clone(); + window.on_window_event(move |event| { + if let WindowEvent::CloseRequested { .. } = event { + if let Some(win) = app_handle.get_webview_window(&captured_label) { + // Save the inner size: it is restored via `.inner_size(...)` + // below, so saving `outer_size()` would grow the window by + // the decoration height on each detach→close→reopen cycle. + if let (Ok(pos), Ok(size)) = (win.outer_position(), win.inner_size()) { + let store = app_handle.state::>(); + if let Ok(mut bounds) = store.bounds.lock() { + bounds.insert( + captured_tab_id.clone(), + WindowBounds { + x: pos.x, + y: pos.y, + width: size.width, + height: size.height, + }, + ); + }; + } + } + // Let the main window re-attach this tab's results panel. + let _ = app_handle.emit( + "results-window:closed", + serde_json::json!({ "tabId": captured_tab_id }), + ); + } + }); + Ok(()) + } + } +} + +/// Programmatically close a tab's detached results window (used by the +/// "Re-attach" button and when the bound tab is closed). +#[tauri::command] +pub async fn close_results_window(app: AppHandle, tab_id: String) -> Result<(), String> { + if let Some(window) = app.get_webview_window(&window_label(&tab_id)) { + window + .close() + .map_err(|e| format!("Failed to close results window: {}", e))?; + } + Ok(()) +} diff --git a/src-tauri/src/transport/desktop/runtime.rs b/src-tauri/src/transport/desktop/runtime.rs new file mode 100644 index 000000000..d54986511 --- /dev/null +++ b/src-tauri/src/transport/desktop/runtime.rs @@ -0,0 +1,2 @@ +pub mod events; +pub mod lifecycle; diff --git a/src-tauri/src/transport/desktop/runtime/events.rs b/src-tauri/src/transport/desktop/runtime/events.rs new file mode 100644 index 000000000..235cc1014 --- /dev/null +++ b/src-tauri/src/transport/desktop/runtime/events.rs @@ -0,0 +1,21 @@ +use crate::runtime::events::*; +use serde_json::Value; +use tauri::Emitter; + +pub struct TauriRuntimeEvents { + app: tauri::AppHandle, +} + +impl TauriRuntimeEvents { + pub fn new(app: tauri::AppHandle) -> Self { + Self { app } + } +} + +impl RuntimeEvents for TauriRuntimeEvents { + fn emit(&self, event: &str, payload: Value) -> Result<(), String> { + self.app + .emit(event, payload) + .map_err(|error| error.to_string()) + } +} diff --git a/src-tauri/src/transport/desktop/runtime/lifecycle.rs b/src-tauri/src/transport/desktop/runtime/lifecycle.rs new file mode 100644 index 000000000..44077c3f8 --- /dev/null +++ b/src-tauri/src/transport/desktop/runtime/lifecycle.rs @@ -0,0 +1,12 @@ +pub fn start_desktop_schedulers(app: tauri::AppHandle, ping_interval_secs: u64) { + let health_check_app = app.clone(); + crate::async_rt::spawn(async move { + crate::transport::desktop::health_check::start_ping_loop( + health_check_app, + ping_interval_secs, + ) + .await; + }); + crate::transport::desktop::ai_approval_watcher::spawn(app.clone()); + crate::transport::desktop::backup::spawn_scheduler(app); +} diff --git a/src-tauri/src/transport/desktop/saved_queries.rs b/src-tauri/src/transport/desktop/saved_queries.rs new file mode 100644 index 000000000..5d6fc754d --- /dev/null +++ b/src-tauri/src/transport/desktop/saved_queries.rs @@ -0,0 +1,188 @@ +use crate::application::productivity::{self, ProductivityCommand}; +use crate::saved_queries::*; +use crate::saved_query_folders::SavedQueryFolder; +use serde_json::from_value; +use tauri::{AppHandle, Manager, Runtime}; + +#[tauri::command] +pub async fn get_saved_queries( + app: AppHandle, + connection_id: String, +) -> Result, String> { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + from_value( + productivity::execute( + config_dir, + ProductivityCommand::GetSavedQueries { connection_id }, + ) + .await?, + ) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn save_query( + app: AppHandle, + connection_id: String, + name: String, + sql: String, + database: Option, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + from_value( + productivity::execute( + config_dir, + ProductivityCommand::SaveQuery { + connection_id, + name, + sql, + database, + }, + ) + .await?, + ) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn update_saved_query( + app: AppHandle, + connection_id: Option, + id: String, + name: String, + sql: String, + database: Option, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + from_value( + productivity::execute( + config_dir, + ProductivityCommand::UpdateSavedQuery { + connection_id, + id, + name, + sql, + database, + }, + ) + .await?, + ) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn delete_saved_query( + app: AppHandle, + connection_id: Option, + id: String, +) -> Result<(), String> { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::execute( + config_dir, + ProductivityCommand::DeleteSavedQuery { connection_id, id }, + ) + .await?; + Ok(()) +} + +pub fn backfill_missing_database_for_connection( + app: &AppHandle, + connection_id: &str, + database: &str, +) -> Result { + let runtime = app.state::(); + let config_dir = runtime.paths.config_dir(); + productivity::backfill_saved_queries_for_connection(config_dir, connection_id, database) +} + +#[tauri::command] +pub async fn get_saved_query_folders( + app: AppHandle, + connection_id: String, +) -> Result, String> { + execute_typed( + &app, + ProductivityCommand::GetSavedQueryFolders { connection_id }, + ) + .await +} + +#[tauri::command] +pub async fn create_saved_query_folder( + app: AppHandle, + connection_id: String, + name: String, +) -> Result { + execute_typed( + &app, + ProductivityCommand::CreateSavedQueryFolder { + connection_id, + name, + }, + ) + .await +} + +#[tauri::command] +pub async fn rename_saved_query_folder( + app: AppHandle, + connection_id: Option, + id: String, + name: String, +) -> Result { + execute_typed( + &app, + ProductivityCommand::RenameSavedQueryFolder { + connection_id, + id, + name, + }, + ) + .await +} + +/// Only empty folders can be deleted; see `saved_query_folders::delete_folder`. +#[tauri::command] +pub async fn delete_saved_query_folder( + app: AppHandle, + connection_id: Option, + id: String, +) -> Result<(), String> { + execute_typed( + &app, + ProductivityCommand::DeleteSavedQueryFolder { connection_id, id }, + ) + .await +} + +/// Moves a saved query into a folder, or to Unfiled when `folder_id` is null. +#[tauri::command] +pub async fn move_saved_query( + app: AppHandle, + connection_id: Option, + id: String, + folder_id: Option, +) -> Result<(), String> { + execute_typed( + &app, + ProductivityCommand::MoveSavedQuery { + connection_id, + id, + folder_id, + }, + ) + .await +} + +async fn execute_typed( + app: &AppHandle, + command: ProductivityCommand, +) -> Result { + let runtime = app.state::(); + from_value(productivity::execute(runtime.paths.config_dir(), command).await?) + .map_err(|error| error.to_string()) +} diff --git a/src-tauri/src/transport/desktop/sql_file.rs b/src-tauri/src/transport/desktop/sql_file.rs new file mode 100644 index 000000000..c155ca2b9 --- /dev/null +++ b/src-tauri/src/transport/desktop/sql_file.rs @@ -0,0 +1,9 @@ +#[tauri::command] +pub async fn read_sql_file(path: String) -> Result { + crate::sql_file::read_sql_file(path).await +} + +#[tauri::command] +pub async fn write_sql_file(path: String, content: String) -> Result<(), String> { + crate::sql_file::write_sql_file(path, content).await +} diff --git a/src-tauri/src/transport/desktop/sqlite_database.rs b/src-tauri/src/transport/desktop/sqlite_database.rs new file mode 100644 index 000000000..3718b4119 --- /dev/null +++ b/src-tauri/src/transport/desktop/sqlite_database.rs @@ -0,0 +1,4 @@ +#[tauri::command] +pub async fn create_sqlite_file(path: String) -> Result { + crate::sqlite_database::create_sqlite_file(path).await +} diff --git a/src-tauri/src/transport/desktop/storage_location.rs b/src-tauri/src/transport/desktop/storage_location.rs new file mode 100644 index 000000000..643021b56 --- /dev/null +++ b/src-tauri/src/transport/desktop/storage_location.rs @@ -0,0 +1,45 @@ +use crate::storage_location::*; +use std::fs; + +/// Reveal the folder currently in use in the system file manager. +#[tauri::command] +pub fn open_storage_location(app: tauri::AppHandle) -> Result<(), String> { + use tauri_plugin_opener::OpenerExt; + let dir = crate::paths::get_app_config_dir(); + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + app.opener() + .open_path(dir.to_string_lossy().to_string(), None::<&str>) + .map_err(|e| format!("Failed to open storage folder: {e}")) +} + +#[tauri::command] +pub fn get_storage_location() -> StorageLocationInfo { + crate::storage_location::get_storage_location() +} + +#[tauri::command] +pub fn inspect_storage_location(path: String) -> Result { + crate::storage_location::inspect_storage_location(path) +} + +/// Record `path` as the storage folder, optionally copying the current data +/// into it. Takes effect on the next launch. +#[tauri::command] +pub fn set_storage_location(path: String, copy_data: bool) -> Result { + crate::storage_location::set_storage_location(path, copy_data) +} + +/// Go back to the platform default folder on the next launch. Data in the +/// custom folder is left untouched. +#[tauri::command] +pub fn reset_storage_location() -> Result { + crate::storage_location::reset_storage_location() +} + +/// Absolute data directory, for the frontend to build `asset://` URLs of +/// connection icons. Replaces `appDataDir()` from the Tauri JS API, which +/// knows nothing about the custom location. +#[tauri::command] +pub fn get_app_data_dir() -> String { + crate::storage_location::get_app_data_dir() +} diff --git a/src-tauri/src/system_theme.rs b/src-tauri/src/transport/desktop/system_theme.rs similarity index 100% rename from src-tauri/src/system_theme.rs rename to src-tauri/src/transport/desktop/system_theme.rs diff --git a/src-tauri/src/system_theme/portal.rs b/src-tauri/src/transport/desktop/system_theme/portal.rs similarity index 100% rename from src-tauri/src/system_theme/portal.rs rename to src-tauri/src/transport/desktop/system_theme/portal.rs diff --git a/src-tauri/src/system_theme/portal/tests.rs b/src-tauri/src/transport/desktop/system_theme/portal/tests.rs similarity index 100% rename from src-tauri/src/system_theme/portal/tests.rs rename to src-tauri/src/transport/desktop/system_theme/portal/tests.rs diff --git a/src-tauri/src/task_manager.rs b/src-tauri/src/transport/desktop/task_manager.rs similarity index 95% rename from src-tauri/src/task_manager.rs rename to src-tauri/src/transport/desktop/task_manager.rs index e1f659197..b1c27af03 100644 --- a/src-tauri/src/task_manager.rs +++ b/src-tauri/src/transport/desktop/task_manager.rs @@ -55,7 +55,7 @@ pub async fn open_task_manager_window(app: AppHandle) -> Result<(), String> { .inner_size(900.0, 600.0) .min_inner_size(700.0, 450.0) .center() - .decorations(crate::window_decorations::native_decorations_enabled()) + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) .build() .map_err(|error| format!("Failed to create task manager window: {error}"))?; diff --git a/src-tauri/src/transport/desktop/tests.rs b/src-tauri/src/transport/desktop/tests.rs new file mode 100644 index 000000000..321e02b32 --- /dev/null +++ b/src-tauri/src/transport/desktop/tests.rs @@ -0,0 +1,155 @@ +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::secrets::RuntimeSecrets; +use crate::runtime::RuntimeContext; +use std::sync::Arc; + +struct NoSecrets; + +impl RuntimeSecrets for NoSecrets { + fn get(&self, _account: &str) -> Result, String> { + Ok(None) + } + + fn set(&self, _account: &str, _secret: &str) -> Result<(), String> { + Ok(()) + } + + fn delete(&self, _account: &str) -> Result<(), String> { + Ok(()) + } +} + +#[tokio::test] +async fn desktop_productivity_commands_use_the_managed_custom_config_directory() { + use crate::transport::desktop::{query_history, saved_queries}; + let root = tempfile::tempdir().unwrap(); + let config = root.path().join("custom-config"); + let runtime = RuntimeContext::new( + Arc::new(crate::runtime::paths::FixedRuntimePaths::new( + config.clone(), + root.path().join("data"), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoSecrets), + ); + let app = tauri::test::mock_builder() + .manage(runtime) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + let handle = app.handle().clone(); + let connection = uuid::Uuid::new_v4().to_string(); + let seed = crate::application::productivity::execute( + &config, + crate::application::productivity::ProductivityCommand::SaveQuery { + connection_id: connection.clone(), + name: "Seed".into(), + sql: "SELECT 0".into(), + database: None, + }, + ) + .await + .unwrap(); + assert_eq!( + saved_queries::get_saved_queries(handle.clone(), connection.clone()) + .await + .unwrap() + .len(), + 1, + "desktop reads must use the managed runtime path" + ); + saved_queries::delete_saved_query( + handle.clone(), + Some(connection.clone()), + seed["id"].as_str().unwrap().into(), + ) + .await + .unwrap(); + let saved = saved_queries::save_query( + handle.clone(), + connection.clone(), + "Custom".into(), + "SELECT 1".into(), + None, + ) + .await + .unwrap(); + assert!( + config.join("saved_queries").exists(), + "saved queries must use the runtime config directory" + ); + assert_eq!( + saved_queries::get_saved_queries(handle.clone(), connection.clone()) + .await + .unwrap() + .len(), + 1 + ); + saved_queries::update_saved_query( + handle.clone(), + Some(connection.clone()), + saved.id.clone(), + "Updated".into(), + "SELECT 2".into(), + None, + ) + .await + .unwrap(); + assert_eq!( + saved_queries::backfill_missing_database_for_connection(&handle, &connection, "db") + .unwrap(), + 1 + ); + saved_queries::delete_saved_query(handle.clone(), Some(connection.clone()), saved.id) + .await + .unwrap(); + assert!( + saved_queries::get_saved_queries(handle.clone(), connection.clone()) + .await + .unwrap() + .is_empty() + ); + let entry = query_history::add_query_history_entry( + handle.clone(), + connection.clone(), + "SELECT 1".into(), + "2026-10-15T00:00:00Z".into(), + None, + "success".into(), + None, + None, + None, + ) + .await + .unwrap(); + assert!( + config.join("query_history").exists(), + "history must use the runtime config directory" + ); + assert_eq!( + query_history::get_query_history(handle.clone(), connection.clone()) + .await + .unwrap() + .entries + .len(), + 1 + ); + assert_eq!( + query_history::backfill_missing_database_for_connection(&handle, &connection, "db") + .await + .unwrap(), + 1 + ); + query_history::delete_query_history_entry(handle.clone(), connection.clone(), entry.id) + .await + .unwrap(); + query_history::clear_query_history(handle.clone(), connection.clone()) + .await + .unwrap(); + query_history::remove_history_for_connection(&handle, &connection) + .await + .unwrap(); + assert!(!config + .join("query_history") + .join(format!("{connection}.json")) + .exists()); +} diff --git a/src-tauri/src/theme_commands.rs b/src-tauri/src/transport/desktop/theme_commands.rs similarity index 100% rename from src-tauri/src/theme_commands.rs rename to src-tauri/src/transport/desktop/theme_commands.rs diff --git a/src-tauri/src/transport/desktop/theme_packages.rs b/src-tauri/src/transport/desktop/theme_packages.rs new file mode 100644 index 000000000..82b6da3c0 --- /dev/null +++ b/src-tauri/src/transport/desktop/theme_packages.rs @@ -0,0 +1 @@ +pub mod commands; diff --git a/src-tauri/src/transport/desktop/theme_packages/commands.rs b/src-tauri/src/transport/desktop/theme_packages/commands.rs new file mode 100644 index 000000000..3438627e7 --- /dev/null +++ b/src-tauri/src/transport/desktop/theme_packages/commands.rs @@ -0,0 +1,19 @@ +use crate::theme_packages::{lifecycle, *}; + +/// Standalone import preview validates without creating a personal file. +#[tauri::command] +pub fn preview_theme_document(source: String, name: String) -> Result { + crate::theme_packages::commands::preview_theme_document(source, name) +} + +#[tauri::command] +pub async fn preview_local_theme_package( + path: String, +) -> Result { + crate::theme_packages::commands::preview_local_theme_package(path).await +} + +#[tauri::command] +pub fn cancel_theme_install(registry_key: String, package_name: String) -> bool { + crate::theme_packages::commands::cancel_theme_install(registry_key, package_name) +} diff --git a/src-tauri/src/ui_state_commands.rs b/src-tauri/src/transport/desktop/ui_state_commands.rs similarity index 100% rename from src-tauri/src/ui_state_commands.rs rename to src-tauri/src/transport/desktop/ui_state_commands.rs diff --git a/src-tauri/src/updater.rs b/src-tauri/src/transport/desktop/updater.rs similarity index 98% rename from src-tauri/src/updater.rs rename to src-tauri/src/transport/desktop/updater.rs index b6bfc2aa8..3a6cf6403 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/transport/desktop/updater.rs @@ -184,7 +184,7 @@ fn categorize_asset(name: &str) -> String { #[cfg(feature = "desktop")] /// Effective update channel from config. Anything other than "nightly" ⇒ stable. fn release_channel(app: &tauri::AppHandle) -> String { - crate::config::load_config_internal(app) + crate::transport::desktop::config::load_config_internal(app) .release_channel .unwrap_or_else(|| "stable".to_string()) } @@ -198,7 +198,7 @@ pub async fn check_for_updates(app: AppHandle, force: bool) -> Result Result<(), String> { .await .map_err(|e| e.to_string())?; - crate::window_placement::persist_cached(&app); + crate::transport::desktop::window_placement::persist_cached(&app); app.restart(); } else { Err("No update available".to_string()) diff --git a/src-tauri/src/updater/installation_source.rs b/src-tauri/src/transport/desktop/updater/installation_source.rs similarity index 100% rename from src-tauri/src/updater/installation_source.rs rename to src-tauri/src/transport/desktop/updater/installation_source.rs diff --git a/src-tauri/src/updater/installation_source/tests.rs b/src-tauri/src/transport/desktop/updater/installation_source/tests.rs similarity index 100% rename from src-tauri/src/updater/installation_source/tests.rs rename to src-tauri/src/transport/desktop/updater/installation_source/tests.rs diff --git a/src-tauri/src/window_decorations.rs b/src-tauri/src/transport/desktop/window_decorations.rs similarity index 100% rename from src-tauri/src/window_decorations.rs rename to src-tauri/src/transport/desktop/window_decorations.rs diff --git a/src-tauri/src/window_decorations_tests.rs b/src-tauri/src/transport/desktop/window_decorations_tests.rs similarity index 100% rename from src-tauri/src/window_decorations_tests.rs rename to src-tauri/src/transport/desktop/window_decorations_tests.rs diff --git a/src-tauri/src/window_placement.rs b/src-tauri/src/transport/desktop/window_placement.rs similarity index 100% rename from src-tauri/src/window_placement.rs rename to src-tauri/src/transport/desktop/window_placement.rs diff --git a/src-tauri/src/transport/mod.rs b/src-tauri/src/transport/mod.rs index fdd460376..3819b6872 100644 --- a/src-tauri/src/transport/mod.rs +++ b/src-tauri/src/transport/mod.rs @@ -1 +1,3 @@ +#[cfg(feature = "desktop")] +pub mod desktop; pub mod web; diff --git a/web-ui-project/docs/WEB_UI_PLAN.md b/web-ui-project/docs/WEB_UI_PLAN.md index 2c89ba52d..ab892e5dd 100644 --- a/web-ui-project/docs/WEB_UI_PLAN.md +++ b/web-ui-project/docs/WEB_UI_PLAN.md @@ -40,7 +40,7 @@ Current repository facts relevant to this plan: - 106 frontend files import at least one `@tauri-apps/*` API. - Native dependencies include IPC, events, windows, dialogs, filesystem access, clipboard access, notifications, updater, deep links, and URL opening. - The CLI already supports `--mcp`, `--debug`, and `--explain` in `src-tauri/src/cli.rs`. -- Startup, driver registration, state registration, plugin loading, schedulers, and the full Tauri command registry are currently concentrated in `src-tauri/src/lib.rs::run`. +- Startup, driver registration, state registration, plugin loading, schedulers, and the full Tauri command registry are currently concentrated in `src-tauri/src/transport/desktop/mod.rs::run`. - Existing frontend coverage is substantial, and Rust has dedicated test modules for major backend areas. This makes a visual rewrite unnecessary. The primary work is platform separation and backend transport extraction. diff --git a/web-ui-project/docs/web-ui-parity.json b/web-ui-project/docs/web-ui-parity.json index 99a40b3b9..540fd7bc2 100644 --- a/web-ui-project/docs/web-ui-parity.json +++ b/web-ui-project/docs/web-ui-parity.json @@ -3,7 +3,7 @@ "generatedBy": "pnpm web:inventory:write", "sources": { "frontend": "packages/web-ui/src", - "tauriHandler": "src-tauri/src/lib.rs" + "tauriHandler": "src-tauri/src/transport/desktop/mod.rs" }, "classifications": { "featureGroup": [ diff --git a/web-ui-project/scripts/generate-web-ui-api-inventory.mjs b/web-ui-project/scripts/generate-web-ui-api-inventory.mjs index 67f048b1d..320c9b289 100644 --- a/web-ui-project/scripts/generate-web-ui-api-inventory.mjs +++ b/web-ui-project/scripts/generate-web-ui-api-inventory.mjs @@ -7,7 +7,7 @@ import ts from "typescript"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const FRONTEND_ROOT = "packages/web-ui/src"; -const TAURI_HANDLER_PATH = "src-tauri/src/lib.rs"; +const TAURI_HANDLER_PATH = "src-tauri/src/transport/desktop/mod.rs"; const INVENTORY_PATH = "web-ui-project/docs/web-ui-parity.json"; const CLASSIFICATION_VALUES = { From 861fd1cd56b94df74904fa8a6938a4626c49f7bb Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 15:13:12 +0200 Subject: [PATCH 4/6] test(web): list databases of saved connections in the e2e matrix --- web-ui-project/e2e/tests/web-ui-matrix.spec.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/web-ui-project/e2e/tests/web-ui-matrix.spec.ts b/web-ui-project/e2e/tests/web-ui-matrix.spec.ts index c64d07d67..318abb10d 100644 --- a/web-ui-project/e2e/tests/web-ui-matrix.spec.ts +++ b/web-ui-project/e2e/tests/web-ui-matrix.spec.ts @@ -156,6 +156,14 @@ for (const fixture of databaseFixtures) { }), ).resolves.toContain("Connection successful"); + const databases = await rpc(page, "list_databases", { + request: { params: fixture.params, connection_id: connection.id }, + }); + // SQLite has no server to list databases from. + if (fixture.name !== "sqlite") { + expect(databases).toContain(fixture.params.database); + } + const identity = await execute(page, connection.id, fixture.identityQuery); expect(String(identity.rows[0]?.[0])).toContain(fixture.expectedIdentity); From 8d226c8aa17a1347206138de36d572886ac3610a Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 16:56:49 +0200 Subject: [PATCH 5/6] refactor(desktop): remove commands the frontend never calls None of these 15 registered commands has a caller in the frontend, the e2e suites or the plugin API (plugins must not invoke Tauri commands): list_all_preferences, get_theme, save_blob_to_file, preview_tabularis_import, apply_tabularis_import, export_connections_payload, import_connections_payload, encrypt_export_payload, decrypt_export_payload, open_visual_explain_window, open_json_viewer_window, get_json_viewer_session, complete_json_viewer_session, open_results_window and close_results_window. The JSON viewer and results windows are opened from the frontend, so their Rust session stores (`json_viewer`, `results_window`) were write-only and go too. The driver method `save_blob_to_file` stays; only the command that wrapped it is gone. --- src-tauri/src/commands.rs | 24 +-- src-tauri/src/json_viewer.rs | 113 ---------- src-tauri/src/lib.rs | 2 - src-tauri/src/results_window.rs | 77 ------- src-tauri/src/runtime/state.rs | 4 - src-tauri/src/transport/desktop/commands.rs | 96 +-------- .../desktop/connection_import_commands.rs | 37 ---- .../src/transport/desktop/explain_import.rs | 9 - .../src/transport/desktop/json_viewer.rs | 200 ------------------ src-tauri/src/transport/desktop/mod.rs | 19 -- .../src/transport/desktop/preferences.rs | 30 --- .../src/transport/desktop/results_window.rs | 96 --------- .../src/transport/desktop/theme_commands.rs | 16 -- web-ui-project/docs/web-ui-parity.json | 21 +- 14 files changed, 8 insertions(+), 736 deletions(-) delete mode 100644 src-tauri/src/json_viewer.rs delete mode 100644 src-tauri/src/results_window.rs delete mode 100644 src-tauri/src/transport/desktop/json_viewer.rs delete mode 100644 src-tauri/src/transport/desktop/results_window.rs diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 16c78034f..74e02917e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -7,7 +7,7 @@ use urlencoding::encode; use crate::credential_cache; use crate::models::{ BatchStatementResult, ConnectionGroup, ConnectionParams, - ExportPayload, QueryResult, SavedConnection, + QueryResult, SavedConnection, }; // Constants @@ -20,12 +20,6 @@ async fn driver_for( .ok_or_else(|| format!("Unsupported driver: {}", id)) } -pub(crate) async fn driver_for_params( - params: &ConnectionParams, -) -> Result, String> { - crate::drivers::registry::get_connection_driver(params).await -} - const DEFAULT_MYSQL_PORT: u16 = 3306; const DEFAULT_POSTGRES_PORT: u16 = 5432; @@ -1883,19 +1877,3 @@ pub(crate) fn reject_if_would_create_cycle( ) } -pub async fn encrypt_export_payload( - payload: ExportPayload, - password: String, -) -> Result { - let plaintext = serde_json::to_string(&payload).map_err(|e| e.to_string())?; - crate::export_crypto::encrypt(&plaintext, &password) -} - -pub async fn decrypt_export_payload( - envelope: crate::export_crypto::EncryptedEnvelope, - password: String, -) -> Result { - let plaintext = crate::export_crypto::decrypt(&envelope, &password)?; - serde_json::from_str(&plaintext).map_err(|e| format!("Invalid export payload: {e}")) -} - diff --git a/src-tauri/src/json_viewer.rs b/src-tauri/src/json_viewer.rs deleted file mode 100644 index 6ef51eee6..000000000 --- a/src-tauri/src/json_viewer.rs +++ /dev/null @@ -1,113 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -use serde::{Deserialize, Serialize}; - - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct JsonViewerSession { - pub value: serde_json::Value, - pub original_value: serde_json::Value, - pub col_name: String, - pub read_only: bool, - pub cell_key: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct JsonViewerSavedPayload { - pub session_id: String, - pub value: serde_json::Value, -} - -#[derive(Debug, Clone, Copy)] -pub struct WindowBounds { - pub x: i32, - pub y: i32, - pub width: u32, - pub height: u32, -} - -#[derive(Default)] -pub struct JsonViewerStore { - pub sessions: Mutex>, - pub cell_index: Mutex>, - pub last_bounds: Mutex>, -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn insert_and_retrieve_session() { - let store = JsonViewerStore::default(); - { - let mut guard = store.sessions.lock().unwrap(); - guard.insert( - "sess-1".into(), - JsonViewerSession { - value: json!({"key": "value"}), - original_value: json!({"key": "value"}), - col_name: "metadata".into(), - read_only: false, - cell_key: None, - }, - ); - } - let guard = store.sessions.lock().unwrap(); - let session = guard.get("sess-1").unwrap(); - assert_eq!(session.col_name, "metadata"); - assert_eq!(session.value, json!({"key": "value"})); - assert!(!session.read_only); - } - - #[test] - fn cell_index_tracks_active_session() { - let store = JsonViewerStore::default(); - { - let mut sessions = store.sessions.lock().unwrap(); - sessions.insert( - "sess-2".into(), - JsonViewerSession { - value: json!([1, 2, 3]), - original_value: json!([1, 2, 3]), - col_name: "tags".into(), - read_only: false, - cell_key: Some("pk:42:tags".into()), - }, - ); - let mut index = store.cell_index.lock().unwrap(); - index.insert("pk:42:tags".into(), "sess-2".into()); - } - let index = store.cell_index.lock().unwrap(); - assert_eq!(index.get("pk:42:tags"), Some(&"sess-2".to_string())); - } - - #[test] - fn bounds_round_trip() { - let store = JsonViewerStore::default(); - { - let mut bounds = store.last_bounds.lock().unwrap(); - *bounds = Some(WindowBounds { - x: 100, - y: 200, - width: 800, - height: 600, - }); - } - let bounds = store.last_bounds.lock().unwrap(); - let b = bounds.unwrap(); - assert_eq!(b.x, 100); - assert_eq!(b.y, 200); - assert_eq!(b.width, 800); - assert_eq!(b.height, 600); - } - - #[test] - fn missing_session_returns_none() { - let store = JsonViewerStore::default(); - let guard = store.sessions.lock().unwrap(); - assert!(guard.get("no-such-session").is_none()); - } -} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 69855a9b3..2c47c04ee 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -62,7 +62,6 @@ pub mod health_check; pub mod heartbeat; #[cfg(test)] pub mod heartbeat_tests; -pub mod json_viewer; pub mod k8s_tunnel; pub mod keychain_utils; #[cfg(test)] @@ -90,7 +89,6 @@ pub mod proxy; pub mod query_history; #[cfg(test)] pub mod query_history_tests; -pub mod results_window; pub mod runtime; pub mod sandbox; #[cfg(test)] diff --git a/src-tauri/src/results_window.rs b/src-tauri/src/results_window.rs deleted file mode 100644 index c66eb6f04..000000000 --- a/src-tauri/src/results_window.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - - -/// Persisted geometry so a re-opened detached results window restores where the -/// user last left it. Mirrors the pattern used by `json_viewer.rs`. -#[derive(Debug, Clone, Copy)] -pub struct WindowBounds { - pub x: i32, - pub y: i32, - pub width: u32, - pub height: u32, -} - -/// Geometry is remembered per tab so that with several windows detached at once -/// each one re-opens where its own window last was, instead of all stacking on -/// top of the most-recently-closed one. -#[derive(Default)] -pub struct ResultsWindowStore { - pub bounds: Mutex>, -} - -/// One detached results window per editor tab. The frontend keeps each window's -/// data in sync over Tauri events keyed by `tab_id`. -pub(crate) fn window_label(tab_id: &str) -> String { - format!("results-window-{}", tab_id) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn window_label_is_tab_scoped() { - assert_eq!(window_label("abc"), "results-window-abc"); - assert_eq!(window_label("tab-123"), "results-window-tab-123"); - // Distinct tabs must map to distinct labels (each gets its own window). - assert_ne!(window_label("a"), window_label("b")); - } - - #[test] - fn bounds_are_remembered_per_tab() { - let store = ResultsWindowStore::default(); - { - let mut bounds = store.bounds.lock().unwrap(); - bounds.insert( - "tab-a".to_string(), - WindowBounds { - x: 100, - y: 200, - width: 800, - height: 600, - }, - ); - bounds.insert( - "tab-b".to_string(), - WindowBounds { - x: 10, - y: 20, - width: 400, - height: 300, - }, - ); - } - let bounds = store.bounds.lock().unwrap(); - let a = bounds.get("tab-a").unwrap(); - assert_eq!((a.x, a.y, a.width, a.height), (100, 200, 800, 600)); - let b = bounds.get("tab-b").unwrap(); - assert_eq!((b.x, b.y, b.width, b.height), (10, 20, 400, 300)); - } - - #[test] - fn bounds_default_is_empty() { - let store = ResultsWindowStore::default(); - assert!(store.bounds.lock().unwrap().is_empty()); - } -} diff --git a/src-tauri/src/runtime/state.rs b/src-tauri/src/runtime/state.rs index 159ea166b..b5104505d 100644 --- a/src-tauri/src/runtime/state.rs +++ b/src-tauri/src/runtime/state.rs @@ -13,8 +13,6 @@ pub struct ApplicationState { pub connection_cache: Arc, pub import_envelope_cache: Arc, pub pending_explain_file: Arc, - pub json_viewer_store: Arc, - pub results_window_store: Arc, pub web_active_connections: Mutex>>, pub web_approval_owners: Mutex>, pub web_preferences: @@ -54,8 +52,6 @@ impl Default for ApplicationState { connection_cache: Arc::new(crate::connection_cache::ConnectionCache::default()), import_envelope_cache: Arc::new(ImportEnvelopeCache::default()), pending_explain_file: Arc::new(crate::explain_import::PendingExplainFile::default()), - json_viewer_store: Arc::new(crate::json_viewer::JsonViewerStore::default()), - results_window_store: Arc::new(crate::results_window::ResultsWindowStore::default()), web_active_connections: Mutex::new(HashMap::new()), web_approval_owners: Mutex::new(HashMap::new()), web_preferences: Mutex::new(HashMap::new()), diff --git a/src-tauri/src/transport/desktop/commands.rs b/src-tauri/src/transport/desktop/commands.rs index c60a4491e..3a6232123 100644 --- a/src-tauri/src/transport/desktop/commands.rs +++ b/src-tauri/src/transport/desktop/commands.rs @@ -2,10 +2,10 @@ use crate::commands::*; use crate::credential_cache; use crate::keychain_utils; use crate::models::{ - BatchStatementResult, ColumnDefinition, ConnectionParams, ExplainQueryOutput, ExportPayload, - ForeignKey, Index, K8sConnection, K8sConnectionInput, QueryResult, RoutineInfo, - RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, SshTestParams, - TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, + BatchStatementResult, ColumnDefinition, ConnectionParams, ExplainQueryOutput, ForeignKey, + Index, K8sConnection, K8sConnectionInput, QueryResult, RoutineInfo, RoutineParameter, + SavedConnection, SshConnection, SshConnectionInput, SshTestParams, TableColumn, TableInfo, + TestConnectionRequest, TriggerInfo, }; use crate::persistence; use std::collections::HashMap; @@ -1292,36 +1292,6 @@ pub async fn update_record( .await } -#[tauri::command] -pub async fn save_blob_to_file( - app: AppHandle, - connection_id: String, - table: String, - col_name: String, - pk_map: std::collections::HashMap, - file_path: String, - schema: Option, - database: Option, -) -> Result<(), String> { - let saved_conn = find_connection_by_id(&app, &connection_id)?; - let expanded_params = expand_ssh_connection_params(&app, &saved_conn.params).await?; - let expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; - let mut params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let drv = driver_for_params(¶ms).await?; - drv.save_blob_to_file( - ¶ms, - &table, - &col_name, - &pk_map, - schema.as_deref(), - &file_path, - ) - .await -} - #[tauri::command] pub async fn fetch_blob( app: AppHandle, @@ -2393,48 +2363,6 @@ pub async fn get_server_now( .await } -#[tauri::command] -pub async fn export_connections_payload( - app: AppHandle, - include_secrets: Option, - connection_ids: Option>, -) -> Result { - crate::application::connection_files::export_payload( - app.state::().inner(), - include_secrets.unwrap_or(true), - connection_ids, - ) - .await -} - -#[tauri::command] -pub async fn import_connections_payload( - app: AppHandle, - payload: ExportPayload, -) -> Result<(), String> { - apply_export_payload(app, payload).await -} - -/// Merge an `ExportPayload` into the user's stored connections, groups, SSH and -/// K8s records, moving any inline secrets into the keychain. Shared by the JSON -/// import command above and the foreign-app import flow. -pub async fn apply_export_payload( - app: AppHandle, - payload: ExportPayload, -) -> Result<(), String> { - crate::application::connection_files::apply_export_payload( - app.state::().inner(), - app.state::>() - .inner() - .as_ref(), - app.state::>() - .inner() - .as_ref(), - payload, - ) - .await -} - /// Detects the MIME type of base64-encoded binary data using magic-byte analysis /// and returns the canonical blob wire format: "BLOB:::". /// Called by the frontend after the user selects a file to upload. @@ -2489,19 +2417,3 @@ pub async fn get_driver_manifest( ) -> Option { crate::commands::get_driver_manifest(driver_id).await } - -#[tauri::command] -pub async fn encrypt_export_payload( - payload: ExportPayload, - password: String, -) -> Result { - crate::commands::encrypt_export_payload(payload, password).await -} - -#[tauri::command] -pub async fn decrypt_export_payload( - envelope: crate::export_crypto::EncryptedEnvelope, - password: String, -) -> Result { - crate::commands::decrypt_export_payload(envelope, password).await -} diff --git a/src-tauri/src/transport/desktop/connection_import_commands.rs b/src-tauri/src/transport/desktop/connection_import_commands.rs index 7d2833594..2f21ef168 100644 --- a/src-tauri/src/transport/desktop/connection_import_commands.rs +++ b/src-tauri/src/transport/desktop/connection_import_commands.rs @@ -8,7 +8,6 @@ use crate::application::connection_files::{ TabularisImportPreviewResult, }; use crate::connection_import::{analyzer, convert}; -use crate::models::ExportPayload; pub use crate::application::connection_files::ImportEnvelopeCache; @@ -77,42 +76,6 @@ pub async fn apply_connection_import( .await } -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn preview_tabularis_import( - app: AppHandle, - payload: ExportPayload, -) -> Result { - connection_files::preview_tabularis_payload( - app.state::().inner(), - &payload, - ) - .await -} - -#[cfg(feature = "desktop")] -#[tauri::command] -pub async fn apply_tabularis_import( - app: AppHandle, - connection_cache: tauri::State<'_, std::sync::Arc>, - credential_cache: tauri::State<'_, std::sync::Arc>, - payload: ExportPayload, - resolutions: Vec, -) -> Result<(), String> { - let runtime = app.state::(); - let groups = crate::persistence::load_connections_file(&runtime.paths.connections_file()) - .unwrap_or_default() - .groups; - let payload = crate::connection_import::tabularis::apply(&payload, &resolutions, &groups); - connection_files::apply_export_payload( - &runtime, - connection_cache.inner().as_ref(), - credential_cache.inner().as_ref(), - payload, - ) - .await -} - #[cfg(feature = "desktop")] #[tauri::command] pub async fn preview_tabularis_import_file( diff --git a/src-tauri/src/transport/desktop/explain_import.rs b/src-tauri/src/transport/desktop/explain_import.rs index 09c6fc16d..5531a3507 100644 --- a/src-tauri/src/transport/desktop/explain_import.rs +++ b/src-tauri/src/transport/desktop/explain_import.rs @@ -51,15 +51,6 @@ pub fn spawn_visual_explain_window>( Ok(()) } -/// Tauri command wrapper around [`spawn_visual_explain_window`]. -#[tauri::command] -pub async fn open_visual_explain_window( - app: tauri::AppHandle, - file: Option, -) -> Result<(), String> { - spawn_visual_explain_window(&app, file) -} - /// Tauri command: read an EXPLAIN file from disk. /// /// The content comes back untouched; the frontend sniffs the format and diff --git a/src-tauri/src/transport/desktop/json_viewer.rs b/src-tauri/src/transport/desktop/json_viewer.rs deleted file mode 100644 index d79177c3c..000000000 --- a/src-tauri/src/transport/desktop/json_viewer.rs +++ /dev/null @@ -1,200 +0,0 @@ -use crate::json_viewer::*; -use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -use ulid::Ulid; -use urlencoding::encode; - -#[tauri::command] -pub async fn open_json_viewer_window( - app: AppHandle, - store: State<'_, std::sync::Arc>, - value: serde_json::Value, - original_value: Option, - col_name: String, - row_label: Option, - read_only: bool, - cell_key: Option, -) -> Result { - let original_value = original_value.unwrap_or_else(|| value.clone()); - if let Some(key) = cell_key.as_deref() { - let existing_id = { - let cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.get(key).cloned() - }; - if let Some(existing_id) = existing_id { - let existing_label = format!("json-viewer-{}", existing_id); - if let Some(window) = app.get_webview_window(&existing_label) { - let _ = window.unminimize(); - let _ = window.set_focus(); - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - if let Some(session) = sessions.get_mut(&existing_id) { - session.value = value; - } - return Ok(existing_id); - } - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.remove(key); - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - sessions.remove(&existing_id); - } - } - - let session_id = Ulid::new().to_string(); - let window_label = format!("json-viewer-{}", session_id); - - { - let mut guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard.insert( - session_id.clone(), - JsonViewerSession { - value, - original_value, - col_name: col_name.clone(), - read_only, - cell_key: cell_key.clone(), - }, - ); - } - if let Some(key) = cell_key.as_deref() { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.insert(key.to_string(), session_id.clone()); - } - - let url = format!("/json-viewer?session={}", encode(&session_id)); - let title = match row_label.as_deref().filter(|s| !s.is_empty()) { - Some(label) => format!("{} \u{00b7} {} \u{2014} JSON Viewer", col_name, label), - None => format!("{} \u{2014} JSON Viewer", col_name), - }; - - let remembered = store - .last_bounds - .lock() - .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? - .clone(); - - let mut builder = WebviewWindowBuilder::new(&app, &window_label, WebviewUrl::App(url.into())) - .title(&title) - .min_inner_size(600.0, 400.0) - .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) - .background_color(tauri::webview::Color(2, 6, 23, 255)); - - builder = match remembered { - Some(b) => builder - .inner_size(b.width as f64, b.height as f64) - .position(b.x as f64, b.y as f64), - None => builder.inner_size(900.0, 700.0).center(), - }; - - let build_result = builder.build(); - - match build_result { - Err(e) => { - let mut sessions = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - sessions.remove(&session_id); - if let Some(key) = cell_key.as_deref() { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - cell_index.remove(key); - } - Err(format!("Failed to create JSON viewer window: {}", e)) - } - Ok(window) => { - let app_handle = app.clone(); - let captured_label = window_label.clone(); - window.on_window_event(move |event| { - if let WindowEvent::CloseRequested { .. } = event { - if let Some(win) = app_handle.get_webview_window(&captured_label) { - if let (Ok(pos), Ok(size)) = (win.outer_position(), win.outer_size()) { - let store = app_handle.state::>(); - let mut bounds = match store.last_bounds.lock() { - Ok(g) => g, - Err(_) => return, - }; - *bounds = Some(WindowBounds { - x: pos.x, - y: pos.y, - width: size.width, - height: size.height, - }); - } - } - } - }); - Ok(session_id) - } - } -} - -#[tauri::command] -pub async fn get_json_viewer_session( - store: State<'_, std::sync::Arc>, - session_id: String, -) -> Result { - let guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard - .get(&session_id) - .cloned() - .ok_or_else(|| format!("JSON viewer session '{}' not found", session_id)) -} - -#[tauri::command] -pub async fn complete_json_viewer_session( - app: AppHandle, - store: State<'_, std::sync::Arc>, - session_id: String, - value: serde_json::Value, -) -> Result<(), String> { - let cell_key = { - let mut guard = store - .sessions - .lock() - .map_err(|e| format!("Failed to acquire session store lock: {}", e))?; - guard.remove(&session_id).and_then(|s| s.cell_key) - }; - if let Some(key) = cell_key { - let mut cell_index = store - .cell_index - .lock() - .map_err(|e| format!("Failed to acquire cell index lock: {}", e))?; - if cell_index - .get(&key) - .map(|v| v == &session_id) - .unwrap_or(false) - { - cell_index.remove(&key); - } - } - - app.emit( - "json-viewer:saved", - JsonViewerSavedPayload { session_id, value }, - ) - .map_err(|e| format!("Failed to emit json-viewer:saved: {}", e))?; - - Ok(()) -} diff --git a/src-tauri/src/transport/desktop/mod.rs b/src-tauri/src/transport/desktop/mod.rs index e56d42ea8..f16b1ecca 100644 --- a/src-tauri/src/transport/desktop/mod.rs +++ b/src-tauri/src/transport/desktop/mod.rs @@ -19,7 +19,6 @@ pub mod e2e_dialog_mock; pub mod explain_import; pub mod export; pub mod health_check; -pub mod json_viewer; pub mod log_commands; pub mod mcp; pub mod notebooks; @@ -27,7 +26,6 @@ pub mod plugins; pub mod preferences; pub mod proxy; pub mod query_history; -pub mod results_window; pub mod runtime; pub mod saved_queries; pub mod sql_file; @@ -136,8 +134,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { .manage(application_state.connection_cache.clone()) .manage(application_state.import_envelope_cache.clone()) .manage(application_state.pending_explain_file.clone()) - .manage(application_state.json_viewer_store.clone()) - .manage(application_state.results_window_store.clone()) .manage(application_state.clone()) .manage(window_placement::WindowPlacementCache::default()) .setup(move |app| { @@ -391,20 +387,14 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { commands::update_connection_tag, commands::delete_connection_tag, commands::set_connection_tags, - commands::export_connections_payload, - commands::encrypt_export_payload, connection_import_commands::export_connections_file, backup::get_connections_backup_status, backup::set_connections_backup_password, backup::set_connections_backup_target_password, backup::run_connections_backup, - commands::decrypt_export_payload, - commands::import_connections_payload, connection_import_commands::list_connection_import_sources, connection_import_commands::preview_connection_import, connection_import_commands::apply_connection_import, - connection_import_commands::preview_tabularis_import, - connection_import_commands::apply_tabularis_import, connection_import_commands::preview_tabularis_import_file, connection_import_commands::apply_prepared_tabularis_import, commands::get_schemas, @@ -417,7 +407,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { commands::delete_record, commands::update_record, commands::insert_record, - commands::save_blob_to_file, commands::fetch_blob, commands::fetch_blob_as_data_url, commands::load_blob_from_file, @@ -446,7 +435,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { commands::open_er_diagram_window, explain_import::load_explain_from_file, explain_import::get_pending_explain_file, - explain_import::open_visual_explain_window, export::export_query_to_file, export::cancel_export, sql_file::read_sql_file, @@ -592,7 +580,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { theme_commands::update_personal_snapshot, theme_commands::duplicate_personal_theme, theme_commands::get_all_themes, - theme_commands::get_theme, theme_commands::save_custom_theme, theme_commands::delete_custom_theme, theme_commands::import_theme, @@ -619,7 +606,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { preferences::save_editor_preferences, preferences::load_editor_preferences, preferences::delete_editor_preferences, - preferences::list_all_preferences, // Notebooks notebooks::create_notebook, notebooks::save_notebook, @@ -645,11 +631,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { plugins::manager::get_plugin_startup_errors, plugins::runtime_version::get_plugin_runtime_warnings, // JSON Viewer - json_viewer::open_json_viewer_window, - json_viewer::get_json_viewer_session, - json_viewer::complete_json_viewer_session, - results_window::open_results_window, - results_window::close_results_window, // Connection Window connection_window::open_connection_window, // Task Manager diff --git a/src-tauri/src/transport/desktop/preferences.rs b/src-tauri/src/transport/desktop/preferences.rs index 29c2cc2fb..e814b9845 100644 --- a/src-tauri/src/transport/desktop/preferences.rs +++ b/src-tauri/src/transport/desktop/preferences.rs @@ -1,5 +1,4 @@ use crate::preferences::*; -use std::collections::HashMap; use tauri::{AppHandle, Manager}; #[tauri::command] @@ -36,32 +35,3 @@ pub async fn delete_editor_preferences( &connection_id, ) } - -#[tauri::command] -pub async fn list_all_preferences( - app: AppHandle, -) -> Result, String> { - let preferences_dir = app - .state::() - .paths - .config_dir() - .join("preferences"); - if !preferences_dir.exists() { - return Ok(HashMap::new()); - } - - let mut preferences = HashMap::new(); - for entry in std::fs::read_dir(preferences_dir).map_err(|error| error.to_string())? { - let entry = entry.map_err(|error| error.to_string())?; - let Some(connection_id) = entry.file_name().to_str().map(str::to_string) else { - continue; - }; - if let Some(value) = crate::application::persistence::load_editor_preferences_for_desktop( - &app.state::(), - &connection_id, - )? { - preferences.insert(connection_id, value); - } - } - Ok(preferences) -} diff --git a/src-tauri/src/transport/desktop/results_window.rs b/src-tauri/src/transport/desktop/results_window.rs deleted file mode 100644 index 758411bf0..000000000 --- a/src-tauri/src/transport/desktop/results_window.rs +++ /dev/null @@ -1,96 +0,0 @@ -use crate::results_window::*; -use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -use urlencoding::encode; - -/// Open (or focus) the detached results window for a given tab. Result data is -/// streamed from the main window via `resultsSyncEvent(tabId)` in -/// `src/utils/resultsWindowSync.ts`, so no payload is passed here. -#[tauri::command] -pub async fn open_results_window( - app: AppHandle, - store: tauri::State<'_, std::sync::Arc>, - tab_id: String, - title: Option, -) -> Result<(), String> { - let label = window_label(&tab_id); - - // If it already exists, just bring it to the front. - if let Some(window) = app.get_webview_window(&label) { - let _ = window.unminimize(); - let _ = window.set_focus(); - return Ok(()); - } - - let window_title = title.unwrap_or_else(|| "Query Results".to_string()); - - let remembered = store - .bounds - .lock() - .map_err(|e| format!("Failed to acquire bounds lock: {}", e))? - .get(&tab_id) - .copied(); - - let url = format!("/results-window?tab={}", encode(&tab_id)); - let mut builder = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) - .title(&window_title) - .min_inner_size(500.0, 300.0) - .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) - .background_color(tauri::webview::Color(2, 6, 23, 255)); - - builder = match remembered { - Some(b) => builder - .inner_size(b.width as f64, b.height as f64) - .position(b.x as f64, b.y as f64), - None => builder.inner_size(900.0, 600.0).center(), - }; - - match builder.build() { - Err(e) => Err(format!("Failed to create results window: {}", e)), - Ok(window) => { - let app_handle = app.clone(); - let captured_label = label.clone(); - let captured_tab_id = tab_id.clone(); - window.on_window_event(move |event| { - if let WindowEvent::CloseRequested { .. } = event { - if let Some(win) = app_handle.get_webview_window(&captured_label) { - // Save the inner size: it is restored via `.inner_size(...)` - // below, so saving `outer_size()` would grow the window by - // the decoration height on each detach→close→reopen cycle. - if let (Ok(pos), Ok(size)) = (win.outer_position(), win.inner_size()) { - let store = app_handle.state::>(); - if let Ok(mut bounds) = store.bounds.lock() { - bounds.insert( - captured_tab_id.clone(), - WindowBounds { - x: pos.x, - y: pos.y, - width: size.width, - height: size.height, - }, - ); - }; - } - } - // Let the main window re-attach this tab's results panel. - let _ = app_handle.emit( - "results-window:closed", - serde_json::json!({ "tabId": captured_tab_id }), - ); - } - }); - Ok(()) - } - } -} - -/// Programmatically close a tab's detached results window (used by the -/// "Re-attach" button and when the bound tab is closed). -#[tauri::command] -pub async fn close_results_window(app: AppHandle, tab_id: String) -> Result<(), String> { - if let Some(window) = app.get_webview_window(&window_label(&tab_id)) { - window - .close() - .map_err(|e| format!("Failed to close results window: {}", e))?; - } - Ok(()) -} diff --git a/src-tauri/src/transport/desktop/theme_commands.rs b/src-tauri/src/transport/desktop/theme_commands.rs index b4cc3b8b2..0271cb9d0 100644 --- a/src-tauri/src/transport/desktop/theme_commands.rs +++ b/src-tauri/src/transport/desktop/theme_commands.rs @@ -20,22 +20,6 @@ pub fn get_all_themes(app: AppHandle) -> Result, String> { crate::application::persistence::get_all_themes(&app.state::()) } -#[tauri::command] -pub fn get_theme(app: AppHandle, theme_id: String) -> Result { - let entry = themes::catalog(&app.state::()) - .themes - .into_iter() - .find(|entry| entry.id == theme_id) - .ok_or("Theme not found or unavailable")?; - if entry.format != "legacy" || entry.editor.is_some() { - return Err("Use get_theme_catalog for v1 definitions and independent snapshots".into()); - } - let mut value: Value = serde_json::from_str(&entry.source).map_err(|e| e.to_string())?; - value["isPreset"] = Value::Bool(entry.origin["kind"] == "builtin"); - value["isReadOnly"] = Value::Bool(entry.read_only); - Ok(value) -} - #[tauri::command] pub fn save_custom_theme(app: AppHandle, theme: Value) -> Result<(), String> { crate::application::persistence::save_custom_theme(&app.state::(), theme) diff --git a/web-ui-project/docs/web-ui-parity.json b/web-ui-project/docs/web-ui-parity.json index 540fd7bc2..8cd7fac3a 100644 --- a/web-ui-project/docs/web-ui-parity.json +++ b/web-ui-project/docs/web-ui-parity.json @@ -56,11 +56,11 @@ "literalCommandCount": 15, "literalCallSiteCount": 16, "dynamicCallSiteCount": 0, - "handlerRegistrationCount": 308, - "registeredCommandCount": 308, + "handlerRegistrationCount": 293, + "registeredCommandCount": 293, "duplicateHandlerRegistrations": [], "frontendCommandsMissingRegistration": [], - "registeredCommandsWithoutFrontendCall": 293 + "registeredCommandsWithoutFrontendCall": 278 }, "commands": [ { @@ -286,7 +286,6 @@ "apply_connection_import", "apply_db_user_privileges", "apply_prepared_tabularis_import", - "apply_tabularis_import", "build_routine_call_sql", "cancel_chatgpt_sign_in", "cancel_dump", @@ -301,8 +300,6 @@ "clear_logs", "clear_query_history", "close_devtools", - "close_results_window", - "complete_json_viewer_session", "count_query", "create_connection_group", "create_connection_tag", @@ -317,7 +314,6 @@ "create_trigger", "create_view", "decide_pending_approval", - "decrypt_export_payload", "delete_ai_key", "delete_connection", "delete_connection_group", @@ -348,7 +344,6 @@ "duplicate_connection", "duplicate_personal_theme", "enable_plugin", - "encrypt_export_payload", "execute_clipboard_import", "execute_query", "execute_query_batch", @@ -358,7 +353,6 @@ "export_ai_activity_json", "export_ai_session_as_notebook", "export_connections_file", - "export_connections_payload", "export_logs", "export_query_to_file", "export_theme", @@ -411,7 +405,6 @@ "get_indexes", "get_installation_source", "get_installed_plugins", - "get_json_viewer_session", "get_k8s_connections", "get_k8s_contexts_cmd", "get_k8s_namespaces_cmd", @@ -453,7 +446,6 @@ "get_tables", "get_tabrename_prompt", "get_tabularis_children", - "get_theme", "get_theme_catalog", "get_trigger_definition", "get_triggers", @@ -461,7 +453,6 @@ "get_view_columns", "get_view_definition", "get_views", - "import_connections_payload", "import_database", "import_theme", "insert_record", @@ -472,7 +463,6 @@ "install_registry_theme", "is_debug_mode", "kill_plugin_process", - "list_all_preferences", "list_connection_import_sources", "list_connection_tags", "list_databases", @@ -488,14 +478,10 @@ "open_chatgpt_usage", "open_devtools", "open_er_diagram_window", - "open_json_viewer_window", "open_plugins_dir", - "open_results_window", "open_task_manager_window", - "open_visual_explain_window", "preview_connection_import", "preview_local_theme_package", - "preview_tabularis_import", "preview_tabularis_import_file", "preview_theme_document", "proxy_password_is_set", @@ -518,7 +504,6 @@ "respond_ssh_askpass", "restart_plugin_process", "run_connections_backup", - "save_blob_to_file", "save_cellname_prompt", "save_config", "save_config_json", From 61d1d05eac60625b4a57b76f6fd75e64c427bc78 Mon Sep 17 00:00:00 2001 From: NewtTheWolf Date: Thu, 22 Oct 2026 16:56:49 +0200 Subject: [PATCH 6/6] docs(agents): describe the desktop and web transport layout Points contributors and their agents at transport/desktop for Tauri code and lists what in-flight branches need to change when they rebase. --- AGENTS.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 8b29320be..d2136407b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,8 @@ # AGENTS.md +> [!IMPORTANT] +> **The backend layout changed (October 2026).** All Tauri code now lives in `src-tauri/src/transport/desktop/`, and desktop commands are thin wrappers over `src-tauri/src/application/`. Read [Backend layout](#backend-layout-desktop-and-web-transports) before you start, rebase, or review a PR that touches `src-tauri/`. + ## Directives Adhere to the rules defined in the [rules directory](./.rules/): - [General Rules](./.rules/general.md) (Logging & Language) @@ -14,6 +17,27 @@ Adhere to the rules defined in the [rules directory](./.rules/): When reviewing pull requests, follow [REVIEW.md](./REVIEW.md). +## Backend layout: desktop and web transports + +The Rust backend serves two transports over the same React frontend: + +- **Tauri desktop app:** `src-tauri/src/transport/desktop/` +- **`tabularis web` server:** `src-tauri/src/transport/web/` + +Shared logic lives in `src-tauri/src/application/` (and plain modules), so the app and the web behave the same. + +- **Tauri code goes in `transport/desktop/` only.** That covers `#[tauri::command]`, `tauri_plugin_*`, and anything taking an `AppHandle`, `Window` or Tauri `State`. It is the only module behind the `desktop` cargo feature; `cargo build --no-default-features` builds the server without Tauri. +- **A desktop command is a thin wrapper over `application/`.** Implement the behaviour there, call it from the desktop command, and give the web RPC (`transport/web/rpc.rs`) a route to the same function. +- **The desktop command registry is in `transport/desktop/mod.rs`** (`run()` and `generate_handler!`), not in `lib.rs`. +- **CI enforces the boundary:** `cargo check --no-default-features` must pass, and a grep fails the build when `tauri::` or `tauri_plugin` appears outside `transport/desktop/`. See rule 7 in [Rust Rules](./.rules/rust.md). + +**Branches and PRs started before this layout:** +- Rebase onto it. +- Move new or changed Tauri commands from `commands.rs`, `config.rs` and the like into the mirrored file under `transport/desktop/`. +- Drop `#[cfg(feature = "desktop")]` and `#[cfg_attr(feature = "desktop", tauri::command)]` from shared modules. +- Register commands in `transport/desktop/mod.rs`. +- Check for these commands, which had no frontend caller and were removed: `list_all_preferences`, `get_theme`, `save_blob_to_file`, `preview_tabularis_import`, `apply_tabularis_import`, `export_connections_payload`, `import_connections_payload`, `encrypt_export_payload`, `decrypt_export_payload`, `open_visual_explain_window`, `open_json_viewer_window`, `get_json_viewer_session`, `complete_json_viewer_session`, `open_results_window` and `close_results_window`. + # GitNexus — Code Intelligence