diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 91024cc56..cfb2e7324 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,6 +87,19 @@ 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 + + - 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/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 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/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/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..029935f0c 100644 --- a/src-tauri/src/ai.rs +++ b/src-tauri/src/ai.rs @@ -8,7 +8,6 @@ use std::collections::{HashMap, HashSet}; use std::fs; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; -use tauri::{AppHandle, Manager}; // --- Data Structures --- @@ -384,11 +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() { @@ -397,19 +391,6 @@ pub fn clear_models_cache(runtime: &RuntimeContext) -> Result<(), String> { Ok(()) } -#[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, @@ -580,49 +561,6 @@ pub async fn get_models( Ok(models) } -#[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 -} - // --- Shared helpers --- async fn resolve_model( @@ -893,19 +831,6 @@ pub async fn generate_cellname( .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 -} - pub async fn suggest_table_name_with_runtime( runtime: &RuntimeContext, cache: &CredentialCache, @@ -969,19 +894,6 @@ pub async fn suggest_table_name_with_runtime( } } -#[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 a96df60ba..4ecd75aec 100644 --- a/src-tauri/src/ai_approval_watcher.rs +++ b/src-tauri/src/ai_approval_watcher.rs @@ -4,20 +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; -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 @@ -109,85 +107,3 @@ pub fn spawn_headless( }) } -/// 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 || { - 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 { - 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/ai_commands.rs deleted file mode 100644 index b73a0131c..000000000 --- a/src-tauri/src/ai_commands.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Tauri commands exposed to the frontend for AI activity, approval gates, -//! 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_notebook_export::NotebookExport; - -#[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())? -} - -#[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_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 clear_ai_activity() -> Result<(), String> { - tokio::task::spawn_blocking(ai_activity::clear) - .await - .map_err(|e| e.to_string())? -} - -#[tauri::command] -pub async fn export_ai_activity_json() -> Result { - crate::application::generic_exports::generate_ai_activity_json().await -} - -#[tauri::command] -pub async fn export_ai_activity_csv() -> Result { - crate::application::generic_exports::generate_ai_activity_csv().await -} - -#[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] -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] -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/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/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/askpass/mod.rs b/src-tauri/src/askpass/mod.rs index d0e837194..046581404 100644 --- a/src-tauri/src/askpass/mod.rs +++ b/src-tauri/src/askpass/mod.rs @@ -24,7 +24,8 @@ 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; + use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{sync_channel, SyncSender}; @@ -32,7 +33,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use serde::Serialize; -use tauri::AppHandle; + use uuid::Uuid; /// Event emitted to the frontend when ssh needs user input. @@ -44,9 +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. -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); @@ -60,11 +61,6 @@ fn pending_responses() -> &'static Mutex> { PENDING.get_or_init(|| Mutex::new(HashMap::new())) } -/// 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 @@ -76,17 +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 { - let app = APP_HANDLE + let events = FRONTEND_EVENTS .get() .ok_or_else(|| "Askpass UI unavailable: application not initialised".to_string())?; 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, @@ -180,7 +181,6 @@ impl AskpassUi for FrontendUi { /// Frontend answer to an askpass prompt. `response = None` means the user /// cancelled. -#[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..12bf0ed87 100644 --- a/src-tauri/src/backup/mod.rs +++ b/src-tauri/src/backup/mod.rs @@ -11,7 +11,6 @@ use chrono::NaiveDateTime; use keyring::Entry; use std::fs; use std::path::PathBuf; -use tauri::{AppHandle, Manager, Runtime}; use crate::runtime::RuntimeContext; @@ -325,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 } @@ -416,15 +415,7 @@ pub async fn run_backup_for_runtime( }) } -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() @@ -432,80 +423,6 @@ fn backup_mode(config: &crate::config::AppConfig) -> String { .unwrap_or_else(|| "manual".to_string()) } -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::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::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) { - tauri::async_runtime::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)] @@ -572,41 +489,6 @@ pub fn set_backup_target_password( } } -#[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 { - Ok( - run_backup_for_runtime(app.state::().inner(), "manual") - .await? - .location, - ) -} - 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 d03cf9492..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,139 +158,7 @@ async fn callback( } } -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 = 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, @@ -318,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 0042a35ca..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,54 +37,16 @@ pub struct ChatGptSession { profiles: Vec, } -fn http_client() -> Result { +pub(crate) fn http_client() -> Result { crate::proxy::ai_http_client("chatgpt") } -#[tauri::command] pub async fn get_chatgpt_session() -> Result { let _guard = SESSION_LOCK.lock().await; let disk = storage::LockedStore::open()?; Ok(session(&disk.load()?)) } -#[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 cancel_chatgpt_sign_in() { if let Ok(mut sender) = SIGN_IN_CANCEL.lock() { if let Some(sender) = sender.take() { @@ -93,7 +55,6 @@ pub fn cancel_chatgpt_sign_in() { } } -#[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 +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()?; @@ -130,17 +90,8 @@ pub async fn sign_out_chatgpt(profile_id: String) -> Result, Stri Ok(warning) } -#[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()) -} - pub use inference::{generate, list_models}; -#[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 0aaca403b..5f1ce2109 100644 --- a/src-tauri/src/clipboard_import.rs +++ b/src-tauri/src/clipboard_import.rs @@ -3,7 +3,6 @@ use crate::models::TableColumn; use crate::{drivers::driver_trait::DatabaseDriver, models::ColumnDefinition}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; -use tauri::{AppHandle, Manager, Runtime}; #[derive(Deserialize, Debug)] pub struct ClipboardImportRequest { @@ -172,14 +171,6 @@ fn table_ref(table_name: &str, schema: Option<&str>, quote: &str) -> String { } } -#[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 0c6e57f24..74e02917e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,21 +1,14 @@ use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; -use tauri::{AppHandle, Emitter, 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, ConnectionsFile, - ExplainQueryOutput, ExportPayload, ForeignKey, Index, K8sConnection, K8sConnectionInput, - QueryResult, RoutineInfo, RoutineParameter, SavedConnection, SshConnection, SshConnectionInput, - SshTestParams, TableColumn, TableInfo, TestConnectionRequest, TriggerInfo, + BatchStatementResult, ConnectionGroup, ConnectionParams, + QueryResult, SavedConnection, }; -use crate::persistence; // Constants /// Resolve the driver from the registry or return a descriptive error. @@ -27,25 +20,6 @@ async fn driver_for( .ok_or_else(|| format!("Unsupported driver: {}", id)) } -async fn driver_for_params( - params: &ConnectionParams, -) -> Result, String> { - crate::drivers::registry::get_connection_driver(params).await -} - -#[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; @@ -103,16 +77,6 @@ pub(crate) fn unregister_abort_handle( // --- Persistence Helpers --- -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)] @@ -120,75 +84,6 @@ 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(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")); - } - - #[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")); - } - - #[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(); - } - - #[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(); - } - - #[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(); - } -} - pub fn resolve_connection_params(params: &ConnectionParams) -> Result { crate::application::tunnels::resolve_expanded_connection_params(params, None) } @@ -230,22 +125,6 @@ pub fn resolve_connection_params_with_id( resolve_connection_params(&with_id) } -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")) -} - fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { params .connection_uri @@ -253,194 +132,9 @@ fn runtime_connection_uri(params: &ConnectionParams) -> Option<&str> { .filter(|value| !value.trim().is_empty()) } -/// 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(()) -} - -/// 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})")), - }, - } -} - -/// 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()) -} - -/// `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(()) - }, - 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()) - }, - ) -} - -/// 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>, -} - -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); - } - - 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); - } - } -} - -/// 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 -} - /// 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, @@ -463,88 +157,6 @@ fn restore_runtime_connection_uri( } } -/// 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) -} - /// 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). @@ -579,1737 +191,94 @@ 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}")), - } -} - -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(()) -} - // --- Commands --- -#[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 -} +// ==================== SSH Connection Management ==================== -#[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 -} +// ==================== PostgreSQL Plugin SSL Mode Migration ==================== +// +// The shared, path-based migration logic lives in `connection_migrations` +// (also callable from the standalone `--mcp` server process, which has no +// `AppHandle`). This is a thin wrapper: resolve the path, run the shared +// core, and invalidate the connection cache only if it actually rewrote +// something. -/// 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 -} +// --------------------------------------------------------------------------- +// Kubernetes Connections +// --------------------------------------------------------------------------- -/// 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 -} +// --------------------------------------------------------------------------- +// AWS SSM +// --------------------------------------------------------------------------- -#[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(test)] +mod tests { + use super::*; + use crate::models::DatabaseSelection; -#[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 -} + fn base_params() -> ConnectionParams { + ConnectionParams { + driver: "mysql".to_string(), + host: Some("localhost".to_string()), + port: Some(3306), + username: Some("root".to_string()), + database: DatabaseSelection::Single("testdb".to_string()), + ..Default::default() + } + } -#[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 -} + #[test] + fn resolve_leaves_network_database_names_untouched() { + let params = ConnectionParams { + database: DatabaseSelection::Single("'quoted_schema'".to_string()), + ..base_params() + }; -#[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 -} + let resolved = resolve_connection_params(¶ms).expect("resolve"); + assert_eq!(resolved.database.primary(), "'quoted_schema'"); + } -#[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 -} + #[test] + fn params_for_pool_close_disables_all_tunnel_types() { + // Pool keys depend on connection_id, not the tunnel's local port, so + // closing a pool must never respawn an SSH/SSM/K8s tunnel (#1065). + // Verify that all three are forced off regardless of the input. + let params = ConnectionParams { + k8s_enabled: Some(true), + ssh_enabled: Some(true), + ssm_enabled: Some(true), + ssh_host: Some("bastion".to_string()), + ssh_port: Some(22), + ssh_user: Some("user".to_string()), + ..base_params() + }; -#[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 resolved = params_for_pool_close(¶ms, "conn-1").expect("resolve"); + assert_eq!(resolved.k8s_enabled, Some(false)); + 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")); } - 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, - )) -} + #[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() + }; -#[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) -} - -#[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(()) -} - -#[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(()) -} - -#[tauri::command] -pub async fn set_connection_appearance( - app: AppHandle, - id: String, - appearance: 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(()) -} - -#[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, - 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) -} - -#[tauri::command] -pub async fn get_connections( - 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) -} - -// ==================== SSH Connection Management ==================== - -/// 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` -// (also callable from the standalone `--mcp` server process, which has no -// `AppHandle`). This is a thin wrapper: resolve the path, run the shared -// core, and invalidate the connection cache only if it actually rewrote -// something. - -/// 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 -} - -// --------------------------------------------------------------------------- -// Kubernetes Connections -// --------------------------------------------------------------------------- - -#[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, - ) -} - -#[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); - crate::k8s_tunnel::test_k8s_connection(&context, &namespace, &options) -} - -#[tauri::command] -pub async fn get_k8s_contexts_cmd( - _app: AppHandle, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result, String> { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_contexts(&options) -} - -#[tauri::command] -pub async fn get_k8s_namespaces_cmd( - _app: AppHandle, - context: String, - kubectl_path: Option, - kubeconfig_path: Option, -) -> Result, String> { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_namespaces(&context, &options) -} - -#[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, String> { - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - crate::k8s_tunnel::get_k8s_resources(&context, &namespace, &resource_type, &options) -} - -#[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, String> { - 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, - ) -} - -#[tauri::command] -pub async fn validate_k8s_path_cmd( - _app: AppHandle, - path: String, - kind: String, -) -> Result<(), String> { - crate::k8s_tunnel::validate_k8s_path(&path, &kind) -} - -// --------------------------------------------------------------------------- -// AWS SSM -// --------------------------------------------------------------------------- - -#[tauri::command] -pub async fn test_ssm_connection_cmd( - app: AppHandle, - target: String, - profile: Option, - region: Option, - host: String, - port: u16, -) -> Result { - let result = crate::application::tunnels::execute( - &app.state::(), - None, - crate::application::tunnels::TunnelCommand::TestSsmConnection { - target, - profile, - region, - host, - port, - }, - ) - .await?; - serde_json::from_value(result).map_err(|e| e.to_string()) -} - -/// 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 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()) -} - -/// 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, - }), - ); -} - -/// 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::*; - use crate::models::DatabaseSelection; - - fn base_params() -> ConnectionParams { - ConnectionParams { - driver: "mysql".to_string(), - host: Some("localhost".to_string()), - port: Some(3306), - username: Some("root".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ..Default::default() - } - } - - #[test] - fn resolve_leaves_network_database_names_untouched() { - let params = ConnectionParams { - database: DatabaseSelection::Single("'quoted_schema'".to_string()), - ..base_params() - }; - - let resolved = resolve_connection_params(¶ms).expect("resolve"); - assert_eq!(resolved.database.primary(), "'quoted_schema'"); - } - - #[test] - fn params_for_pool_close_disables_all_tunnel_types() { - // Pool keys depend on connection_id, not the tunnel's local port, so - // closing a pool must never respawn an SSH/SSM/K8s tunnel (#1065). - // Verify that all three are forced off regardless of the input. - let params = ConnectionParams { - k8s_enabled: Some(true), - ssh_enabled: Some(true), - ssm_enabled: Some(true), - ssh_host: Some("bastion".to_string()), - ssh_port: Some(22), - ssh_user: Some("user".to_string()), - ..base_params() - }; - - let resolved = params_for_pool_close(¶ms, "conn-1").expect("resolve"); - assert_eq!(resolved.k8s_enabled, Some(false)); - 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)); - } - - #[test] - fn previous_uri_fails_on_a_genuine_keychain_error() { - let previous = - previous_keychain_connection_uri(true, || Err("securityd is not running".to_string())); - - assert_eq!( - previous, - Err("Failed to read the stored connection URI from the OS keychain".to_string()) - ); + 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] @@ -2355,24 +324,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(), @@ -2449,114 +400,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::*; @@ -3625,346 +1468,22 @@ mod tests { } } -#[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 -} - -#[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 -} - -/// 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::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. -#[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 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. +pub fn detect_blob_mime(base64_data: String) -> Result { + crate::application::records::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::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] pub fn get_file_stats(file_path: String) -> Result { use std::io::Read; @@ -3995,7 +1514,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. -#[tauri::command] pub async fn read_file_as_data_url(file_path: String) -> Result { use base64::Engine; use std::io::Read; @@ -4030,27 +1548,6 @@ pub async fn read_file_as_data_url(file_path: String) -> Result .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 -} - #[cfg(test)] pub(crate) fn cancel_query_impl( state: &QueryCancellationState, @@ -4059,137 +1556,8 @@ pub(crate) fn cancel_query_impl( crate::application::queries::cancel_registered_queries(state, None, connection_id, None) } -#[tauri::command] -pub async fn cancel_query( - state: State<'_, QueryCancellationState>, - 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<'_, QueryCancellationState>, - 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<'_, QueryCancellationState>, - 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 -} - // --- Explain Query Plan --- -#[tauri::command] -pub async fn explain_query_plan( - app: AppHandle, - state: State<'_, QueryCancellationState>, - 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. @@ -4224,165 +1592,8 @@ pub(crate) async fn read_in_open_transaction( // --- Count Query --- -#[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. -#[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::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()); @@ -4409,561 +1620,103 @@ pub async fn build_connection_url(params: &ConnectionParams) -> Result Err("Unsupported driver".into()), - } -} - -fn resolve_test_connection_password( - params: &ConnectionParams, - saved_conn: Option<&SavedConnection>, - 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) -/// 3. Credential from saved connection (as fallback) -#[cfg(test)] -fn resolve_ssh_test_credential( - request_credential: Option<&str>, - connection_id: Option<&str>, - get_ssh_connection: impl Fn(&str) -> Option, - get_keychain_credential: impl Fn(&str) -> Result, - extract_saved_credential: impl Fn(&SshConnection) -> Option, -) -> Option { - // Priority 1: Credential from request - // If credential field is present in request, use it even if empty - // Empty string means "use empty credential", not "fallback to keychain" - if let Some(cred) = request_credential { - return Some(cred.to_string()); - } - - // If no connection_id, we can't look up saved credentials - let conn_id = connection_id?; - let saved = get_ssh_connection(conn_id)?; - - // Priority 2: Credential from keychain - if saved.save_in_keychain.unwrap_or(false) { - if let Ok(cred) = get_keychain_credential(conn_id) { - if !cred.trim().is_empty() { - return Some(cred); - } - } - } - - // Priority 3: Credential from saved connection - extract_saved_credential(&saved) -} - -/// Fills SSH secrets that are still unresolved from the inline SSH fields of -/// a saved database connection (already hydrated from the keychain by -/// `find_connection_by_id`). Secrets explicitly provided by the request keep -/// priority; blank saved values are ignored. -#[cfg(test)] -fn apply_inline_ssh_secret_fallback( - resolved_password: Option, - resolved_passphrase: Option, - saved_params: &ConnectionParams, -) -> (Option, Option) { - fn non_blank(value: &Option) -> Option { - value.as_ref().filter(|v| !v.trim().is_empty()).cloned() - } - ( - resolved_password.or_else(|| non_blank(&saved_params.ssh_password)), - resolved_passphrase.or_else(|| non_blank(&saved_params.ssh_key_passphrase)), - ) -} - -/// Helper for backward compatibility - resolves SSH password -#[cfg(test)] -fn resolve_ssh_test_password( - request_password: Option<&str>, - connection_id: Option<&str>, - get_ssh_connection: impl Fn(&str) -> Option, - get_keychain_password: impl Fn(&str) -> Result, -) -> Option { - resolve_ssh_test_credential( - request_password, - connection_id, - get_ssh_connection, - get_keychain_password, - |conn| { - conn.password - .as_ref() - .filter(|p| !p.trim().is_empty()) - .cloned() - }, - ) -} - -// ==================== View Management Commands ==================== - -#[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 + )), + _ => Err("Unsupported driver".into()), + } } -// --- User management (gated by `DriverCapabilities::user_management`) ------- - -#[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 -} +/// 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) +/// 3. Credential from saved connection (as fallback) +#[cfg(test)] +use crate::models::SshConnection; -#[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(test)] +fn resolve_ssh_test_credential( + request_credential: Option<&str>, + connection_id: Option<&str>, + get_ssh_connection: impl Fn(&str) -> Option, + get_keychain_credential: impl Fn(&str) -> Result, + extract_saved_credential: impl Fn(&SshConnection) -> Option, +) -> Option { + // Priority 1: Credential from request + // If credential field is present in request, use it even if empty + // Empty string means "use empty credential", not "fallback to keychain" + if let Some(cred) = request_credential { + return Some(cred.to_string()); + } -#[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 -} + // If no connection_id, we can't look up saved credentials + let conn_id = connection_id?; + let saved = get_ssh_connection(conn_id)?; -#[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 -} + // Priority 2: Credential from keychain + if saved.save_in_keychain.unwrap_or(false) { + if let Ok(cred) = get_keychain_credential(conn_id) { + if !cred.trim().is_empty() { + return Some(cred); + } + } + } -#[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 + // Priority 3: Credential from saved connection + extract_saved_credential(&saved) } -#[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, +/// Fills SSH secrets that are still unresolved from the inline SSH fields of +/// a saved database connection (already hydrated from the keychain by +/// `find_connection_by_id`). Secrets explicitly provided by the request keep +/// priority; blank saved values are ignored. +#[cfg(test)] +fn apply_inline_ssh_secret_fallback( + resolved_password: Option, + resolved_passphrase: Option, + saved_params: &ConnectionParams, +) -> (Option, Option) { + fn non_blank(value: &Option) -> Option { + value.as_ref().filter(|v| !v.trim().is_empty()).cloned() + } + ( + resolved_password.or_else(|| non_blank(&saved_params.ssh_password)), + resolved_passphrase.or_else(|| non_blank(&saved_params.ssh_key_passphrase)), ) - .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, +/// Helper for backward compatibility - resolves SSH password +#[cfg(test)] +fn resolve_ssh_test_password( + request_password: Option<&str>, + connection_id: Option<&str>, + get_ssh_connection: impl Fn(&str) -> Option, + get_keychain_password: impl Fn(&str) -> Result, +) -> Option { + resolve_ssh_test_credential( + request_password, + connection_id, + get_ssh_connection, + get_keychain_password, + |conn| { + conn.password + .as_ref() + .filter(|p| !p.trim().is_empty()) + .cloned() + }, ) - .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 -} +// ==================== View Management Commands ==================== -/// 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; -} +// --- User management (gated by `DriverCapabilities::user_management`) ------- /// 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::health_check::active_connections().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 -} - // --- Type Registry --- -#[tauri::command] pub async fn get_data_types(driver: String) -> Result { log::debug!("Fetching data types for driver: {}", driver); @@ -4973,25 +1726,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 @@ -5054,208 +1788,10 @@ pub(crate) fn sql_builder_params( params } -#[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_registered_drivers() -> Vec { crate::drivers::registry::list_drivers().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_driver_manifest( driver_id: String, ) -> Option { @@ -5271,63 +1807,6 @@ pub async fn get_driver_manifest( // ==================== Connection Groups Management ==================== -#[tauri::command] -pub async fn get_connection_groups( - app: AppHandle, -) -> Result, String> { - let path = get_config_path(&app)?; - persistence::load_groups(&path) -} - -#[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) -} - -#[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> { @@ -5355,132 +1834,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. -#[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()) -} - -#[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. -#[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. @@ -5524,191 +1877,3 @@ pub(crate) fn reject_if_would_create_cycle( ) } -#[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(()) -} - -#[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) -} - -#[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(()) -} - -#[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(()) -} - -#[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 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) -} - -#[tauri::command] -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}")) -} - -#[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 -} diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 6dd2fa7e6..0fab2539b 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -1,10 +1,7 @@ use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use std::fs; -use std::path::PathBuf; use std::sync::RwLock; -use tauri::AppHandle; -use tauri::Manager; use std::collections::HashMap; @@ -306,10 +303,6 @@ pub enum MigrationMode { static CONFIG_CACHE: Lazy> = Lazy::new(|| RwLock::new(AppConfig::default())); -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); @@ -390,51 +383,6 @@ pub fn is_connection_readonly(config: &AppConfig, connection_id: &str) -> bool { } } -// 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::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); - tauri::async_runtime::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 @@ -471,160 +419,6 @@ pub(crate) fn resolve_schema_preference( None } -#[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 - )) -} - #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct AiKeyStatus { @@ -632,215 +426,6 @@ pub struct AiKeyStatus { pub from_env: bool, } -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::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, - ) -} - #[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 e44466167..a541b9392 100644 --- a/src-tauri/src/connection_appearance.rs +++ b/src-tauri/src/connection_appearance.rs @@ -1,7 +1,6 @@ use std::fs; use std::path::Path; use sha2::{Digest, Sha256}; -use tauri::AppHandle; pub(crate) const MAX_ICON_BYTES: u64 = 512 * 1024; @@ -175,36 +174,3 @@ pub fn copy_icon_for_duplicate( Ok(format!("connection-icons/{filename}")) } -#[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()) -} - -#[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_tags.rs b/src-tauri/src/connection_tags.rs index 2c0757e4d..93ba911f0 100644 --- a/src-tauri/src/connection_tags.rs +++ b/src-tauri/src/connection_tags.rs @@ -2,12 +2,9 @@ //! `connections.json` next to the groups. Tags are purely organizational; //! assignment lives on `SavedConnection.tag_ids`. -use tauri::{AppHandle, Runtime}; use uuid::Uuid; -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. @@ -172,63 +169,6 @@ pub fn merge_imported_tags( // ---------- Tauri commands ---------- -#[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) -} - -#[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) -} - -#[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) -} - -#[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) -} - -#[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/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 9265866b5..35a37b605 100644 --- a/src-tauri/src/dump_commands.rs +++ b/src-tauri/src/dump_commands.rs @@ -1,66 +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; -use tauri::State; -#[tauri::command] -pub async fn cancel_dump( - state: State<'_, DumpCancellationState>, - 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<'_, DumpCancellationState>, - 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<'_, DumpCancellationState>, - 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<'_, DumpCancellationState>, - 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 350546605..0f7cf95ab 100644 --- a/src-tauri/src/explain_import.rs +++ b/src-tauri/src/explain_import.rs @@ -9,7 +9,6 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use serde::{Deserialize, Serialize}; -use tauri::{Manager, Runtime, State}; /// A plan file read from disk, parsed on the frontend by `@tabularis/explain`. #[derive(Debug, Serialize, Deserialize, Clone)] @@ -44,68 +43,10 @@ impl PendingExplainFile { /// /// 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 { 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". -#[tauri::command] -pub fn get_pending_explain_file(state: State<'_, PendingExplainFile>) -> 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::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) -} - /// 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 34ef4b22c..1225e5b05 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -11,16 +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; -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>, @@ -34,44 +31,6 @@ impl Default for ExportCancellationState { } } -#[tauri::command] -pub async fn cancel_export( - state: State<'_, ExportCancellationState>, - 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<'_, ExportCancellationState>, - 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 fcfcb66b2..cdb4800ee 100644 --- a/src-tauri/src/health_check.rs +++ b/src-tauri/src/health_check.rs @@ -1,24 +1,24 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; use once_cell::sync::Lazy; -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) { @@ -42,57 +42,6 @@ pub async fn active_connections() -> Vec { ACTIVE_CONNECTIONS.read().await.iter().cloned().collect() } -/// 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; - } - } - } - }); -} - /// Stop the running ping loop, if any. pub async fn stop_ping_loop() { let mut guard = PING_STOP_TX.lock().await; @@ -101,148 +50,3 @@ pub async fn stop_ping_loop() { } } -/// 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::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())? -} - -/// 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/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 deleted file mode 100644 index efeb7dc8d..000000000 --- a/src-tauri/src/json_viewer.rs +++ /dev/null @@ -1,307 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -use serde::{Deserialize, Serialize}; -use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -use ulid::Ulid; -use urlencoding::encode; - -#[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>, -} - -#[tauri::command] -pub async fn open_json_viewer_window( - app: AppHandle, - store: State<'_, JsonViewerStore>, - 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) - } - } -} - -#[tauri::command] -pub async fn get_json_viewer_session( - store: State<'_, JsonViewerStore>, - 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<'_, JsonViewerStore>, - 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::*; - 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 588bd1e37..2c47c04ee 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,8 @@ +// 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))] + pub mod ai; pub mod ai_activity; #[cfg(test)] @@ -8,7 +13,7 @@ pub mod ai_approval; #[cfg(test)] pub mod ai_approval_tests; pub mod ai_approval_watcher; -pub mod ai_commands; + pub mod ai_notebook_export; #[cfg(test)] pub mod ai_notebook_export_tests; @@ -30,14 +35,12 @@ pub mod connection_cache; #[cfg(test)] pub mod connection_cache_tests; pub mod connection_import; -pub mod connection_import_commands; + pub mod connection_migrations; #[cfg(test)] pub mod connection_migrations_tests; pub mod connection_tags; -pub mod connection_window; -#[cfg(test)] -pub mod connection_window_tests; + pub mod credential_cache; pub mod dump_commands; // Added #[cfg(test)] @@ -59,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)] @@ -70,7 +72,7 @@ pub mod mcp; pub mod models; #[cfg(test)] pub mod models_tests; -pub mod notebooks; + pub mod paths; // Added #[cfg(test)] pub mod paths_tests; @@ -87,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)] @@ -111,24 +112,26 @@ pub mod ssm_tunnel; pub mod storage_location; #[cfg(test)] pub mod storage_location_tests; -mod system_theme; -pub mod task_manager; + pub mod team_share; -pub mod theme_commands; + pub mod theme_models; pub mod theme_packages; pub mod transport; pub mod ui_state; -pub mod ui_state_commands; + #[cfg(test)] pub mod ui_state_tests; -pub mod updater; -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; -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,27 +149,12 @@ pub mod drivers { pub mod sqlite; } -use tauri::Manager; - pub use runtime::bootstrap::get_log_buffer; -#[tauri::command] -fn is_debug_mode() -> bool { +pub(crate) fn is_debug_mode() -> bool { runtime::bootstrap::is_debug_mode() } -#[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"); -} - #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { // When ssh re-executes this binary as its SSH_ASKPASS helper (see the @@ -263,624 +251,13 @@ pub fn run() { return; } - // 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 = 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"))] + #[cfg(feature = "desktop")] + transport::desktop::run(args, log_buffer); + #[cfg(not(feature = "desktop"))] { - builder = builder.plugin(tauri_plugin_dialog::init()); + drop(log_buffer); + eprintln!("This build has no desktop app. Run `tabularis web` or `tabularis --mcp`."); + std::process::exit(2); } - #[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) - .manage(application_state.query_cancellation) - .manage(application_state.export_cancellation) - .manage(application_state.dump_cancellation) - .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(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. - { - 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, - sqlite_database::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, - 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::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, - 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_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_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::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, - connection_appearance::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 aaf25b712..045b699ec 100644 --- a/src-tauri/src/log_commands.rs +++ b/src-tauri/src/log_commands.rs @@ -1,55 +1,9 @@ use crate::application::operations; -use crate::logger::{LogEntry, SharedLogBuffer}; -use std::path::PathBuf; -use tauri::State; pub use operations::{GetLogsRequest, LogSettings}; -#[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) { match level.as_str() { "error" => log::error!(target: "frontend", "{}", message), @@ -60,7 +14,6 @@ pub fn log_frontend_event(level: String, message: String) { } } -#[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..139597f9c 100644 --- a/src-tauri/src/mcp/install.rs +++ b/src-tauri/src/mcp/install.rs @@ -1,16 +1,2 @@ -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/plugins/commands.rs b/src-tauri/src/plugins/commands.rs index 9c340da7e..1f048c6ef 100644 --- a/src-tauri/src/plugins/commands.rs +++ b/src-tauri/src/plugins/commands.rs @@ -1,73 +1,15 @@ -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}; +use crate::plugins::installer::{self}; -#[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 fn cancel_plugin_install(plugin_id: String) -> bool { crate::application::plugins::cancel_plugin_install(plugin_id).unwrap_or(false) } -#[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 disable_plugin(plugin_id: String) -> Result<(), String> { crate::application::plugins::disable_plugin(plugin_id).await } -#[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) -} - /// 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 { let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; plugin_dir @@ -76,50 +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. -#[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, - ) -} diff --git a/src-tauri/src/plugins/connection_metadata.rs b/src-tauri/src/plugins/connection_metadata.rs index ca1db2f6d..296d2076d 100644 --- a/src-tauri/src/plugins/connection_metadata.rs +++ b/src-tauri/src/plugins/connection_metadata.rs @@ -18,16 +18,6 @@ pub struct DriverManifestDetails { pub connection_metadata: Option, } -/// 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}), - ); -} - /// 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 44bb4d1a1..acda32dc7 100644 --- a/src-tauri/src/plugins/deep_link.rs +++ b/src-tauri/src/plugins/deep_link.rs @@ -24,7 +24,7 @@ use std::sync::Mutex; use serde::{Deserialize, Serialize}; -use tauri::{AppHandle, Emitter, Manager}; + use url::Url; /// Tauri-managed state holding the most recent install request that has not @@ -136,59 +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()) } -/// 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<'_, PendingInstall>, -) -> 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 7d5f876bc..93a30f494 100644 --- a/src-tauri/src/plugins/force_install.rs +++ b/src-tauri/src/plugins/force_install.rs @@ -15,10 +15,9 @@ //! [`MIGRATABLE_DRIVERS`] and a call site, not a new function. use serde::Serialize; -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 @@ -27,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 @@ -42,109 +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, -} - -/// 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() - }, - ) +pub(crate) struct PluginActivatedPayload<'a> { + pub(crate) plugin_id: &'a str, } /// Pure helper: return a copy of `config` with `plugin_id` added to @@ -185,55 +83,6 @@ pub(crate) fn merge_active_driver( } } -/// 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)) -} - -/// 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 @@ -264,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 20e2cf3bc..fce544113 100644 --- a/src-tauri/src/plugins/manager.rs +++ b/src-tauri/src/plugins/manager.rs @@ -4,7 +4,6 @@ use std::sync::Mutex; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; -use tauri::AppHandle; use crate::config::PluginConfig; use crate::drivers::driver_trait::{ @@ -41,7 +40,6 @@ pub struct PluginLoadError { pub error: String, } -#[tauri::command] pub fn get_plugin_startup_errors() -> Vec { crate::application::plugins::get_plugin_startup_errors() } @@ -110,18 +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"]; -/// 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 8d0de94b4..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) } -#[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..faf636c5c 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -1,6 +1,4 @@ use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use tauri::{AppHandle, Manager}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EditorPreferences { @@ -8,66 +6,3 @@ pub struct EditorPreferences { pub active_tab_id: Option, } -#[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/proxy/mod.rs b/src-tauri/src/proxy/mod.rs index 5ced6c4bd..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; -#[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> } } -#[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)) } -#[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..d6ebb6216 100644 --- a/src-tauri/src/query_history.rs +++ b/src-tauri/src/query_history.rs @@ -1,118 +1,6 @@ -use crate::application::productivity::{self, ProductivityCommand}; -use serde_json::from_value; -use tauri::{AppHandle, Manager, Runtime, State}; 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; - -#[tauri::command] -pub async fn get_query_history( - app: AppHandle, - _state: State<'_, QueryHistoryState>, - 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, - _state: State<'_, QueryHistoryState>, - 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, - _state: State<'_, QueryHistoryState>, - 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, - _state: State<'_, QueryHistoryState>, - 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/results_window.rs b/src-tauri/src/results_window.rs deleted file mode 100644 index 879a7e313..000000000 --- a/src-tauri/src/results_window.rs +++ /dev/null @@ -1,172 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -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`. -#[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`. -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. -#[tauri::command] -pub async fn open_results_window( - app: AppHandle, - store: tauri::State<'_, ResultsWindowStore>, - 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). -#[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::*; - - #[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/events.rs b/src-tauri/src/runtime/events.rs index 44b1ac537..bf8d9965f 100644 --- a/src-tauri/src/runtime/events.rs +++ b/src-tauri/src/runtime/events.rs @@ -1,5 +1,4 @@ use serde_json::Value; -use tauri::Emitter; pub trait RuntimeEvents: Send + Sync { fn emit(&self, event: &str, payload: Value) -> Result<(), String>; @@ -18,20 +17,3 @@ impl RuntimeEvents for NoopRuntimeEvents { } } -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/runtime/lifecycle.rs b/src-tauri/src/runtime/lifecycle.rs index d2ab2c8f3..f2a953203 100644 --- a/src-tauri/src/runtime/lifecycle.rs +++ b/src-tauri/src/runtime/lifecycle.rs @@ -38,15 +38,6 @@ pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { crate::drivers::registry::shutdown_external_drivers().await; } -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::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/state.rs b/src-tauri/src/runtime/state.rs index b4c7e5a5f..b5104505d 100644 --- a/src-tauri/src/runtime/state.rs +++ b/src-tauri/src/runtime/state.rs @@ -5,17 +5,14 @@ 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 web_active_connections: Mutex>>, pub web_approval_owners: Mutex>, pub web_preferences: @@ -47,17 +44,14 @@ 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()), 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 3f0ca5854..9aaf6f9ec 100644 --- a/src-tauri/src/runtime/tests.rs +++ b/src-tauri/src/runtime/tests.rs @@ -154,148 +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}; - use tauri::Manager; - 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) - .manage(query_history::QueryHistoryState) - .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(), - handle.state(), - 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(), handle.state(), 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(), - handle.state(), - connection.clone(), - entry.id, - ) - .await - .unwrap(); - query_history::clear_query_history(handle.clone(), handle.state(), 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 25511d91a..80132e1ed 100644 --- a/src-tauri/src/saved_queries.rs +++ b/src-tauri/src/saved_queries.rs @@ -1,187 +1,5 @@ -use crate::application::productivity::{self, ProductivityCommand}; -use serde_json::from_value; -use tauri::{AppHandle, Manager, Runtime}; pub use crate::application::productivity::{SavedQuery, SavedQueryMeta}; -use crate::saved_query_folders::SavedQueryFolder; - -#[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 use crate::application::productivity::backfill_saved_query_metadata as backfill_missing_database; -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/sql_file.rs b/src-tauri/src/sql_file.rs index 8430c75af..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)) } -#[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())? } -#[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..f389af57e 100644 --- a/src-tauri/src/sqlite_database.rs +++ b/src-tauri/src/sqlite_database.rs @@ -1,9 +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}; -use tauri::{AppHandle, Runtime}; const SQLITE_EXTENSIONS: [&str; 3] = ["db", "sqlite", "sqlite3"]; @@ -101,7 +99,6 @@ pub(crate) async fn initialize_sqlite_file(path: &Path) -> Result<(), String> { Ok(()) } -#[tauri::command] pub async fn create_sqlite_file(path: String) -> Result { let path = normalize_sqlite_path(&path)?; initialize_sqlite_file(&path).await?; @@ -110,30 +107,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()) } - -#[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/storage_location.rs b/src-tauri/src/storage_location.rs index f5d7fd23f..26af8a7de 100644 --- a/src-tauri/src/storage_location.rs +++ b/src-tauri/src/storage_location.rs @@ -312,12 +312,10 @@ fn info() -> StorageLocationInfo { } } -#[tauri::command] pub fn get_storage_location() -> StorageLocationInfo { info() } -#[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,28 +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. -#[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}")) -} - /// 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::paths::get_app_data_dir() .to_string_lossy() diff --git a/src-tauri/src/theme_commands.rs b/src-tauri/src/theme_commands.rs deleted file mode 100644 index a84f1e289..000000000 --- a/src-tauri/src/theme_commands.rs +++ /dev/null @@ -1,176 +0,0 @@ -use crate::paths::{get_app_config_dir, get_default_app_data_dir}; -use crate::theme_packages::{self, ThemeCatalog, ThemeContribution}; -use serde_json::Value; -use tauri::{AppHandle, Emitter}; - -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) -} - -#[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"), - ) -} - -/// Legacy command names and argument names remain available. Raw metadata is -/// retained instead of round-tripping files through the historical Rust model. -#[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() -} - -#[tauri::command] -pub fn get_theme(theme_id: String) -> Result { - let entry = get_theme_catalog() - .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> { - committed( - &app, - theme_packages::save_legacy_theme(&get_app_config_dir(), theme), - ) -} - -#[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), - ) -} - -#[tauri::command] -pub 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) -} - -#[tauri::command] -pub fn export_theme(theme_id: String) -> Result { - theme_packages::export_personal_theme(&get_app_config_dir(), &theme_id) -} - -#[tauri::command] -pub fn create_personal_theme( - app: AppHandle, - name: String, - source: String, -) -> Result { - committed( - &app, - theme_packages::create_personal_definition(&get_app_config_dir(), &name, &source), - ) -} - -#[tauri::command] -pub fn create_personal_snapshot( - app: AppHandle, - name: String, - source: String, -) -> Result { - committed( - &app, - theme_packages::create_personal_snapshot(&get_app_config_dir(), &name, &source), - ) -} - -#[tauri::command] -pub fn update_personal_theme( - app: AppHandle, - theme_id: String, - name: String, - source: String, - expected_revision: String, -) -> Result { - committed( - &app, - theme_packages::update_personal_definition( - &get_app_config_dir(), - &theme_id, - &name, - &source, - &expected_revision, - ), - ) -} - -#[tauri::command] -pub fn update_personal_snapshot( - app: AppHandle, - theme_id: String, - name: String, - source: String, - editor: Value, - expected_revision: String, -) -> Result { - committed( - &app, - theme_packages::update_personal_snapshot( - &get_app_config_dir(), - &theme_id, - &name, - &source, - editor, - &expected_revision, - ), - ) -} - -#[tauri::command] -pub fn duplicate_personal_theme( - app: AppHandle, - theme_id: String, - name: String, - editor: Option, -) -> Result { - committed( - &app, - theme_packages::duplicate_personal_theme( - &get_app_config_dir(), - &get_default_app_data_dir(), - env!("CARGO_PKG_VERSION"), - &theme_id, - &name, - editor, - ), - ) -} 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 ba04d2ee7..fcecf286c 100644 --- a/src-tauri/src/theme_packages/commands.rs +++ b/src-tauri/src/theme_packages/commands.rs @@ -2,32 +2,12 @@ use super::{catalog::PACKAGES_DIR, lifecycle, *}; use crate::plugins::{install_cancellation, registry, tabularium}; use sha2::{Digest, Sha256}; use std::path::Path; -use tauri::{AppHandle, Emitter}; - -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}") } -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. -#[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 +41,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 +59,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 +91,10 @@ 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] 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,23 +102,6 @@ pub async fn preview_local_theme_package( preview_local_package_bytes(bytes).await } -#[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 { @@ -148,15 +110,6 @@ pub struct ThemeRegistrySnapshot { pub plugins: Vec, } -#[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, @@ -190,23 +143,6 @@ pub async fn fetch_registry( }) } -/// 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 { - 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, @@ -231,24 +167,6 @@ pub async fn fetch_package_detail( Ok(detail) } -#[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, @@ -267,23 +185,10 @@ pub async fn install_registry( .await } -#[tauri::command] pub fn cancel_theme_install(registry_key: String, package_name: String) -> bool { install_cancellation::cancel(&operation_id(®istry_key, &package_name)) } -#[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, @@ -297,16 +202,6 @@ pub fn set_package_enabled( ) } -/// Recovery is an explicit action, never a catalog-read or hydration side effect. -#[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); @@ -316,17 +211,6 @@ pub fn recover_packages() -> Vec { } } -#[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/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/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/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/transport/desktop/ai_commands.rs b/src-tauri/src/transport/desktop/ai_commands.rs new file mode 100644 index 000000000..d530a5954 --- /dev/null +++ b/src-tauri/src/transport/desktop/ai_commands.rs @@ -0,0 +1,94 @@ +//! Tauri commands exposed to the frontend for AI activity, approval gates, +//! 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::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}; + +async fn execute(app: &AppHandle, command: AiCommand) -> Result { + let state = app.state::>(); + ai::execute(&app.state::(), &state, None, command).await +} + +#[tauri::command] +pub async fn get_ai_activity(app: AppHandle, filter: Option) -> Result { + execute(&app, AiCommand::GetActivity { filter }).await +} + +#[tauri::command] +pub async fn get_ai_sessions(app: AppHandle) -> Result { + execute(&app, AiCommand::GetSessions).await +} + +#[tauri::command] +pub async fn get_ai_session_events(app: AppHandle, session_id: String) -> Result { + execute(&app, AiCommand::GetSessionEvents { session_id }).await +} + +#[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 +} + +#[tauri::command] +pub async fn export_ai_activity_csv() -> Result { + crate::application::generic_exports::generate_ai_activity_csv().await +} + +#[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 +} 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..3a6232123 --- /dev/null +++ b/src-tauri/src/transport/desktop/commands.rs @@ -0,0 +1,2419 @@ +use crate::commands::*; +use crate::credential_cache; +use crate::keychain_utils; +use crate::models::{ + 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; +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 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 +} + +/// 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 +} 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 68% rename from src-tauri/src/connection_import_commands.rs rename to src-tauri/src/transport/desktop/connection_import_commands.rs index 7f4a98379..2f21ef168 100644 --- a/src-tauri/src/connection_import_commands.rs +++ b/src-tauri/src/transport/desktop/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::{ @@ -7,10 +8,10 @@ use crate::application::connection_files::{ TabularisImportPreviewResult, }; use crate::connection_import::{analyzer, convert}; -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,15 +29,16 @@ 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, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, source_id: String, include_passwords: bool, file: Option, @@ -52,10 +54,11 @@ pub async fn preview_connection_import( .await } +#[cfg(feature = "desktop")] #[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, @@ -73,44 +76,11 @@ pub async fn apply_connection_import( .await } -#[tauri::command] -pub async fn preview_tabularis_import( - app: AppHandle, - payload: ExportPayload, -) -> Result { - connection_files::preview_tabularis_payload( - app.state::().inner(), - &payload, - ) - .await -} - -#[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( app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, + cache: tauri::State<'_, std::sync::Arc>, file: ConnectionImportFile, password: Option, ) -> Result { @@ -124,10 +94,11 @@ pub async fn preview_tabularis_import_file( .await } +#[cfg(feature = "desktop")] #[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_window.rs b/src-tauri/src/transport/desktop/connection_window.rs similarity index 91% rename from src-tauri/src/connection_window.rs rename to src-tauri/src/transport/desktop/connection_window.rs index 525c2c436..132f1c001 100644 --- a/src-tauri/src/connection_window.rs +++ b/src-tauri/src/transport/desktop/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, @@ -56,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 @@ -74,9 +76,9 @@ 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 + 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 100% rename from src-tauri/src/e2e_dialog_mock.rs rename to src-tauri/src/transport/desktop/e2e_dialog_mock.rs 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..5531a3507 --- /dev/null +++ b/src-tauri/src/transport/desktop/explain_import.rs @@ -0,0 +1,61 @@ +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: 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/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..f16b1ecca --- /dev/null +++ b/src-tauri/src/transport/desktop/mod.rs @@ -0,0 +1,669 @@ +//! 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 log_commands; +pub mod mcp; +pub mod notebooks; +pub mod plugins; +pub mod preferences; +pub mod proxy; +pub mod query_history; +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.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, + 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, + 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_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::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, + 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::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, + // 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 + // 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 69% rename from src-tauri/src/notebooks.rs rename to src-tauri/src/transport/desktop/notebooks.rs index c349b8725..74c3d2564 100644 --- a/src-tauri/src/notebooks.rs +++ b/src-tauri/src/transport/desktop/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; #[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, @@ -22,12 +24,13 @@ pub async fn create_notebook( #[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, @@ -39,11 +42,12 @@ pub async fn save_notebook( #[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, @@ -53,9 +57,13 @@ pub async fn load_notebook( } #[tauri::command] -pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Result<(), String> { +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, @@ -66,12 +74,13 @@ pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Resu #[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, @@ -82,9 +91,12 @@ pub async fn rename_notebook( } #[tauri::command] -pub async fn list_notebooks(connection_id: String) -> Result, String> { +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/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..e814b9845 --- /dev/null +++ b/src-tauri/src/transport/desktop/preferences.rs @@ -0,0 +1,37 @@ +use crate::preferences::*; +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, + ) +} 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/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 85% rename from src-tauri/src/system_theme.rs rename to src-tauri/src/transport/desktop/system_theme.rs index 619f3f34d..5bd68802e 100644 --- a/src-tauri/src/system_theme.rs +++ b/src-tauri/src/transport/desktop/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/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 81% rename from src-tauri/src/task_manager.rs rename to src-tauri/src/transport/desktop/task_manager.rs index 36503d81a..b1c27af03 100644 --- a/src-tauri/src/task_manager.rs +++ b/src-tauri/src/transport/desktop/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") { @@ -52,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/transport/desktop/theme_commands.rs b/src-tauri/src/transport/desktop/theme_commands.rs new file mode 100644 index 000000000..0271cb9d0 --- /dev/null +++ b/src-tauri/src/transport/desktop/theme_commands.rs @@ -0,0 +1,234 @@ +use crate::application::themes::{self, LocalThemeArchive, ThemeCommand}; +use crate::runtime::RuntimeContext; +use crate::theme_packages::ThemeCatalog; +use serde_json::Value; +use tauri::{AppHandle, Manager}; + +async fn execute(app: &AppHandle, command: ThemeCommand) -> Result { + themes::execute(&app.state::(), command).await +} + +#[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. +#[tauri::command] +pub fn get_all_themes(app: AppHandle) -> Result, String> { + crate::application::persistence::get_all_themes(&app.state::()) +} + +#[tauri::command] +pub fn save_custom_theme(app: AppHandle, theme: Value) -> Result<(), String> { + crate::application::persistence::save_custom_theme(&app.state::(), theme) +} + +#[tauri::command] +pub fn delete_custom_theme(app: AppHandle, theme_id: String) -> Result<(), String> { + crate::application::persistence::delete_custom_theme(&app.state::(), &theme_id) +} + +#[tauri::command] +pub async fn import_theme( + app: AppHandle, + theme_json: String, + name: Option, +) -> Result { + execute(&app, ThemeCommand::ImportTheme { theme_json, name }).await +} + +#[tauri::command] +pub async fn export_theme(app: AppHandle, theme_id: String) -> Result { + execute(&app, ThemeCommand::ExportTheme { theme_id }).await +} + +#[tauri::command] +pub async fn create_personal_theme( + app: AppHandle, + name: String, + source: String, +) -> Result { + execute(&app, ThemeCommand::CreatePersonalTheme { name, source }).await +} + +#[tauri::command] +pub async fn create_personal_snapshot( + app: AppHandle, + name: String, + source: String, +) -> Result { + execute(&app, ThemeCommand::CreatePersonalSnapshot { name, source }).await +} + +#[tauri::command] +pub async fn update_personal_theme( + app: AppHandle, + theme_id: String, + name: String, + source: String, + expected_revision: String, +) -> Result { + execute( + &app, + ThemeCommand::UpdatePersonalTheme { + theme_id, + name, + source, + expected_revision, + }, + ) + .await +} + +#[tauri::command] +pub async fn update_personal_snapshot( + app: AppHandle, + theme_id: String, + name: String, + source: String, + editor: Value, + expected_revision: String, +) -> Result { + execute( + &app, + ThemeCommand::UpdatePersonalSnapshot { + theme_id, + name, + source, + editor, + expected_revision, + }, + ) + .await +} + +#[tauri::command] +pub async fn duplicate_personal_theme( + app: AppHandle, + theme_id: String, + name: String, + editor: Option, +) -> Result { + execute( + &app, + 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/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 89% rename from src-tauri/src/ui_state_commands.rs rename to src-tauri/src/transport/desktop/ui_state_commands.rs index b8ec1ff89..e194501b4 100644 --- a/src-tauri/src/ui_state_commands.rs +++ b/src-tauri/src/transport/desktop/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/transport/desktop/updater.rs similarity index 97% rename from src-tauri/src/updater.rs rename to src-tauri/src/transport/desktop/updater.rs index 8fa37ddf7..3a6cf6403 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/transport/desktop/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,14 +181,16 @@ 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()) } // 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. @@ -193,7 +198,7 @@ pub async fn check_for_updates(app: AppHandle, force: bool) -> Result 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(); @@ -378,7 +386,7 @@ pub async fn download_and_install_update(app: AppHandle) -> 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 97% rename from src-tauri/src/window_decorations.rs rename to src-tauri/src/transport/desktop/window_decorations.rs index 767b7fad5..440b7c084 100644 --- a/src-tauri/src/window_decorations.rs +++ b/src-tauri/src/transport/desktop/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_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 97% rename from src-tauri/src/window_placement.rs rename to src-tauri/src/transport/desktop/window_placement.rs index 26ed20a58..286c10ca3 100644 --- a/src-tauri/src/window_placement.rs +++ b/src-tauri/src/transport/desktop/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/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/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] 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. 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..8cd7fac3a 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": [ @@ -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", 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); 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 = {