diff --git a/.claude/skills/tabularis-plugin-driver/SKILL.md b/.claude/skills/tabularis-plugin-driver/SKILL.md index 17b18240a..d2695c3a3 100644 --- a/.claude/skills/tabularis-plugin-driver/SKILL.md +++ b/.claude/skills/tabularis-plugin-driver/SKILL.md @@ -7,7 +7,7 @@ description: "Use when creating or updating a Tabularis database driver plugin i Use this skill when building or updating a database plugin for Tabularis. -The skill is optimized for this repository. Follow `AGENTS.md`, the files in `.rules/`, and the current plugin-system behavior in `src-tauri/src/plugins/` and `src/types/plugins.ts`. +The skill is optimized for this repository. Follow `AGENTS.md`, the files in `.rules/`, and the current plugin-system behavior in `src-tauri/src/plugins/` and `packages/web-ui/src/types/plugins.ts`. ## Goals @@ -55,7 +55,7 @@ Keep `src/main.rs` thin. It should mostly parse requests, dispatch methods, and 1. Read the current plugin manifest shape in: - `plugins/manifest.schema.json` - - `src/types/plugins.ts` + - `packages/web-ui/src/types/plugins.ts` - `src-tauri/src/plugins/manager.rs` 2. Read the JSON-RPC expectations in: - `plugins/PLUGIN_GUIDE.md` @@ -64,9 +64,9 @@ Keep `src/main.rs` thin. It should mostly parse requests, dispatch methods, and 3. Read a built-in driver with broad coverage to understand expected behaviors: - `src-tauri/src/drivers/mysql/mod.rs` 4. Read plugin-loading behavior and modern feature flags in: - - `src/hooks/useDrivers.ts` - - `src/utils/connectionStringParser.ts` - - `src/utils/driverCapabilities.ts` + - `packages/web-ui/src/hooks/useDrivers.ts` + - `packages/web-ui/src/utils/connectionStringParser.ts` + - `packages/web-ui/src/utils/driverCapabilities.ts` ## Implementation Workflow diff --git a/.claude/skills/tabularis-pr-review/SKILL.md b/.claude/skills/tabularis-pr-review/SKILL.md index 98f0a29a9..bf936e951 100644 --- a/.claude/skills/tabularis-pr-review/SKILL.md +++ b/.claude/skills/tabularis-pr-review/SKILL.md @@ -28,14 +28,14 @@ Read `.rules/*.md` for every changed file's domain before forming opinions. The - **`react.md` #1** — exhaustive `useEffect`/`useMemo`/`useCallback` deps. - **`typescript.md`** — no `any`. - **`rust.md`** — pure helpers extracted + unit-tested; `mod.rs` stays orchestration-only; public APIs re-exported on refactor. -- **`general.md`** — English-only comments; new user-facing strings need i18n keys in `src/i18n/locales/*`. +- **`general.md`** — English-only comments; new user-facing strings need i18n keys in `packages/web-ui/src/i18n/locales/*`. - **`plugins.md`** — what happens on a plugin driver? Look for `driver === ""` checks, SQL helpers called without `activeCapabilities`, frontend SQL (`LIMIT`, `COUNT(DISTINCT)`, casts) shown to every dialect, and slot contexts that pass capabilities instead of the driver id. ### 3. Verify the PR's claims — don't take them on faith For each factual assertion in the description, prove it: -- "Uses `common.search` / `common.noResults` i18n keys" → `grep '"search"\|"noResults"' src/i18n/locales/en.json`. -- "Removing `searchable={false}` enables search" → read the component default (`grep searchable src/components/ui/Select.tsx`). -- "Reads `default_port` from the manifest" → check the type (`src/types/plugins.ts`) — is it nullable? What's the fallback? +- "Uses `common.search` / `common.noResults` i18n keys" → `grep '"search"\|"noResults"' packages/web-ui/src/i18n/locales/en.json`. +- "Removing `searchable={false}` enables search" → read the component default (`grep searchable packages/web-ui/src/components/ui/Select.tsx`). +- "Reads `default_port` from the manifest" → check the type (`packages/web-ui/src/types/plugins.ts`) — is it nullable? What's the fallback? - New Tauri command → confirm it's registered in `src-tauri/src/lib.rs` `invoke_handler`. ### 4. Impact analysis (per AGENTS.md) diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..130811407 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +# Allowlist: the image only needs the workspace manifests, the packages, the +# Rust crate and the docker helpers. +* +!package.json +!roadmap.json +!pnpm-lock.yaml +!pnpm-workspace.yaml +!.node-version +!packages/ +!plugins/manifest.schema.json +!src-tauri/ +!docker/ + +**/node_modules +**/dist +**/coverage +src-tauri/target +src-tauri/gen diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e39dbb994..54f0a7847 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -340,16 +340,86 @@ jobs: rm -rf "$extract_dir" done - - name: Upload portable executable (Windows only) + - name: Verify packaged Web UI (Linux) + if: matrix.platform == 'ubuntu-24.04' + shell: bash + run: | + set -euo pipefail + deb=$(find src-tauri/target -path '*/bundle/deb/*.deb' -print -quit) + appimage=$(find src-tauri/target -path '*/bundle/appimage/*.AppImage' -print -quit) + test -n "$deb" + test -n "$appimage" + web-ui-project/scripts/verify-linux-web-package.sh assets "$deb" + web-ui-project/scripts/verify-linux-web-package.sh assets "$appimage" + + - name: Smoke-test headless Web mode (Linux) + if: matrix.platform == 'ubuntu-24.04' + shell: bash + run: | + set -euo pipefail + deb=$(find src-tauri/target -path '*/bundle/deb/*.deb' -print -quit) + test -n "$deb" + web-ui-project/scripts/verify-linux-web-package.sh headless "$deb" + + - name: Verify packaged Web UI (macOS) + if: startsWith(matrix.platform, 'macos') + shell: bash + run: | + set -euo pipefail + app=$(find src-tauri/target -path '*/bundle/macos/*.app' -type d -print -quit) + test -n "$app" + web_root="$app/Contents/Resources/web-ui" + test -f "$web_root/index.html" + test -n "$(find "$web_root/assets" -type f -print -quit)" + cmp packages/web-ui/dist/index.html "$web_root/index.html" + + - name: Verify packaged Web UI (Windows) + if: matrix.platform == 'windows-latest' + shell: pwsh + run: | + $msi = Get-ChildItem src-tauri\target -Recurse -File -Filter *.msi | Select-Object -First 1 + if (-not $msi) { throw "No MSI artifact was produced" } + + $extract = Join-Path $env:RUNNER_TEMP "tabularis-msi-$([guid]::NewGuid())" + New-Item -ItemType Directory -Path $extract | Out-Null + $msiExtraction = Start-Process msiexec.exe -ArgumentList "/a", "`"$($msi.FullName)`"", "/qn", "TARGETDIR=`"$extract`"" -Wait -PassThru + if ($msiExtraction.ExitCode -ne 0) { + throw "MSI extraction failed with exit code $($msiExtraction.ExitCode)" + } + + $index = Get-ChildItem $extract -Recurse -File -Filter index.html | + Where-Object { $_.FullName -match '[\\/]web-ui[\\/]index\.html$' } | + Select-Object -First 1 + if (-not $index) { throw "The MSI does not contain web-ui/index.html" } + $assets = Join-Path $index.DirectoryName "assets" + if (-not (Get-ChildItem $assets -Recurse -File | Select-Object -First 1)) { + throw "The MSI does not contain Web UI assets" + } + if ((Get-FileHash packages\web-ui\dist\index.html).Hash -ne (Get-FileHash $index.FullName).Hash) { + throw "The MSI Web UI index differs from the built distribution" + } + Remove-Item $extract -Recurse -Force + + - name: Package and upload portable Web UI bundle (Windows only) if: matrix.platform == 'windows-latest' && !inputs.preview shell: pwsh env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | $version = "${{ inputs.tag }}".TrimStart('v') - $src = "src-tauri\target\release\tabularis.exe" - $portable = "tabularis_${version}_x64-portable.exe" - Copy-Item $src $portable + $portableRoot = "tabularis_${version}_x64-portable" + $portable = "tabularis_${version}_x64-portable.zip" + New-Item -ItemType Directory -Path $portableRoot | Out-Null + Copy-Item src-tauri\target\release\tabularis.exe (Join-Path $portableRoot "tabularis.exe") + Copy-Item packages\web-ui\dist (Join-Path $portableRoot "web-ui") -Recurse + Compress-Archive -Path "$portableRoot\*" -DestinationPath $portable + + $verify = Join-Path $env:RUNNER_TEMP "tabularis-portable-$([guid]::NewGuid())" + Expand-Archive $portable -DestinationPath $verify + if (-not (Test-Path (Join-Path $verify "tabularis.exe"))) { throw "Portable executable is missing" } + if (-not (Test-Path (Join-Path $verify "web-ui\index.html"))) { throw "Portable Web UI is missing" } + Remove-Item $verify -Recurse -Force + gh release upload "${{ inputs.tag }}" $portable --clobber # WinGet uses an NSIS installer, not the portable executable layout. @@ -371,12 +441,18 @@ jobs: RELEASE_TAG: ${{ inputs.tag }} run: node scripts/stage-winget-installer.mjs "$env:RELEASE_TAG" - - name: Stage portable executable (Windows only, preview mode) + # Same layout as the release portable bundle: the executable serves the + # Web UI from the sibling web-ui/ directory. + - name: Stage portable Web UI bundle (Windows only, preview mode) if: matrix.platform == 'windows-latest' && inputs.preview shell: pwsh run: | $version = (Get-Content src-tauri\tauri.conf.json -Raw | ConvertFrom-Json).version - Copy-Item "src-tauri\target\release\tabularis.exe" "src-tauri\target\release\bundle\tabularis_${version}_x64-portable.exe" + $portableRoot = Join-Path $env:RUNNER_TEMP "tabularis_${version}_x64-portable" + New-Item -ItemType Directory -Path $portableRoot | Out-Null + Copy-Item src-tauri\target\release\tabularis.exe (Join-Path $portableRoot "tabularis.exe") + Copy-Item packages\web-ui\dist (Join-Path $portableRoot "web-ui") -Recurse + Compress-Archive -Path "$portableRoot\*" -DestinationPath "src-tauri\target\release\bundle\tabularis_${version}_x64-portable.zip" # Only the installable bundles: the raw .app directory, the deb/rpm # staging trees and the binaries themselves are noise for a tester. @@ -392,5 +468,6 @@ jobs: src-tauri/target/**/release/bundle/**/*.AppImage src-tauri/target/**/release/bundle/**/*.msi src-tauri/target/**/release/bundle/**/*.exe + src-tauri/target/**/release/bundle/**/*-portable.zip if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a07dffe67..cfb2e7324 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,24 +8,26 @@ on: push: branches: [main] paths: - - 'src/**' + - 'packages/web-ui/**' - 'src-tauri/**' - 'tests/**' - 'packages/explain/**' # imported from source by the host - 'package.json' - 'pnpm-lock.yaml' - - 'tsconfig.json' + - 'eslint.config.js' + - 'web-ui-project/**' - '.github/workflows/**' pull_request: branches: [main] paths: - - 'src/**' + - 'packages/web-ui/**' - 'src-tauri/**' - 'tests/**' - 'packages/explain/**' # imported from source by the host - 'package.json' - 'pnpm-lock.yaml' - - 'tsconfig.json' + - 'eslint.config.js' + - 'web-ui-project/**' - '.github/workflows/**' jobs: @@ -58,8 +60,108 @@ jobs: - name: Lint run: pnpm run lint + - name: Check web API inventory + run: pnpm run web:inventory + + - name: Check web frontend boundaries + run: pnpm run web:boundaries + + - name: Check Web UI packaging contract + run: pnpm run web:packaging + + - name: Check Web UI documentation + run: pnpm run web:docs + + - name: Check signed Web UI parity audit + run: pnpm run web:manual-parity + - name: Build run: pnpm run build + - name: Check dual-transport contract + run: pnpm run test:web-contract + + - name: Check Web UI resilience + run: pnpm run test:web-resilience + - 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 + + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: tabularis-e2e + POSTGRES_DB: tabularis_e2e + ports: + - 45432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d tabularis_e2e" + --health-interval 2s + --health-timeout 3s + --health-retries 30 + mysql: + image: mysql:8.4 + env: + MYSQL_ROOT_PASSWORD: tabularis-e2e + MYSQL_DATABASE: tabularis_e2e + ports: + - 43306:3306 + options: >- + --health-cmd "mysqladmin ping -h 127.0.0.1 -uroot -ptabularis-e2e" + --health-interval 2s + --health-timeout 3s + --health-retries 45 + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + name: Install pnpm + + - name: Install Rust/Tauri dependencies + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libsoup-3.0-dev build-essential curl wget file libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev + + - name: Cache Rust dependencies + uses: swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + workspaces: src-tauri + + - name: Install dependencies + run: pnpm install + + - name: Install browser engines + run: pnpm exec playwright install --with-deps chromium firefox webkit + + - name: Run real-database browser matrix + env: + TABULARIS_E2E_MANAGED_DATABASES: "1" + run: pnpm test:web-e2e:browsers + + - name: Upload browser E2E artifacts + if: failure() + uses: actions/upload-artifact@v4 + with: + name: web-e2e-artifacts + path: web-ui-project/.runtime/e2e + if-no-files-found: ignore diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 000000000..6ca921a14 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,179 @@ +name: Docker + +# Container image (amd64 + arm64 on native runners) and the Helm chart, +# published to ghcr.io on release tags. +# Pull requests that touch the container files build and smoke-test amd64. +on: + push: + tags: + - "v*" + pull_request: + paths: + - "docker/**" + - "charts/**" + - ".dockerignore" + - ".github/workflows/docker.yml" + workflow_dispatch: + inputs: + push: + description: "Push the image (tagged with the branch name) to ghcr.io" + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: docker-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + PUSH: ${{ github.event_name == 'push' || inputs.push == true }} + +jobs: + image: + name: image / ${{ matrix.arch }} + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + arch: ${{ fromJSON(github.event_name == 'pull_request' && '["amd64"]' || '["amd64","arm64"]') }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Image name + run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/tabularis" >> "$GITHUB_ENV" + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build for the smoke test + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/${{ matrix.arch }} + load: true + tags: tabularis:smoke + build-args: TABULARIS_BUILD_COMMIT=${{ github.sha }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,scope=${{ matrix.arch }},mode=max + + - name: Smoke test + run: docker/smoke-test.sh tabularis:smoke + + - if: env.PUSH == 'true' + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Push by digest + if: env.PUSH == 'true' + id: push + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/${{ matrix.arch }} + build-args: TABULARIS_BUILD_COMMIT=${{ github.sha }} + labels: | + org.opencontainers.image.source=https://github.com/${{ github.repository }} + org.opencontainers.image.revision=${{ github.sha }} + outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true + provenance: mode=max + sbom: true + cache-from: type=gha,scope=${{ matrix.arch }} + + - name: Export digest + if: env.PUSH == 'true' + run: | + mkdir -p /tmp/digests + touch "/tmp/digests/${DIGEST#sha256:}" + env: + DIGEST: ${{ steps.push.outputs.digest }} + + - if: env.PUSH == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: digests-${{ matrix.arch }} + path: /tmp/digests/* + retention-days: 1 + + manifest: + name: manifest + needs: image + if: github.event_name == 'push' || inputs.push == true + runs-on: ubuntu-24.04 + permissions: + contents: read + packages: write + steps: + - name: Image name + run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/tabularis" >> "$GITHUB_ENV" + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: digests-* + path: /tmp/digests + merge-multiple: true + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - id: meta + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ${{ env.IMAGE }} + flavor: | + latest=false + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}},enable=${{ !contains(github.ref, '-') }} + type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, '-') }} + type=ref,event=branch + + - name: Create manifest list + working-directory: /tmp/digests + run: | + # shellcheck disable=SC2046 + docker buildx imagetools create \ + $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf "$IMAGE@sha256:%s " *) + + - name: Inspect + run: docker buildx imagetools inspect "$IMAGE:${{ steps.meta.outputs.version }}" + + chart: + name: Helm chart + runs-on: ubuntu-24.04 + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1 + + - name: Lint and render + run: | + helm lint charts/tabularis --set publicUrl=https://tabularis.example.com + helm template smoke charts/tabularis \ + --set publicUrl=https://tabularis.example.com \ + --set ingress.enabled=true >/dev/null + + - name: Publish to ghcr.io + if: github.event_name == 'push' + run: | + version="${GITHUB_REF_NAME#v}" + helm package charts/tabularis --version "$version" --app-version "$version" + echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io -u "${{ github.actor }}" --password-stdin + helm push "tabularis-$version.tgz" "oci://ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/charts" diff --git a/.github/workflows/mysql-integration.yml b/.github/workflows/mysql-integration.yml index 04b748f01..9d9155040 100644 --- a/.github/workflows/mysql-integration.yml +++ b/.github/workflows/mysql-integration.yml @@ -65,6 +65,9 @@ jobs: sudo apt-get update sudo apt-get install -y libwebkit2gtk-4.1-dev libsoup-3.0-dev build-essential libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev + - name: Prepare Tauri frontend resource directory + run: mkdir -p packages/web-ui/dist + - name: Run MySQL integration tests working-directory: src-tauri env: diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index aed3165c6..fca74f4ca 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -1,8 +1,8 @@ name: Packages -# Tests, builds and checks the workspace packages under packages/*. Each -# package owns its vitest (node environment); the root vitest (jsdom) only -# covers the host app. Runs only when a package, or a host file a package +# Tests, builds and checks the library packages under packages/*. Each +# package owns its vitest (node environment); the host app (packages/web-ui) +# is not in the matrix: its jsdom vitest runs through the root `pnpm test`. Runs only when a package, or a host file a package # imports, changes, and only for the packages actually affected: a `changes` # job maps changed paths to packages and builds the matrix from that. The # lockfile and this workflow count as shared and re-run every package. @@ -16,20 +16,20 @@ on: branches: [main] paths: - 'packages/**' - - 'src/pluginApi.ts' # plugin-api check:sync - - 'src/schemas/theme*' # imported by create-plugin - - 'src/types/theme*' - - 'src/utils/theme*' + - 'packages/web-ui/src/pluginApi.ts' # plugin-api check:sync + - 'packages/web-ui/src/schemas/theme*' # imported by create-plugin + - 'packages/web-ui/src/types/theme*' + - 'packages/web-ui/src/utils/theme*' - 'pnpm-lock.yaml' - '.github/workflows/packages.yml' pull_request: branches: [main] paths: - 'packages/**' - - 'src/pluginApi.ts' - - 'src/schemas/theme*' - - 'src/types/theme*' - - 'src/utils/theme*' + - 'packages/web-ui/src/pluginApi.ts' + - 'packages/web-ui/src/schemas/theme*' + - 'packages/web-ui/src/types/theme*' + - 'packages/web-ui/src/utils/theme*' - 'pnpm-lock.yaml' - '.github/workflows/packages.yml' @@ -62,14 +62,14 @@ jobs: - '.github/workflows/packages.yml' plugin-api: - 'packages/plugin-api/**' - - 'src/pluginApi.ts' + - 'packages/web-ui/src/pluginApi.ts' explain: - 'packages/explain/**' create-plugin: - 'packages/create-plugin/**' - - 'src/schemas/theme*' - - 'src/types/theme*' - - 'src/utils/theme*' + - 'packages/web-ui/src/schemas/theme*' + - 'packages/web-ui/src/types/theme*' + - 'packages/web-ui/src/utils/theme*' - name: Build the package matrix id: matrix diff --git a/.github/workflows/pg-integration.yml b/.github/workflows/pg-integration.yml index 59c49c44d..cacf6e557 100644 --- a/.github/workflows/pg-integration.yml +++ b/.github/workflows/pg-integration.yml @@ -72,6 +72,9 @@ jobs: sudo apt-get update sudo apt-get install -y libwebkit2gtk-4.1-dev libsoup-3.0-dev build-essential libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev + - name: Prepare Tauri frontend resource directory + run: mkdir -p packages/web-ui/dist + - name: Run PostgreSQL integration tests working-directory: src-tauri env: diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index e01c8db37..e5d844de9 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -8,9 +8,8 @@ on: push: branches: [main] paths: - - 'src/**' - 'packages/*/src/**' - - 'tests/utils/themeContrast.test.ts' + - 'packages/web-ui/tests/utils/themeContrast.test.ts' - 'scripts/check-theme-tokens.mjs' - 'eslint.config.js' - 'package.json' @@ -19,9 +18,8 @@ on: pull_request: branches: [main] paths: - - 'src/**' - 'packages/*/src/**' - - 'tests/utils/themeContrast.test.ts' + - 'packages/web-ui/tests/utils/themeContrast.test.ts' - 'scripts/check-theme-tokens.mjs' - 'eslint.config.js' - 'package.json' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d03716a67..04cb2a4dd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,7 +54,7 @@ jobs: # so always read it from the ref that triggered the workflow. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - # Prepend the announcement blog post (from src/data/changelog.ts) to the + # Prepend the announcement blog post (from packages/web-ui/src/data/changelog.ts) to the # release body when one exists for this version. GitHub's auto-generated # "What's Changed" section is appended after the body, so the link always # shows up above it. @@ -68,7 +68,7 @@ jobs: version="${TAG#v}" blog_url="$(node -e ' const fs = require("fs"); - const src = fs.readFileSync("src/data/changelog.ts", "utf8"); + const src = fs.readFileSync("packages/web-ui/src/data/changelog.ts", "utf8"); const version = process.argv[1]; const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const m = src.match(new RegExp(`"${escaped}":\\s*"([^"]+)"`)); diff --git a/.prettierignore b/.prettierignore index 57bc66f75..69a945b70 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,12 +5,12 @@ pnpm-lock.yaml src-tauri packages/*/dist e2e/.drv-* -src/themes/monaco -src/themes/builtin-themes.json -src/schemas -src/i18n/locales +packages/web-ui/src/themes/monaco +packages/web-ui/src/themes/builtin-themes.json +packages/web-ui/src/schemas +packages/web-ui/src/i18n/locales *.md -tests/fixtures +packages/web-ui/tests/fixtures .github .claude snap @@ -18,3 +18,15 @@ aur demo public plugins/*.schema.json + +# Helm templates contain Go expressions, not plain YAML. +charts/**/templates + +# Frozen compatibility fixtures retain their original bytes. +tests/fixtures + +# This inventory has a byte-for-byte generator contract. +web-ui-project/docs/web-ui-parity.json + +# Browser test sessions and reports are generated runtime data. +web-ui-project/.runtime diff --git a/.rules/accessibility.md b/.rules/accessibility.md index eb328f641..da7549851 100644 --- a/.rules/accessibility.md +++ b/.rules/accessibility.md @@ -3,7 +3,7 @@ ESLint runs the `jsx-a11y` recommended rules on every `.tsx` file (`no-autofocus` is off: modals focus their primary field, see [modals.md](./modals.md)). The `Design & Accessibility` workflow fails on any violation. Fix the markup rather than silencing the rule. 1. **Clickable means a button.** An element with `onClick` and no nested controls is a ` + + +
+
+ + + {listing?.path ?? t('serverFilePicker.roots')} + +
+ +
+ {loading ? ( +
+ + {t('common.loading')} +
+ ) : error ? ( +
{error}
+ ) : visibleEntries.length === 0 ? ( +
+ {t('serverFilePicker.empty')} +
+ ) : ( + visibleEntries.map((entry) => { + const isSelected = selected?.path === entry.path; + return ( + + ); + }) + )} +
+ + {request.options.mode === 'save' && ( +
+ + setFileName(event.target.value)} + autoFocus + className="w-full rounded-lg border border-strong bg-base px-3 py-2 text-primary focus:border-focus focus:outline-none" + /> +
+ )} +
+ +
+ + +
+ + + ); +} diff --git a/src/components/modals/ClipboardImport/ColumnResizeHandle.tsx b/packages/web-ui/src/components/modals/ClipboardImport/ColumnResizeHandle.tsx similarity index 100% rename from src/components/modals/ClipboardImport/ColumnResizeHandle.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/ColumnResizeHandle.tsx diff --git a/src/components/modals/ClipboardImport/DataPreview.tsx b/packages/web-ui/src/components/modals/ClipboardImport/DataPreview.tsx similarity index 100% rename from src/components/modals/ClipboardImport/DataPreview.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/DataPreview.tsx diff --git a/src/components/modals/ClipboardImport/FormatBadge.tsx b/packages/web-ui/src/components/modals/ClipboardImport/FormatBadge.tsx similarity index 100% rename from src/components/modals/ClipboardImport/FormatBadge.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/FormatBadge.tsx diff --git a/src/components/modals/ClipboardImport/ModeToggle.tsx b/packages/web-ui/src/components/modals/ClipboardImport/ModeToggle.tsx similarity index 100% rename from src/components/modals/ClipboardImport/ModeToggle.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/ModeToggle.tsx diff --git a/src/components/modals/ClipboardImport/ParseSummary.tsx b/packages/web-ui/src/components/modals/ClipboardImport/ParseSummary.tsx similarity index 100% rename from src/components/modals/ClipboardImport/ParseSummary.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/ParseSummary.tsx diff --git a/src/components/modals/ClipboardImport/SchemaEditor.tsx b/packages/web-ui/src/components/modals/ClipboardImport/SchemaEditor.tsx similarity index 100% rename from src/components/modals/ClipboardImport/SchemaEditor.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/SchemaEditor.tsx diff --git a/src/components/modals/ClipboardImport/TableNameInput.tsx b/packages/web-ui/src/components/modals/ClipboardImport/TableNameInput.tsx similarity index 100% rename from src/components/modals/ClipboardImport/TableNameInput.tsx rename to packages/web-ui/src/components/modals/ClipboardImport/TableNameInput.tsx diff --git a/src/components/modals/ClipboardImportModal.tsx b/packages/web-ui/src/components/modals/ClipboardImportModal.tsx similarity index 96% rename from src/components/modals/ClipboardImportModal.tsx rename to packages/web-ui/src/components/modals/ClipboardImportModal.tsx index 56b696f3c..a5deaf048 100644 --- a/src/components/modals/ClipboardImportModal.tsx +++ b/packages/web-ui/src/components/modals/ClipboardImportModal.tsx @@ -13,15 +13,13 @@ import { Rows, Table2, } from 'lucide-react'; -import {invoke} from '@tauri-apps/api/core'; -import {open} from '@tauri-apps/plugin-dialog'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import { readDataImportFile, DataImportFileError, DATA_IMPORT_EXTENSIONS, } from '@/utils/dataImportFile'; import {toErrorMessage} from '@/utils/errors'; -import {readText} from '@tauri-apps/plugin-clipboard-manager'; import {Modal} from '@/components/ui/Modal'; import {Select} from '@/components/ui/Select'; import {useDatabase} from '@/hooks/useDatabase'; @@ -32,7 +30,7 @@ import {TableNameInput} from './ClipboardImport/TableNameInput'; import {ParseSummary} from './ClipboardImport/ParseSummary'; import {ModeToggle} from './ClipboardImport/ModeToggle'; import {useDataTypes} from '@/hooks/useDataTypes'; -import type {TableColumn} from '@/utils/sqlGenerator'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {resolveCreateTableSchema} from '@/utils/createTable'; import { parseClipboardText, @@ -74,6 +72,8 @@ export function ClipboardImportModal({ onSuccess, schema, }: ClipboardImportModalProps) { + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const {t} = useTranslation(); const titleId = useId(); const descriptionId = useId(); @@ -92,7 +92,7 @@ export function ClipboardImportModal({ const [ifExists, setIfExists] = useState('fail'); const [existingTables, setExistingTables] = useState([]); const [maximizedPane, setMaximizedPane] = useState<'schema' | 'preview' | null>(null); - const [targetColumns, setTargetColumns] = useState([]); + const [targetColumns, setTargetColumns] = useState>([]); const sourceRequest = useRef(0); const invalidateSource = useCallback(() => { @@ -121,9 +121,9 @@ export function ClipboardImportModal({ })); if (!activeDriver || inferred.length === 0) return base; try { - const mapped = await invoke('map_inferred_column_types', { + const mapped = await client.call('map_inferred_column_types', { driver: activeDriver, - connectionId: activeConnectionId, + connectionId: activeConnectionId ?? undefined, kinds: inferred.map((c) => c.sqlType), }); return base.map((c, i) => ({...c, sqlType: mapped[i] ?? c.sqlType})); @@ -131,7 +131,7 @@ export function ClipboardImportModal({ return base; } }, - [activeDriver, activeConnectionId], + [client, activeDriver, activeConnectionId], ); const tableExists = existingTables.some( @@ -166,30 +166,28 @@ export function ClipboardImportModal({ setIsLoadingFile(false); setError(null); try { - await applyText((await readText()) ?? '', id, null); + await applyText((await platform.readClipboard()) ?? '', id, null); } catch { if (id === sourceRequest.current) setError(t('clipboardImport.noData')); } finally { if (id === sourceRequest.current) setIsLoadingClipboard(false); } - }, [t, applyText]); + }, [platform, t, applyText]); const readFile = useCallback(async () => { const id = ++sourceRequest.current; setIsLoadingFile(true); setIsLoadingClipboard(false); try { - const path = await open({ - multiple: false, - directory: false, + const file = await platform.chooseInputFile({ filters: [ {name: t('clipboardImport.fileSource'), extensions: DATA_IMPORT_EXTENSIONS}, ], }); - if (id !== sourceRequest.current || typeof path !== 'string') return; + if (id !== sourceRequest.current || !file) return; setLastSource('file'); - const text = await readDataImportFile(path); - await applyText(text, id, path.split(/[\\/]/).pop() ?? path); + const text = await readDataImportFile(file, platform); + await applyText(text, id, file.name); } catch (err) { if (id !== sourceRequest.current) return; setError( @@ -208,7 +206,7 @@ export function ClipboardImportModal({ } finally { if (id === sourceRequest.current) setIsLoadingFile(false); } - }, [t, applyText]); + }, [platform, t, applyText]); const close = useCallback(() => { invalidateSource(); @@ -219,7 +217,7 @@ export function ClipboardImportModal({ const loadTables = useCallback(async () => { if (!activeConnectionId) return; try { - const tables = await invoke<{name: string}[]>('get_tables', { + const tables = await client.call('get_tables', { connectionId: activeConnectionId, ...(targetSchema ? {schema: targetSchema} : {}), }); @@ -227,7 +225,7 @@ export function ClipboardImportModal({ } catch { // Non-critical } - }, [activeConnectionId, targetSchema]); + }, [client, activeConnectionId, targetSchema]); useEffect(() => { if (isOpen) { @@ -254,10 +252,10 @@ export function ClipboardImportModal({ let cancelled = false; (async () => { try { - const cols = await invoke('get_columns', { + const cols = await client.call('get_columns', { connectionId: activeConnectionId, tableName: tableName.trim(), - schema: targetSchema ?? null, + schema: targetSchema ?? undefined, }); if (!cancelled) setTargetColumns(cols); } catch { @@ -267,7 +265,7 @@ export function ClipboardImportModal({ return () => { cancelled = true; }; - }, [importMode, tableExists, tableName, activeConnectionId, targetSchema]); + }, [client, importMode, tableExists, tableName, activeConnectionId, targetSchema]); // Auto-map parsed columns to target columns by name (case-insensitive) when // entering append mode or when the target column list changes. @@ -320,7 +318,7 @@ export function ClipboardImportModal({ if (!settings.aiProvider || !parsed) return; setIsAiLoading(true); try { - const name = await invoke('suggest_table_name', { + const name = await client.call('suggest_table_name', { req: { provider: settings.aiProvider, model: settings.aiModel || '', @@ -336,7 +334,7 @@ export function ClipboardImportModal({ } finally { setIsAiLoading(false); } - }, [settings, parsed]); + }, [client, settings, parsed]); const handleImport = useCallback(async () => { if (!activeConnectionId || !parsed || !tableName.trim() || columns.length === 0) return; @@ -390,7 +388,7 @@ export function ClipboardImportModal({ }), ); - const result = await invoke('execute_clipboard_import', { + const result = await client.call('execute_clipboard_import', { req: { connection_id: activeConnectionId, table_name: tableName.trim(), @@ -411,6 +409,7 @@ export function ClipboardImportModal({ setIsImporting(false); } }, [ + client, activeConnectionId, parsed, tableName, diff --git a/src/components/modals/CommandPaletteModal.tsx b/packages/web-ui/src/components/modals/CommandPaletteModal.tsx similarity index 100% rename from src/components/modals/CommandPaletteModal.tsx rename to packages/web-ui/src/components/modals/CommandPaletteModal.tsx diff --git a/src/components/modals/CommunityModal.tsx b/packages/web-ui/src/components/modals/CommunityModal.tsx similarity index 94% rename from src/components/modals/CommunityModal.tsx rename to packages/web-ui/src/components/modals/CommunityModal.tsx index 2bc2b8cde..1daa6904b 100644 --- a/src/components/modals/CommunityModal.tsx +++ b/packages/web-ui/src/components/modals/CommunityModal.tsx @@ -1,6 +1,6 @@ import {useTranslation} from 'react-i18next'; import {X, Github, Star} from 'lucide-react'; -import {openUrl} from '@tauri-apps/plugin-opener'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import {GITHUB_URL, DISCORD_URL} from '@/config/links'; import {DiscordIcon} from '@/components/icons/DiscordIcon'; import {SocialLinks} from '@/components/SocialLinks'; @@ -12,6 +12,7 @@ interface CommunityModalProps { } export const CommunityModal = ({isOpen, onClose}: CommunityModalProps) => { + const platform = usePlatformCapabilities(); const {t} = useTranslation(); return ( @@ -46,7 +47,7 @@ export const CommunityModal = ({isOpen, onClose}: CommunityModalProps) => { {/* GitHub Star */} )} diff --git a/src/components/modals/GenerateSQLModal.tsx b/packages/web-ui/src/components/modals/GenerateSQLModal.tsx similarity index 93% rename from src/components/modals/GenerateSQLModal.tsx rename to packages/web-ui/src/components/modals/GenerateSQLModal.tsx index 498a201f3..31545cb3e 100644 --- a/src/components/modals/GenerateSQLModal.tsx +++ b/packages/web-ui/src/components/modals/GenerateSQLModal.tsx @@ -2,7 +2,6 @@ import {useState, useEffect} from 'react'; import {useTranslation} from 'react-i18next'; import clsx from 'clsx'; import {X, Loader2, Copy, Check, FileCode, List, Table2, PenLine, Trash2, Play} from 'lucide-react'; -import {invoke} from '@tauri-apps/api/core'; import {useNavigate} from 'react-router-dom'; import {useDatabase} from '@/hooks/useDatabase'; import {useCopyFeedback} from '@/hooks/useCopyFeedback'; @@ -13,14 +12,12 @@ import { generateCreateTableSQL, generateTableQuerySQL, type TableColumn, - type ForeignKey, - type Index, } from '@/utils/sqlGenerator'; import {loadTableQueryTemplates, type TableQueryTemplates} from '@/utils/tableQueryTemplates'; import type {TableTarget} from '@/types/databaseObjects'; -import type {TableInfo} from '@/contexts/DatabaseContext'; import type {CommandRuntime} from '@/types/commands'; import {openEditor as navigateToEditor} from '@/utils/editorNavigation'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; interface GenerateSQLModalProps { isOpen: boolean; @@ -34,6 +31,7 @@ interface GenerateSQLModalProps { } export const GenerateSQLModal = ({isOpen, onClose, target, openEditor}: GenerateSQLModalProps) => { + const client = useTabularisClient(); const {t} = useTranslation(); const navigate = useNavigate(); const {connectionDataMap} = useDatabase(); @@ -71,35 +69,40 @@ export const GenerateSQLModal = ({isOpen, onClose, target, openEditor}: Generate try { const schemaParam = schema ? {schema} : {}; const databaseParam = database ? {database} : {}; - const [fetchedColumns, foreignKeys, indexes, tables] = await Promise.all([ - invoke('get_columns', { + const [columnMetadata, foreignKeys, indexes, tables] = await Promise.all([ + client.call('get_columns', { connectionId, tableName, ...schemaParam, ...databaseParam, }), - invoke('get_foreign_keys', { + client.call('get_foreign_keys', { connectionId, tableName, ...schemaParam, ...databaseParam, }), - invoke('get_indexes', { + client.call('get_indexes', { connectionId, tableName, ...schemaParam, ...databaseParam, }), - invoke('get_tables', { + client.call('get_tables', { connectionId, ...schemaParam, ...databaseParam, }), ]); + const fetchedColumns: TableColumn[] = columnMetadata.map((column) => ({ + ...column, + default_value: column.default_value ?? null, + })); const generatedTemplates = typeof dialect === 'object' && dialect.table_query_templates ? await loadTableQueryTemplates( + client, connectionId, tableName, schema, @@ -136,7 +139,18 @@ export const GenerateSQLModal = ({isOpen, onClose, target, openEditor}: Generate return () => { cancelled = true; }; - }, [isOpen, connectionId, tableName, dialect, t, schema, database, showAlert, requestKey]); + }, [ + client, + isOpen, + connectionId, + tableName, + dialect, + t, + schema, + database, + showAlert, + requestKey, + ]); const getTabSql = (currentTab: SqlTab): string => { if (currentTab !== 'create' && templates[currentTab] != null) { diff --git a/src/components/modals/ImportDatabaseModal.tsx b/packages/web-ui/src/components/modals/ImportDatabaseModal.tsx similarity index 75% rename from src/components/modals/ImportDatabaseModal.tsx rename to packages/web-ui/src/components/modals/ImportDatabaseModal.tsx index 18d7c5f8f..05d042b8c 100644 --- a/src/components/modals/ImportDatabaseModal.tsx +++ b/packages/web-ui/src/components/modals/ImportDatabaseModal.tsx @@ -1,19 +1,18 @@ import {useState, useEffect, useCallback, useRef} from 'react'; import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import {useAlert} from '@/hooks/useAlert'; import {Loader2, Database, X, CheckCircle2, XCircle} from 'lucide-react'; import {formatElapsedTime} from '@/utils/formatTime'; import {useDatabase} from '@/hooks/useDatabase'; import {Modal} from '@/components/ui/Modal'; - -interface ImportProgress { - statements_executed: number; - total_statements: number; - percentage: number; - current_operation: string; -} +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import { + DATABASE_TRANSFER_DEADLINE_MS, + prepareDatabaseImportSource, +} from '@/utils/databaseTransfers'; +import type {ChosenInputFile} from '@/platform/capabilities'; +import type {EventPayload} from '@/api/events'; interface ImportDatabaseModalProps { isOpen: boolean; @@ -23,7 +22,7 @@ interface ImportDatabaseModalProps { databaseName: string; /** Actual database to scope the import to. Undefined when unknown. */ targetDatabase?: string; - filePath: string; + inputFile: ChosenInputFile; onSuccess?: () => void; /** Explicit schema for a schema-based multi-db connection (Postgres nested * tree), overriding the connection's global active schema. */ @@ -36,16 +35,18 @@ export const ImportDatabaseModal = ({ connectionId, databaseName, targetDatabase, - filePath, + inputFile, onSuccess, schema: schemaProp, }: ImportDatabaseModalProps) => { const {t} = useTranslation(); + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const {activeSchema: connectionActiveSchema} = useDatabase(); const activeSchema = schemaProp ?? connectionActiveSchema; const {showAlert} = useAlert(); const [isImporting, setIsImporting] = useState(false); - const [progress, setProgress] = useState(null); + const [progress, setProgress] = useState | null>(null); const [error, setError] = useState(null); const [success, setSuccess] = useState(false); const [elapsedTime, setElapsedTime] = useState(0); // in seconds @@ -54,8 +55,25 @@ export const ImportDatabaseModal = ({ // mounts, and startImport being recreated when its deps change, both re-run the // effect. Without this the whole dump is executed twice against the database. const hasStartedRef = useRef(false); + const operationRef = useRef<{ + dispatched: boolean; + cancelled: boolean; + cancelling: boolean; + } | null>(null); + const mountedRef = useRef(false); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); const startImport = useCallback(async () => { + const operation = {dispatched: false, cancelled: false, cancelling: false}; + operationRef.current = operation; + const isCurrent = () => + mountedRef.current && operationRef.current === operation && !operation.cancelled; setIsImporting(true); setError(null); setSuccess(false); @@ -63,13 +81,26 @@ export const ImportDatabaseModal = ({ setElapsedTime(0); try { - await invoke('import_database', { - connectionId, - filePath, - ...(activeSchema ? {schema: activeSchema} : {}), - ...(targetDatabase ? {database: targetDatabase} : {}), - }); + const source = await prepareDatabaseImportSource(client, platform, inputFile); + // Uploads can finish after cancellation, closing, or a newer opening. + if (!isCurrent()) return; + operation.dispatched = true; + await client.call( + 'import_database', + { + connectionId, + ...source, + ...(activeSchema ? {schema: activeSchema} : {}), + ...(targetDatabase ? {database: targetDatabase} : {}), + }, + { + deadlineMs: DATABASE_TRANSFER_DEADLINE_MS, + cancellationId: crypto.randomUUID(), + }, + ); + if (!isCurrent()) return; + operationRef.current = null; setSuccess(true); setIsImporting(false); @@ -77,11 +108,13 @@ export const ImportDatabaseModal = ({ onSuccess(); } } catch (e) { + if (!isCurrent()) return; + operationRef.current = null; // The error is rendered inside this modal — no extra alert dialog. setError(String(e)); setIsImporting(false); } - }, [connectionId, filePath, activeSchema, targetDatabase, onSuccess]); + }, [activeSchema, client, connectionId, inputFile, onSuccess, platform, targetDatabase]); useEffect(() => { if (!isOpen) { @@ -94,6 +127,7 @@ export const ImportDatabaseModal = ({ setElapsedTime(0); setStartTime(null); hasStartedRef.current = false; + operationRef.current = null; return; } @@ -112,14 +146,19 @@ export const ImportDatabaseModal = ({ useEffect(() => { if (!isOpen) return; - const unlisten = listen('import_progress', (event) => { - setProgress(event.payload); + const subscription = client.subscribe('import_progress', (update) => { + if ( + operationRef.current?.dispatched && + !operationRef.current.cancelled && + update.connection_id === connectionId + ) { + setProgress(update); + } }); - return () => { - unlisten.then((fn) => fn()); + void subscription.then((unsubscribe) => unsubscribe()); }; - }, [isOpen]); + }, [client, connectionId, isOpen]); // Timer for elapsed time useEffect(() => { @@ -134,24 +173,38 @@ export const ImportDatabaseModal = ({ }, [isImporting, startTime]); const handleCancel = async () => { - if (!isImporting) { + const operation = operationRef.current; + if (!operation) { onClose(); return; } + if (operation.cancelling) return; + operation.cancelling = true; try { - await invoke('cancel_import', {connectionId}); + if (operation.dispatched) { + // Keep receiving progress and completion until cancellation succeeds. + await client.call('cancel_import', {connectionId}); + } + // Uploads have no backend job: invalidate them locally before they can + // dispatch SQL. For running imports, only an acknowledgement cancels them. + if (!mountedRef.current || operationRef.current !== operation) return; + operation.cancelled = true; + operationRef.current = null; + setIsImporting(false); showAlert(t('dump.importCancelled'), {kind: 'info'}); onClose(); } catch (e) { - console.error('Failed to cancel import:', e); + if (!mountedRef.current || operationRef.current !== operation) return; + operation.cancelling = false; + showAlert(String(e), {kind: 'error'}); } }; return (
@@ -263,7 +316,7 @@ export const ImportDatabaseModal = ({ {/* File Info */}
- {t('dump.importingFrom')}: {filePath.split(/[/\\]/).pop()} + {t('dump.importingFrom')}: {inputFile.name}
diff --git a/src/components/modals/ImportFromAppModal.tsx b/packages/web-ui/src/components/modals/ImportFromAppModal.tsx similarity index 93% rename from src/components/modals/ImportFromAppModal.tsx rename to packages/web-ui/src/components/modals/ImportFromAppModal.tsx index 2d80e99d5..73ce9cf75 100644 --- a/src/components/modals/ImportFromAppModal.tsx +++ b/packages/web-ui/src/components/modals/ImportFromAppModal.tsx @@ -14,10 +14,6 @@ import { FlaskConical, ListChecks, } from 'lucide-react'; -import {invoke} from '@tauri-apps/api/core'; -import {open} from '@tauri-apps/plugin-dialog'; -import {readTextFile} from '@tauri-apps/plugin-fs'; -import {openUrl} from '@tauri-apps/plugin-opener'; import clsx from 'clsx'; import {toErrorMessage} from '@/utils/errors'; import {useDatabase} from '@/hooks/useDatabase'; @@ -27,6 +23,7 @@ import {Select} from '@/components/ui/Select'; import {PasswordInput} from '@/components/ui/PasswordInput'; import {BetaBadge} from '@/components/ui/BetaBadge'; import {GITHUB_ISSUES_URL} from '@/config/links'; +import type {ConnectionImportFile} from '@/api/contract'; import type { ImportSourceInfo, ImportPreview, @@ -34,6 +31,9 @@ import type { ImportResolution, ImportAction, } from '@/types/connectionImport'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {prepareConnectionImportFile} from '@/utils/connectionFiles'; interface ImportFromAppModalProps { isOpen: boolean; @@ -58,6 +58,8 @@ const ACTION_KEEP = '__keep__'; export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppModalProps) => { const {t} = useTranslation(); + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const {connectionGroups} = useDatabase(); const [step, setStep] = useState('picker'); @@ -73,12 +75,9 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM const [newGroupParent, setNewGroupParent] = useState>({}); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); - // Encrypted Tabularis export: the parsed envelope awaiting a password. - const [pendingEnvelope, setPendingEnvelope] = useState(null); + // Encrypted Tabularis export: the opaque backend file reference awaiting a password. + const [pendingFile, setPendingFile] = useState(null); const [password, setPassword] = useState(''); - // Parsed (and decrypted) Tabularis payload backing the preview, so `apply` - // can re-send it without re-reading the file. - const [tabularisPayload, setTabularisPayload] = useState(null); // Bulk actions shown above the preview list. const [bulkAction, setBulkAction] = useState(ACTION_KEEP); const [bulkGroup, setBulkGroup] = useState(GROUP_KEEP); @@ -95,9 +94,8 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM setNewGroupName({}); setError(null); setLoading(false); - setPendingEnvelope(null); + setPendingFile(null); setPassword(''); - setTabularisPayload(null); setBulkAction(ACTION_KEEP); setBulkGroup(GROUP_KEEP); setBulkNewName(''); @@ -118,7 +116,8 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM needsFile: true, manualPathSupported: false, }; - invoke('list_connection_import_sources') + client + .call('list_connection_import_sources', undefined) .then((list) => { const all = [tabularisSource, ...list]; setSources(all); @@ -129,7 +128,7 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM }) .catch((e) => setError(toErrorMessage(e))) .finally(() => setLoading(false)); - }, [isOpen, reset]); + }, [client, isOpen, reset]); const selectedSource = sources.find((s) => s.id === selectedId) ?? null; const canContinueFromPicker = @@ -172,16 +171,6 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM setStep('preview'); }; - // Preview a parsed Tabularis payload (plain or already decrypted) so it goes - // through the same per-item group picker as a foreign-app import. - const previewTabularis = async (payload: unknown) => { - const result = await invoke('preview_tabularis_import', { - payload, - }); - setTabularisPayload(payload); - showPreview(result); - }; - const handleContinue = async () => { if ( !selectedSource || @@ -196,47 +185,40 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM try { // Tabularis export file: parse (decrypt if needed), then preview. if (selectedSource.id === TABULARIS_SOURCE_ID) { - const picked = await open({ + const picked = await platform.chooseInputFile({ filters: [{name: 'JSON', extensions: ['json']}], - multiple: false, }); - if (!picked || Array.isArray(picked)) { - setLoading(false); - return; - } - const content = await readTextFile(picked); - const payload = JSON.parse(content) as {encrypted?: boolean}; - // Encrypted exports are an opaque envelope: prompt for the password - // and decrypt before previewing. - if (payload && payload.encrypted === true) { - setPendingEnvelope(payload); + if (!picked) return; + const file = await prepareConnectionImportFile(client, platform, picked); + const result = await client.call('preview_tabularis_import_file', { + file, + }); + if (result.kind === 'passwordRequired') { + setPendingFile(file); setPassword(''); setError(null); setStep('password'); - setLoading(false); return; } - await previewTabularis(payload); + showPreview(result.preview); return; } - let filePath: string | null = null; + let file: ConnectionImportFile | null = null; const needsManualPath = selectedSource.manualPathSupported && !selectedSource.available; - if (selectedSource.needsFile || needsManualPath) { - const picked = await open({ - multiple: false, - directory: needsManualPath, - }); - if (!picked || Array.isArray(picked)) { - setLoading(false); - return; - } - filePath = picked; + if (needsManualPath) { + const picked = await platform.chooseServerPath({kind: 'directory'}); + if (!picked) return; + file = {kind: 'serverPath', path: picked.reference}; + } else if (selectedSource.needsFile) { + const picked = await platform.chooseInputFile(); + if (!picked) return; + file = await prepareConnectionImportFile(client, platform, picked); } - const result = await invoke('preview_connection_import', { + const result = await client.call('preview_connection_import', { sourceId: selectedSource.id, includePasswords, - filePath, + file, }); showPreview(result); } catch (e) { @@ -247,15 +229,18 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM }; const handleDecryptImport = async () => { - if (!pendingEnvelope || !password) return; + if (!pendingFile || !password) return; setError(null); setLoading(true); try { - const payload = await invoke('decrypt_export_payload', { - envelope: pendingEnvelope, + const result = await client.call('preview_tabularis_import_file', { + file: pendingFile, password, }); - await previewTabularis(payload); + if (result.kind === 'passwordRequired') { + throw new Error('This connection export requires a password'); + } + showPreview(result.preview); } catch (e) { setError(toErrorMessage(e)); } finally { @@ -299,12 +284,11 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM return {index: item.index, action}; }); if (selectedSource.id === TABULARIS_SOURCE_ID) { - await invoke('apply_tabularis_import', { - payload: tabularisPayload, + await client.call('apply_prepared_tabularis_import', { resolutions: payload, }); } else { - await invoke('apply_connection_import', { + await client.call('apply_connection_import', { sourceId: selectedSource.id, resolutions: payload, }); @@ -428,7 +412,7 @@ export const ImportFromAppModal = ({isOpen, onClose, onImported}: ImportFromAppM {t('connections.importFromApp.betaNotice')}{' '} + {platform.negotiation.environment === 'browser' ? ( + setServerDirectory(event.target.value)} + onBlur={() => + void updateSetting('backupDirectory', serverDirectory.trim()) + } + placeholder="/srv/tabularis/backups" + aria-label={t('settings.backup.directory')} + className={textInputClass} + /> + ) : ( + + )} )} @@ -776,16 +802,35 @@ export function BackupTab() { - + {platform.negotiation.environment === 'browser' ? ( + setDbDirectoryDraft(event.target.value)} + onBlur={(event) => { + const destinationDirectory = event.target.value.trim(); + setDbDirectoryDraft(null); + if (destinationDirectory !== plan.destinationDirectory) + void updatePlan({destinationDirectory}); + }} + aria-label={t('settings.backup.dbBackupDirectory')} + className={textInputClass} + /> + ) : ( + + )} {/* Daily Run Time (24h clock) */} diff --git a/src/components/settings/ChatGptSettings.tsx b/packages/web-ui/src/components/settings/ChatGptSettings.tsx similarity index 89% rename from src/components/settings/ChatGptSettings.tsx rename to packages/web-ui/src/components/settings/ChatGptSettings.tsx index b81261324..123522641 100644 --- a/src/components/settings/ChatGptSettings.tsx +++ b/packages/web-ui/src/components/settings/ChatGptSettings.tsx @@ -1,5 +1,5 @@ import {useCallback, useEffect, useId, useRef, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {useTranslation} from 'react-i18next'; import { AlertCircle, @@ -21,6 +21,7 @@ const secondaryButton = 'inline-flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-secondary bg-surface-secondary border border-default rounded-lg hover:bg-surface-hover hover:text-primary transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus'; export function ChatGptSettings() { + const client = useTabularisClient(); const {t} = useTranslation(); const {settings, updateSetting} = useSettings(); const fieldId = useId(); @@ -31,25 +32,29 @@ export function ChatGptSettings() { const signingIn = useRef(false); const active = session?.profiles.find((p) => p.id === session.activeProfileId); - const loadModels = useCallback(async (next: ChatGptSession) => { - const profile = next.profiles.find((p) => p.id === next.activeProfileId); - if (!profile?.sharing) { - setModels([]); - return; - } - const available = await invoke('get_chatgpt_models'); - setModels(available); - }, []); + const loadModels = useCallback( + async (next: ChatGptSession) => { + const profile = next.profiles.find((p) => p.id === next.activeProfileId); + if (!profile?.sharing) { + setModels([]); + return; + } + const available = await client.call('get_chatgpt_models', undefined); + setModels(available); + }, + [client], + ); useEffect(() => { let alive = true; - invoke('get_chatgpt_session') + client + .call('get_chatgpt_session', undefined) .then(async (next) => { if (!alive) return; setSession(next); const profile = next.profiles.find((p) => p.id === next.activeProfileId); if (profile?.sharing) { - const available = await invoke('get_chatgpt_models'); + const available = await client.call('get_chatgpt_models', undefined); if (alive) setModels(available); } }) @@ -61,16 +66,17 @@ export function ChatGptSettings() { }); return () => { alive = false; - if (signingIn.current) void invoke('cancel_chatgpt_sign_in').catch(console.error); + if (signingIn.current) + void client.call('cancel_chatgpt_sign_in', undefined).catch(console.error); }; - }, []); + }, [client]); const signIn = async (profileId: string | null) => { setError(null); setBusy('signIn'); signingIn.current = true; try { - const next = await invoke('sign_in_chatgpt', { + const next = await client.call('sign_in_chatgpt', { profileId, }); setSession(next); @@ -80,7 +86,7 @@ export function ChatGptSettings() { } catch (e) { setError(String(e)); // Failed code exchanges can still have a saved client registration. - const next = await invoke('get_chatgpt_session').catch(() => null); + const next = await client.call('get_chatgpt_session', undefined).catch(() => null); if (next) setSession(next); } finally { signingIn.current = false; @@ -94,7 +100,7 @@ export function ChatGptSettings() { setModels([]); try { await updateSetting('aiModel', ''); - const next = await invoke('select_chatgpt_profile', { + const next = await client.call('select_chatgpt_profile', { profileId, }); setSession(next); @@ -111,12 +117,12 @@ export function ChatGptSettings() { setBusy('account'); setError(null); try { - const warning = await invoke('sign_out_chatgpt', { + const warning = await client.call('sign_out_chatgpt', { profileId: active.id, }); setModels([]); await updateSetting('aiModel', ''); - setSession(await invoke('get_chatgpt_session')); + setSession(await client.call('get_chatgpt_session', undefined)); if (warning) setError(warning); } catch (e) { setError(String(e)); @@ -206,7 +212,9 @@ export function ChatGptSettings() { type="button" className={secondaryButton} onClick={() => - void invoke('open_chatgpt_usage').catch((e: unknown) => setError(String(e))) + void client + .call('open_chatgpt_usage', undefined) + .catch((e: unknown) => setError(String(e))) } >
+ {items.map(({id, fallback}) => ( +
+
+ {fallback.kind === 'external-url' ? ( + + ) : ( + + )} +
+
+ {fallback.kind === 'notification' ? ( + <> +
{fallback.title}
+ {fallback.body && ( +
+ {fallback.body} +
+ )} + + ) : ( +
+ {fallback.url} + + )} +
+ +
+ ))} +
+ ); +} diff --git a/src/components/ui/CellCodeEditor.tsx b/packages/web-ui/src/components/ui/CellCodeEditor.tsx similarity index 100% rename from src/components/ui/CellCodeEditor.tsx rename to packages/web-ui/src/components/ui/CellCodeEditor.tsx diff --git a/src/components/ui/CellDiffEditor.tsx b/packages/web-ui/src/components/ui/CellDiffEditor.tsx similarity index 100% rename from src/components/ui/CellDiffEditor.tsx rename to packages/web-ui/src/components/ui/CellDiffEditor.tsx diff --git a/src/components/ui/Chip.tsx b/packages/web-ui/src/components/ui/Chip.tsx similarity index 100% rename from src/components/ui/Chip.tsx rename to packages/web-ui/src/components/ui/Chip.tsx diff --git a/src/components/ui/ColumnStatsPopover.tsx b/packages/web-ui/src/components/ui/ColumnStatsPopover.tsx similarity index 100% rename from src/components/ui/ColumnStatsPopover.tsx rename to packages/web-ui/src/components/ui/ColumnStatsPopover.tsx diff --git a/src/components/ui/CompactCard.tsx b/packages/web-ui/src/components/ui/CompactCard.tsx similarity index 100% rename from src/components/ui/CompactCard.tsx rename to packages/web-ui/src/components/ui/CompactCard.tsx diff --git a/src/components/ui/ContextMenu.tsx b/packages/web-ui/src/components/ui/ContextMenu.tsx similarity index 100% rename from src/components/ui/ContextMenu.tsx rename to packages/web-ui/src/components/ui/ContextMenu.tsx diff --git a/src/components/ui/CountBadge.tsx b/packages/web-ui/src/components/ui/CountBadge.tsx similarity index 100% rename from src/components/ui/CountBadge.tsx rename to packages/web-ui/src/components/ui/CountBadge.tsx diff --git a/src/components/ui/DataGrid.tsx b/packages/web-ui/src/components/ui/DataGrid.tsx similarity index 98% rename from src/components/ui/DataGrid.tsx rename to packages/web-ui/src/components/ui/DataGrid.tsx index 08e4318a3..1ffc14ab3 100644 --- a/src/components/ui/DataGrid.tsx +++ b/packages/web-ui/src/components/ui/DataGrid.tsx @@ -16,7 +16,6 @@ import { createColumnHelper, } from '@tanstack/react-table'; import {useVirtualizer} from '@tanstack/react-virtual'; -import {openUrl} from '@tauri-apps/plugin-opener'; import {ContextMenu, type ContextMenuItem} from './ContextMenu'; import {SlotAnchor} from './SlotAnchor'; import {ColumnStatsPopover} from './ColumnStatsPopover'; @@ -53,8 +52,8 @@ import { Table, ChartColumn, } from 'lucide-react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {getJsonViewerSessionHost} from '@/platform/secondaryWindowSessions'; import {useAlert} from '@/hooks/useAlert'; import {useToast} from '@/hooks/useToast'; import { @@ -87,9 +86,9 @@ import { type RangeExtendKey, } from '@/utils/dataGrid'; import {isTypingTarget} from '@/utils/keyboardEvents'; -import {readText, writeHtml} from '@tauri-apps/plugin-clipboard-manager'; import {getSortButtonAction} from '@/utils/tableToolbar'; import {useSettings} from '@/hooks/useSettings'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {useJsonEditorActivity} from '@/hooks/useJsonEditorActivity'; import {isGeometricType, formatGeometricValue} from '@/utils/geometry'; import {isBlobColumn, isBlobWireFormat} from '@/utils/blob'; @@ -334,6 +333,8 @@ export const DataGrid = React.memo(function DataGrid({ scrollToNewInsertion, }: DataGridProps) { const {t} = useTranslation(); + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const keybindings = useContext(KeybindingsContext); const { activeSchema: globalActiveSchema, @@ -359,8 +360,6 @@ export const DataGrid = React.memo(function DataGrid({ const { count: jsonEditorCount, begin: beginJsonEdit, - watch: watchJsonEditor, - release: releaseJsonEditor, isEditing: isJsonEditing, } = useJsonEditorActivity(); const colorByType = settings.resultColorByType ?? false; @@ -481,10 +480,6 @@ export const DataGrid = React.memo(function DataGrid({ useEffect(() => { editingCellRef.current = editingCell; }, [editingCell]); - const pendingJsonSessions = useRef< - Map - >(new Map()); - const isGridEditing = !!editingCell || !!expandedCell || @@ -650,53 +645,47 @@ export const DataGrid = React.memo(function DataGrid({ cellKey = `pk:${serialized}:${colName}`; } } - const sessionId = await invoke('open_json_viewer_window', { - value, - originalValue, - colName, - rowLabel, - readOnly: readOnly || !canSaveBack, - cellKey, - }); - pendingJsonSessions.current.set(sessionId, { - colName, - rowData, - isInsertion, - tempId, - }); - if (end) void watchJsonEditor(sessionId, end); + await getJsonViewerSessionHost(platform).open( + { + value, + originalValue, + columnName: colName, + rowLabel, + readOnly: readOnly || !canSaveBack, + cellKey, + }, + readOnly || !canSaveBack + ? undefined + : (savedValue) => { + if (isInsertion && onPendingInsertionChange && tempId) { + onPendingInsertionChange(tempId, colName, savedValue); + } else if ( + !isInsertion && + onPendingChange && + pkIndexMaps.length > 0 + ) { + const pkMapVal = buildPkMap(pkColumns!, rowData, pkIndexMaps); + onPendingChange(pkMapVal, colName, savedValue); + } + }, + end, + ); } catch (e) { end?.(); console.error('Failed to open JSON viewer window:', e); } }, - [buildRowLabel, pkIndexMaps, pkColumns, beginJsonEdit, watchJsonEditor], + [ + buildRowLabel, + onPendingChange, + onPendingInsertionChange, + pkIndexMaps, + pkColumns, + platform, + beginJsonEdit, + ], ); - useEffect(() => { - const unlistenPromise = listen<{session_id: string; value: unknown}>( - 'json-viewer:saved', - (event) => { - const {session_id, value} = event.payload; - const session = pendingJsonSessions.current.get(session_id); - if (!session) return; - pendingJsonSessions.current.delete(session_id); - - const {colName, rowData, isInsertion, tempId} = session; - if (isInsertion && onPendingInsertionChange && tempId) { - onPendingInsertionChange(tempId, colName, value); - } else if (!isInsertion && onPendingChange && pkIndexMaps.length > 0) { - const pkMapVal = buildPkMap(pkColumns!, rowData, pkIndexMaps); - onPendingChange(pkMapVal, colName, value); - } - releaseJsonEditor(session_id); - }, - ); - return () => { - unlistenPromise.then((fn) => fn()); - }; - }, [onPendingChange, onPendingInsertionChange, pkIndexMaps, pkColumns, releaseJsonEditor]); - const fksByColumn = useMemo(() => pickPrimaryForeignKeyByColumn(foreignKeys), [foreignKeys]); // Merge existing rows with pending insertions @@ -1263,7 +1252,7 @@ export const DataGrid = React.memo(function DataGrid({ // Legacy immediate update try { - await invoke('update_record', { + await client.call('update_record', { connectionId, table: tableName, pkMap: pkMapVal, @@ -1299,6 +1288,7 @@ export const DataGrid = React.memo(function DataGrid({ showAlert, t, guardProductionWrite, + client, ]); const handleKeyDown = useCallback( @@ -1879,7 +1869,8 @@ export const DataGrid = React.memo(function DataGrid({ if (!dateMode) return; setContextMenu(null); - invoke('get_server_now', {connectionId}) + client + .call('get_server_now', {connectionId}) .then((raw) => { const formatted = formatDateTime(parseDateTime(raw), dateMode); if (isInsertion && onPendingInsertionChange && mergedRow?.tempId) { @@ -1902,6 +1893,7 @@ export const DataGrid = React.memo(function DataGrid({ pkColumns, t, showAlert, + client, ]); // Runs a clipboard write, then shows the success toast or the error alert. @@ -1966,10 +1958,14 @@ export const DataGrid = React.memo(function DataGrid({ if (!rows) return; await writeToClipboard( - () => writeHtml(rowsToHtmlTable(rows, columns, 'null'), formatRows(rows, true)), + () => + platform.writeClipboardHtml( + rowsToHtmlTable(rows, columns, 'null'), + formatRows(rows, true), + ), rowsCopiedToast(rows.length), ); - }, [getContextRows, columns, formatRows, writeToClipboard, rowsCopiedToast]); + }, [getContextRows, columns, formatRows, writeToClipboard, rowsCopiedToast, platform]); // "Column statistics" (issue #1001). Masked columns only get counts: // min / max and top values would show the hidden values. @@ -2352,7 +2348,7 @@ export const DataGrid = React.memo(function DataGrid({ let text: string | null = null; try { - text = await readText(); + text = await platform.readClipboard(); } catch (e) { console.error('Failed to read clipboard:', e); showToast(t('dataGrid.pasteReadFailed'), {kind: 'error'}); @@ -2415,6 +2411,7 @@ export const DataGrid = React.memo(function DataGrid({ }, [ readonlyProp, + platform, cellRange, focusedCell, selectedRowIndices, @@ -3306,7 +3303,7 @@ export const DataGrid = React.memo(function DataGrid({ icon: ExternalLink, action: () => { setContextMenu(null); - openUrl(link).catch((e: unknown) => { + platform.openExternalUrl(link).catch((e: unknown) => { console.error('Failed to open link:', e); showToast( t('contextMenu.openLinkFailed', {error: String(e)}), diff --git a/src/components/ui/DataGridRow.tsx b/packages/web-ui/src/components/ui/DataGridRow.tsx similarity index 100% rename from src/components/ui/DataGridRow.tsx rename to packages/web-ui/src/components/ui/DataGridRow.tsx diff --git a/src/components/ui/DateInput.tsx b/packages/web-ui/src/components/ui/DateInput.tsx similarity index 100% rename from src/components/ui/DateInput.tsx rename to packages/web-ui/src/components/ui/DateInput.tsx diff --git a/src/components/ui/EditorErrorBoundary.tsx b/packages/web-ui/src/components/ui/EditorErrorBoundary.tsx similarity index 100% rename from src/components/ui/EditorErrorBoundary.tsx rename to packages/web-ui/src/components/ui/EditorErrorBoundary.tsx diff --git a/src/components/ui/EnumSetInput.tsx b/packages/web-ui/src/components/ui/EnumSetInput.tsx similarity index 100% rename from src/components/ui/EnumSetInput.tsx rename to packages/web-ui/src/components/ui/EnumSetInput.tsx diff --git a/src/components/ui/ErrorDisplay.tsx b/packages/web-ui/src/components/ui/ErrorDisplay.tsx similarity index 100% rename from src/components/ui/ErrorDisplay.tsx rename to packages/web-ui/src/components/ui/ErrorDisplay.tsx diff --git a/src/components/ui/FieldEditor.tsx b/packages/web-ui/src/components/ui/FieldEditor.tsx similarity index 100% rename from src/components/ui/FieldEditor.tsx rename to packages/web-ui/src/components/ui/FieldEditor.tsx diff --git a/src/components/ui/FilterRow.tsx b/packages/web-ui/src/components/ui/FilterRow.tsx similarity index 100% rename from src/components/ui/FilterRow.tsx rename to packages/web-ui/src/components/ui/FilterRow.tsx diff --git a/src/components/ui/FilterValuePicker.tsx b/packages/web-ui/src/components/ui/FilterValuePicker.tsx similarity index 100% rename from src/components/ui/FilterValuePicker.tsx rename to packages/web-ui/src/components/ui/FilterValuePicker.tsx diff --git a/src/components/ui/GeometryInput.tsx b/packages/web-ui/src/components/ui/GeometryInput.tsx similarity index 100% rename from src/components/ui/GeometryInput.tsx rename to packages/web-ui/src/components/ui/GeometryInput.tsx diff --git a/src/components/ui/ImagePreviewHover.tsx b/packages/web-ui/src/components/ui/ImagePreviewHover.tsx similarity index 100% rename from src/components/ui/ImagePreviewHover.tsx rename to packages/web-ui/src/components/ui/ImagePreviewHover.tsx diff --git a/src/components/ui/InlineBanner.tsx b/packages/web-ui/src/components/ui/InlineBanner.tsx similarity index 100% rename from src/components/ui/InlineBanner.tsx rename to packages/web-ui/src/components/ui/InlineBanner.tsx diff --git a/src/components/ui/JoinEdge.tsx b/packages/web-ui/src/components/ui/JoinEdge.tsx similarity index 100% rename from src/components/ui/JoinEdge.tsx rename to packages/web-ui/src/components/ui/JoinEdge.tsx diff --git a/src/components/ui/JsonCell.tsx b/packages/web-ui/src/components/ui/JsonCell.tsx similarity index 100% rename from src/components/ui/JsonCell.tsx rename to packages/web-ui/src/components/ui/JsonCell.tsx diff --git a/src/components/ui/JsonExpansionEditor.tsx b/packages/web-ui/src/components/ui/JsonExpansionEditor.tsx similarity index 100% rename from src/components/ui/JsonExpansionEditor.tsx rename to packages/web-ui/src/components/ui/JsonExpansionEditor.tsx diff --git a/src/components/ui/JsonInput.tsx b/packages/web-ui/src/components/ui/JsonInput.tsx similarity index 95% rename from src/components/ui/JsonInput.tsx rename to packages/web-ui/src/components/ui/JsonInput.tsx index d6ad29bb4..403df0fc7 100644 --- a/src/components/ui/JsonInput.tsx +++ b/packages/web-ui/src/components/ui/JsonInput.tsx @@ -11,7 +11,8 @@ import { WrapText, X, } from 'lucide-react'; -import {invoke} from '@tauri-apps/api/core'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {getJsonViewerSessionHost} from '@/platform/secondaryWindowSessions'; import {formatJsonForEditor, parseJsonEditorValue, validateJson} from '@/utils/json'; import {CellCodeEditor} from './CellCodeEditor'; import {CellDiffEditor} from './CellDiffEditor'; @@ -46,6 +47,7 @@ export const JsonInput: React.FC = ({ originalValue, }) => { const {t} = useTranslation(); + const platform = usePlatformCapabilities(); const [mode, setMode] = useState('code'); const valueKey = JSON.stringify(value); const [text, setText] = useState(() => formatJsonForEditor(value)); @@ -147,18 +149,21 @@ export const JsonInput: React.FC = ({ const handleExpandToWindow = useCallback(async () => { try { - await invoke('open_json_viewer_window', { - value: expandValue, - originalValue: originalValue ?? expandValue, - colName: '', - rowLabel: null, - readOnly, - cellKey: null, - }); + await getJsonViewerSessionHost(platform).open( + { + value: expandValue, + originalValue: originalValue ?? expandValue, + columnName: '', + rowLabel: null, + readOnly, + cellKey: null, + }, + readOnly ? undefined : onChange, + ); } catch (e) { console.error('Failed to open JSON viewer window:', e); } - }, [expandValue, originalValue, readOnly]); + }, [expandValue, onChange, originalValue, platform, readOnly]); const showToolbar = isTextMode || !disableExpand; diff --git a/src/components/ui/JsonTreeView.tsx b/packages/web-ui/src/components/ui/JsonTreeView.tsx similarity index 98% rename from src/components/ui/JsonTreeView.tsx rename to packages/web-ui/src/components/ui/JsonTreeView.tsx index 0072af4ee..8c0248a6b 100644 --- a/src/components/ui/JsonTreeView.tsx +++ b/packages/web-ui/src/components/ui/JsonTreeView.tsx @@ -1,7 +1,7 @@ import {useContext, useMemo, useState} from 'react'; import {useTranslation} from 'react-i18next'; import {ChevronsDownUp, ChevronsUpDown, ExternalLink, Search} from 'lucide-react'; -import {openUrl} from '@tauri-apps/plugin-opener'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import { JsonEditor, defaultTheme, @@ -86,12 +86,13 @@ function buildTheme(theme: Theme | undefined): JerTheme { } const LinkNode: React.FC = ({value, originalNode}) => { + const platform = usePlatformCapabilities(); const url = typeof value === 'string' ? value.trim() : ''; const handleOpen = async (e: React.MouseEvent) => { e.stopPropagation(); try { - await openUrl(url); + await platform.openExternalUrl(url); } catch (err) { console.error('Failed to open URL:', err); } diff --git a/src/components/ui/K8sAdvancedSettings.tsx b/packages/web-ui/src/components/ui/K8sAdvancedSettings.tsx similarity index 100% rename from src/components/ui/K8sAdvancedSettings.tsx rename to packages/web-ui/src/components/ui/K8sAdvancedSettings.tsx diff --git a/src/components/ui/LazyMonaco.tsx b/packages/web-ui/src/components/ui/LazyMonaco.tsx similarity index 100% rename from src/components/ui/LazyMonaco.tsx rename to packages/web-ui/src/components/ui/LazyMonaco.tsx diff --git a/src/components/ui/LoadingState.tsx b/packages/web-ui/src/components/ui/LoadingState.tsx similarity index 100% rename from src/components/ui/LoadingState.tsx rename to packages/web-ui/src/components/ui/LoadingState.tsx diff --git a/src/components/ui/MiniResultGrid.tsx b/packages/web-ui/src/components/ui/MiniResultGrid.tsx similarity index 100% rename from src/components/ui/MiniResultGrid.tsx rename to packages/web-ui/src/components/ui/MiniResultGrid.tsx diff --git a/src/components/ui/Modal.tsx b/packages/web-ui/src/components/ui/Modal.tsx similarity index 100% rename from src/components/ui/Modal.tsx rename to packages/web-ui/src/components/ui/Modal.tsx diff --git a/src/components/ui/MonacoEditors.ts b/packages/web-ui/src/components/ui/MonacoEditors.ts similarity index 100% rename from src/components/ui/MonacoEditors.ts rename to packages/web-ui/src/components/ui/MonacoEditors.ts diff --git a/src/components/ui/MultiResultPanel.tsx b/packages/web-ui/src/components/ui/MultiResultPanel.tsx similarity index 99% rename from src/components/ui/MultiResultPanel.tsx rename to packages/web-ui/src/components/ui/MultiResultPanel.tsx index 2fb42e022..77bb76434 100644 --- a/src/components/ui/MultiResultPanel.tsx +++ b/packages/web-ui/src/components/ui/MultiResultPanel.tsx @@ -23,7 +23,7 @@ import { ChevronsUpDown, } from 'lucide-react'; import clsx from 'clsx'; -import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {ResultEntryContent} from './ResultEntryContent'; import type {DataGridCommandTarget} from './DataGrid'; import {StackedResultItem} from './StackedResultItem'; @@ -278,6 +278,7 @@ export function MultiResultPanel({ }: MultiResultPanelProps) { const {t} = useTranslation(); const {settings} = useSettings(); + const client = useTabularisClient(); const scrollRef = useRef(null); const [canScrollLeft, setCanScrollLeft] = useState(false); const [canScrollRight, setCanScrollRight] = useState(false); @@ -354,7 +355,7 @@ export function MultiResultPanel({ if (!entry?.query.trim() || !settings.aiProvider) return; setAiRenamingEntryId(entryId); try { - const name = await invoke('generate_tab_rename', { + const name = await client.call('generate_tab_rename', { req: { provider: settings.aiProvider, model: settings.aiModel || '', diff --git a/src/components/ui/PageSizeSelector.tsx b/packages/web-ui/src/components/ui/PageSizeSelector.tsx similarity index 100% rename from src/components/ui/PageSizeSelector.tsx rename to packages/web-ui/src/components/ui/PageSizeSelector.tsx diff --git a/src/components/ui/PaginationControls.tsx b/packages/web-ui/src/components/ui/PaginationControls.tsx similarity index 100% rename from src/components/ui/PaginationControls.tsx rename to packages/web-ui/src/components/ui/PaginationControls.tsx diff --git a/src/components/ui/PasswordInput.tsx b/packages/web-ui/src/components/ui/PasswordInput.tsx similarity index 100% rename from src/components/ui/PasswordInput.tsx rename to packages/web-ui/src/components/ui/PasswordInput.tsx diff --git a/src/components/ui/RelatedRecordsPanel.tsx b/packages/web-ui/src/components/ui/RelatedRecordsPanel.tsx similarity index 100% rename from src/components/ui/RelatedRecordsPanel.tsx rename to packages/web-ui/src/components/ui/RelatedRecordsPanel.tsx diff --git a/src/components/ui/ResultEntryContent.tsx b/packages/web-ui/src/components/ui/ResultEntryContent.tsx similarity index 100% rename from src/components/ui/ResultEntryContent.tsx rename to packages/web-ui/src/components/ui/ResultEntryContent.tsx diff --git a/src/components/ui/RowEditorPanel.tsx b/packages/web-ui/src/components/ui/RowEditorPanel.tsx similarity index 100% rename from src/components/ui/RowEditorPanel.tsx rename to packages/web-ui/src/components/ui/RowEditorPanel.tsx diff --git a/src/components/ui/SchemaDiagram.tsx b/packages/web-ui/src/components/ui/SchemaDiagram.tsx similarity index 97% rename from src/components/ui/SchemaDiagram.tsx rename to packages/web-ui/src/components/ui/SchemaDiagram.tsx index 0d10fa488..9c0fd1842 100644 --- a/src/components/ui/SchemaDiagram.tsx +++ b/packages/web-ui/src/components/ui/SchemaDiagram.tsx @@ -28,8 +28,6 @@ import { Lock, LockOpen, } from 'lucide-react'; -import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; import {generateMermaidErDiagram, generateDbml} from '@/utils/schemaExport'; import {useAlert} from '@/hooks/useAlert'; import {toErrorMessage} from '@/utils/errors'; @@ -40,6 +38,8 @@ import {useSettings} from '@/hooks/useSettings'; import {useTheme} from '@/hooks/useTheme'; import {withThemeAlpha} from '@/utils/themeColor'; import {DEFAULT_SETTINGS} from '@/contexts/SettingsContext'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {downloadTextFile} from '@/utils/fileDownloads'; const nodeTypes = { schemaTable: SchemaTableNodeComponent, @@ -130,6 +130,7 @@ const SchemaDiagramContent = ({ const {getSchema} = useEditor(); const {showAlert} = useAlert(); const {settings} = useSettings(); + const platform = usePlatformCapabilities(); const {currentTheme} = useTheme(); const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); @@ -197,28 +198,28 @@ const SchemaDiagramContent = ({ const extension = isMermaid ? 'mmd' : 'dbml'; try { - const filePath = await save({ + const content = isMermaid + ? generateMermaidErDiagram(allNodes, allEdges) + : generateDbml(allNodes, allEdges); + const downloaded = await downloadTextFile(platform, { + fileName: `schema_${new Date().toISOString().slice(0, 10)}.${extension}`, + contents: content, + mimeType: 'text/plain', filters: [ { name: isMermaid ? 'Mermaid' : 'DBML', extensions: [extension], }, ], - defaultPath: `schema_${new Date().toISOString().slice(0, 10)}.${extension}`, }); - if (!filePath) return; - - const content = isMermaid - ? generateMermaidErDiagram(allNodes, allEdges) - : generateDbml(allNodes, allEdges); - - await writeTextFile(filePath, content); - showAlert(t('erDiagram.exportSuccess'), {kind: 'info'}); + if (downloaded) { + showAlert(t('erDiagram.exportSuccess'), {kind: 'info'}); + } } catch (err) { showAlert(String(err), {kind: 'error'}); } }, - [allNodes, allEdges, showAlert, t], + [allNodes, allEdges, platform, showAlert, t], ); // Callback per tornare alla vista completa diff --git a/src/components/ui/SchemaTableNode.tsx b/packages/web-ui/src/components/ui/SchemaTableNode.tsx similarity index 100% rename from src/components/ui/SchemaTableNode.tsx rename to packages/web-ui/src/components/ui/SchemaTableNode.tsx diff --git a/src/components/ui/Select.tsx b/packages/web-ui/src/components/ui/Select.tsx similarity index 100% rename from src/components/ui/Select.tsx rename to packages/web-ui/src/components/ui/Select.tsx diff --git a/src/components/ui/SlotAnchor.tsx b/packages/web-ui/src/components/ui/SlotAnchor.tsx similarity index 100% rename from src/components/ui/SlotAnchor.tsx rename to packages/web-ui/src/components/ui/SlotAnchor.tsx diff --git a/src/components/ui/SlotErrorBoundary.tsx b/packages/web-ui/src/components/ui/SlotErrorBoundary.tsx similarity index 100% rename from src/components/ui/SlotErrorBoundary.tsx rename to packages/web-ui/src/components/ui/SlotErrorBoundary.tsx diff --git a/src/components/ui/SpotlightPalette.tsx b/packages/web-ui/src/components/ui/SpotlightPalette.tsx similarity index 100% rename from src/components/ui/SpotlightPalette.tsx rename to packages/web-ui/src/components/ui/SpotlightPalette.tsx diff --git a/src/components/ui/SqlEditorWrapper.tsx b/packages/web-ui/src/components/ui/SqlEditorWrapper.tsx similarity index 99% rename from src/components/ui/SqlEditorWrapper.tsx rename to packages/web-ui/src/components/ui/SqlEditorWrapper.tsx index 468196cb9..4872375eb 100644 --- a/src/components/ui/SqlEditorWrapper.tsx +++ b/packages/web-ui/src/components/ui/SqlEditorWrapper.tsx @@ -5,8 +5,8 @@ import {MonacoEditor} from './LazyMonaco'; import type * as Monaco from 'monaco-editor'; import {useEditorTheme} from '@/hooks/useEditorTheme'; import {loadMonacoTheme} from '@/themes/themeUtils'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import {getMonacoThemeId} from '@/themes/themeRuntime'; -import {readText, writeText} from '@tauri-apps/plugin-clipboard-manager'; import {useSettings} from '@/hooks/useSettings'; import {useKeybindings} from '@/hooks/useKeybindings'; import {CommandPaletteDispatchContext} from '@/contexts/CommandPaletteContext'; @@ -106,6 +106,7 @@ const SqlEditorInternal = ({ onRunContextChange, foldPreview = false, }: SqlEditorWrapperProps & {editorKey: string}) => { + const platform = usePlatformCapabilities(); const updateTimeoutRef = useRef | null>(null); const {t} = useTranslation(); const editorRef = useRef[0] | null>(null); @@ -264,7 +265,7 @@ const SqlEditorInternal = ({ const tauriPaste = async (ed: Monaco.editor.ICodeEditor) => { try { - const text = await readText(); + const text = await platform.readClipboard(); const selections = ed.getSelections(); if (selections && selections.length > 0 && text) { const lines = text.split('\n'); @@ -297,7 +298,7 @@ const SqlEditorInternal = ({ const tauriCopy = async (ed: Monaco.editor.ICodeEditor) => { try { const text = getSelectedText(ed); - if (text) await writeText(text); + if (text) await platform.writeClipboard(text); } catch (err) { console.error('Failed to write clipboard:', err); } @@ -307,7 +308,7 @@ const SqlEditorInternal = ({ try { const text = getSelectedText(ed); if (!text) return; - await writeText(text); + await platform.writeClipboard(text); const model = ed.getModel(); const selections = ed.getSelections(); if (!model || !selections) return; diff --git a/src/components/ui/SqlHighlight.tsx b/packages/web-ui/src/components/ui/SqlHighlight.tsx similarity index 100% rename from src/components/ui/SqlHighlight.tsx rename to packages/web-ui/src/components/ui/SqlHighlight.tsx diff --git a/src/components/ui/SqlMatchExcerpt.tsx b/packages/web-ui/src/components/ui/SqlMatchExcerpt.tsx similarity index 100% rename from src/components/ui/SqlMatchExcerpt.tsx rename to packages/web-ui/src/components/ui/SqlMatchExcerpt.tsx diff --git a/src/components/ui/SqlPreview.tsx b/packages/web-ui/src/components/ui/SqlPreview.tsx similarity index 100% rename from src/components/ui/SqlPreview.tsx rename to packages/web-ui/src/components/ui/SqlPreview.tsx diff --git a/src/components/ui/StackedResultItem.tsx b/packages/web-ui/src/components/ui/StackedResultItem.tsx similarity index 100% rename from src/components/ui/StackedResultItem.tsx rename to packages/web-ui/src/components/ui/StackedResultItem.tsx diff --git a/src/components/ui/StyledSelect.tsx b/packages/web-ui/src/components/ui/StyledSelect.tsx similarity index 100% rename from src/components/ui/StyledSelect.tsx rename to packages/web-ui/src/components/ui/StyledSelect.tsx diff --git a/src/components/ui/TableNode.tsx b/packages/web-ui/src/components/ui/TableNode.tsx similarity index 100% rename from src/components/ui/TableNode.tsx rename to packages/web-ui/src/components/ui/TableNode.tsx diff --git a/src/components/ui/TableToolbar.tsx b/packages/web-ui/src/components/ui/TableToolbar.tsx similarity index 100% rename from src/components/ui/TableToolbar.tsx rename to packages/web-ui/src/components/ui/TableToolbar.tsx diff --git a/src/components/ui/TextCell.tsx b/packages/web-ui/src/components/ui/TextCell.tsx similarity index 100% rename from src/components/ui/TextCell.tsx rename to packages/web-ui/src/components/ui/TextCell.tsx diff --git a/src/components/ui/TextExpansionEditor.tsx b/packages/web-ui/src/components/ui/TextExpansionEditor.tsx similarity index 100% rename from src/components/ui/TextExpansionEditor.tsx rename to packages/web-ui/src/components/ui/TextExpansionEditor.tsx diff --git a/src/components/ui/TextInput.tsx b/packages/web-ui/src/components/ui/TextInput.tsx similarity index 100% rename from src/components/ui/TextInput.tsx rename to packages/web-ui/src/components/ui/TextInput.tsx diff --git a/src/components/ui/ThemeDialog.tsx b/packages/web-ui/src/components/ui/ThemeDialog.tsx similarity index 100% rename from src/components/ui/ThemeDialog.tsx rename to packages/web-ui/src/components/ui/ThemeDialog.tsx diff --git a/src/components/ui/ThemeDialogButton.tsx b/packages/web-ui/src/components/ui/ThemeDialogButton.tsx similarity index 100% rename from src/components/ui/ThemeDialogButton.tsx rename to packages/web-ui/src/components/ui/ThemeDialogButton.tsx diff --git a/src/components/ui/ThemeSqlSample.tsx b/packages/web-ui/src/components/ui/ThemeSqlSample.tsx similarity index 100% rename from src/components/ui/ThemeSqlSample.tsx rename to packages/web-ui/src/components/ui/ThemeSqlSample.tsx diff --git a/src/components/ui/ToastContainer.tsx b/packages/web-ui/src/components/ui/ToastContainer.tsx similarity index 100% rename from src/components/ui/ToastContainer.tsx rename to packages/web-ui/src/components/ui/ToastContainer.tsx diff --git a/src/components/ui/UpdateBadge.tsx b/packages/web-ui/src/components/ui/UpdateBadge.tsx similarity index 100% rename from src/components/ui/UpdateBadge.tsx rename to packages/web-ui/src/components/ui/UpdateBadge.tsx diff --git a/src/components/ui/UpdateTooltip.tsx b/packages/web-ui/src/components/ui/UpdateTooltip.tsx similarity index 100% rename from src/components/ui/UpdateTooltip.tsx rename to packages/web-ui/src/components/ui/UpdateTooltip.tsx diff --git a/src/components/ui/VisualQueryBuilder.tsx b/packages/web-ui/src/components/ui/VisualQueryBuilder.tsx similarity index 99% rename from src/components/ui/VisualQueryBuilder.tsx rename to packages/web-ui/src/components/ui/VisualQueryBuilder.tsx index d63bb4852..650e17a23 100644 --- a/src/components/ui/VisualQueryBuilder.tsx +++ b/packages/web-ui/src/components/ui/VisualQueryBuilder.tsx @@ -17,13 +17,13 @@ import '@xyflow/react/dist/style.css'; import {TableNodeComponent, type TableNodeData, type ColumnAggregation} from './TableNode'; import {JoinEdge} from './JoinEdge'; import {useDatabase} from '@/hooks/useDatabase'; -import {invoke} from '@tauri-apps/api/core'; import {dragState} from '@/utils/dragState'; import {useEditor} from '@/hooks/useEditor'; import {useTheme} from '@/hooks/useTheme'; import {withThemeAlpha} from '@/utils/themeColor'; import {Filter, SortAsc, Group, Hash, X, Plus} from 'lucide-react'; import {generateVisualQuerySQL, type WhereCondition, type OrderByClause} from '@/utils/visualQuery'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; const nodeTypes = { table: TableNodeComponent, @@ -33,14 +33,8 @@ const edgeTypes = { join: JoinEdge, }; -interface TableColumn { - name: string; - data_type: string; - is_pk: boolean; - is_nullable: boolean; -} - const VisualQueryBuilderContent = () => { + const client = useTabularisClient(); const {activeConnectionId, activeDriver, activeCapabilities, activeSchema} = useDatabase(); const {activeTab, activeTabId, updateTab} = useEditor(); const {currentTheme} = useTheme(); @@ -231,7 +225,7 @@ const VisualQueryBuilderContent = () => { }); try { - const columns = await invoke('get_columns', { + const columns = await client.call('get_columns', { connectionId: activeConnectionId, tableName, ...(tableSchema ? {schema: tableSchema} : {}), @@ -265,6 +259,7 @@ const VisualQueryBuilderContent = () => { } }, [ + client, activeConnectionId, screenToFlowPosition, setNodes, diff --git a/src/components/users/UserManagementView.tsx b/packages/web-ui/src/components/users/UserManagementView.tsx similarity index 96% rename from src/components/users/UserManagementView.tsx rename to packages/web-ui/src/components/users/UserManagementView.tsx index 498f350c0..bbc9ced37 100644 --- a/src/components/users/UserManagementView.tsx +++ b/packages/web-ui/src/components/users/UserManagementView.tsx @@ -1,7 +1,7 @@ import {useCallback, useEffect, useMemo, useState} from 'react'; import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import {confirm} from '@tauri-apps/plugin-dialog'; +import {bindPlatformConfirm} from '@/platform/dialogs'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import clsx from 'clsx'; import { Globe, @@ -18,29 +18,8 @@ import { } from 'lucide-react'; import {useDatabase} from '@/hooks/useDatabase'; import {toErrorMessage} from '@/utils/errors'; - -interface DbUserInfo { - user: string; - host: string; - locked: boolean; -} - -/** The dialect's privilege keywords, supplied by the driver. */ -interface DbPrivilegeCatalog { - /** Privileges valid at the database scope (and also globally). */ - database: string[]; - /** Privileges valid only at the global scope. */ - global: string[]; - /** Privileges valid at the table scope. */ - table: string[]; -} - -/** One scope's parsed privileges. `database === null` is the global scope. */ -interface DbUserGrantSet { - database: string | null; - table: string | null; - privileges: string[]; -} +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import type {DbPrivilegeCatalog, DbUserGrantSet, DbUserInfo} from '@/api/contract'; const scopeKey = (s: Pick) => `${s.database ?? '*'}\0${s.table ?? '*'}`; @@ -165,6 +144,9 @@ function ScopeCard({ * model that way (roles, column-level) remain visible in the raw list. */ export function UserManagementView({connectionId, isActive}: Props) { + const platform = usePlatformCapabilities(); + const confirm = bindPlatformConfirm(platform); + const client = useTabularisClient(); const {t} = useTranslation(); const {selectedDatabases} = useDatabase(); @@ -209,21 +191,23 @@ export function UserManagementView({connectionId, isActive}: Props) { const [addTable, setAddTable] = useState(''); useEffect(() => { - invoke('get_db_privilege_catalog', {connectionId}) + client + .call('get_db_privilege_catalog', {connectionId}) .then(setCatalog) .catch((e: unknown) => { console.error('Failed to load privilege catalog:', e); }); - }, [connectionId]); + }, [client, connectionId]); const refreshUsers = useCallback(() => { setLoading(true); setLoadError(null); - return invoke('get_db_users', {connectionId}) + return client + .call('get_db_users', {connectionId}) .then(setUsers) .catch((e: unknown) => setLoadError(toErrorMessage(e))) .finally(() => setLoading(false)); - }, [connectionId]); + }, [client, connectionId]); useEffect(() => { refreshUsers(); @@ -239,8 +223,8 @@ export function UserManagementView({connectionId, isActive}: Props) { host: account.host, }; return Promise.all([ - invoke('get_db_user_grants', target), - invoke('get_db_user_privileges', target), + client.call('get_db_user_grants', target), + client.call('get_db_user_privileges', target), ]) .then(([lines, sets]) => { setGrants(lines); @@ -249,7 +233,7 @@ export function UserManagementView({connectionId, isActive}: Props) { .catch((e: unknown) => setGrantsError(toErrorMessage(e))) .finally(() => setGrantsLoading(false)); }, - [connectionId], + [client, connectionId], ); useEffect(() => { @@ -310,7 +294,7 @@ export function UserManagementView({connectionId, isActive}: Props) { runAction(async () => { const user = newUser.trim(); const host = newHost.trim() || '%'; - await invoke('create_db_user', { + await client.call('create_db_user', { connectionId, user, host, @@ -319,7 +303,7 @@ export function UserManagementView({connectionId, isActive}: Props) { // Initial privileges, scoped to the chosen database (or globally // when the field is left empty on purpose). if (newPrivs.size > 0) { - await invoke('apply_db_user_privileges', { + await client.call('apply_db_user_privileges', { connectionId, user, host, @@ -348,7 +332,7 @@ export function UserManagementView({connectionId, isActive}: Props) { ); if (!ok) return; await runAction(async () => { - await invoke('drop_db_user', { + await client.call('drop_db_user', { connectionId, user: account.user, host: account.host, @@ -363,7 +347,7 @@ export function UserManagementView({connectionId, isActive}: Props) { const handleChangePassword = () => runAction(async () => { if (!selected) return; - await invoke('set_db_user_password', { + await client.call('set_db_user_password', { connectionId, user: selected.user, host: selected.host, @@ -406,14 +390,14 @@ export function UserManagementView({connectionId, isActive}: Props) { // Revoke first: switching away from ALL PRIVILEGES is expressed as // "revoke ALL, grant the subset", which only works in this order. if (toRevoke.length > 0) { - await invoke('apply_db_user_privileges', { + await client.call('apply_db_user_privileges', { ...base, privileges: toRevoke, grant: false, }); } if (toGrant.length > 0) { - await invoke('apply_db_user_privileges', { + await client.call('apply_db_user_privileges', { ...base, privileges: toGrant, grant: true, diff --git a/src/config/links.ts b/packages/web-ui/src/config/links.ts similarity index 100% rename from src/config/links.ts rename to packages/web-ui/src/config/links.ts diff --git a/src/config/shortcuts.json b/packages/web-ui/src/config/shortcuts.json similarity index 100% rename from src/config/shortcuts.json rename to packages/web-ui/src/config/shortcuts.json diff --git a/src/config/socialLinks.ts b/packages/web-ui/src/config/socialLinks.ts similarity index 100% rename from src/config/socialLinks.ts rename to packages/web-ui/src/config/socialLinks.ts diff --git a/src/contexts/AlertContext.ts b/packages/web-ui/src/contexts/AlertContext.ts similarity index 100% rename from src/contexts/AlertContext.ts rename to packages/web-ui/src/contexts/AlertContext.ts diff --git a/src/contexts/AlertProvider.tsx b/packages/web-ui/src/contexts/AlertProvider.tsx similarity index 100% rename from src/contexts/AlertProvider.tsx rename to packages/web-ui/src/contexts/AlertProvider.tsx diff --git a/src/contexts/CommandPaletteContext.ts b/packages/web-ui/src/contexts/CommandPaletteContext.ts similarity index 100% rename from src/contexts/CommandPaletteContext.ts rename to packages/web-ui/src/contexts/CommandPaletteContext.ts diff --git a/src/contexts/CommandPaletteProvider.tsx b/packages/web-ui/src/contexts/CommandPaletteProvider.tsx similarity index 100% rename from src/contexts/CommandPaletteProvider.tsx rename to packages/web-ui/src/contexts/CommandPaletteProvider.tsx diff --git a/src/contexts/CommandPaletteScopeContext.ts b/packages/web-ui/src/contexts/CommandPaletteScopeContext.ts similarity index 100% rename from src/contexts/CommandPaletteScopeContext.ts rename to packages/web-ui/src/contexts/CommandPaletteScopeContext.ts diff --git a/src/contexts/ConnectionLayoutContext.ts b/packages/web-ui/src/contexts/ConnectionLayoutContext.ts similarity index 100% rename from src/contexts/ConnectionLayoutContext.ts rename to packages/web-ui/src/contexts/ConnectionLayoutContext.ts diff --git a/src/contexts/ConnectionLayoutProvider.tsx b/packages/web-ui/src/contexts/ConnectionLayoutProvider.tsx similarity index 100% rename from src/contexts/ConnectionLayoutProvider.tsx rename to packages/web-ui/src/contexts/ConnectionLayoutProvider.tsx diff --git a/src/contexts/DatabaseContext.ts b/packages/web-ui/src/contexts/DatabaseContext.ts similarity index 99% rename from src/contexts/DatabaseContext.ts rename to packages/web-ui/src/contexts/DatabaseContext.ts index fe6d660da..38049c266 100644 --- a/src/contexts/DatabaseContext.ts +++ b/packages/web-ui/src/contexts/DatabaseContext.ts @@ -56,6 +56,8 @@ export interface SavedConnection { driver: string; host?: string; database: string | string[]; + default_database?: string; + save_in_keychain?: boolean; port?: number; username?: string; password?: string; diff --git a/src/contexts/DatabaseProvider.tsx b/packages/web-ui/src/contexts/DatabaseProvider.tsx similarity index 81% rename from src/contexts/DatabaseProvider.tsx rename to packages/web-ui/src/contexts/DatabaseProvider.tsx index 9e06884b4..4c930b549 100644 --- a/src/contexts/DatabaseProvider.tsx +++ b/packages/web-ui/src/contexts/DatabaseProvider.tsx @@ -1,11 +1,10 @@ import {useState, useCallback, useEffect, useRef, useMemo} from 'react'; import {useTranslation} from 'react-i18next'; import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import {getCurrentWindow} from '@tauri-apps/api/window'; +import {detectPlatformEnvironment} from '@/platform/environment'; import { DatabaseContext, - type TableInfo, type ViewInfo, type RoutineInfo, type TriggerInfo, @@ -14,10 +13,9 @@ import { type NestedDatabaseData, type SchemaData, type ConnectionGroup, - type ConnectionsFile, } from './DatabaseContext'; import type {ReactNode} from 'react'; -import type {ConnectionMetadata, PluginManifest} from '@/types/plugins'; +import type {PluginManifest} from '@/types/plugins'; import {clearAutocompleteCache} from '@/utils/autocomplete'; import {loadOptionalMetadata} from '@/utils/connectionMetadata'; import {toErrorMessage} from '@/utils/errors'; @@ -31,6 +29,8 @@ import { getDatabaseList, reconcileDatabaseSelection, } from '@/utils/database'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import type {TypedCommandCaller} from '@/api/contract'; /** Label of the main window; Tauri defaults to this when none is configured. */ const MAIN_WINDOW_LABEL = 'main'; @@ -46,6 +46,7 @@ interface RoutineMetadataResult { } const getRoutinesOrEmpty = async ( + client: TypedCommandCaller, connectionId: string, schema: string | undefined, onError: (error: unknown, schema?: string) => void, @@ -53,7 +54,7 @@ const getRoutinesOrEmpty = async ( ): Promise => { try { return { - routines: await invoke('get_routines', {connectionId, schema, database}), + routines: await client.call('get_routines', {connectionId, schema, database}), }; } catch (error) { onError(error, schema); @@ -112,6 +113,7 @@ const createEmptyConnectionData = ( }); export const DatabaseProvider = ({children}: {children: ReactNode}) => { + const client = useTabularisClient(); const {settings} = useSettings(); const {showToast} = useToast(); const {t} = useTranslation(); @@ -190,7 +192,11 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { : activeDatabaseName; title = `tabularis - ${activeConnectionName} (${dbDisplay}${schemaSuffix})`; } - await invoke('set_window_title', {title}); + if (detectPlatformEnvironment() === 'tauri') { + await invoke('set_window_title', {title}); + } else { + document.title = title; + } } catch (e) { console.error('Failed to update window title', e); } @@ -339,9 +345,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // ones disappear. if (data?.allDatabasesMode) { try { - const available = await invoke('get_available_databases', { - connectionId, - }); + const available = await client.call('get_available_databases', {connectionId}); const added = available.filter((db) => !current.includes(db)); const removed = current.filter((db) => !available.includes(db)); if (added.length > 0 || removed.length > 0) { @@ -373,7 +377,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } try { - const available = await invoke('get_available_databases', {connectionId}); + const available = await client.call('get_available_databases', {connectionId}); // Same guard as the connect-time reconciliation: an incomplete server // list (e.g. restricted privileges) must not be mistaken for missing @@ -395,20 +399,24 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // have if triggered outside of connect() - flagging rather than // guessing at a fix here. updateConnectionData(connectionId, {selectedDatabases: selection}); - invoke('set_selected_databases', { - connectionId, - databases: selection, - }).catch((e) => - console.error('Failed to persist reconciled database selection:', e), - ); + client + .call('set_selected_databases', { + connectionId, + databases: selection, + }) + .catch((e) => + console.error('Failed to persist reconciled database selection:', e), + ); showToast(t('sidebar.droppedDatabasesRemoved', {names: removed.join(', ')}), { title: t('sidebar.databaseSelectionUpdated'), kind: 'warning', }); - invoke('log_frontend_event', { - level: 'warn', - message: `Connection "${conn.name}": removed ${removed.join(', ')} from the database selection (no longer on the server)`, - }).catch(() => {}); + client + .call('log_frontend_event', { + level: 'warn', + message: `Connection "${conn.name}": removed ${removed.join(', ')} from the database selection (no longer on the server)`, + }) + .catch(() => {}); } else { if (notifyWhenUnchanged) { showToast(t('sidebar.databaseListUpToDate'), {kind: 'info'}); @@ -419,7 +427,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { showToast(String(e), {kind: 'error'}); } }, - [connections, connectionDataMap, updateConnectionData, showToast, t], + [client, connections, connectionDataMap, updateConnectionData, showToast, t], ); // Lets the listener below subscribe once: `refreshDatabaseSelection` is @@ -434,7 +442,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (!connId) return; updateConnectionData(connId, {isLoadingTables: true}); try { - const result = await invoke('get_tables', {connectionId: connId}); + const result = await client.call('get_tables', {connectionId: connId}); updateConnectionData(connId, {tables: result, isLoadingTables: false}); } catch (e) { console.error('Failed to refresh tables:', e); @@ -449,7 +457,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const result = await loadOptionalMetadata( connectionDataMap[connId]?.metadata?.capabilities.views, - () => invoke('get_views', {connectionId: connId}), + () => client.call('get_views', {connectionId: connId}), [], ); updateConnectionData(connId, {views: result, isLoadingViews: false}); @@ -466,7 +474,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const result = await loadOptionalMetadata( connectionDataMap[connId]?.metadata?.capabilities.routines, - () => invoke('get_routines', {connectionId: connId}), + () => client.call('get_routines', {connectionId: connId}), [], ); updateConnectionData(connId, { @@ -490,7 +498,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const result = await loadOptionalMetadata( connectionDataMap[connId]?.metadata?.capabilities.triggers, - () => invoke('get_triggers', {connectionId: connId}), + () => client.call('get_triggers', {connectionId: connId}), [], ); updateConnectionData(connId, {triggers: result, isLoadingTriggers: false}); @@ -521,30 +529,29 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema}), + client.call('get_tables', {connectionId: connId, schema}), loadOptionalMetadata( currentData.metadata?.capabilities.views, - () => invoke('get_views', {connectionId: connId, schema}), + () => client.call('get_views', {connectionId: connId, schema}), [] as ViewInfo[], ), currentData.capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId: connId, - schema, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', {connectionId: connId, schema}) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( currentData.metadata?.capabilities.routines, - () => getRoutinesOrEmpty(connId, schema, handleRoutineMetadataError), + () => + getRoutinesOrEmpty(client, connId, schema, handleRoutineMetadataError), {routines: []}, ), loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -564,7 +571,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { updateSchemaData(connId, schema, {...EMPTY_SCHEMA_DATA, isLoaded: true}); } }, - [activeConnectionId, connectionDataMap, updateSchemaData, handleRoutineMetadataError], + [ + client, + activeConnectionId, + connectionDataMap, + updateSchemaData, + handleRoutineMetadataError, + ], ); const refreshSchemaData = useCallback( @@ -585,30 +598,29 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema}), + client.call('get_tables', {connectionId: connId, schema}), loadOptionalMetadata( currentData.metadata?.capabilities.views, - () => invoke('get_views', {connectionId: connId, schema}), + () => client.call('get_views', {connectionId: connId, schema}), [] as ViewInfo[], ), currentData.capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId: connId, - schema, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', {connectionId: connId, schema}) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( currentData.metadata?.capabilities.routines, - () => getRoutinesOrEmpty(connId, schema, handleRoutineMetadataError), + () => + getRoutinesOrEmpty(client, connId, schema, handleRoutineMetadataError), {routines: []}, ), loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -628,7 +640,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { updateSchemaData(connId, schema, {isLoading: false}); } }, - [activeConnectionId, connectionDataMap, updateSchemaData, handleRoutineMetadataError], + [ + client, + activeConnectionId, + connectionDataMap, + updateSchemaData, + handleRoutineMetadataError, + ], ); const loadDatabaseData = useCallback( @@ -659,28 +677,30 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const [tablesResult, viewsResult, routineMetadata, triggersResult] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema: database}), + client.call('get_tables', {connectionId: connId, schema: database}), loadOptionalMetadata( currentData.metadata?.capabilities.views, () => - invoke('get_views', { - connectionId: connId, - schema: database, - }), + client.call('get_views', {connectionId: connId, schema: database}), [] as ViewInfo[], ), loadOptionalMetadata( currentData.metadata?.capabilities.routines, - () => getRoutinesOrEmpty(connId, database, handleRoutineMetadataError), + () => + getRoutinesOrEmpty( + client, + connId, + database, + handleRoutineMetadataError, + ), {routines: []}, ), loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema: database, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema: database}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -722,7 +742,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } } }, - [activeConnectionId, connectionDataMap, updateConnectionData, handleRoutineMetadataError], + [ + client, + activeConnectionId, + connectionDataMap, + updateConnectionData, + handleRoutineMetadataError, + ], ); const refreshDatabaseData = useCallback( @@ -752,28 +778,30 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const [tablesResult, viewsResult, routineMetadata, triggersResult] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema: database}), + client.call('get_tables', {connectionId: connId, schema: database}), loadOptionalMetadata( currentData.metadata?.capabilities.views, () => - invoke('get_views', { - connectionId: connId, - schema: database, - }), + client.call('get_views', {connectionId: connId, schema: database}), [] as ViewInfo[], ), loadOptionalMetadata( currentData.metadata?.capabilities.routines, - () => getRoutinesOrEmpty(connId, database, handleRoutineMetadataError), + () => + getRoutinesOrEmpty( + client, + connId, + database, + handleRoutineMetadataError, + ), {routines: []}, ), loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema: database, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema: database}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -817,7 +845,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } } }, - [activeConnectionId, connectionDataMap, updateConnectionData, handleRoutineMetadataError], + [ + client, + activeConnectionId, + connectionDataMap, + updateConnectionData, + handleRoutineMetadataError, + ], ); const setSelectedSchemas = useCallback( @@ -834,7 +868,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); try { - await invoke('set_selected_schemas', { + await client.call('set_selected_schemas', { connectionId: connId, schemas: newSchemas, }); @@ -853,14 +887,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { const nextSchema = newSchemas[0] || null; updateConnectionData(connId, {activeSchema: nextSchema}); if (nextSchema) { - invoke('set_schema_preference', { - connectionId: connId, - schema: nextSchema, - }).catch(() => {}); + client + .call('set_schema_preference', {connectionId: connId, schema: nextSchema}) + .catch(() => {}); } } }, - [activeConnectionId, connectionDataMap, updateConnectionData, loadSchemaData], + [client, activeConnectionId, connectionDataMap, updateConnectionData, loadSchemaData], ); const loadNestedSchemaData = useCallback( @@ -898,28 +931,26 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema, database}), + client.call('get_tables', {connectionId: connId, schema, database}), loadOptionalMetadata( currentData.metadata?.capabilities.views, - () => - invoke('get_views', { - connectionId: connId, - schema, - database, - }), + () => client.call('get_views', {connectionId: connId, schema, database}), [] as ViewInfo[], ), currentData.capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId: connId, - schema, - database, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', { + connectionId: connId, + schema, + database, + }) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( currentData.metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connId, schema, handleRoutineMetadataError, @@ -930,11 +961,9 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema, - database, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema, database}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -972,6 +1001,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } }, [ + client, activeConnectionId, connectionDataMap, updateNestedDatabaseData, @@ -1011,28 +1041,26 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', {connectionId: connId, schema, database}), + client.call('get_tables', {connectionId: connId, schema, database}), loadOptionalMetadata( currentData.metadata?.capabilities.views, - () => - invoke('get_views', { - connectionId: connId, - schema, - database, - }), + () => client.call('get_views', {connectionId: connId, schema, database}), [] as ViewInfo[], ), currentData.capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId: connId, - schema, - database, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', { + connectionId: connId, + schema, + database, + }) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( currentData.metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connId, schema, handleRoutineMetadataError, @@ -1043,11 +1071,9 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( currentData.metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId: connId, - schema, - database, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId: connId, schema, database}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -1087,6 +1113,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } }, [ + client, activeConnectionId, connectionDataMap, updateNestedDatabaseData, @@ -1118,7 +1145,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); try { - await invoke('set_selected_schemas', { + await client.call('set_selected_schemas', { connectionId: connId, schemas: newSchemas, database, @@ -1135,14 +1162,22 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } if (activeSchemaNeedsChange && nextSchema) { - invoke('set_schema_preference', { - connectionId: connId, - schema: nextSchema, - database, - }).catch(() => {}); + client + .call('set_schema_preference', { + connectionId: connId, + schema: nextSchema, + database, + }) + .catch(() => {}); } }, - [activeConnectionId, connectionDataMap, updateNestedDatabaseData, loadNestedSchemaData], + [ + client, + activeConnectionId, + connectionDataMap, + updateNestedDatabaseData, + loadNestedSchemaData, + ], ); /** @@ -1171,14 +1206,14 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { updateNestedDatabaseData(connId, database, {isLoadingSchemas: true}); try { - const schemasResult = await invoke('get_schemas', { + const schemasResult = await client.call('get_schemas', { connectionId: connId, database, }); let savedSelection: string[] = []; try { - savedSelection = await invoke('get_selected_schemas', { + savedSelection = await client.call('get_selected_schemas', { connectionId: connId, database, }); @@ -1201,7 +1236,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { let preferredSchema = validSelection[0]; try { - const saved = await invoke('get_schema_preference', { + const saved = await client.call('get_schema_preference', { connectionId: connId, database, }); @@ -1234,7 +1269,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); } }, - [activeConnectionId, connectionDataMap, updateNestedDatabaseData, loadNestedSchemaData], + [ + client, + activeConnectionId, + connectionDataMap, + updateNestedDatabaseData, + loadNestedSchemaData, + ], ); const setSelectedDatabases = useCallback( @@ -1261,10 +1302,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); if (newDatabases.length > 0) { - invoke('set_selected_databases', { - connectionId: connId, - databases: newDatabases, - }).catch((e) => console.error('Failed to persist selected databases:', e)); + client + .call('set_selected_databases', { + connectionId: connId, + databases: newDatabases, + }) + .catch((e) => console.error('Failed to persist selected databases:', e)); } for (const db of newDatabases) { @@ -1292,10 +1335,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); if (newDatabases.length > 0) { - invoke('set_selected_databases', { - connectionId: connId, - databases: newDatabases, - }).catch((e) => console.error('Failed to persist selected databases:', e)); + client + .call('set_selected_databases', { + connectionId: connId, + databases: newDatabases, + }) + .catch((e) => console.error('Failed to persist selected databases:', e)); } for (const db of newDatabases) { @@ -1306,6 +1351,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } }, [ + client, activeConnectionId, connectionDataMap, updateConnectionData, @@ -1348,7 +1394,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } try { - const allConnections = await invoke('get_connections'); + const allConnections = await client.call('get_connections', undefined); const conn = allConnections.find((c) => c.id === connectionId); if (!conn) { throw new Error('Connection not found'); @@ -1359,9 +1405,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // Fetch driver manifest to access capabilities (driver-agnostic feature detection) let driverManifest: PluginManifest | null = null; try { - driverManifest = await invoke('get_driver_manifest', { - driverId: driver, - }); + driverManifest = await client.call('get_driver_manifest', {driverId: driver}); } catch { // Manifest not found; capabilities will be null and features will degrade gracefully } @@ -1379,7 +1423,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }); try { - await invoke('test_connection', { + await client.call('test_connection', { request: { params: conn.params, connection_id: connectionId, @@ -1401,7 +1445,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (!isCurrentAttempt()) return; const metadata = driverManifest?.connection_metadata - ? await invoke('get_connection_metadata', {connectionId}) + ? await client.call('get_connection_metadata', {connectionId}) : null; if (!isCurrentAttempt()) return; if (metadata) { @@ -1410,7 +1454,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } // Register for health-check pinging. - await invoke('register_active_connection', {connectionId}); + await client.call('register_active_connection', {connectionId}); // Whether this saved connection has explicitly opted into database // selection browsing — see hasOptedIntoDatabaseSelection for why this @@ -1435,7 +1479,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (allDatabasesMode) { try { - dbList = await invoke('get_available_databases', {connectionId}); + dbList = await client.call('get_available_databases', {connectionId}); isMultiDb = dbList.length > 0; } catch (e) { // Without a database list the connection is unusable (it has no @@ -1456,9 +1500,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // Reconcile the saved selection against the server so databases // dropped outside the app don't linger in the sidebar (#518). try { - const available = await invoke('get_available_databases', { - connectionId, - }); + const available = await client.call('get_available_databases', {connectionId}); // The primary database must exist while this connection is open: if // the server list doesn't include it, the list is unreliable (e.g. // filtered by privileges) and pruning from it would drop valid @@ -1468,15 +1510,17 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (removed.length > 0) { dbList = selection; isMultiDb = selection.length >= 1; - invoke('set_selected_databases', { - connectionId, - databases: selection, - }).catch((e) => - console.error( - 'Failed to persist reconciled database selection:', - e, - ), - ); + client + .call('set_selected_databases', { + connectionId, + databases: selection, + }) + .catch((e) => + console.error( + 'Failed to persist reconciled database selection:', + e, + ), + ); showToast( t('sidebar.droppedDatabasesRemoved', {names: removed.join(', ')}), { @@ -1484,10 +1528,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { kind: 'warning', }, ); - invoke('log_frontend_event', { - level: 'warn', - message: `Connection "${conn.name}": removed ${removed.join(', ')} from the database selection (no longer on the server)`, - }).catch(() => {}); + client + .call('log_frontend_event', { + level: 'warn', + message: `Connection "${conn.name}": removed ${removed.join(', ')} from the database selection (no longer on the server)`, + }) + .catch(() => {}); } } else { console.warn( @@ -1515,20 +1561,17 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { try { const [tablesResult, viewsResult, routineMetadata, triggersResult] = await Promise.all([ - invoke('get_tables', {connectionId, schema: firstDb}), + client.call('get_tables', {connectionId, schema: firstDb}), loadOptionalMetadata( metadata?.capabilities.views, - () => - invoke('get_views', { - connectionId, - schema: firstDb, - }), + () => client.call('get_views', {connectionId, schema: firstDb}), [] as ViewInfo[], ), loadOptionalMetadata( metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connectionId, firstDb, handleRoutineMetadataError, @@ -1538,10 +1581,9 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId, - schema: firstDb, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', {connectionId, schema: firstDb}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -1590,14 +1632,14 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (firstDb) { try { - const schemasResult = await invoke('get_schemas', { + const schemasResult = await client.call('get_schemas', { connectionId, database: firstDb, }); let savedSelection: string[] = []; try { - savedSelection = await invoke('get_selected_schemas', { + savedSelection = await client.call('get_selected_schemas', { connectionId, database: firstDb, }); @@ -1611,7 +1653,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (validSelection.length > 0) { let preferredSchema = validSelection[0]; try { - const saved = await invoke('get_schema_preference', { + const saved = await client.call('get_schema_preference', { connectionId, database: firstDb, }); @@ -1629,7 +1671,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', { + client.call('get_tables', { connectionId, schema: preferredSchema, database: firstDb, @@ -1637,7 +1679,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( metadata?.capabilities.views, () => - invoke('get_views', { + client.call('get_views', { connectionId, schema: preferredSchema, database: firstDb, @@ -1645,16 +1687,19 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { [] as ViewInfo[], ), capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId, - schema: preferredSchema, - database: firstDb, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', { + connectionId, + schema: preferredSchema, + database: firstDb, + }) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connectionId, preferredSchema, handleRoutineMetadataError, @@ -1665,11 +1710,13 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId, - schema: preferredSchema, - database: firstDb, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', { + connectionId, + schema: preferredSchema, + database: firstDb, + }) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -1730,14 +1777,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { updateCurrentConnection(connectionId, {isLoadingSchemas: true}); try { - const schemasResult = await invoke('get_schemas', {connectionId}); + const schemasResult = await client.call('get_schemas', {connectionId}); updateCurrentConnection(connectionId, {schemas: schemasResult}); let savedSelection: string[] = []; try { - savedSelection = await invoke('get_selected_schemas', { - connectionId, - }); + savedSelection = await client.call('get_selected_schemas', {connectionId}); } catch { // Ignore - no saved selection exists yet } @@ -1747,7 +1792,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { if (validSelection.length > 0) { let preferredSchema = validSelection[0]; try { - const saved = await invoke('get_schema_preference', { + const saved = await client.call('get_schema_preference', { connectionId, }); if (saved && validSelection.includes(saved)) { @@ -1764,29 +1809,29 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { routineMetadata, triggersResult, ] = await Promise.all([ - invoke('get_tables', { - connectionId, - schema: preferredSchema, - }), + client.call('get_tables', {connectionId, schema: preferredSchema}), loadOptionalMetadata( metadata?.capabilities.views, () => - invoke('get_views', { + client.call('get_views', { connectionId, schema: preferredSchema, }), [] as ViewInfo[], ), capabilities?.materialized_views - ? invoke('get_materialized_views', { - connectionId, - schema: preferredSchema, - }).catch(() => [] as ViewInfo[]) + ? client + .call('get_materialized_views', { + connectionId, + schema: preferredSchema, + }) + .catch(() => [] as ViewInfo[]) : Promise.resolve([] as ViewInfo[]), loadOptionalMetadata( metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connectionId, preferredSchema, handleRoutineMetadataError, @@ -1796,10 +1841,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( metadata?.capabilities.triggers, () => - invoke('get_triggers', { - connectionId, - schema: preferredSchema, - }).catch(() => [] as TriggerInfo[]), + client + .call('get_triggers', { + connectionId, + schema: preferredSchema, + }) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -1859,16 +1906,17 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } else { const [tablesResult, viewsResult, routineMetadata, triggersResult] = await Promise.all([ - invoke('get_tables', {connectionId}), + client.call('get_tables', {connectionId}), loadOptionalMetadata( metadata?.capabilities.views, - () => invoke('get_views', {connectionId}), + () => client.call('get_views', {connectionId}), [] as ViewInfo[], ), loadOptionalMetadata( metadata?.capabilities.routines, () => getRoutinesOrEmpty( + client, connectionId, undefined, handleRoutineMetadataError, @@ -1878,9 +1926,9 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { loadOptionalMetadata( metadata?.capabilities.triggers, () => - invoke('get_triggers', {connectionId}).catch( - () => [] as TriggerInfo[], - ), + client + .call('get_triggers', {connectionId}) + .catch(() => [] as TriggerInfo[]), [] as TriggerInfo[], ), ]); @@ -1925,7 +1973,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { clearAutocompleteCache(targetId); try { - await invoke('disconnect_connection', {connectionId: targetId}); + await client.call('disconnect_connection', {connectionId: targetId}); } catch (error) { console.error(`[DatabaseProvider] Failed to disconnect from ${targetId}:`, error); } @@ -1944,7 +1992,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // the empty list to protect the startup state) — otherwise disconnecting the // last connection would leave it in `last_open_connection_ids` and the app // would auto-reconnect it (and restore its tabs) on next launch. - invoke('set_last_open_connections', {connectionIds: remainingIds}).catch(() => {}); + client.call('set_last_open_connections', {connectionIds: remainingIds}).catch(() => {}); if (activeConnectionId === targetId) { if (remainingIds.length > 0) { @@ -1952,7 +2000,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { } else { setActiveConnectionId(null); setActiveTable(null); - invoke('set_last_active_connection', {connectionId: null}).catch(() => {}); + client.call('set_last_active_connection', {connectionId: null}).catch(() => {}); } } }; @@ -1995,40 +2043,43 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { setActiveTable(table); if (schema !== undefined && schema !== null && activeConnectionId) { updateConnectionData(activeConnectionId, {activeSchema: schema}); - invoke('set_schema_preference', {connectionId: activeConnectionId, schema}).catch( - () => {}, - ); + client + .call('set_schema_preference', {connectionId: activeConnectionId, schema}) + .catch(() => {}); } }, - [activeConnectionId, updateConnectionData], + [client, activeConnectionId, updateConnectionData], ); - const loadConnections = useCallback((options?: {ifNeeded?: boolean}) => { - if (options?.ifNeeded) { - if (connectionsLoadRef.current) return connectionsLoadRef.current; - if (connectionsLoadedRef.current) return Promise.resolve(); - } - const version = ++connectionsLoadVersionRef.current; - connectionsLoadRef.current = (async () => { - setIsLoadingConnections(true); - try { - const result = await invoke('get_connections_with_groups'); - if (version === connectionsLoadVersionRef.current) { - setConnections(result.connections); - setConnectionGroups(result.groups); - connectionsLoadedRef.current = true; - } - } catch (e) { - console.error('Failed to load connections:', e); - } finally { - if (version === connectionsLoadVersionRef.current) { - setIsLoadingConnections(false); - connectionsLoadRef.current = null; - } + const loadConnections = useCallback( + (options?: {ifNeeded?: boolean}) => { + if (options?.ifNeeded) { + if (connectionsLoadRef.current) return connectionsLoadRef.current; + if (connectionsLoadedRef.current) return Promise.resolve(); } - })(); - return connectionsLoadRef.current; - }, []); + const version = ++connectionsLoadVersionRef.current; + connectionsLoadRef.current = (async () => { + setIsLoadingConnections(true); + try { + const result = await client.call('get_connections_with_groups', undefined); + if (version === connectionsLoadVersionRef.current) { + setConnections(result.connections); + setConnectionGroups(result.groups); + connectionsLoadedRef.current = true; + } + } catch (e) { + console.error('Failed to load connections:', e); + } finally { + if (version === connectionsLoadVersionRef.current) { + setIsLoadingConnections(false); + connectionsLoadRef.current = null; + } + } + })(); + return connectionsLoadRef.current; + }, + [client], + ); const getConnectionData = useCallback( (connectionId: string): ConnectionData | undefined => { @@ -2083,8 +2134,10 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // the value before the startup auto-connect gets a chance to read it. useEffect(() => { if (!activeConnectionId) return; - invoke('set_last_active_connection', {connectionId: activeConnectionId}).catch(() => {}); - }, [activeConnectionId]); + client + .call('set_last_active_connection', {connectionId: activeConnectionId}) + .catch(() => {}); + }, [activeConnectionId, client]); // Persist the full set of open connections so the app can reopen all of them // on next launch. Skip the empty startup state so the saved list isn't wiped @@ -2100,96 +2153,89 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // longer needs to chase the empty state for correctness.) useEffect(() => { if (openConnectionIds.length === 0) return; - invoke('set_last_open_connections', {connectionIds: openConnectionIds}).catch(() => {}); - }, [openConnectionIds]); + client + .call('set_last_open_connections', {connectionIds: openConnectionIds}) + .catch(() => {}); + }, [client, openConnectionIds]); // Invalidate open dynamic contexts when their saved parameters or plugin change. useEffect(() => { - const unlisten = listen<{connectionId?: string; driverId?: string}>( - 'connection-metadata-invalidated', - ({payload}) => { - const ids = Object.entries(connectionDataMapRef.current) - .filter( - ([id, data]) => - data.usesConnectionMetadata && - (id === payload.connectionId || data.driver === payload.driverId), - ) - .map(([id]) => id); - if (ids.length === 0) return; - for (const id of ids) { - connectionAttemptsRef.current.delete(id); - clearAutocompleteCache(id); - void invoke('disconnect_connection', {connectionId: id}).catch((error) => { - console.error('Failed to release invalidated connection:', error); - }); - } - setOpenConnectionIds((previous) => previous.filter((id) => !ids.includes(id))); - setConnectionDataMap((previous) => - Object.fromEntries( - Object.entries(previous).filter(([id]) => !ids.includes(id)), - ), - ); - setActiveConnectionId((previous) => - previous && ids.includes(previous) - ? (openConnectionIdsRef.current.find((id) => !ids.includes(id)) ?? null) - : previous, - ); - }, - ); + const unlisten = client.subscribe('connection-metadata-invalidated', (payload) => { + const ids = Object.entries(connectionDataMapRef.current) + .filter( + ([id, data]) => + data.usesConnectionMetadata && + (id === payload.connectionId || data.driver === payload.driverId), + ) + .map(([id]) => id); + if (ids.length === 0) return; + for (const id of ids) { + connectionAttemptsRef.current.delete(id); + clearAutocompleteCache(id); + void client.call('disconnect_connection', {connectionId: id}).catch((error) => { + console.error('Failed to release invalidated connection:', error); + }); + } + setOpenConnectionIds((previous) => previous.filter((id) => !ids.includes(id))); + setConnectionDataMap((previous) => + Object.fromEntries(Object.entries(previous).filter(([id]) => !ids.includes(id))), + ); + setActiveConnectionId((previous) => + previous && ids.includes(previous) + ? (openConnectionIdsRef.current.find((id) => !ids.includes(id)) ?? null) + : previous, + ); + }); return () => { unlisten.then((fn) => fn()); }; - }, []); + }, [client]); // Listen for backend health-check failures and clean up dead connections. useEffect(() => { - const unlisten = listen<{connectionId: string; error: string}>( - 'connection-health-failed', - (event) => { - const {connectionId} = event.payload; - connectionAttemptsRef.current.delete(connectionId); - console.warn( - `[DatabaseProvider] Connection health check failed for ${connectionId}: ${event.payload.error}`, - ); + const unlisten = client.subscribe('connection-health-failed', (payload) => { + const {connectionId} = payload; + connectionAttemptsRef.current.delete(connectionId); + console.warn( + `[DatabaseProvider] Connection health check failed for ${connectionId}: ${payload.error}`, + ); - clearAutocompleteCache(connectionId); + clearAutocompleteCache(connectionId); - setOpenConnectionIds((prev) => prev.filter((id) => id !== connectionId)); - setConnectionDataMap((prev) => { - const next = {...prev}; - delete next[connectionId]; - return next; - }); + setOpenConnectionIds((prev) => prev.filter((id) => id !== connectionId)); + setConnectionDataMap((prev) => { + const next = {...prev}; + delete next[connectionId]; + return next; + }); - setActiveConnectionId((prev) => { - if (prev !== connectionId) return prev; - const remaining = openConnectionIdsRef.current.filter( - (id) => id !== connectionId, - ); - if (remaining.length > 0) return remaining[0]; - setActiveTable(null); - return null; - }); - }, - ); + setActiveConnectionId((prev) => { + if (prev !== connectionId) return prev; + const remaining = openConnectionIdsRef.current.filter((id) => id !== connectionId); + if (remaining.length > 0) return remaining[0]; + setActiveTable(null); + return null; + }); + }); return () => { unlisten.then((fn) => fn()); }; - }, []); + }, [client]); // Track the set of connections open anywhere (across all windows). Seed from // the backend snapshot, then keep in sync via the broadcast event. useEffect(() => { - invoke('get_active_connections') + client + .call('get_active_connections', undefined) .then(setGloballyOpenConnectionIds) .catch(() => {}); - const unlisten = listen('connections:active-changed', (event) => { - setGloballyOpenConnectionIds(event.payload); + const unlisten = client.subscribe('connections:active-changed', (payload) => { + setGloballyOpenConnectionIds(payload); }); return () => { unlisten.then((fn) => fn()); }; - }, []); + }, [client]); // A `DROP DATABASE` that succeeded inside the app leaves the stored selection // stale; the backend now says so instead of making the user press refresh @@ -2203,19 +2249,21 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // close with their connection. Other windows pick the change up on their next // refresh. useEffect(() => { - if (getCurrentWindow().label !== MAIN_WINDOW_LABEL) return; - const unlisten = listen<{connectionId: string; database: string}>( - 'database-dropped', - (event) => { - void refreshDatabaseSelectionRef.current(event.payload.connectionId, { - notifyWhenUnchanged: false, - }); - }, - ); + if ( + detectPlatformEnvironment() === 'tauri' && + getCurrentWindow().label !== MAIN_WINDOW_LABEL + ) { + return; + } + const unlisten = client.subscribe('database-dropped', (payload) => { + void refreshDatabaseSelectionRef.current(payload.connectionId, { + notifyWhenUnchanged: false, + }); + }); return () => { unlisten.then((fn) => fn()); }; - }, []); + }, [client]); // Connection Group methods const createGroup = useCallback( @@ -2225,29 +2273,29 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { // and the Rust deserializer maps it to `None`. Passing `undefined` // would also work because serde's default attribute treats it the // same, but we normalise to `null` for explicitness. - const group = await invoke('create_connection_group', { + const group = await client.call('create_connection_group', { name, parentId: parentId ?? null, }); setConnectionGroups((prev) => [...prev, group]); return group; }, - [], + [client], ); const createGroupPath = useCallback( async (path: string, parentId?: string | null): Promise => { - const group = await invoke('create_group_path', { + const group = await client.call('create_group_path', { path, parentId: parentId ?? null, }); // Re-fetch the full group list because the backend may have reused // existing segments and created new ones we don't yet know about. - const fresh = await invoke('get_connection_groups'); + const fresh = await client.call('get_connection_groups', undefined); setConnectionGroups(fresh); return group; }, - [], + [client], ); const updateGroup = useCallback( @@ -2255,38 +2303,46 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { id: string, updates: {name?: string; collapsed?: boolean; sort_order?: number}, ): Promise => { - await invoke('update_connection_group', {id, ...updates}); + await client.call('update_connection_group', { + id, + name: updates.name, + collapsed: updates.collapsed, + sortOrder: updates.sort_order, + }); setConnectionGroups((prev) => prev.map((g) => (g.id === id ? {...g, ...updates} : g))); }, - [], + [client], ); const moveGroupToParent = useCallback( async (id: string, parentId: string | null): Promise => { - await invoke('move_group_to_parent', {id, parentId}); + await client.call('move_group_to_parent', {id, parentId}); setConnectionGroups((prev) => prev.map((g) => (g.id === id ? {...g, parent_id: parentId} : g)), ); }, - [], + [client], ); - const deleteGroup = useCallback(async (id: string): Promise => { - // The backend cascade-deletes the target group, every nested child - // group, and all connections belonging to any group in that subtree. - // Re-load from the backend instead of mirroring the cascade in - // optimistic state — this keeps the optimistic update trivial and - // guarantees the UI matches the persisted file even if the cascade - // behaviour evolves. - await invoke('delete_connection_group', {id}); - const fresh = await invoke('get_connections_with_groups'); - setConnections(fresh.connections); - setConnectionGroups(fresh.groups); - }, []); + const deleteGroup = useCallback( + async (id: string): Promise => { + // The backend cascade-deletes the target group, every nested child + // group, and all connections belonging to any group in that subtree. + // Re-load from the backend instead of mirroring the cascade in + // optimistic state — this keeps the optimistic update trivial and + // guarantees the UI matches the persisted file even if the cascade + // behaviour evolves. + await client.call('delete_connection_group', {id}); + const fresh = await client.call('get_connections_with_groups', undefined); + setConnections(fresh.connections); + setConnectionGroups(fresh.groups); + }, + [client], + ); const moveConnectionToGroup = useCallback( async (connectionId: string, groupId: string | null, sortOrder?: number): Promise => { - await invoke('move_connection_to_group', {connectionId, groupId, sortOrder}); + await client.call('move_connection_to_group', {connectionId, groupId, sortOrder}); setConnections((prev) => prev.map((c) => c.id === connectionId @@ -2299,12 +2355,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { ), ); }, - [], + [client], ); const reorderGroups = useCallback( async (groupOrders: Array<[string, number]>): Promise => { - await invoke('reorder_groups', {groupOrders}); + await client.call('reorder_groups', {groupOrders}); setConnectionGroups((prev) => { const orderMap = new Map(groupOrders); return prev @@ -2315,12 +2371,12 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { .sort((a, b) => a.sort_order - b.sort_order); }); }, - [], + [client], ); const reorderConnectionsInGroup = useCallback( async (connectionOrders: Array<[string, number]>): Promise => { - await invoke('reorder_connections_in_group', {connectionOrders}); + await client.call('reorder_connections_in_group', {connectionOrders}); setConnections((prev) => { const orderMap = new Map(connectionOrders); return prev.map((c) => ({ @@ -2329,7 +2385,7 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { })); }); }, - [], + [client], ); const toggleGroupCollapsed = useCallback( diff --git a/src/contexts/EditorContext.ts b/packages/web-ui/src/contexts/EditorContext.ts similarity index 100% rename from src/contexts/EditorContext.ts rename to packages/web-ui/src/contexts/EditorContext.ts diff --git a/src/contexts/EditorProvider.tsx b/packages/web-ui/src/contexts/EditorProvider.tsx similarity index 96% rename from src/contexts/EditorProvider.tsx rename to packages/web-ui/src/contexts/EditorProvider.tsx index 821d8c504..9d3f7a075 100644 --- a/src/contexts/EditorProvider.tsx +++ b/packages/web-ui/src/contexts/EditorProvider.tsx @@ -3,7 +3,7 @@ import type {ReactNode} from 'react'; import type {Tab, SchemaCache, TableSchema, QueryResultEntry} from '@/types/editor'; import {EditorContext, type AddTabOptions} from './EditorContext'; import {useDatabase} from '@/hooks/useDatabase'; -import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import { generateTabId, loadEditorPreferences, @@ -35,6 +35,7 @@ import { import {createNotebookFromState, evictFromCache, flushAllPendingSaves} from '@/utils/notebookStore'; export const EditorProvider = ({children}: {children: ReactNode}) => { + const client = useTabularisClient(); const {activeConnectionId} = useDatabase(); const [tabs, setTabs] = useState([]); const [activeTabIds, setActiveTabIds] = useState>({}); @@ -138,14 +139,16 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { const open = new Set(tabs.map((t) => t.id)); for (const tab of previous) { if (open.has(tab.id)) continue; - void invoke('release_query_session', { - connectionId: tab.connectionId, - sessionId: tab.id, - }).catch(() => { - // The tab is already gone; nothing useful to surface. - }); + void client + .call('release_query_session', { + connectionId: tab.connectionId, + sessionId: tab.id, + }) + .catch(() => { + // The tab is already gone; nothing useful to surface. + }); } - }, [tabs, activeConnectionId]); + }, [tabs, activeConnectionId, client]); // Load tabs from file storage when connection changes useEffect(() => { @@ -167,7 +170,7 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { setIsLoading(true); try { const {tabs: loadedTabs, activeTabId: loadedActiveTabId} = - await loadEditorPreferences(activeConnectionId); + await loadEditorPreferences(client, activeConnectionId); // Migrate old notebook tabs: notebookState → notebookId for (const tab of loadedTabs) { @@ -177,6 +180,7 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { tab.title, tab.notebookState, activeConnectionId, + client, ); tab.notebookId = notebookId; tab.notebookState = undefined; @@ -232,7 +236,7 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { }; loadPreferences(); - }, [activeConnectionId]); + }, [activeConnectionId, client]); const createInitialTab = useCallback( (partial?: Partial): Tab => { @@ -257,8 +261,8 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { const connectionTabs = tabs.filter((t) => t.connectionId === activeConnectionId); const activeTabId = activeTabIds[activeConnectionId] || null; - saveTabsToStorage(activeConnectionId, connectionTabs, activeTabId); - }, [tabs, activeTabIds, activeConnectionId, isLoading]); + saveTabsToStorage(client, activeConnectionId, connectionTabs, activeTabId); + }, [client, tabs, activeTabIds, activeConnectionId, isLoading]); const activeTabId = activeConnectionId ? activeTabIds[activeConnectionId] || null : null; @@ -547,7 +551,7 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { return cached!.data; } - const data = await invoke('get_schema_snapshot', { + const data = await client.call('get_schema_snapshot', { connectionId, ...(schema ? {schema} : {}), ...(database ? {database} : {}), @@ -561,8 +565,8 @@ export const EditorProvider = ({children}: {children: ReactNode}) => { return data; }, - [], - ); // No dependencies - stable function + [client], + ); const activeTab = useMemo(() => { return getActiveTab(tabs, activeConnectionId, activeTabId); diff --git a/src/contexts/KeybindingsContext.ts b/packages/web-ui/src/contexts/KeybindingsContext.ts similarity index 100% rename from src/contexts/KeybindingsContext.ts rename to packages/web-ui/src/contexts/KeybindingsContext.ts diff --git a/src/contexts/KeybindingsProvider.tsx b/packages/web-ui/src/contexts/KeybindingsProvider.tsx similarity index 86% rename from src/contexts/KeybindingsProvider.tsx rename to packages/web-ui/src/contexts/KeybindingsProvider.tsx index 38bad3536..4922a9ada 100644 --- a/src/contexts/KeybindingsProvider.tsx +++ b/packages/web-ui/src/contexts/KeybindingsProvider.tsx @@ -1,5 +1,4 @@ import {useState, useEffect, useCallback, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import shortcutDefs from '@/config/shortcuts.json'; import { mergeShortcuts, @@ -10,21 +9,24 @@ import { type KeyMatch, } from '@/utils/keybindings'; import {KeybindingsContext} from './KeybindingsContext'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().includes('MAC'); export const KeybindingsProvider = ({children}: {children: ReactNode}) => { + const client = useTabularisClient(); const [overrides, setOverrides] = useState({}); useEffect(() => { - invoke('get_keybindings') + client + .call('get_keybindings', undefined) .then((data) => { - if (data && typeof data === 'object') setOverrides(data as UserOverrides); + if (data && typeof data === 'object') setOverrides(data); }) .catch(() => { // no keybindings file yet — use defaults }); - }, []); + }, [client]); const shortcuts = mergeShortcuts(shortcutDefs as ShortcutDef[], overrides, isMac); @@ -49,13 +51,13 @@ export const KeybindingsProvider = ({children}: {children: ReactNode}) => { const next = {...overrides, [id]: {mac, win}}; setOverrides(next); try { - await invoke('save_keybindings', {keybindings: next}); + await client.call('save_keybindings', {keybindings: next}); } catch (error) { setOverrides((current) => (current === next ? overrides : current)); throw error; } }, - [overrides], + [client, overrides], ); const resetOverride = useCallback( @@ -64,13 +66,13 @@ export const KeybindingsProvider = ({children}: {children: ReactNode}) => { delete next[id]; setOverrides(next); try { - await invoke('save_keybindings', {keybindings: next}); + await client.call('save_keybindings', {keybindings: next}); } catch (error) { setOverrides((current) => (current === next ? overrides : current)); throw error; } }, - [overrides], + [client, overrides], ); return ( diff --git a/packages/web-ui/src/contexts/PlatformCapabilitiesContext.ts b/packages/web-ui/src/contexts/PlatformCapabilitiesContext.ts new file mode 100644 index 000000000..44b29d6f3 --- /dev/null +++ b/packages/web-ui/src/contexts/PlatformCapabilitiesContext.ts @@ -0,0 +1,4 @@ +import {createContext} from 'react'; +import type {PlatformCapabilities} from '@/platform/capabilities'; + +export const PlatformCapabilitiesContext = createContext(null); diff --git a/packages/web-ui/src/contexts/PlatformCapabilitiesProvider.tsx b/packages/web-ui/src/contexts/PlatformCapabilitiesProvider.tsx new file mode 100644 index 000000000..ea58a8a32 --- /dev/null +++ b/packages/web-ui/src/contexts/PlatformCapabilitiesProvider.tsx @@ -0,0 +1,19 @@ +import type {ReactNode} from 'react'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {PlatformCapabilitiesContext} from './PlatformCapabilitiesContext'; + +interface PlatformCapabilitiesProviderProps { + children: ReactNode; + capabilities: PlatformCapabilities; +} + +export function PlatformCapabilitiesProvider({ + children, + capabilities, +}: PlatformCapabilitiesProviderProps) { + return ( + + {children} + + ); +} diff --git a/src/contexts/PluginModalContext.ts b/packages/web-ui/src/contexts/PluginModalContext.ts similarity index 100% rename from src/contexts/PluginModalContext.ts rename to packages/web-ui/src/contexts/PluginModalContext.ts diff --git a/src/contexts/PluginModalProvider.tsx b/packages/web-ui/src/contexts/PluginModalProvider.tsx similarity index 100% rename from src/contexts/PluginModalProvider.tsx rename to packages/web-ui/src/contexts/PluginModalProvider.tsx diff --git a/src/contexts/PluginRegistryContext.ts b/packages/web-ui/src/contexts/PluginRegistryContext.ts similarity index 100% rename from src/contexts/PluginRegistryContext.ts rename to packages/web-ui/src/contexts/PluginRegistryContext.ts diff --git a/src/contexts/PluginRegistryProvider.tsx b/packages/web-ui/src/contexts/PluginRegistryProvider.tsx similarity index 83% rename from src/contexts/PluginRegistryProvider.tsx rename to packages/web-ui/src/contexts/PluginRegistryProvider.tsx index 4c19b281e..1eca1e0a2 100644 --- a/src/contexts/PluginRegistryProvider.tsx +++ b/packages/web-ui/src/contexts/PluginRegistryProvider.tsx @@ -1,8 +1,7 @@ import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import {PluginRegistryContext} from './PluginRegistryContext'; import {useSettings} from '@/hooks/useSettings'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import type {RegistryPluginWithStatus} from '@/types/plugins'; import {toErrorMessage} from '@/utils/errors'; import {getPluginUpdates} from '@/utils/pluginUpdates'; @@ -10,6 +9,7 @@ import {APP_VERSION} from '@/version'; export function PluginRegistryProvider({children}: {children: ReactNode}) { const {settings, isLoading: settingsLoading} = useSettings(); + const client = useTabularisClient(); const [plugins, setPlugins] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -23,7 +23,7 @@ export function PluginRegistryProvider({children}: {children: ReactNode}) { setLoading(true); setError(null); try { - const result = await invoke('fetch_plugin_registry'); + const result = await client.call('fetch_plugin_registry', undefined); if (request === requestId.current) setPlugins(result); } catch (err) { if (request === requestId.current) setError(toErrorMessage(err)); @@ -31,7 +31,7 @@ export function PluginRegistryProvider({children}: {children: ReactNode}) { if (request === requestId.current) setLoading(false); } }); - }, []); + }, [client]); useEffect(() => { if (settingsLoading) return; @@ -43,11 +43,12 @@ export function PluginRegistryProvider({children}: {children: ReactNode}) { useEffect(() => { let mounted = true; - const subscriptions = ['tabularis://plugin-installed', 'tabularis://plugin-activated'].map( - (event) => - listen(event, () => { - if (mounted) refresh(); - }), + const subscriptions = ( + ['tabularis://plugin-installed', 'tabularis://plugin-activated'] as const + ).map((event) => + client.subscribe(event, () => { + if (mounted) refresh(); + }), ); for (const subscription of subscriptions) { void subscription.catch((err) => @@ -60,7 +61,7 @@ export function PluginRegistryProvider({children}: {children: ReactNode}) { void subscription.then((unlisten) => unlisten()).catch(() => {}); } }; - }, [refresh]); + }, [client, refresh]); const updates = useMemo(() => getPluginUpdates(plugins, APP_VERSION), [plugins]); const value = useMemo( diff --git a/src/contexts/PluginSlotContext.ts b/packages/web-ui/src/contexts/PluginSlotContext.ts similarity index 100% rename from src/contexts/PluginSlotContext.ts rename to packages/web-ui/src/contexts/PluginSlotContext.ts diff --git a/src/contexts/PluginSlotProvider.tsx b/packages/web-ui/src/contexts/PluginSlotProvider.tsx similarity index 87% rename from src/contexts/PluginSlotProvider.tsx rename to packages/web-ui/src/contexts/PluginSlotProvider.tsx index 65c780d25..2ecb42af3 100644 --- a/src/contexts/PluginSlotProvider.tsx +++ b/packages/web-ui/src/contexts/PluginSlotProvider.tsx @@ -1,7 +1,6 @@ import {useState, useCallback, useMemo, useEffect, useRef} from 'react'; import * as React from 'react'; import * as ReactJSXRuntime from 'react/jsx-runtime'; -import {invoke} from '@tauri-apps/api/core'; import * as explainApi from '@tabularis/explain'; import i18n from 'i18next'; @@ -10,8 +9,12 @@ import type {PluginSlotRegistryType} from './PluginSlotContext'; import type {SlotContribution, SlotName, SlotContext} from '@/types/pluginSlots'; import {VALID_SLOTS} from '@/types/pluginSlots'; import type {PluginManifest} from '@/types/plugins'; +import type {TabularisClient} from '@/api/client'; import * as pluginApi from '@/pluginApi'; +import {API_VERSION} from '@/pluginApiVersion'; +import {isPluginApiCompatible} from '@/utils/pluginApiCompatibility'; import {useSettings} from '@/hooks/useSettings'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {loadPluginExplainParsers} from '@/utils/pluginExplainLoader'; interface PluginSlotProviderProps { @@ -22,12 +25,6 @@ interface PluginSlotProviderProps { * Expose host globals so external plugin bundles (IIFE format) can access * React and the Tabularis plugin API without bundling their own copies. */ -/** - * Keep in sync with `packages/plugin-api/src/version.ts` (API_VERSION). - * Bump when the host API shape changes in a way plugin bundles can observe. - */ -const HOST_API_VERSION = '0.1.1'; - let globalsExposed = false; function exposePluginGlobals() { if (globalsExposed) return; @@ -35,7 +32,7 @@ function exposePluginGlobals() { (window as unknown as Record).React = React; (window as unknown as Record).ReactJSXRuntime = ReactJSXRuntime; (window as unknown as Record).__TABULARIS_API__ = pluginApi; - (window as unknown as Record).__TABULARIS_API_VERSION__ = HOST_API_VERSION; + (window as unknown as Record).__TABULARIS_API_VERSION__ = API_VERSION; (window as unknown as Record).__TABULARIS_EXPLAIN__ = explainApi; } @@ -45,17 +42,14 @@ function exposePluginGlobals() { * Missing locale files are silently skipped. * Each plugin's translations are registered under its own namespace (plugin id). */ -async function loadPluginTranslations(pluginId: string): Promise { +async function loadPluginTranslations(client: TabularisClient, pluginId: string): Promise { const langs = Array.from(new Set([i18n.language?.split('-')[0], 'en'])).filter( Boolean, ) as string[]; for (const lang of langs) { if (i18n.hasResourceBundle(lang, pluginId)) continue; try { - const raw = await invoke('read_plugin_file', { - pluginId, - filePath: `locales/${lang}.json`, - }); + const raw = await client.readPluginAsset(pluginId, `locales/${lang}.json`); const translations = JSON.parse(raw) as Record; i18n.addResourceBundle(lang, pluginId, translations, true, true); } catch { @@ -74,6 +68,7 @@ async function loadPluginTranslations(pluginId: string): Promise { * '@tabularis/plugin-api': '__TABULARIS_API__' } */ async function loadExternalPluginContributions( + client: TabularisClient, manifest: PluginManifest, ): Promise { if (!manifest.ui_extensions?.length) return []; @@ -83,6 +78,12 @@ async function loadExternalPluginContributions( // Group entries by module path to load each bundle once. const byModule = new Map(); for (const entry of manifest.ui_extensions) { + if (!isPluginApiCompatible(API_VERSION, entry.api_version)) { + console.warn( + `[PluginSlot] Plugin "${manifest.id}" requires incompatible plugin API ${entry.api_version ?? 'unknown'}; host is ${API_VERSION}. Skipping.`, + ); + continue; + } const list = byModule.get(entry.module) ?? []; list.push(entry); byModule.set(entry.module, list); @@ -92,10 +93,7 @@ async function loadExternalPluginContributions( for (const [modulePath, entries] of byModule) { try { - const source = await invoke('read_plugin_file', { - pluginId: manifest.id, - filePath: modulePath, - }); + const source = await client.readPluginAsset(manifest.id, modulePath); // Execute the IIFE, passing React globals as parameters. // The bundle assigns its exports to the local `__tabularis_plugin__` var. @@ -149,6 +147,7 @@ async function loadExternalPluginContributions( } export const PluginSlotProvider = ({children}: PluginSlotProviderProps) => { + const client = useTabularisClient(); const [contributions, setContributions] = useState([]); const {settings} = useSettings(); const activeExternalDrivers = settings.activeExternalDrivers ?? []; @@ -192,13 +191,12 @@ export const PluginSlotProvider = ({children}: PluginSlotProviderProps) => { for (const pluginId of enabledIds) { if (cancelled) break; try { - const manifest = await invoke('get_plugin_manifest', { - pluginId, - }); + const manifest = await client.call('get_plugin_manifest', {pluginId}); exposePluginGlobals(); - await loadPluginTranslations(pluginId); + await loadPluginTranslations(client, pluginId); const parserFormats = await loadPluginExplainParsers( manifest, + (id, assetPath) => client.readPluginAsset(id, assetPath), () => !cancelled, ); if (cancelled) { @@ -210,7 +208,10 @@ export const PluginSlotProvider = ({children}: PluginSlotProviderProps) => { loadedExplainFormats.push(...parserFormats); loadedExplainFormatsRef.current = loadedExplainFormats; - const pluginContributions = await loadExternalPluginContributions(manifest); + const pluginContributions = await loadExternalPluginContributions( + client, + manifest, + ); loadedContributions.push(...pluginContributions); } catch (err) { console.error( @@ -234,7 +235,7 @@ export const PluginSlotProvider = ({children}: PluginSlotProviderProps) => { loadedExplainFormatsRef.current = []; } }; - }, [enabledKey]); + }, [client, enabledKey]); const registerAll = useCallback((newContributions: SlotContribution[]) => { setContributions((prev) => [...prev, ...newContributions]); diff --git a/src/contexts/ProductionGuardContext.tsx b/packages/web-ui/src/contexts/ProductionGuardContext.tsx similarity index 100% rename from src/contexts/ProductionGuardContext.tsx rename to packages/web-ui/src/contexts/ProductionGuardContext.tsx diff --git a/src/contexts/QueryHistoryContext.ts b/packages/web-ui/src/contexts/QueryHistoryContext.ts similarity index 100% rename from src/contexts/QueryHistoryContext.ts rename to packages/web-ui/src/contexts/QueryHistoryContext.ts diff --git a/src/contexts/QueryHistoryProvider.tsx b/packages/web-ui/src/contexts/QueryHistoryProvider.tsx similarity index 53% rename from src/contexts/QueryHistoryProvider.tsx rename to packages/web-ui/src/contexts/QueryHistoryProvider.tsx index 5c4b83444..04e3746ca 100644 --- a/src/contexts/QueryHistoryProvider.tsx +++ b/packages/web-ui/src/contexts/QueryHistoryProvider.tsx @@ -1,11 +1,14 @@ -import {useState, useEffect, useCallback, useRef, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; +import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react'; import {useDatabase} from '@/hooks/useDatabase'; -import {QueryHistoryContext, type QueryHistoryEntry} from './QueryHistoryContext'; -import type {QueryHistoryRecoveryNotice, QueryHistoryResponse} from '@/types/queryHistory'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {QueryHistoryContext, type QueryHistoryEntry} from '@/contexts/QueryHistoryContext'; +import type {QueryHistoryRecoveryNotice} from '@/types/queryHistory'; export const QueryHistoryProvider = ({children}: {children: ReactNode}) => { const {activeConnectionId} = useDatabase(); + const client = useTabularisClient(); + const activeConnectionIdRef = useRef(activeConnectionId); + activeConnectionIdRef.current = activeConnectionId; const [entries, setEntries] = useState([]); const [isLoading, setIsLoading] = useState(false); // Session-only pause toggle: survives opening/closing the history section @@ -26,38 +29,41 @@ export const QueryHistoryProvider = ({children}: {children: ReactNode}) => { }, []); const refreshHistory = useCallback(async () => { - if (!activeConnectionId) { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) { setEntries([]); setRecoveryNotice(null); + setIsLoading(false); return; } setIsLoading(true); try { - const result = await invoke('get_query_history', { - connectionId: activeConnectionId, - }); + const result = await client.call('get_query_history', {connectionId}); + if (activeConnectionIdRef.current !== connectionId) return; setEntries(result.entries); if (result.recoveredBackupPath) { setRecoveryNotice({ - connectionId: activeConnectionId, + connectionId, backupPath: result.recoveredBackupPath, }); } else { - setRecoveryNotice((prev) => - prev && prev.connectionId === activeConnectionId ? prev : null, + setRecoveryNotice((previous) => + previous && previous.connectionId === connectionId ? previous : null, ); } - } catch (e) { - console.error('Failed to load query history:', e); + } catch (error) { + console.error('Failed to load query history:', error); } finally { - setIsLoading(false); + if (activeConnectionIdRef.current === connectionId) { + setIsLoading(false); + } } - }, [activeConnectionId]); + }, [client]); useEffect(() => { - refreshHistory(); - }, [refreshHistory]); + void refreshHistory(); + }, [activeConnectionId, refreshHistory]); const addEntry = useCallback( async ( @@ -68,10 +74,11 @@ export const QueryHistoryProvider = ({children}: {children: ReactNode}) => { error: string | null, database?: string | null, ) => { - if (!activeConnectionId || isPausedRef.current) return; + const connectionId = activeConnectionId; + if (!connectionId || isPausedRef.current) return; try { - const entry = await invoke('add_query_history_entry', { - connectionId: activeConnectionId, + const entry = await client.call('add_query_history_entry', { + connectionId, sql, executedAt: new Date().toISOString(), executionTimeMs, @@ -80,43 +87,45 @@ export const QueryHistoryProvider = ({children}: {children: ReactNode}) => { error, database: database ?? null, }); - setEntries((prev) => { - if (prev.length > 0 && prev[0].id === entry.id) { - return [entry, ...prev.slice(1)]; + if (activeConnectionIdRef.current !== connectionId) return; + setEntries((previous) => { + if (previous.length > 0 && previous[0].id === entry.id) { + return [entry, ...previous.slice(1)]; } - return [entry, ...prev]; + return [entry, ...previous]; }); - } catch (e) { - console.error('Failed to add query history entry:', e); + } catch (caught) { + console.error('Failed to add query history entry:', caught); } }, - [activeConnectionId], + [activeConnectionId, client], ); const deleteEntry = async (id: string) => { - if (!activeConnectionId) return; + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; try { - await invoke('delete_query_history_entry', { - connectionId: activeConnectionId, - id, - }); - setEntries((prev) => prev.filter((e) => e.id !== id)); - } catch (e) { - console.error('Failed to delete query history entry:', e); - throw e; + await client.call('delete_query_history_entry', {connectionId, id}); + if (activeConnectionIdRef.current === connectionId) { + setEntries((previous) => previous.filter((entry) => entry.id !== id)); + } + } catch (error) { + console.error('Failed to delete query history entry:', error); + throw error; } }; const clearHistory = async () => { - if (!activeConnectionId) return; + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; try { - await invoke('clear_query_history', { - connectionId: activeConnectionId, - }); - setEntries([]); - } catch (e) { - console.error('Failed to clear query history:', e); - throw e; + await client.call('clear_query_history', {connectionId}); + if (activeConnectionIdRef.current === connectionId) { + setEntries([]); + } + } catch (error) { + console.error('Failed to clear query history:', error); + throw error; } }; diff --git a/src/contexts/RightSidebarContext.ts b/packages/web-ui/src/contexts/RightSidebarContext.ts similarity index 100% rename from src/contexts/RightSidebarContext.ts rename to packages/web-ui/src/contexts/RightSidebarContext.ts diff --git a/src/contexts/RightSidebarProvider.tsx b/packages/web-ui/src/contexts/RightSidebarProvider.tsx similarity index 100% rename from src/contexts/RightSidebarProvider.tsx rename to packages/web-ui/src/contexts/RightSidebarProvider.tsx diff --git a/src/contexts/SavedQueriesContext.ts b/packages/web-ui/src/contexts/SavedQueriesContext.ts similarity index 100% rename from src/contexts/SavedQueriesContext.ts rename to packages/web-ui/src/contexts/SavedQueriesContext.ts diff --git a/packages/web-ui/src/contexts/SavedQueriesProvider.tsx b/packages/web-ui/src/contexts/SavedQueriesProvider.tsx new file mode 100644 index 000000000..706b578d5 --- /dev/null +++ b/packages/web-ui/src/contexts/SavedQueriesProvider.tsx @@ -0,0 +1,149 @@ +import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react'; +import {useDatabase} from '@/hooks/useDatabase'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import { + SavedQueriesContext, + type SavedQuery, + type SavedQueryFolder, +} from '@/contexts/SavedQueriesContext'; + +export const SavedQueriesProvider = ({children}: {children: ReactNode}) => { + const {activeConnectionId} = useDatabase(); + const client = useTabularisClient(); + const activeConnectionIdRef = useRef(activeConnectionId); + activeConnectionIdRef.current = activeConnectionId; + const [queries, setQueries] = useState([]); + const [folders, setFolders] = useState([]); + const [isLoading, setIsLoading] = useState(false); + + const refreshQueries = useCallback(async () => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) { + setQueries([]); + setFolders([]); + setIsLoading(false); + return; + } + + setIsLoading(true); + try { + const [result, folderResult] = await Promise.all([ + client.call('get_saved_queries', {connectionId}), + // Folders are organizational only: if they can't load, queries still show as unfiled. + client.call('get_saved_query_folders', {connectionId}).catch((error: unknown) => { + console.error('Failed to load saved query folders:', error); + return [] as SavedQueryFolder[]; + }), + ]); + if (activeConnectionIdRef.current === connectionId) { + setQueries(result); + setFolders(Array.isArray(folderResult) ? folderResult : []); + } + } catch (error) { + console.error('Failed to load saved queries:', error); + } finally { + if (activeConnectionIdRef.current === connectionId) { + setIsLoading(false); + } + } + }, [client]); + + useEffect(() => { + void refreshQueries(); + }, [activeConnectionId, refreshQueries]); + + const saveQuery = async (name: string, sql: string, database?: string | null) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + try { + await client.call('save_query', { + connectionId, + name, + sql, + database: database ?? null, + }); + await refreshQueries(); + } catch (error) { + console.error('Failed to save query:', error); + throw error; + } + }; + + const updateQuery = async (id: string, name: string, sql: string, database?: string | null) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + try { + await client.call('update_saved_query', { + connectionId, + id, + name, + sql, + database: database ?? null, + }); + await refreshQueries(); + } catch (error) { + console.error('Failed to update query:', error); + throw error; + } + }; + + const deleteQuery = async (id: string) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + try { + await client.call('delete_saved_query', {connectionId, id}); + await refreshQueries(); + } catch (error) { + console.error('Failed to delete query:', error); + throw error; + } + }; + + const createFolder = async (name: string) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + await client.call('create_saved_query_folder', {connectionId, name}); + await refreshQueries(); + }; + + const renameFolder = async (id: string, name: string) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + await client.call('rename_saved_query_folder', {connectionId, id, name}); + await refreshQueries(); + }; + + const deleteFolder = async (id: string) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + await client.call('delete_saved_query_folder', {connectionId, id}); + await refreshQueries(); + }; + + const moveQuery = async (id: string, folderId: string | null) => { + const connectionId = activeConnectionIdRef.current; + if (!connectionId) return; + await client.call('move_saved_query', {connectionId, id, folderId}); + await refreshQueries(); + }; + + return ( + + {children} + + ); +}; diff --git a/src/contexts/SettingsContext.ts b/packages/web-ui/src/contexts/SettingsContext.ts similarity index 100% rename from src/contexts/SettingsContext.ts rename to packages/web-ui/src/contexts/SettingsContext.ts diff --git a/src/contexts/SettingsProvider.tsx b/packages/web-ui/src/contexts/SettingsProvider.tsx similarity index 91% rename from src/contexts/SettingsProvider.tsx rename to packages/web-ui/src/contexts/SettingsProvider.tsx index 0bb189b0a..ec8691a2f 100644 --- a/src/contexts/SettingsProvider.tsx +++ b/packages/web-ui/src/contexts/SettingsProvider.tsx @@ -1,11 +1,10 @@ import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react'; import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import {loadStartupConfig} from '@/utils/startupConfig'; import {detectAiDefaults} from '@/utils/aiDefaults'; import {SettingsContext, DEFAULT_SETTINGS, type Settings} from './SettingsContext'; import {applyResultFontToDocument, stripSessionFields, applyFontToDocument} from '@/utils/settings'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {resolveAutoLanguage} from '@/i18n/language'; const LANGUAGE_APPLICATION_TIMEOUT_MS = 3000; @@ -41,6 +40,7 @@ function matchesAppliedLanguage( export const SettingsProvider = ({children}: {children: ReactNode}) => { const {i18n} = useTranslation(); + const client = useTabularisClient(); const [settings, setSettings] = useState(DEFAULT_SETTINGS); const [isLoading, setIsLoading] = useState(true); const [languageState, setLanguageState] = useState({ @@ -144,7 +144,7 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { const loadSettings = async () => { try { - const config = await loadStartupConfig(); + const config = await loadStartupConfig(client); // Migration logic: Check localStorage if backend is empty/default const savedLocal = localStorage.getItem('tabularis_settings'); @@ -160,7 +160,9 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { }; // Save migrated data to backend. Strip session-persistence fields — // those belong to the DatabaseProvider's own write path. - await invoke('save_config', {config: stripSessionFields(finalSettings)}); + await client.call('save_config', { + config: stripSessionFields(finalSettings), + }); } else { // Use backend config finalSettings = { @@ -204,7 +206,7 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { setSettings(finalSettings); // Discovery can perform network requests. Publish persisted settings first, // and never overwrite a selection made while discovery was in flight. - void detectAiDefaults(finalSettings) + void detectAiDefaults(client, finalSettings) .then((defaults) => { if (!defaults.aiProvider) return; setSettings((current) => { @@ -237,7 +239,7 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { }; loadSettings(); - }, [isLanguageApplied, queueLanguageApplication]); + }, [client, isLanguageApplied, queueLanguageApplication]); // The backend's force-install flow (`ensure_plugin_installed`) can persist // `activeExternalDrivers` from a spawned background task, well after this @@ -251,20 +253,22 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { useEffect(() => { let mounted = true; let cleanup: (() => void) | null = null; - listen('tabularis://plugin-activated', () => { - if (!mounted) return; - invoke>('get_config') - .then((config) => { - if (!mounted) return; - setSettings((prev) => ({ - ...prev, - activeExternalDrivers: config.activeExternalDrivers, - })); - }) - .catch((err) => { - console.error('Failed to refresh settings after plugin activation:', err); - }); - }) + client + .subscribe('tabularis://plugin-activated', () => { + if (!mounted) return; + client + .call('get_config', undefined) + .then((config) => { + if (!mounted) return; + setSettings((prev) => ({ + ...prev, + activeExternalDrivers: config.activeExternalDrivers, + })); + }) + .catch((err) => { + console.error('Failed to refresh settings after plugin activation:', err); + }); + }) .then((unlisten) => { if (mounted) { cleanup = unlisten; @@ -279,7 +283,7 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { mounted = false; cleanup?.(); }; - }, []); + }, [client]); // Update i18n when language changes useEffect(() => { @@ -400,16 +404,16 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => { const newSettings = {...prev, [key]: nextValue}; - // Persist to backend. Strip session-persistence fields — they are - // managed by DatabaseProvider through dedicated backend commands - // (set_last_open_connections, set_last_active_connection); the Rust - // merge treats any Some as authoritative, so forwarding a stale copy - // captured at app start would clobber what the session code wrote. - persistPromise = invoke('save_config', { - config: stripSessionFields(newSettings), - }).catch((err) => { - console.error('Failed to save settings:', err); - }); + // Persist only the changed user preference. Sending the full snapshot + // would let concurrent browser sessions overwrite one another's changes; + // session restore state is owned by DatabaseProvider's dedicated commands. + persistPromise = client + .call('save_config', { + config: stripSessionFields({[key]: nextValue}), + }) + .catch((err) => { + console.error('Failed to save settings:', err); + }); // If font setting changed, update cache immediately if (key === 'fontFamily' || key === 'fontSize') { diff --git a/packages/web-ui/src/contexts/TabularisClientContext.ts b/packages/web-ui/src/contexts/TabularisClientContext.ts new file mode 100644 index 000000000..ed51f1463 --- /dev/null +++ b/packages/web-ui/src/contexts/TabularisClientContext.ts @@ -0,0 +1,4 @@ +import {createContext} from 'react'; +import type {TabularisClient} from '@/api/client'; + +export const TabularisClientContext = createContext(null); diff --git a/packages/web-ui/src/contexts/TabularisClientProvider.tsx b/packages/web-ui/src/contexts/TabularisClientProvider.tsx new file mode 100644 index 000000000..8555bf2a7 --- /dev/null +++ b/packages/web-ui/src/contexts/TabularisClientProvider.tsx @@ -0,0 +1,14 @@ +import type {ReactNode} from 'react'; +import type {TabularisClient} from '@/api/client'; +import {TabularisClientContext} from './TabularisClientContext'; + +interface TabularisClientProviderProps { + children: ReactNode; + client: TabularisClient; +} + +export function TabularisClientProvider({children, client}: TabularisClientProviderProps) { + return ( + {children} + ); +} diff --git a/src/contexts/ThemeContext.ts b/packages/web-ui/src/contexts/ThemeContext.ts similarity index 100% rename from src/contexts/ThemeContext.ts rename to packages/web-ui/src/contexts/ThemeContext.ts diff --git a/src/contexts/ThemeProvider.tsx b/packages/web-ui/src/contexts/ThemeProvider.tsx similarity index 86% rename from src/contexts/ThemeProvider.tsx rename to packages/web-ui/src/contexts/ThemeProvider.tsx index b5bf8819f..8bf87f5dc 100644 --- a/src/contexts/ThemeProvider.tsx +++ b/packages/web-ui/src/contexts/ThemeProvider.tsx @@ -1,7 +1,4 @@ import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; -import {getCurrentWindow} from '@tauri-apps/api/window'; import {loadStartupConfig} from '@/utils/startupConfig'; import {useTranslation} from 'react-i18next'; import {ThemeContext} from './ThemeContext'; @@ -24,12 +21,16 @@ import { type ThemeSettings, type MonacoThemeDefinition, } from '@/types/theme'; -import type {NativeThemeCatalog, NativeThemeContribution} from '@/types/themeCatalog'; +import type {NativeThemeContribution} from '@/types/themeCatalog'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; type SettingsPatch = Partial | ((previous: ThemeSettings) => Partial); export const ThemeProvider = ({children}: {children: ReactNode}) => { const {t} = useTranslation(); + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const [catalog, setCatalog] = useState(builtinCatalog); const [settings, setSettings] = useState(DEFAULT_THEME_SETTINGS); const [systemDark, setSystemDark] = useState(true); @@ -43,26 +44,27 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { const refreshCatalog = useCallback(async () => { const request = ++catalogRequest.current.version; - const native = await invoke('get_theme_catalog'); + const native = await client.call('get_theme_catalog', undefined); const resolved = resolveNativeCatalog(native, catalogRef.current); if (request === catalogRequest.current.version) { catalogRef.current = resolved; setCatalog(resolved); } return resolved; - }, []); + }, [client]); useEffect(() => { let disposed = false; const requests = catalogRequest.current; let stopCatalog: (() => void) | undefined; // Subscribe before reading. Out-of-order reads cannot undo a later refresh. - void listen('theme-catalog-changed', () => { - if (!disposed) - void refreshCatalog().catch((error) => - console.error('Failed to refresh themes:', error), - ); - }) + void client + .subscribe('theme-catalog-changed', () => { + if (!disposed) + void refreshCatalog().catch((error) => + console.error('Failed to refresh themes:', error), + ); + }) .then((stop) => { if (disposed) stop(); else stopCatalog = stop; @@ -70,7 +72,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { .catch((error) => console.error('Failed to subscribe to theme changes:', error)); void (async () => { try { - const startup = Promise.all([loadStartupConfig(), getSystemIsDark()]); + const startup = Promise.all([loadStartupConfig(client), getSystemIsDark()]); const catalogReady = refreshCatalog().catch((error) => console.error('Failed to load theme catalog:', error), ); @@ -106,7 +108,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { ++requests.version; stopCatalog?.(); }; - }, [refreshCatalog]); + }, [client, refreshCatalog]); useEffect(() => { if (!settings.followSystemTheme) return; @@ -138,8 +140,9 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { useEffect(() => { if (isLoading) return; applyThemeToCSS(currentTheme); - getCurrentWindow() - .setTheme( + // Native window chrome only exists in the desktop host; browsers no-op. + platform + .setNativeWindowTheme( settings.followSystemTheme && !preview && !isLinuxDesktop() ? null : themeRegistry.isDarkTheme(currentTheme) @@ -147,7 +150,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { : 'light', ) .catch((error) => console.error('Failed to set window theme:', error)); - }, [currentTheme, isLoading, settings.followSystemTheme, preview]); + }, [currentTheme, isLoading, platform, settings.followSystemTheme, preview]); // Persistence only follows explicit user actions, never hydration, system // changes, preview, package refresh, or missing-package fallback. @@ -163,7 +166,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { ...previous, ...(typeof patch === 'function' ? patch(previous) : patch), }; - await invoke('save_config', { + await client.call('save_config', { config: { theme: merged.activeThemeId, followSystemTheme: merged.followSystemTheme, @@ -186,7 +189,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { saveQueue.current = task; return task; }, - [isLoading], + [client, isLoading], ); const setTheme = useCallback( @@ -261,7 +264,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { ({entry}) => entry.id === themeId && entry.available, ); if (!base) throw new Error('Theme is unavailable'); - const entry = await invoke('duplicate_personal_theme', { + const entry = await client.call('duplicate_personal_theme', { themeId, name: newName, editor: base.entry.format === 'legacy' ? base.resolved.editor : null, @@ -269,7 +272,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { await refreshAfterCommit(); return resolveCatalogEntry(entry).resolved.theme; }, - [refreshAfterCommit], + [client, refreshAfterCommit], ); const createCustomTheme = duplicateTheme; @@ -287,20 +290,21 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { const snapshot = previous.entry.format === 'legacy' && !!previous.entry.editor; if (previous.entry.format !== 'v1' && (!snapshot || !editor)) throw new Error('An independent snapshot requires its exact editor definition'); - const entry = await invoke( - snapshot ? 'update_personal_snapshot' : 'update_personal_theme', - { - themeId, - name, - source, - expectedRevision: expectedRevision ?? previous.entry.revision, - ...(snapshot ? {editor} : {}), - }, - ); + const request = { + themeId, + name, + source, + expectedRevision: expectedRevision ?? previous.entry.revision, + }; + // A snapshot always carries its editor definition (checked above). + const entry = + snapshot && editor + ? await client.call('update_personal_snapshot', {...request, editor}) + : await client.call('update_personal_theme', request); await refreshAfterCommit(); return resolveCatalogEntry(entry).resolved.theme; }, - [refreshAfterCommit], + [client, refreshAfterCommit], ); const updateCustomTheme = useCallback( @@ -315,11 +319,11 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { editThemeDefinition(previous.entry.source, previous.resolved.theme, theme), ); } else { - await invoke('save_custom_theme', {theme}); + await client.call('save_custom_theme', {theme}); await refreshAfterCommit(); } }, - [refreshAfterCommit, updatePersonalSource], + [client, refreshAfterCommit, updatePersonalSource], ); const deleteCustomTheme = useCallback( @@ -327,7 +331,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { const previous = catalogRef.current.themes.find(({entry}) => entry.id === themeId); if (!previous || previous.entry.origin.kind !== 'personal') throw new Error('Cannot delete preset or installed themes'); - await invoke('delete_custom_theme', {themeId}); + await client.call('delete_custom_theme', {themeId}); await refreshAfterCommit(); // Preserve the explicit legacy personal-delete behavior. Package removal // does NOT use this operation and never changes the user's saved choices. @@ -356,7 +360,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { setCatalog(next); } }, - [refreshAfterCommit, updateSettings], + [client, refreshAfterCommit, updateSettings], ); const importTheme = useCallback( @@ -368,7 +372,7 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { 'themeSnapshotVersion' in parsed && !('colors' in parsed) ) { - const entry = await invoke('create_personal_snapshot', { + const entry = await client.call('create_personal_snapshot', { name: name ?? t('themePackages.importedTheme'), source: themeJson, }); @@ -382,14 +386,14 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { 'schemaVersion' in parsed && !('monacoTheme' in parsed) ) { - const entry = await invoke('create_personal_theme', { + const entry = await client.call('create_personal_theme', { name: name ?? t('themePackages.importedTheme'), source: themeJson, }); await refreshAfterCommit(); return resolveCatalogEntry(entry).resolved.theme; } - const legacy = await invoke( + const legacy = await client.call( 'import_theme', name === undefined ? {themeJson} : {themeJson, name}, ); @@ -407,16 +411,19 @@ export const ThemeProvider = ({children}: {children: ReactNode}) => { }).theme ); }, - [refreshAfterCommit, t], + [client, refreshAfterCommit, t], ); - const exportTheme = useCallback(async (themeId: string): Promise => { - const theme = catalogRef.current.themes.find(({entry}) => entry.id === themeId); - if (!theme) throw new Error('Theme is unavailable'); - if (theme.entry.origin.kind === 'personal') - return invoke('export_theme', {themeId}); - return theme.entry.source; - }, []); + const exportTheme = useCallback( + async (themeId: string): Promise => { + const theme = catalogRef.current.themes.find(({entry}) => entry.id === themeId); + if (!theme) throw new Error('Theme is unavailable'); + if (theme.entry.origin.kind === 'personal') + return client.call('export_theme', {themeId}); + return theme.entry.source; + }, + [client], + ); const value = useMemo( () => ({ diff --git a/src/contexts/ToastContext.ts b/packages/web-ui/src/contexts/ToastContext.ts similarity index 100% rename from src/contexts/ToastContext.ts rename to packages/web-ui/src/contexts/ToastContext.ts diff --git a/src/contexts/ToastProvider.tsx b/packages/web-ui/src/contexts/ToastProvider.tsx similarity index 100% rename from src/contexts/ToastProvider.tsx rename to packages/web-ui/src/contexts/ToastProvider.tsx diff --git a/packages/web-ui/src/contexts/UiStateProvider.tsx b/packages/web-ui/src/contexts/UiStateProvider.tsx new file mode 100644 index 000000000..41397ab07 --- /dev/null +++ b/packages/web-ui/src/contexts/UiStateProvider.tsx @@ -0,0 +1,26 @@ +import {useEffect, type ReactNode} from 'react'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {uiStateStore, type UiStateStore} from '@/utils/uiStateStore'; + +interface UiStateProviderProps { + children: ReactNode; + /** Tests inject an isolated store. */ + store?: UiStateStore; +} + +/** Connects the shared UI state store to the active backend client. */ +export function UiStateProvider({children, store = uiStateStore}: UiStateProviderProps) { + const client = useTabularisClient(); + + useEffect(() => { + const detach = store.attach(client); + const flush = () => store.flush(); + window.addEventListener('pagehide', flush); + return () => { + window.removeEventListener('pagehide', flush); + detach(); + }; + }, [client, store]); + + return <>{children}; +} diff --git a/src/contexts/UpdateContext.ts b/packages/web-ui/src/contexts/UpdateContext.ts similarity index 73% rename from src/contexts/UpdateContext.ts rename to packages/web-ui/src/contexts/UpdateContext.ts index 9f9b57e04..6ae4e7138 100644 --- a/src/contexts/UpdateContext.ts +++ b/packages/web-ui/src/contexts/UpdateContext.ts @@ -1,4 +1,5 @@ import {createContext} from 'react'; +import type {ServerBuildInformation} from '@/api/session'; export interface UpdateCheckResult { hasUpdate: boolean; @@ -17,6 +18,13 @@ interface DownloadAsset { platform: string; } +export type UpdaterMode = 'native' | 'server-managed'; + +export interface ServerRuntimeInformation { + readonly version: string; + readonly build: ServerBuildInformation; +} + interface UpdateContextType { availableUpdate: UpdateCheckResult | null; updateInfo: UpdateCheckResult | null; @@ -29,6 +37,8 @@ interface UpdateContextType { error: string | null; isUpToDate: boolean; installationSource: string | null; + updaterMode: UpdaterMode; + serverInfo: ServerRuntimeInformation | null; } export const UpdateContext = createContext(undefined); diff --git a/packages/web-ui/src/contexts/UpdateProvider.tsx b/packages/web-ui/src/contexts/UpdateProvider.tsx new file mode 100644 index 000000000..894e0a276 --- /dev/null +++ b/packages/web-ui/src/contexts/UpdateProvider.tsx @@ -0,0 +1,166 @@ +import {useCallback, useState, useEffect, type ReactNode} from 'react'; +import {invoke} from '@tauri-apps/api/core'; +import {listen} from '@tauri-apps/api/event'; +import {UpdateContext, type UpdateCheckResult} from './UpdateContext'; +import {toErrorMessage} from '@/utils/errors'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import type {SessionNegotiation} from '@/api/session'; + +interface UpdateProviderProps { + readonly children: ReactNode; + readonly session?: SessionNegotiation | null; +} + +export const UpdateProvider = ({children, session = null}: UpdateProviderProps) => { + const client = useTabularisClient(); + const nativeUpdater = session?.capabilities.nativeUpdater ?? true; + const updaterMode = nativeUpdater ? 'native' : 'server-managed'; + const serverInfo = session + ? {version: session.serverVersion, build: session.serverBuild} + : null; + const [availableUpdate, setAvailableUpdate] = useState(null); + const [updateInfo, setUpdateInfo] = useState(null); + const [isChecking, setIsChecking] = useState(false); + const [isDownloading, setIsDownloading] = useState(false); + const [downloadProgress, setDownloadProgress] = useState(0); + const [error, setError] = useState(null); + const [isUpToDate, setIsUpToDate] = useState(false); + const [installationSource, setInstallationSource] = useState(null); + + // Native updater events do not exist in browser-hosted sessions. + useEffect(() => { + if (!nativeUpdater) return; + + const unlistenProgress = listen('update-progress', (event) => { + setDownloadProgress(event.payload); + }); + + const unlistenInstalling = listen('update-installing', () => { + setDownloadProgress(100); + }); + + return () => { + unlistenProgress.then((fn) => fn()); + unlistenInstalling.then((fn) => fn()); + }; + }, [nativeUpdater]); + + const checkForUpdates = useCallback( + async (force = false) => { + if (!nativeUpdater) return; + + setIsChecking(true); + setError(null); + setIsUpToDate(false); + try { + const result = await invoke('check_for_updates', { + force, + }); + setAvailableUpdate(result.hasUpdate ? result : null); + if (result.hasUpdate) { + // A manual check (force) always surfaces an available update. Only a + // background check honours a previous "remind me later" dismissal, + // otherwise the button would keep reporting "up to date" forever once + // a version has been dismissed. + let dismissed = false; + if (!force) { + const config = await client.call('get_config', undefined); + dismissed = config.lastDismissedVersion === result.latestVersion; + } + + if (dismissed) { + setUpdateInfo(null); + setIsUpToDate(false); + } else { + setUpdateInfo(result); + setIsUpToDate(false); + } + } else { + // No update available + setUpdateInfo(null); + setIsUpToDate(true); + } + } catch (err) { + console.error('Failed to check for updates:', err); + setError(toErrorMessage(err)); + setIsUpToDate(false); + } finally { + setIsChecking(false); + } + }, + [client, nativeUpdater], + ); + + const downloadAndInstall = async () => { + if (!nativeUpdater) return; + + setIsDownloading(true); + setDownloadProgress(0); + setError(null); + try { + await invoke('download_and_install_update'); + // The application restarts automatically after installation. + } catch (err) { + console.error('Failed to download/install update:', err); + setError(toErrorMessage(err)); + setIsDownloading(false); + } + }; + + const dismissUpdate = async () => { + if (updateInfo) { + await client.call('save_config', { + config: {lastDismissedVersion: updateInfo.latestVersion}, + }); + setUpdateInfo(null); + } + }; + + // Check on mount (startup) only when the host advertises the native updater. + useEffect(() => { + if (!nativeUpdater) return; + + const performStartupCheck = async () => { + try { + // Detect installation source first; managed packages skip built-in updates + const source = await client.call('get_installation_source', undefined); + setInstallationSource(source ?? null); + if (source) return; + + const config = await client.call('get_config', undefined); + if (config.autoCheckUpdatesOnStartup !== false) { + // Default: check on startup + await checkForUpdates(false); + } + } catch (err) { + console.error('Startup update check failed:', err); + } + }; + + // Delay startup checks so they do not block application initialization. + const timer = setTimeout(performStartupCheck, 2000); + return () => clearTimeout(timer); + }, [checkForUpdates, client, nativeUpdater]); + + return ( + + {children} + + ); +}; diff --git a/src/data/changelog.ts b/packages/web-ui/src/data/changelog.ts similarity index 100% rename from src/data/changelog.ts rename to packages/web-ui/src/data/changelog.ts diff --git a/src/hooks/useAiActivity.ts b/packages/web-ui/src/hooks/useAiActivity.ts similarity index 73% rename from src/hooks/useAiActivity.ts rename to packages/web-ui/src/hooks/useAiActivity.ts index b60eb0342..1c5d16e14 100644 --- a/src/hooks/useAiActivity.ts +++ b/packages/web-ui/src/hooks/useAiActivity.ts @@ -1,6 +1,6 @@ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; +import {useTabularisClient} from './useTabularisClient'; +import type {TabularisClient} from '@/api/client'; import type { AiActivityEvent, AiEventFilter, @@ -24,6 +24,7 @@ export interface UseAiActivityEventsResult { } export function useAiActivityEvents(filter: AiEventFilter = {}): UseAiActivityEventsResult { + const client = useTabularisClient(); const [events, setEvents] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -38,7 +39,7 @@ export function useAiActivityEvents(filter: AiEventFilter = {}): UseAiActivityEv setLoading(true); setError(null); try { - const data = await invoke('get_ai_activity', { + const data = await client.call('get_ai_activity', { filter: stableFilter, }); setEvents(data); @@ -47,7 +48,7 @@ export function useAiActivityEvents(filter: AiEventFilter = {}): UseAiActivityEv } finally { setLoading(false); } - }, [stableFilter]); + }, [client, stableFilter]); useEffect(() => { refetch(); @@ -68,6 +69,7 @@ export interface UseAiSessionsResult { } export function useAiSessions(): UseAiSessionsResult { + const client = useTabularisClient(); const [sessions, setSessions] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -76,14 +78,14 @@ export function useAiSessions(): UseAiSessionsResult { setLoading(true); setError(null); try { - const data = await invoke('get_ai_sessions'); + const data = await client.call('get_ai_sessions', undefined); setSessions(data); } catch (err) { setError(String(err)); } finally { setLoading(false); } - }, []); + }, [client]); useEffect(() => { refetch(); @@ -103,28 +105,32 @@ export interface UseAiSessionEventsResult { } export function useAiSessionEvents(sessionId: string | null): UseAiSessionEventsResult { + const client = useTabularisClient(); const [events, setEvents] = useState([]); const [loadedSessionId, setLoadedSessionId] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); - const fetchSession = useCallback(async (id: string, isCancelled: () => boolean) => { - setLoading(true); - setError(null); - try { - const data = await invoke('get_ai_session_events', { - sessionId: id, - }); - if (!isCancelled()) { - setEvents(data); - setLoadedSessionId(id); + const fetchSession = useCallback( + async (id: string, isCancelled: () => boolean) => { + setLoading(true); + setError(null); + try { + const data = await client.call('get_ai_session_events', { + sessionId: id, + }); + if (!isCancelled()) { + setEvents(data); + setLoadedSessionId(id); + } + } catch (err) { + if (!isCancelled()) setError(String(err)); + } finally { + if (!isCancelled()) setLoading(false); } - } catch (err) { - if (!isCancelled()) setError(String(err)); - } finally { - if (!isCancelled()) setLoading(false); - } - }, []); + }, + [client], + ); useEffect(() => { if (!sessionId) return; @@ -155,6 +161,7 @@ export interface UsePendingApprovalsResult { } export function usePendingApprovals(): UsePendingApprovalsResult { + const client = useTabularisClient(); const [pending, setPending] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -164,29 +171,29 @@ export function usePendingApprovals(): UsePendingApprovalsResult { setLoading(true); setError(null); try { - const data = await invoke('list_pending_approvals'); + const data = await client.call('list_pending_approvals', undefined); setPending(data); } catch (err) { setError(String(err)); } finally { setLoading(false); } - }, []); + }, [client]); refetchRef.current = refetch; useEffect(() => { refetch(); - const unlisten = listen(PENDING_APPROVAL_EVENT, () => { + const unsubscribe = client.subscribe(PENDING_APPROVAL_EVENT, () => { refetchRef.current(); }); return () => { - unlisten.then((fn) => fn()).catch(() => {}); + unsubscribe.then((fn) => fn()).catch(() => {}); }; - }, [refetch]); + }, [client, refetch]); const decide = useCallback( async ({approvalId, decision, reason, editedQuery}: ApprovalDecisionPayload) => { - await invoke('decide_pending_approval', { + await client.call('decide_pending_approval', { approvalId, decision, reason, @@ -196,7 +203,7 @@ export function usePendingApprovals(): UsePendingApprovalsResult { // will reconcile if anything else changes. setPending((prev) => prev.filter((p) => p.id !== approvalId)); }, - [], + [client], ); return {pending, loading, error, refetch, decide}; @@ -206,20 +213,21 @@ export function usePendingApprovals(): UsePendingApprovalsResult { // Mutations // --------------------------------------------------------------------------- -export async function clearAiActivity(): Promise { - await invoke('clear_ai_activity'); +export async function clearAiActivity(client: TabularisClient): Promise { + await client.call('clear_ai_activity', undefined); } -export async function exportAiActivityJson(): Promise { - return invoke('export_ai_activity_json'); +export function exportAiActivityJson(client: TabularisClient): Promise { + return client.call('export_ai_activity_json', undefined); } -export async function exportAiActivityCsv(): Promise { - return invoke('export_ai_activity_csv'); +export function exportAiActivityCsv(client: TabularisClient): Promise { + return client.call('export_ai_activity_csv', undefined); } -export async function exportSessionAsNotebook(sessionId: string): Promise { - return invoke('export_ai_session_as_notebook', { - sessionId, - }); +export function exportSessionAsNotebook( + client: TabularisClient, + sessionId: string, +): Promise { + return client.call('export_ai_session_as_notebook', {sessionId}); } diff --git a/src/hooks/useAlert.ts b/packages/web-ui/src/hooks/useAlert.ts similarity index 100% rename from src/hooks/useAlert.ts rename to packages/web-ui/src/hooks/useAlert.ts diff --git a/src/hooks/useAutoConnectFromUrl.ts b/packages/web-ui/src/hooks/useAutoConnectFromUrl.ts similarity index 100% rename from src/hooks/useAutoConnectFromUrl.ts rename to packages/web-ui/src/hooks/useAutoConnectFromUrl.ts diff --git a/src/hooks/useAutoRefresh.ts b/packages/web-ui/src/hooks/useAutoRefresh.ts similarity index 100% rename from src/hooks/useAutoRefresh.ts rename to packages/web-ui/src/hooks/useAutoRefresh.ts diff --git a/src/hooks/useAvailableUpdates.ts b/packages/web-ui/src/hooks/useAvailableUpdates.ts similarity index 100% rename from src/hooks/useAvailableUpdates.ts rename to packages/web-ui/src/hooks/useAvailableUpdates.ts diff --git a/src/hooks/useBuiltinDriverMigration.ts b/packages/web-ui/src/hooks/useBuiltinDriverMigration.ts similarity index 94% rename from src/hooks/useBuiltinDriverMigration.ts rename to packages/web-ui/src/hooks/useBuiltinDriverMigration.ts index 13ad8c3b2..f69029ce8 100644 --- a/src/hooks/useBuiltinDriverMigration.ts +++ b/packages/web-ui/src/hooks/useBuiltinDriverMigration.ts @@ -19,16 +19,22 @@ */ import {useCallback, useEffect, useMemo, useRef} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import {useDatabase} from './useDatabase'; import {useDrivers} from './useDrivers'; import {useConnectionCatalogue} from './useConnectionCatalogue'; import {useSettings} from './useSettings'; +import {useTabularisClient} from './useTabularisClient'; import {findConnectionsForDrivers} from '@/utils/connectionManager'; import type {SavedConnection} from '@/contexts/DatabaseContext'; +import type {ConnectionParameters} from '@/api/contract'; /** Which surface the banner should show. Driven by the connectivity gate. */ +/** The saved connection's parameters with only the driver swapped. */ +function paramsWithDriver(conn: SavedConnection | undefined, driver: string): ConnectionParameters { + return {database: '', ...conn?.params, driver}; +} + export type MigrationBannerVariant = 'nudge' | 'offline'; /** Result of a migration attempt, driving the toast / undo / report UI. */ @@ -118,6 +124,7 @@ export function useBuiltinDriverMigration( connections.some((connection) => connection.params.driver === builtinId), ); const {settings, updateSetting} = useSettings(); + const client = useTabularisClient(); // `undoMigration` is handed to callers that invoke it later, from a // closure captured well before the click that actually triggers it — the @@ -270,12 +277,14 @@ export function useBuiltinDriverMigration( // connection-URI connection it drops the stored URI on the driver // change (by design), which the pre-flight warning (Chunk 4) surfaces // before the user ever gets here. - await invoke('update_connection', { + await client.call('update_connection', { id: connectionId, name: conn?.name ?? connectionId, - params: {...conn?.params, driver: pluginId}, - detectJsonInTextColumns: conn?.detect_json_in_text_columns ? true : null, - environment: conn?.environment ?? null, + params: paramsWithDriver(conn, pluginId), + detectJsonInTextColumns: conn?.detect_json_in_text_columns + ? true + : undefined, + environment: conn?.environment ?? undefined, }); await loadConnections(); await recordMigration(connectionId, fromDriver, pluginId); @@ -301,7 +310,7 @@ export function useBuiltinDriverMigration( // credentials. let registeredDrivers: Array<{id: string}>; try { - registeredDrivers = await invoke>('get_registered_drivers'); + registeredDrivers = await client.call('get_registered_drivers', undefined); } catch (e) { const error = e instanceof Error ? e.message : String(e); const outcome: MigrationOutcome = { @@ -320,9 +329,10 @@ export function useBuiltinDriverMigration( // back to a generic one in the UI. let startupError: string | undefined; try { - const startupErrors = await invoke< - Array<{plugin_id: string; error: string}> - >('get_plugin_startup_errors'); + const startupErrors = await client.call( + 'get_plugin_startup_errors', + undefined, + ); startupError = startupErrors.find((e) => e.plugin_id === pluginId)?.error; } catch { // Non-fatal — the UI falls back to a generic message. @@ -339,9 +349,9 @@ export function useBuiltinDriverMigration( // Post-migration test to catch a bad outcome before declaring success. try { - await invoke('test_connection', { + await client.call('test_connection', { request: { - params: {...conn?.params, driver: pluginId}, + params: paramsWithDriver(conn, pluginId), connection_id: connectionId, }, }); @@ -362,9 +372,9 @@ export function useBuiltinDriverMigration( // already persisted on `pluginId` at this point. let preexisting = false; try { - await invoke('test_connection', { + await client.call('test_connection', { request: { - params: {...conn?.params, driver: builtinId}, + params: paramsWithDriver(conn, builtinId), connection_id: connectionId, }, }); @@ -408,6 +418,7 @@ export function useBuiltinDriverMigration( return outcome; }, [ + client, connections, builtinId, pluginId, @@ -461,12 +472,12 @@ export function useBuiltinDriverMigration( await disconnect(connectionId); disconnected = true; } - await invoke('update_connection', { + await client.call('update_connection', { id: connectionId, name: conn?.name ?? connectionId, - params: {...conn?.params, driver: builtinId}, - detectJsonInTextColumns: conn?.detect_json_in_text_columns ? true : null, - environment: conn?.environment ?? null, + params: paramsWithDriver(conn, builtinId), + detectJsonInTextColumns: conn?.detect_json_in_text_columns ? true : undefined, + environment: conn?.environment ?? undefined, }); await loadConnections(); outcome = {ok: true}; @@ -490,7 +501,7 @@ export function useBuiltinDriverMigration( return outcome; }, - [builtinId, pluginId, connect, disconnect, loadConnections], + [client, builtinId, pluginId, connect, disconnect, loadConnections], ); return { diff --git a/src/hooks/useChangelog.ts b/packages/web-ui/src/hooks/useChangelog.ts similarity index 100% rename from src/hooks/useChangelog.ts rename to packages/web-ui/src/hooks/useChangelog.ts diff --git a/src/hooks/useClickOutside.ts b/packages/web-ui/src/hooks/useClickOutside.ts similarity index 100% rename from src/hooks/useClickOutside.ts rename to packages/web-ui/src/hooks/useClickOutside.ts diff --git a/src/hooks/useColumnResize.ts b/packages/web-ui/src/hooks/useColumnResize.ts similarity index 100% rename from src/hooks/useColumnResize.ts rename to packages/web-ui/src/hooks/useColumnResize.ts diff --git a/src/hooks/useCommandPalette.ts b/packages/web-ui/src/hooks/useCommandPalette.ts similarity index 100% rename from src/hooks/useCommandPalette.ts rename to packages/web-ui/src/hooks/useCommandPalette.ts diff --git a/src/hooks/useCommandPaletteActionItems.ts b/packages/web-ui/src/hooks/useCommandPaletteActionItems.ts similarity index 100% rename from src/hooks/useCommandPaletteActionItems.ts rename to packages/web-ui/src/hooks/useCommandPaletteActionItems.ts diff --git a/src/hooks/useCommandPaletteObjectItems.ts b/packages/web-ui/src/hooks/useCommandPaletteObjectItems.ts similarity index 100% rename from src/hooks/useCommandPaletteObjectItems.ts rename to packages/web-ui/src/hooks/useCommandPaletteObjectItems.ts diff --git a/src/hooks/useCommandPaletteScope.ts b/packages/web-ui/src/hooks/useCommandPaletteScope.ts similarity index 100% rename from src/hooks/useCommandPaletteScope.ts rename to packages/web-ui/src/hooks/useCommandPaletteScope.ts diff --git a/src/hooks/useConnectionCatalogue.ts b/packages/web-ui/src/hooks/useConnectionCatalogue.ts similarity index 81% rename from src/hooks/useConnectionCatalogue.ts rename to packages/web-ui/src/hooks/useConnectionCatalogue.ts index a0e496310..41da35538 100644 --- a/src/hooks/useConnectionCatalogue.ts +++ b/packages/web-ui/src/hooks/useConnectionCatalogue.ts @@ -1,6 +1,7 @@ -import {invoke} from '@tauri-apps/api/core'; import {useDrivers} from './useDrivers'; import {useSettings} from './useSettings'; +import {useTabularisClient} from './useTabularisClient'; +import type {TabularisClient} from '@/api/client'; import {createAsyncResource} from '@/utils/asyncResource'; import {useEffect, useMemo, useSyncExternalStore} from 'react'; @@ -32,26 +33,35 @@ export interface ConnectionCatalogue { refresh: () => void; } -const catalogues = new Map>(); +type CatalogueResource = ReturnType; -function createCatalogue() { +// One cache per client (host), keyed by registry URL within it. +const catalogues = new WeakMap>(); + +function createCatalogue(client: TabularisClient) { return createAsyncResource([], () => - invoke('fetch_plugin_registry'), + client.call('fetch_plugin_registry', undefined), ); } export function useConnectionCatalogue(enabled = true): ConnectionCatalogue { + const client = useTabularisClient(); const {settings} = useSettings(); const {allDrivers: registered} = useDrivers(); const registryKey = settings.tabulariumRegistryUrl ?? 'default'; const resource = useMemo(() => { - let resource = catalogues.get(registryKey); + let byRegistry = catalogues.get(client); + if (!byRegistry) { + byRegistry = new Map(); + catalogues.set(client, byRegistry); + } + let resource = byRegistry.get(registryKey); if (!resource) { - resource = createCatalogue(); - catalogues.set(registryKey, resource); + resource = createCatalogue(client); + byRegistry.set(registryKey, resource); } return resource; - }, [registryKey]); + }, [client, registryKey]); const { data: registry, loading, diff --git a/src/hooks/useConnectionLayout.ts b/packages/web-ui/src/hooks/useConnectionLayout.ts similarity index 100% rename from src/hooks/useConnectionLayout.ts rename to packages/web-ui/src/hooks/useConnectionLayout.ts diff --git a/src/hooks/useConnectionLayoutContext.ts b/packages/web-ui/src/hooks/useConnectionLayoutContext.ts similarity index 100% rename from src/hooks/useConnectionLayoutContext.ts rename to packages/web-ui/src/hooks/useConnectionLayoutContext.ts diff --git a/src/hooks/useConnectionManager.ts b/packages/web-ui/src/hooks/useConnectionManager.ts similarity index 100% rename from src/hooks/useConnectionManager.ts rename to packages/web-ui/src/hooks/useConnectionManager.ts diff --git a/src/hooks/useConnectionTags.ts b/packages/web-ui/src/hooks/useConnectionTags.ts similarity index 65% rename from src/hooks/useConnectionTags.ts rename to packages/web-ui/src/hooks/useConnectionTags.ts index 93a1a785d..e6695feaf 100644 --- a/src/hooks/useConnectionTags.ts +++ b/packages/web-ui/src/hooks/useConnectionTags.ts @@ -1,54 +1,53 @@ import {useCallback, useEffect, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import type {ConnectionTag} from '@/types/tags'; +import {useTabularisClient} from './useTabularisClient'; /** * Loads the connection tags and exposes CRUD helpers. Every mutation * re-fetches so all fields (including backend-normalized names) stay in sync. */ export function useConnectionTags() { + const client = useTabularisClient(); const [tags, setTags] = useState([]); const refresh = useCallback( () => - invoke('list_connection_tags') + client + .call('list_connection_tags', undefined) .then(setTags) - .catch((e: unknown) => { - console.error('Failed to load connection tags:', e); + .catch((error: unknown) => { + console.error('Failed to load connection tags:', error); }), - [], + [client], ); useEffect(() => { - refresh(); + void refresh(); }, [refresh]); const createTag = useCallback( async (name: string, color: string): Promise => { - const tag = await invoke('create_connection_tag', { - name, - color, - }); + const tag = await client.call('create_connection_tag', {name, color}); await refresh(); return tag; }, - [refresh], + [client, refresh], ); const updateTag = useCallback( async (id: string, name: string, color: string) => { - await invoke('update_connection_tag', {id, name, color}); + await client.call('update_connection_tag', {id, name, color}); await refresh(); }, - [refresh], + [client, refresh], ); const deleteTag = useCallback( async (id: string) => { - await invoke('delete_connection_tag', {id}); + await client.call('delete_connection_tag', {id}); await refresh(); }, - [refresh], + [client, refresh], ); return {tags, refresh, createTag, updateTag, deleteTag}; diff --git a/src/hooks/useConnectionWindowLifecycle.ts b/packages/web-ui/src/hooks/useConnectionWindowLifecycle.ts similarity index 70% rename from src/hooks/useConnectionWindowLifecycle.ts rename to packages/web-ui/src/hooks/useConnectionWindowLifecycle.ts index a3e166bc7..d2e3a6e12 100644 --- a/src/hooks/useConnectionWindowLifecycle.ts +++ b/packages/web-ui/src/hooks/useConnectionWindowLifecycle.ts @@ -1,9 +1,6 @@ import {useEffect, useRef} from 'react'; -import {getCurrentWindow} from '@tauri-apps/api/window'; import {useDatabase} from './useDatabase'; - -/** Label prefix used for dedicated single-connection windows. */ -const CONNECTION_WINDOW_PREFIX = 'connection-window-'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; /** * Lifecycle for a dedicated connection window: once its bound connection has @@ -12,13 +9,16 @@ const CONNECTION_WINDOW_PREFIX = 'connection-window-'; * is never auto-closed by this hook. */ export function useConnectionWindowLifecycle() { + const platform = usePlatformCapabilities(); const {globallyOpenConnectionIds} = useDatabase(); // The connection id this window was launched to show. Captured on first // render (before the app navigates away and strips the `?connect=` param). const boundIdRef = useRef(undefined); if (boundIdRef.current === undefined) { - boundIdRef.current = new URLSearchParams(window.location.search).get('connect'); + const search = new URLSearchParams(window.location.search); + boundIdRef.current = + search.get('standalone') === 'connection' ? search.get('connect') : null; } // Guard so we don't close before the connection has finished opening on first @@ -27,16 +27,14 @@ export function useConnectionWindowLifecycle() { useEffect(() => { const boundId = boundIdRef.current; - const label = getCurrentWindow().label; - const isDedicated = label.startsWith(CONNECTION_WINDOW_PREFIX); - if (!isDedicated || !boundId) return; + if (!boundId) return; if (globallyOpenConnectionIds.includes(boundId)) { hasBeenOpenRef.current = true; return; } if (hasBeenOpenRef.current) { - void getCurrentWindow().close(); + void platform.closeRoute(); } - }, [globallyOpenConnectionIds]); + }, [globallyOpenConnectionIds, platform]); } diff --git a/src/hooks/useContainerWidth.ts b/packages/web-ui/src/hooks/useContainerWidth.ts similarity index 100% rename from src/hooks/useContainerWidth.ts rename to packages/web-ui/src/hooks/useContainerWidth.ts diff --git a/src/hooks/useCopyFeedback.ts b/packages/web-ui/src/hooks/useCopyFeedback.ts similarity index 100% rename from src/hooks/useCopyFeedback.ts rename to packages/web-ui/src/hooks/useCopyFeedback.ts diff --git a/src/hooks/useCreateSqliteDatabase.ts b/packages/web-ui/src/hooks/useCreateSqliteDatabase.ts similarity index 72% rename from src/hooks/useCreateSqliteDatabase.ts rename to packages/web-ui/src/hooks/useCreateSqliteDatabase.ts index 71dbf0766..0c77d0814 100644 --- a/src/hooks/useCreateSqliteDatabase.ts +++ b/packages/web-ui/src/hooks/useCreateSqliteDatabase.ts @@ -1,11 +1,14 @@ import {useRef, useState} from 'react'; import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import {save} from '@tauri-apps/plugin-dialog'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; +import {choosePlatformSavePath} from '@/platform/dialogs'; import type {SavedConnection} from '@/contexts/DatabaseContext'; +import {useTabularisClient} from './useTabularisClient'; export function useCreateSqliteDatabase() { const {t} = useTranslation(); + const platform = usePlatformCapabilities(); + const client = useTabularisClient(); const inFlightRef = useRef(false); const [isCreating, setIsCreating] = useState(false); @@ -15,7 +18,7 @@ export function useCreateSqliteDatabase() { inFlightRef.current = true; setIsCreating(true); try { - const path = await save({ + const path = await choosePlatformSavePath(platform, { title: t('connections.newSqliteDatabase.dialogTitle'), defaultPath: 'database.db', filters: [ @@ -27,7 +30,7 @@ export function useCreateSqliteDatabase() { }); if (!path) return null; - return await invoke('create_sqlite_database', {path}); + return await client.call('create_sqlite_database', {path}); } finally { inFlightRef.current = false; setIsCreating(false); diff --git a/src/hooks/useDangerousQueryGuard.ts b/packages/web-ui/src/hooks/useDangerousQueryGuard.ts similarity index 100% rename from src/hooks/useDangerousQueryGuard.ts rename to packages/web-ui/src/hooks/useDangerousQueryGuard.ts diff --git a/src/hooks/useDataTypes.ts b/packages/web-ui/src/hooks/useDataTypes.ts similarity index 89% rename from src/hooks/useDataTypes.ts rename to packages/web-ui/src/hooks/useDataTypes.ts index c317ac762..de1bf9c55 100644 --- a/src/hooks/useDataTypes.ts +++ b/packages/web-ui/src/hooks/useDataTypes.ts @@ -1,11 +1,12 @@ import {useContext, useState, useEffect} from 'react'; -import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from './useTabularisClient'; import {DatabaseContext} from '@/contexts/DatabaseContext'; import type {DataTypeRegistry} from '@/types/dataTypes'; const dataTypesCache = new Map(); export function useDataTypes(driver: string | undefined, connectionId?: string | null) { + const client = useTabularisClient(); const context = useContext(DatabaseContext); const targetId = connectionId === undefined ? context?.activeConnectionId : connectionId; const connection = targetId ? context?.connectionDataMap[targetId] : undefined; @@ -22,7 +23,7 @@ export function useDataTypes(driver: string | undefined, connectionId?: string | let cancelled = false; const fetchDataTypes = async () => { try { - const registry = await invoke('get_data_types', {driver}); + const registry = await client.call('get_data_types', {driver}); dataTypesCache.set(driver, registry); if (!cancelled) setResult({driver, dataTypes: registry, error: null}); } catch (err) { @@ -34,7 +35,7 @@ export function useDataTypes(driver: string | undefined, connectionId?: string | return () => { cancelled = true; }; - }, [driver, metadata, cached]); + }, [client, driver, metadata, cached]); if (driver && metadata) { return { diff --git a/src/hooks/useDatabase.ts b/packages/web-ui/src/hooks/useDatabase.ts similarity index 100% rename from src/hooks/useDatabase.ts rename to packages/web-ui/src/hooks/useDatabase.ts diff --git a/src/hooks/useDatabaseObjectActionRuntime.ts b/packages/web-ui/src/hooks/useDatabaseObjectActionRuntime.ts similarity index 78% rename from src/hooks/useDatabaseObjectActionRuntime.ts rename to packages/web-ui/src/hooks/useDatabaseObjectActionRuntime.ts index 385c47df9..71f5a1992 100644 --- a/src/hooks/useDatabaseObjectActionRuntime.ts +++ b/packages/web-ui/src/hooks/useDatabaseObjectActionRuntime.ts @@ -6,17 +6,19 @@ import type {DatabaseObjectActionRuntime} from '@/utils/databaseObjectActions'; import {loadRoutineDefinition, loadTriggerDefinition} from '@/utils/databaseObjectActions'; import {openEditor} from '@/utils/editorNavigation'; import {useAlert} from './useAlert'; +import {useTabularisClient} from './useTabularisClient'; export function useDatabaseObjectActionRuntime(): DatabaseObjectActionRuntime { const {t} = useTranslation(); const navigate = useNavigate(); const {showAlert} = useAlert(); + const client = useTabularisClient(); return useMemo( () => ({ navigateToEditor: (request) => openEditor(navigate, request), - loadRoutineDefinition, - loadTriggerDefinition, + loadRoutineDefinition: (target) => loadRoutineDefinition(client, target), + loadTriggerDefinition: (target) => loadTriggerDefinition(client, target), showDefinitionError: (type, error) => { console.error(error); showAlert( @@ -29,6 +31,6 @@ export function useDatabaseObjectActionRuntime(): DatabaseObjectActionRuntime { ); }, }), - [navigate, showAlert, t], + [client, navigate, showAlert, t], ); } diff --git a/src/hooks/useDatabaseObjectNavigation.ts b/packages/web-ui/src/hooks/useDatabaseObjectNavigation.ts similarity index 100% rename from src/hooks/useDatabaseObjectNavigation.ts rename to packages/web-ui/src/hooks/useDatabaseObjectNavigation.ts diff --git a/src/hooks/useDeepLinkInstall.ts b/packages/web-ui/src/hooks/useDeepLinkInstall.ts similarity index 81% rename from src/hooks/useDeepLinkInstall.ts rename to packages/web-ui/src/hooks/useDeepLinkInstall.ts index 819b7b473..51f71b70c 100644 --- a/src/hooks/useDeepLinkInstall.ts +++ b/packages/web-ui/src/hooks/useDeepLinkInstall.ts @@ -1,17 +1,16 @@ import {useCallback, useEffect, useState} from 'react'; import {listen, type UnlistenFn, emit} from '@tauri-apps/api/event'; import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from './useTabularisClient'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; +import {PLUGIN_INSTALL_DEADLINE_MS, type PluginInstallRequest} from '@/api/pluginLifecycle'; /** * Payload emitted by the Rust backend when the OS hands us a * `tabularis://install/?version=®istry=` URL. Field names match * the camelCased Serde rename of `plugins::deep_link::PluginInstallRequest`. */ -export interface DeepLinkInstallRequest { - slug: string; - version?: string | null; - registry?: string | null; -} +export type DeepLinkInstallRequest = PluginInstallRequest; const EVENT_NAME = 'tabularis://plugin-install'; @@ -34,11 +33,15 @@ interface UseDeepLinkInstallResult { * user click so a malicious URL can't trigger a silent install. */ export function useDeepLinkInstall(): UseDeepLinkInstallResult { + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); + const nativeHandoffs = platform.negotiation.environment === 'tauri'; const [pending, setPending] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); useEffect(() => { + if (!nativeHandoffs) return; let cleanup: UnlistenFn | null = null; let mounted = true; @@ -77,7 +80,7 @@ export function useDeepLinkInstall(): UseDeepLinkInstallResult { mounted = false; cleanup?.(); }; - }, []); + }, [nativeHandoffs]); const cancel = useCallback(() => { setPending(null); @@ -89,10 +92,14 @@ export function useDeepLinkInstall(): UseDeepLinkInstallResult { setBusy(true); setError(null); try { - await invoke('install_plugin', { - pluginId: pending.slug, - version: pending.version ?? null, - }); + await client.call( + 'install_plugin', + { + pluginId: pending.slug, + version: pending.version ?? null, + }, + {deadlineMs: PLUGIN_INSTALL_DEADLINE_MS}, + ); // Tell anything observing the plugin catalogue (PluginsTab, drivers // list) to refresh. Components subscribe to this in their own effects. void emit('tabularis://plugin-installed', {slug: pending.slug}); @@ -104,7 +111,7 @@ export function useDeepLinkInstall(): UseDeepLinkInstallResult { } finally { setBusy(false); } - }, [pending]); + }, [client, pending]); return {pending, confirm, cancel, error, busy}; } diff --git a/src/hooks/useDrivers.ts b/packages/web-ui/src/hooks/useDrivers.ts similarity index 67% rename from src/hooks/useDrivers.ts rename to packages/web-ui/src/hooks/useDrivers.ts index 755cf2b34..f3c963f41 100644 --- a/src/hooks/useDrivers.ts +++ b/packages/web-ui/src/hooks/useDrivers.ts @@ -1,10 +1,10 @@ -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import {useEffect, useSyncExternalStore} from 'react'; +import type {TabularisClient} from '@/api/client'; import {createAsyncResource} from '@/utils/asyncResource'; import type {InstalledPluginInfo, PluginManifest} from '@/types/plugins'; import {useSettings} from './useSettings'; +import {useTabularisClient} from './useTabularisClient'; const FALLBACK_DRIVERS: PluginManifest[] = [ { @@ -133,47 +133,69 @@ const FALLBACK_DRIVERS: PluginManifest[] = [ }, ]; -const driverResource = createAsyncResource<{ +type DriverData = { allDrivers: PluginManifest[]; installedPlugins: InstalledPluginInfo[]; -}>({allDrivers: FALLBACK_DRIVERS, installedPlugins: []}, async () => { - const [allDrivers, installedPlugins] = await Promise.all([ - invoke('get_registered_drivers'), - invoke('get_installed_plugins'), - ]); - return {allDrivers, installedPlugins}; -}); +}; -let subscribers = 0; -let stopListening: (() => void) | undefined; +function createDriverStore(client: TabularisClient) { + const resource = createAsyncResource( + {allDrivers: FALLBACK_DRIVERS, installedPlugins: []}, + async () => { + const [allDrivers, installedPlugins] = await Promise.all([ + client.call('get_registered_drivers', undefined), + client.call('get_installed_plugins', undefined), + ]); + return {allDrivers, installedPlugins}; + }, + ); -function subscribeDrivers(listener: () => void): () => void { - const unsubscribe = driverResource.subscribe(listener); - if (++subscribers === 1) { - let disposed = false; - let unlisten: (() => void) | undefined; - void listen('tabularis://plugin-activated', () => { - void driverResource.refresh(); - }) - .then((cleanup) => { - if (disposed) cleanup(); - else unlisten = cleanup; - }) - .catch((error: unknown) => { - console.warn('Failed to subscribe to plugin activation:', error); - }); - stopListening = () => { - disposed = true; - unlisten?.(); - }; - } - return () => { - unsubscribe(); - if (--subscribers === 0) { - stopListening?.(); - stopListening = undefined; + let subscribers = 0; + let stopListening: (() => void) | undefined; + + const subscribe = (listener: () => void): (() => void) => { + const unsubscribe = resource.subscribe(listener); + if (++subscribers === 1) { + let disposed = false; + let unlisten: (() => void) | undefined; + void client + .subscribe('tabularis://plugin-activated', () => { + void resource.refresh(); + }) + .then((cleanup) => { + if (disposed) cleanup(); + else unlisten = cleanup; + }) + .catch((error: unknown) => { + console.warn('Failed to subscribe to plugin activation:', error); + }); + stopListening = () => { + disposed = true; + unlisten?.(); + }; } + return () => { + unsubscribe(); + if (--subscribers === 0) { + stopListening?.(); + stopListening = undefined; + } + }; }; + + return {...resource, subscribe}; +} + +// One shared store per client, so concurrent readers share requests and refreshes. +const driverStores = new WeakMap>(); + +function getDriverStore(client: TabularisClient) { + let store = driverStores.get(client); + if (!store) { + store = createDriverStore(client); + driverStores.set(client, store); + } + return store; } export function useDrivers(): { @@ -184,19 +206,21 @@ export function useDrivers(): { error: string | null; refresh: () => void; } { + const client = useTabularisClient(); + const driverStore = getDriverStore(client); const {data, loading, error} = useSyncExternalStore( - subscribeDrivers, - driverResource.getSnapshot, + driverStore.subscribe, + driverStore.getSnapshot, ); const {settings} = useSettings(); useEffect(() => { - void driverResource.load(); - }, []); + void driverStore.load(); + }, [driverStore]); const activeExt = settings.activeExternalDrivers; // Match the backend: an absent preference enables installed external drivers. const drivers = data.allDrivers.filter( (driver) => driver.is_builtin === true || activeExt == null || activeExt.includes(driver.id), ); - return {...data, drivers, loading, error, refresh: driverResource.refresh}; + return {...data, drivers, loading, error, refresh: driverStore.refresh}; } diff --git a/src/hooks/useEditor.ts b/packages/web-ui/src/hooks/useEditor.ts similarity index 100% rename from src/hooks/useEditor.ts rename to packages/web-ui/src/hooks/useEditor.ts diff --git a/src/hooks/useEditorTheme.ts b/packages/web-ui/src/hooks/useEditorTheme.ts similarity index 100% rename from src/hooks/useEditorTheme.ts rename to packages/web-ui/src/hooks/useEditorTheme.ts diff --git a/src/hooks/useEscapeKey.ts b/packages/web-ui/src/hooks/useEscapeKey.ts similarity index 100% rename from src/hooks/useEscapeKey.ts rename to packages/web-ui/src/hooks/useEscapeKey.ts diff --git a/src/hooks/useExplainAnalyze.ts b/packages/web-ui/src/hooks/useExplainAnalyze.ts similarity index 100% rename from src/hooks/useExplainAnalyze.ts rename to packages/web-ui/src/hooks/useExplainAnalyze.ts diff --git a/src/hooks/useExplainPlan.ts b/packages/web-ui/src/hooks/useExplainPlan.ts similarity index 87% rename from src/hooks/useExplainPlan.ts rename to packages/web-ui/src/hooks/useExplainPlan.ts index 1577ed02f..2fae80b1f 100644 --- a/src/hooks/useExplainPlan.ts +++ b/packages/web-ui/src/hooks/useExplainPlan.ts @@ -1,12 +1,12 @@ import {useCallback, useState} from 'react'; import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import type {ExplainPlan, ExplainQueryOutput} from '@tabularis/explain'; +import type {ExplainPlan} from '@tabularis/explain'; import {resolveExplainOutput} from '@tabularis/explain'; import type {ExplainViewMode} from '@tabularis/explain/react'; import {isExplainableQuery} from '@/utils/sql'; import {toErrorMessage} from '@/utils/errors'; import {useLatestAsync} from './useLatestAsync'; +import {useTabularisClient} from './useTabularisClient'; interface RunExplainArgs { connectionId: string; @@ -17,13 +17,14 @@ interface RunExplainArgs { } /** - * Owns the state and Tauri call for running EXPLAIN / EXPLAIN ANALYZE. Shared by + * Owns the state and backend call for running EXPLAIN / EXPLAIN ANALYZE. Shared by * every explain surface (the inline SQL-cell section, the modal, and the page) * so the invoke + parse + selection logic lives in one place. Callers own their * own trigger (button, effect) and any `analyze` toggle. */ export function useExplainPlan(initialPlan: ExplainPlan | null = null) { const {t} = useTranslation(); + const client = useTabularisClient(); const [plan, setPlan] = useState(initialPlan); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); @@ -80,17 +81,17 @@ export function useExplainPlan(initialPlan: ExplainPlan | null = null) { if (!isExplainableQuery(query)) { throw t('editor.visualExplain.notExplainable'); } - const result = await invoke('explain_query_plan', { + const result = await client.call('explain_query_plan', { connectionId, query, analyze, - schema: schema || null, - database: database || null, + schema: schema || undefined, + database: database || undefined, }); return resolveExplainOutput(result); }); }, - [invalidate, loadPlan, reset, t], + [client, invalidate, loadPlan, reset, t], ); return { diff --git a/src/hooks/useGlobalShortcuts.ts b/packages/web-ui/src/hooks/useGlobalShortcuts.ts similarity index 100% rename from src/hooks/useGlobalShortcuts.ts rename to packages/web-ui/src/hooks/useGlobalShortcuts.ts diff --git a/packages/web-ui/src/hooks/useJsonEditorActivity.ts b/packages/web-ui/src/hooks/useJsonEditorActivity.ts new file mode 100644 index 000000000..f876b54a8 --- /dev/null +++ b/packages/web-ui/src/hooks/useJsonEditorActivity.ts @@ -0,0 +1,30 @@ +import {useCallback, useEffect, useRef, useState} from 'react'; + +/** Tracks editable secondary windows, including the asynchronous opening phase. */ +export function useJsonEditorActivity() { + const [count, setCount] = useState(0); + const active = useRef(new Set()); + const mounted = useRef(true); + + useEffect(() => { + mounted.current = true; + const activeEditors = active.current; + return () => { + mounted.current = false; + activeEditors.clear(); + }; + }, []); + + const begin = useCallback(() => { + const token = Symbol(); + active.current.add(token); + setCount(active.current.size); + return () => { + active.current.delete(token); + if (mounted.current) setCount(active.current.size); + }; + }, []); + + const isEditing = useCallback(() => active.current.size > 0, []); + return {count, begin, isEditing}; +} diff --git a/src/hooks/useK8sPathOverrides.ts b/packages/web-ui/src/hooks/useK8sPathOverrides.ts similarity index 97% rename from src/hooks/useK8sPathOverrides.ts rename to packages/web-ui/src/hooks/useK8sPathOverrides.ts index a79b76868..c63a9cc99 100644 --- a/src/hooks/useK8sPathOverrides.ts +++ b/packages/web-ui/src/hooks/useK8sPathOverrides.ts @@ -1,4 +1,5 @@ import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import type {TypedCommandCaller} from '@/api/contract'; import {toErrorMessage} from '@/utils/errors'; import {validateK8sPath, type K8sCommandOptions, type K8sPathValidationKind} from '@/utils/k8s'; import {useLatestAsync} from './useLatestAsync'; @@ -34,6 +35,7 @@ interface PendingValidation { } export interface UseK8sPathOverridesOptions { + client?: TypedCommandCaller; onApplied?: (options: K8sCommandOptions) => void; onDraftChanged?: () => void; } @@ -97,7 +99,7 @@ function validationKey(kind: K8sPathValidationKind): string { * the final pair exactly once. */ export function useK8sPathOverrides(options: UseK8sPathOverridesOptions = {}): K8sPathOverrides { - const {onApplied, onDraftChanged} = options; + const {client, onApplied, onDraftChanged} = options; const {invalidate, run} = useLatestAsync(); const [drafts, setDrafts] = useState(() => toDrafts()); const [appliedOptions, setAppliedOptions] = useState({}); @@ -211,7 +213,9 @@ export function useK8sPathOverrides(options: UseK8sPathOverridesOptions = {}): K setValidation(kind, {status: 'validating'}); const promise = (async (): Promise => { - const result = await run(validationKey(kind), () => validateK8sPath(path, kind)); + const result = await run(validationKey(kind), () => + validateK8sPath(path, kind, client), + ); if (result.status === 'stale' || draftsRef.current[kind] !== value) { return {status: 'stale'}; @@ -237,7 +241,7 @@ export function useK8sPathOverrides(options: UseK8sPathOverridesOptions = {}): K return promise; }, - [applyCurrentDrafts, invalidate, run, setValidation], + [applyCurrentDrafts, client, invalidate, run, setValidation], ); const initialize = useCallback( diff --git a/src/hooks/useKeybindings.ts b/packages/web-ui/src/hooks/useKeybindings.ts similarity index 100% rename from src/hooks/useKeybindings.ts rename to packages/web-ui/src/hooks/useKeybindings.ts diff --git a/src/hooks/useLatestAsync.ts b/packages/web-ui/src/hooks/useLatestAsync.ts similarity index 100% rename from src/hooks/useLatestAsync.ts rename to packages/web-ui/src/hooks/useLatestAsync.ts diff --git a/src/hooks/useOpenConnectionInNewWindow.ts b/packages/web-ui/src/hooks/useOpenConnectionInNewWindow.ts similarity index 77% rename from src/hooks/useOpenConnectionInNewWindow.ts rename to packages/web-ui/src/hooks/useOpenConnectionInNewWindow.ts index 1072273e3..a0c9a3de6 100644 --- a/src/hooks/useOpenConnectionInNewWindow.ts +++ b/packages/web-ui/src/hooks/useOpenConnectionInNewWindow.ts @@ -1,7 +1,7 @@ import {useCallback} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import {useDatabase} from './useDatabase'; -import type {SavedConnection} from '@/contexts/DatabaseContext'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; +import {useTabularisClient} from './useTabularisClient'; /** * Open a connection in its own dedicated window. @@ -17,6 +17,8 @@ import type {SavedConnection} from '@/contexts/DatabaseContext'; * stays alive and is reused by the new window, which disconnects it on close). */ export function useOpenConnectionInNewWindow() { + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const {detachConnection, isConnectionOpen, isConnectionOpenAnywhere} = useDatabase(); return useCallback( @@ -25,15 +27,15 @@ export function useOpenConnectionInNewWindow() { // is already open somewhere (then it's known-good and the window either // reuses the warm pool or just gets focused). if (!isConnectionOpenAnywhere(connectionId)) { - const connections = await invoke('get_connections'); + const connections = await client.call('get_connections', undefined); const conn = connections.find((c) => c.id === connectionId); if (!conn) throw new Error('Connection not found'); - await invoke('test_connection', { + await client.call('test_connection', { request: {params: conn.params, connection_id: connectionId}, }); } - await invoke('open_connection_window', { + await platform.openConnectionRoute({ connectionId, title: name ?? null, }); @@ -42,6 +44,6 @@ export function useOpenConnectionInNewWindow() { detachConnection(connectionId); } }, - [detachConnection, isConnectionOpen, isConnectionOpenAnywhere], + [client, detachConnection, isConnectionOpen, isConnectionOpenAnywhere, platform], ); } diff --git a/packages/web-ui/src/hooks/usePlatformCapabilities.ts b/packages/web-ui/src/hooks/usePlatformCapabilities.ts new file mode 100644 index 000000000..6567b8ad3 --- /dev/null +++ b/packages/web-ui/src/hooks/usePlatformCapabilities.ts @@ -0,0 +1,12 @@ +import {useContext} from 'react'; +import {PlatformCapabilitiesContext} from '@/contexts/PlatformCapabilitiesContext'; + +export function usePlatformCapabilities() { + const capabilities = useContext(PlatformCapabilitiesContext); + + if (!capabilities) { + throw new Error('usePlatformCapabilities must be used within PlatformCapabilitiesProvider'); + } + + return capabilities; +} diff --git a/src/hooks/usePluginApi.ts b/packages/web-ui/src/hooks/usePluginApi.ts similarity index 81% rename from src/hooks/usePluginApi.ts rename to packages/web-ui/src/hooks/usePluginApi.ts index b8b8828de..d9ffab4e6 100644 --- a/src/hooks/usePluginApi.ts +++ b/packages/web-ui/src/hooks/usePluginApi.ts @@ -1,7 +1,6 @@ import {useState, useCallback, useContext, useMemo} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {message} from '@tauri-apps/plugin-dialog'; -import {openUrl as openExternal} from '@tauri-apps/plugin-opener'; +import {getActivePlatformCapabilities} from '@/platform/activeCapabilities'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; import {useTranslation} from 'react-i18next'; import {ThemeContext} from '@/contexts/ThemeContext'; @@ -10,11 +9,13 @@ import {SettingsContext} from '@/contexts/SettingsContext'; import {PluginModalContext} from '@/contexts/PluginModalContext'; import type {PluginModalOptions} from '@/contexts/PluginModalContext'; import {toErrorMessage} from '@/utils/errors'; +import {useTabularisClient} from './useTabularisClient'; /** * Hook for plugin components to execute read-only database queries. */ export function usePluginQuery() { + const client = useTabularisClient(); const dbCtx = useContext(DatabaseContext); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); @@ -29,14 +30,11 @@ export function usePluginQuery() { setError(null); try { - const result = await invoke<{columns: string[]; rows: unknown[][]}>( - 'execute_query', - { - connectionId: dbCtx.activeConnectionId, - query, - ...(dbCtx.activeSchema ? {schema: dbCtx.activeSchema} : {}), - }, - ); + const result = await client.call('execute_query', { + connectionId: dbCtx.activeConnectionId, + query, + ...(dbCtx.activeSchema ? {schema: dbCtx.activeSchema} : {}), + }); return result; } catch (err) { const msg = toErrorMessage(err); @@ -46,7 +44,7 @@ export function usePluginQuery() { setLoading(false); } }, - [dbCtx?.activeConnectionId, dbCtx?.activeSchema], + [client, dbCtx?.activeConnectionId, dbCtx?.activeSchema], ); return {executeQuery, loading, error}; @@ -72,17 +70,27 @@ export function usePluginConnection() { * Hook for plugin components to show notifications. */ export function usePluginToast() { - const showInfo = useCallback(async (text: string) => { - await message(text, {kind: 'info'}); - }, []); + const platform = usePlatformCapabilities(); + const showInfo = useCallback( + async (text: string) => { + await platform.showMessage({message: text, kind: 'info'}); + }, + [platform], + ); - const showError = useCallback(async (text: string) => { - await message(text, {kind: 'error'}); - }, []); + const showError = useCallback( + async (text: string) => { + await platform.showMessage({message: text, kind: 'error'}); + }, + [platform], + ); - const showWarning = useCallback(async (text: string) => { - await message(text, {kind: 'warning'}); - }, []); + const showWarning = useCallback( + async (text: string) => { + await platform.showMessage({message: text, kind: 'warning'}); + }, + [platform], + ); return useMemo(() => ({showInfo, showError, showWarning}), [showInfo, showError, showWarning]); } @@ -160,7 +168,7 @@ export function usePluginTranslation(pluginId: string) { * Plugin components should use this instead of window.open for external URLs. */ export async function openUrl(url: string): Promise { - await openExternal(url); + await getActivePlatformCapabilities().openExternalUrl(url); } /** diff --git a/packages/web-ui/src/hooks/usePluginInstallConfirmation.ts b/packages/web-ui/src/hooks/usePluginInstallConfirmation.ts new file mode 100644 index 000000000..36f38da37 --- /dev/null +++ b/packages/web-ui/src/hooks/usePluginInstallConfirmation.ts @@ -0,0 +1,46 @@ +import {useCallback, useState} from 'react'; +import {PLUGIN_INSTALL_DEADLINE_MS, type PluginInstallRequest} from '@/api/pluginLifecycle'; +import {useTabularisClient} from './useTabularisClient'; + +export interface PluginInstallConfirmation { + confirm: (request: PluginInstallRequest | null) => Promise; + clearError: () => void; + error: string | null; + busy: boolean; +} + +/** Executes a validated browser install request after explicit confirmation. */ +export function usePluginInstallConfirmation(): PluginInstallConfirmation { + const client = useTabularisClient(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const clearError = useCallback(() => setError(null), []); + const confirm = useCallback( + async (request: PluginInstallRequest | null): Promise => { + if (!request) return false; + setBusy(true); + setError(null); + try { + await client.call( + 'install_plugin', + { + pluginId: request.slug, + version: request.version ?? null, + registryUrl: request.registry ?? null, + }, + {deadlineMs: PLUGIN_INSTALL_DEADLINE_MS}, + ); + return true; + } catch (installError) { + setError(String(installError)); + return false; + } finally { + setBusy(false); + } + }, + [client], + ); + + return {confirm, clearError, error, busy}; +} diff --git a/src/hooks/usePluginRegistry.ts b/packages/web-ui/src/hooks/usePluginRegistry.ts similarity index 100% rename from src/hooks/usePluginRegistry.ts rename to packages/web-ui/src/hooks/usePluginRegistry.ts diff --git a/src/hooks/usePluginSlotRegistry.ts b/packages/web-ui/src/hooks/usePluginSlotRegistry.ts similarity index 100% rename from src/hooks/usePluginSlotRegistry.ts rename to packages/web-ui/src/hooks/usePluginSlotRegistry.ts diff --git a/src/hooks/useProductionGuard.ts b/packages/web-ui/src/hooks/useProductionGuard.ts similarity index 100% rename from src/hooks/useProductionGuard.ts rename to packages/web-ui/src/hooks/useProductionGuard.ts diff --git a/src/hooks/useQueryGuards.ts b/packages/web-ui/src/hooks/useQueryGuards.ts similarity index 100% rename from src/hooks/useQueryGuards.ts rename to packages/web-ui/src/hooks/useQueryGuards.ts diff --git a/src/hooks/useQueryHistory.ts b/packages/web-ui/src/hooks/useQueryHistory.ts similarity index 100% rename from src/hooks/useQueryHistory.ts rename to packages/web-ui/src/hooks/useQueryHistory.ts diff --git a/src/hooks/useReferencedRecord.ts b/packages/web-ui/src/hooks/useReferencedRecord.ts similarity index 73% rename from src/hooks/useReferencedRecord.ts rename to packages/web-ui/src/hooks/useReferencedRecord.ts index 0984f4ec8..ce90ad528 100644 --- a/src/hooks/useReferencedRecord.ts +++ b/packages/web-ui/src/hooks/useReferencedRecord.ts @@ -1,9 +1,10 @@ import {useState, useEffect, useCallback} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import type {ForeignKey, QueryResult} from '@/types/editor'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; import {quoteTableRef} from '@/utils/identifiers'; import {isForeignKeyValueNavigable, buildForeignKeyFilterClause} from '@/utils/foreignKeys'; +import type {TypedCommandCaller} from '@/api/contract'; +import {useTabularisClient} from './useTabularisClient'; type DriverArg = string | PluginManifest | DriverCapabilities | null | undefined; @@ -20,15 +21,18 @@ export interface FetchReferencedRecordParams { /** * Fetches rows from the referenced table that match the foreign key value. */ -export async function fetchReferencedRecord({ - connectionId, - fk, - value, - driver, - schema, - database, - sourceColumnType, -}: FetchReferencedRecordParams): Promise { +export async function fetchReferencedRecord( + { + connectionId, + fk, + value, + driver, + schema, + database, + sourceColumnType, + }: FetchReferencedRecordParams, + client: TypedCommandCaller, +): Promise { if (!isForeignKeyValueNavigable(value)) { return {columns: [], rows: [], affected_rows: 0}; } @@ -37,7 +41,7 @@ export async function fetchReferencedRecord({ const query = `SELECT * FROM ${quotedTable} WHERE ${filterClause}`; - return invoke('execute_query', { + return client.call('execute_query', { connectionId, query, limit: 100, @@ -66,6 +70,7 @@ export function useReferencedRecord({ database, sourceColumnType, }: UseReferencedRecordParams) { + const client = useTabularisClient(); const [result, setResult] = useState(null); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); @@ -81,15 +86,18 @@ export function useReferencedRecord({ setError(null); try { - const res = await fetchReferencedRecord({ - connectionId, - fk, - value, - driver, - schema, - database, - sourceColumnType, - }); + const res = await fetchReferencedRecord( + { + connectionId, + fk, + value, + driver, + schema, + database, + sourceColumnType, + }, + client, + ); setResult(res); } catch (err) { console.error('Failed to fetch referenced record:', err); @@ -98,7 +106,7 @@ export function useReferencedRecord({ } finally { setIsLoading(false); } - }, [connectionId, fk, value, driver, schema, database, sourceColumnType]); + }, [client, connectionId, fk, value, driver, schema, database, sourceColumnType]); useEffect(() => { loadRecord(); diff --git a/src/hooks/useResultTypeColors.ts b/packages/web-ui/src/hooks/useResultTypeColors.ts similarity index 100% rename from src/hooks/useResultTypeColors.ts rename to packages/web-ui/src/hooks/useResultTypeColors.ts diff --git a/src/hooks/useRightSidebar.ts b/packages/web-ui/src/hooks/useRightSidebar.ts similarity index 100% rename from src/hooks/useRightSidebar.ts rename to packages/web-ui/src/hooks/useRightSidebar.ts diff --git a/packages/web-ui/src/hooks/useRightSidebarResize.ts b/packages/web-ui/src/hooks/useRightSidebarResize.ts new file mode 100644 index 000000000..bef41ffd6 --- /dev/null +++ b/packages/web-ui/src/hooks/useRightSidebarResize.ts @@ -0,0 +1,58 @@ +import {useCallback, useRef} from 'react'; +import {useUiState} from './useUiState'; +import {UI_STATE_KEYS} from '@/utils/uiStateStore'; + +const MIN_WIDTH = 320; +const DEFAULT_WIDTH = 384; +/** Coalesces writes while the handle is being dragged. */ +const PERSIST_DEBOUNCE_MS = 300; + +const computeMaxWidth = () => + typeof window === 'undefined' ? 800 : Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.5)); + +export const useRightSidebarResize = () => { + const [stored, setWidth] = useUiState(UI_STATE_KEYS.rowEditorSidebarWidth, DEFAULT_WIDTH, { + debounceMs: PERSIST_DEBOUNCE_MS, + }); + const width = + typeof stored === 'number' && Number.isFinite(stored) + ? Math.max(MIN_WIDTH, Math.min(stored, computeMaxWidth())) + : DEFAULT_WIDTH; + const isDragging = useRef(false); + + const startResize = useCallback( + (e: React.MouseEvent) => { + e.preventDefault(); + isDragging.current = true; + document.body.style.cursor = 'col-resize'; + document.body.style.userSelect = 'none'; + + const handleMove = (ev: MouseEvent) => { + if (!isDragging.current) return; + const maxWidth = computeMaxWidth(); + const next = window.innerWidth - ev.clientX; + if (next < MIN_WIDTH) { + setWidth(MIN_WIDTH); + } else if (next > maxWidth) { + setWidth(maxWidth); + } else { + setWidth(next); + } + }; + + const stop = () => { + isDragging.current = false; + document.body.style.cursor = ''; + document.body.style.userSelect = ''; + document.removeEventListener('mousemove', handleMove); + document.removeEventListener('mouseup', stop); + }; + + document.addEventListener('mousemove', handleMove); + document.addEventListener('mouseup', stop); + }, + [setWidth], + ); + + return {width, startResize}; +}; diff --git a/src/hooks/useRowEditor.ts b/packages/web-ui/src/hooks/useRowEditor.ts similarity index 100% rename from src/hooks/useRowEditor.ts rename to packages/web-ui/src/hooks/useRowEditor.ts diff --git a/packages/web-ui/src/hooks/useRowEditorResize.ts b/packages/web-ui/src/hooks/useRowEditorResize.ts new file mode 100644 index 000000000..034457bc9 --- /dev/null +++ b/packages/web-ui/src/hooks/useRowEditorResize.ts @@ -0,0 +1,58 @@ +import {useCallback, useRef} from 'react'; +import {useUiState} from './useUiState'; +import {UI_STATE_KEYS} from '@/utils/uiStateStore'; + +const MIN_WIDTH = 320; +const DEFAULT_WIDTH = 384; +/** Coalesces writes while the handle is being dragged. */ +const PERSIST_DEBOUNCE_MS = 300; + +const computeMaxWidth = () => + typeof window === 'undefined' ? 1200 : Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.9)); + +export const useRowEditorResize = () => { + const [stored, setWidth] = useUiState(UI_STATE_KEYS.rowEditorSidebarWidth, DEFAULT_WIDTH, { + debounceMs: PERSIST_DEBOUNCE_MS, + }); + const width = + typeof stored === 'number' && Number.isFinite(stored) + ? Math.max(MIN_WIDTH, stored) + : DEFAULT_WIDTH; + const isDragging = useRef(false); + + const startResize = useCallback( + (e: React.MouseEvent) => { + e.preventDefault(); + isDragging.current = true; + document.body.style.cursor = 'col-resize'; + document.body.style.userSelect = 'none'; + + const handleMove = (ev: MouseEvent) => { + if (!isDragging.current) return; + const maxWidth = computeMaxWidth(); + const next = window.innerWidth - ev.clientX; + if (next < MIN_WIDTH) { + setWidth(MIN_WIDTH); + } else if (next > maxWidth) { + setWidth(maxWidth); + } else { + setWidth(next); + } + }; + + const stop = () => { + isDragging.current = false; + document.body.style.cursor = ''; + document.body.style.userSelect = ''; + document.removeEventListener('mousemove', handleMove); + document.removeEventListener('mouseup', stop); + }; + + document.addEventListener('mousemove', handleMove); + document.addEventListener('mouseup', stop); + }, + [setWidth], + ); + + return {width, startResize}; +}; diff --git a/src/hooks/useSavedQueries.ts b/packages/web-ui/src/hooks/useSavedQueries.ts similarity index 100% rename from src/hooks/useSavedQueries.ts rename to packages/web-ui/src/hooks/useSavedQueries.ts diff --git a/packages/web-ui/src/hooks/useSecondaryWindows.ts b/packages/web-ui/src/hooks/useSecondaryWindows.ts new file mode 100644 index 000000000..837ca978e --- /dev/null +++ b/packages/web-ui/src/hooks/useSecondaryWindows.ts @@ -0,0 +1,101 @@ +import {useCallback, useMemo} from 'react'; +import { + BROWSER_ROUTES, + buildResultsWindowRoute, + buildRouteWindowLabel, + buildSchemaDiagramRoute, + buildVisualExplainRoute, + type SchemaDiagramRouteParams, +} from '@/routing'; +import {usePlatformCapabilities} from './usePlatformCapabilities'; +import { + RESULTS_CLOSE_REQUEST_EVENT, + type ResultsCloseRequest, +} from '@/platform/secondaryWindowSessions'; + +export function useSecondaryWindows() { + const platform = usePlatformCapabilities(); + + const openResultsWindow = useCallback( + async (sessionId: string, title: string) => { + await platform.openRoute({ + route: buildResultsWindowRoute(sessionId), + target: 'new', + label: buildRouteWindowLabel('results-window', sessionId), + title, + window: {width: 900, height: 600, minWidth: 500, minHeight: 300}, + }); + }, + [platform], + ); + + const closeResultsWindow = useCallback( + async (sessionId: string) => { + await platform.publishRouteEvent(RESULTS_CLOSE_REQUEST_EVENT, { + sessionId, + }); + }, + [platform], + ); + + const openSchemaDiagram = useCallback( + async (params: SchemaDiagramRouteParams) => { + const schemaLabel = params.schema ?? ''; + await platform.openRoute({ + route: buildSchemaDiagramRoute(params), + target: 'new', + label: buildRouteWindowLabel( + 'er-diagram', + params.connectionId, + params.databaseName, + schemaLabel, + ), + title: `tabularis - ${params.databaseName} (${params.connectionName}${ + params.schema ? `/${params.schema}` : '' + })`, + window: {width: 1200, height: 800}, + }); + }, + [platform], + ); + + const openTaskManager = useCallback(async () => { + await platform.openRoute({ + route: BROWSER_ROUTES.taskManager, + target: 'new', + label: 'task-manager', + title: 'tabularis - Task Manager', + window: {width: 900, height: 600, minWidth: 700, minHeight: 450}, + }); + }, [platform]); + + const openVisualExplain = useCallback( + async (connectionId: string, query: string) => { + await platform.openRoute({ + route: buildVisualExplainRoute(connectionId, query), + target: 'new', + label: 'visual-explain', + title: 'tabularis - Visual Explain', + window: {width: 1280, height: 820, minWidth: 900, minHeight: 600}, + }); + }, + [platform], + ); + + return useMemo( + () => ({ + openResultsWindow, + closeResultsWindow, + openSchemaDiagram, + openTaskManager, + openVisualExplain, + }), + [ + closeResultsWindow, + openResultsWindow, + openSchemaDiagram, + openTaskManager, + openVisualExplain, + ], + ); +} diff --git a/src/hooks/useSettings.ts b/packages/web-ui/src/hooks/useSettings.ts similarity index 100% rename from src/hooks/useSettings.ts rename to packages/web-ui/src/hooks/useSettings.ts diff --git a/packages/web-ui/src/hooks/useSidebarResize.ts b/packages/web-ui/src/hooks/useSidebarResize.ts new file mode 100644 index 000000000..aeeee8458 --- /dev/null +++ b/packages/web-ui/src/hooks/useSidebarResize.ts @@ -0,0 +1,66 @@ +import {useRef, useEffect, useCallback} from 'react'; +import {useUiState} from './useUiState'; +import {UI_STATE_KEYS} from '@/utils/uiStateStore'; + +const MIN_WIDTH = 150; +const MAX_WIDTH = 600; +const DEFAULT_WIDTH = 256; +const COLLAPSE_THRESHOLD = 100; +/** Coalesces writes while the handle is being dragged. */ +const PERSIST_DEBOUNCE_MS = 300; + +export const useSidebarResize = (onCollapse?: () => void) => { + const [storedWidth, setSidebarWidth] = useUiState(UI_STATE_KEYS.sidebarWidth, DEFAULT_WIDTH, { + debounceMs: PERSIST_DEBOUNCE_MS, + }); + const sidebarWidth = + typeof storedWidth === 'number' && Number.isFinite(storedWidth) + ? storedWidth + : DEFAULT_WIDTH; + const isDragging = useRef(false); + const onCollapseRef = useRef(onCollapse); + + useEffect(() => { + onCollapseRef.current = onCollapse; + }, [onCollapse]); + + const startResize = useCallback( + (e: React.MouseEvent) => { + e.preventDefault(); + isDragging.current = true; + document.body.style.cursor = 'col-resize'; + + const handleResize = (e: MouseEvent) => { + if (!isDragging.current) return; + const newWidth = e.clientX - 64; // Subtract primary sidebar width (w-16 = 64px) + + // Auto-collapse when dragged below threshold + if (newWidth < COLLAPSE_THRESHOLD && onCollapseRef.current) { + isDragging.current = false; + document.body.style.cursor = 'default'; + document.removeEventListener('mousemove', handleResize); + document.removeEventListener('mouseup', stopResize); + onCollapseRef.current(); + return; + } + + if (newWidth > MIN_WIDTH && newWidth < MAX_WIDTH) { + setSidebarWidth(newWidth); + } + }; + + const stopResize = () => { + isDragging.current = false; + document.body.style.cursor = 'default'; + document.removeEventListener('mousemove', handleResize); + document.removeEventListener('mouseup', stopResize); + }; + + document.addEventListener('mousemove', handleResize); + document.addEventListener('mouseup', stopResize); + }, + [setSidebarWidth], + ); + + return {sidebarWidth, startResize}; +}; diff --git a/src/hooks/useSqlAutocompleteRegistration.ts b/packages/web-ui/src/hooks/useSqlAutocompleteRegistration.ts similarity index 97% rename from src/hooks/useSqlAutocompleteRegistration.ts rename to packages/web-ui/src/hooks/useSqlAutocompleteRegistration.ts index 37423e877..540e51a56 100644 --- a/src/hooks/useSqlAutocompleteRegistration.ts +++ b/packages/web-ui/src/hooks/useSqlAutocompleteRegistration.ts @@ -5,6 +5,7 @@ import {useDatabase} from './useDatabase'; import {SettingsContext} from '@/contexts/SettingsContext'; import {usesMultiDatabaseLayout, isSchemaBasedMultiDb} from '@/utils/database'; import {registerSqlAutocomplete, disposeSqlAutocomplete} from '@/utils/autocomplete'; +import {useTabularisClient} from './useTabularisClient'; type Options = { monaco?: Monaco | null; @@ -21,6 +22,7 @@ type Options = { * Pass `monaco` from the main editor when available; otherwise load it on demand. */ export function useSqlAutocompleteRegistration(connectionId: string | null, options?: Options) { + const client = useTabularisClient(); const { tables, activeDriver, @@ -119,6 +121,7 @@ export function useSqlAutocompleteRegistration(connectionId: string | null, opti effectiveTables, defaultNamespace, activeCapabilities ?? activeDriver ?? null, + client, keywordCase, ); @@ -146,6 +149,7 @@ export function useSqlAutocompleteRegistration(connectionId: string | null, opti }); return cleanup; }, [ + client, connectionId, enabled, options?.monaco, diff --git a/src/hooks/useSshAskpass.ts b/packages/web-ui/src/hooks/useSshAskpass.ts similarity index 63% rename from src/hooks/useSshAskpass.ts rename to packages/web-ui/src/hooks/useSshAskpass.ts index 25f950529..2abef3ada 100644 --- a/src/hooks/useSshAskpass.ts +++ b/packages/web-ui/src/hooks/useSshAskpass.ts @@ -1,10 +1,9 @@ import {useCallback, useEffect, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; import type {SshAskpassRequest} from '@/types/askpass'; +import {useTabularisClient} from './useTabularisClient'; -const REQUEST_EVENT = 'ssh-askpass://request'; -const DISMISS_EVENT = 'ssh-askpass://dismiss'; +const REQUEST_EVENT = 'ssh-askpass://request' as const; +const DISMISS_EVENT = 'ssh-askpass://dismiss' as const; export interface UseSshAskpassResult { /** Oldest pending prompt, shown one at a time. */ @@ -21,27 +20,31 @@ export interface UseSshAskpassResult { * notifications). Mounted once at the App level via `SshAskpassGate`. */ export function useSshAskpass(): UseSshAskpassResult { + const client = useTabularisClient(); const [queue, setQueue] = useState([]); useEffect(() => { - const unlistenRequest = listen(REQUEST_EVENT, (event) => { - setQueue((prev) => [...prev, event.payload]); + const unlistenRequest = client.subscribe(REQUEST_EVENT, (payload) => { + setQueue((prev) => [...prev, payload]); }); // The backend dismisses prompts that timed out or whose security-key // notification was satisfied (key touched). - const unlistenDismiss = listen(DISMISS_EVENT, (event) => { - setQueue((prev) => prev.filter((r) => r.id !== event.payload)); + const unlistenDismiss = client.subscribe(DISMISS_EVENT, (id) => { + setQueue((prev) => prev.filter((request) => request.id !== id)); }); return () => { unlistenRequest.then((fn) => fn()).catch(() => {}); unlistenDismiss.then((fn) => fn()).catch(() => {}); }; - }, []); + }, [client]); - const respond = useCallback(async (id: number, response: string | null) => { - setQueue((prev) => prev.filter((r) => r.id !== id)); - await invoke('respond_ssh_askpass', {id, response}); - }, []); + const respond = useCallback( + async (id: number, response: string | null) => { + setQueue((prev) => prev.filter((request) => request.id !== id)); + await client.call('respond_ssh_askpass', {id, response}); + }, + [client], + ); const dismiss = useCallback((id: number) => { setQueue((prev) => prev.filter((r) => r.id !== id)); diff --git a/src/hooks/useTabSwitcher.ts b/packages/web-ui/src/hooks/useTabSwitcher.ts similarity index 100% rename from src/hooks/useTabSwitcher.ts rename to packages/web-ui/src/hooks/useTabSwitcher.ts diff --git a/packages/web-ui/src/hooks/useTabularisClient.ts b/packages/web-ui/src/hooks/useTabularisClient.ts new file mode 100644 index 000000000..eacd4f19d --- /dev/null +++ b/packages/web-ui/src/hooks/useTabularisClient.ts @@ -0,0 +1,12 @@ +import {useContext} from 'react'; +import {TabularisClientContext} from '@/contexts/TabularisClientContext'; + +export function useTabularisClient() { + const client = useContext(TabularisClientContext); + + if (!client) { + throw new Error('useTabularisClient must be used within TabularisClientProvider'); + } + + return client; +} diff --git a/src/hooks/useTaskManager.ts b/packages/web-ui/src/hooks/useTaskManager.ts similarity index 87% rename from src/hooks/useTaskManager.ts rename to packages/web-ui/src/hooks/useTaskManager.ts index 2bc97100d..e411a4b47 100644 --- a/src/hooks/useTaskManager.ts +++ b/packages/web-ui/src/hooks/useTaskManager.ts @@ -1,7 +1,7 @@ import {useCallback, useEffect, useRef, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import type {ProcessInfo, SystemStats} from '@/utils/taskManager'; import {buildProcessRows} from '@/utils/taskManager'; +import {useTabularisClient} from './useTabularisClient'; const POLL_INTERVAL_MS = 2000; @@ -18,6 +18,7 @@ interface UseTaskManagerResult { } export function useTaskManager(): UseTaskManagerResult { + const client = useTabularisClient(); const [processes, setProcesses] = useState([]); const [systemStats, setSystemStats] = useState(null); const [loading, setLoading] = useState(true); @@ -29,8 +30,8 @@ export function useTaskManager(): UseTaskManagerResult { const fetchData = useCallback(async () => { try { const [procs, stats] = await Promise.all([ - invoke('get_process_list'), - invoke('get_system_stats'), + client.call('get_process_list', undefined), + client.call('get_system_stats', undefined), ]); setProcesses(buildProcessRows(procs)); setSystemStats(stats); @@ -40,7 +41,7 @@ export function useTaskManager(): UseTaskManagerResult { } finally { setLoading(false); } - }, []); + }, [client]); const refresh = useCallback(async () => { setLoading(true); @@ -61,7 +62,7 @@ export function useTaskManager(): UseTaskManagerResult { async (pluginId: string) => { setKilling((prev) => new Set(prev).add(pluginId)); try { - await invoke('kill_plugin_process', {pluginId}); + await client.call('kill_plugin_process', {pluginId}); await fetchData(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); @@ -73,15 +74,14 @@ export function useTaskManager(): UseTaskManagerResult { }); } }, - [fetchData], + [client, fetchData], ); const restartProcess = useCallback( async (pluginId: string) => { setRestarting((prev) => new Set(prev).add(pluginId)); try { - await invoke('disable_plugin', {pluginId}); - await invoke('enable_plugin', {pluginId}); + await client.call('restart_plugin_process', {pluginId}); await fetchData(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); @@ -93,7 +93,7 @@ export function useTaskManager(): UseTaskManagerResult { }); } }, - [fetchData], + [client, fetchData], ); return { diff --git a/src/hooks/useTheme.ts b/packages/web-ui/src/hooks/useTheme.ts similarity index 100% rename from src/hooks/useTheme.ts rename to packages/web-ui/src/hooks/useTheme.ts diff --git a/src/hooks/useTimingLabels.ts b/packages/web-ui/src/hooks/useTimingLabels.ts similarity index 100% rename from src/hooks/useTimingLabels.ts rename to packages/web-ui/src/hooks/useTimingLabels.ts diff --git a/src/hooks/useToast.ts b/packages/web-ui/src/hooks/useToast.ts similarity index 100% rename from src/hooks/useToast.ts rename to packages/web-ui/src/hooks/useToast.ts diff --git a/packages/web-ui/src/hooks/useUiState.ts b/packages/web-ui/src/hooks/useUiState.ts new file mode 100644 index 000000000..7df356ce2 --- /dev/null +++ b/packages/web-ui/src/hooks/useUiState.ts @@ -0,0 +1,33 @@ +import {useCallback, useSyncExternalStore} from 'react'; +import {uiStateStore, type UiStateKeyDefinition, type UiStateStore} from '@/utils/uiStateStore'; + +interface UseUiStateOptions { + debounceMs?: number; + store?: UiStateStore; +} + +/** Reads and writes one shared UI state value (see utils/uiStateStore). */ +export function useUiState( + definition: UiStateKeyDefinition, + fallback: T, + {debounceMs, store = uiStateStore}: UseUiStateOptions = {}, +): [T, (value: T) => void] { + const {key} = definition; + const value = useSyncExternalStore( + useCallback((listener: () => void) => store.subscribe(listener), [store]), + () => store.get(key, fallback), + ); + const setValue = useCallback( + (next: T) => store.set(key, next, {debounceMs}), + [store, key, debounceMs], + ); + return [value, setValue]; +} + +/** True once the backend values were loaded (or the load failed). */ +export function useUiStateReady(store: UiStateStore = uiStateStore): boolean { + return useSyncExternalStore( + useCallback((listener: () => void) => store.subscribe(listener), [store]), + () => store.isReady(), + ); +} diff --git a/src/hooks/useUpdate.ts b/packages/web-ui/src/hooks/useUpdate.ts similarity index 100% rename from src/hooks/useUpdate.ts rename to packages/web-ui/src/hooks/useUpdate.ts diff --git a/src/i18n/config.ts b/packages/web-ui/src/i18n/config.ts similarity index 100% rename from src/i18n/config.ts rename to packages/web-ui/src/i18n/config.ts diff --git a/src/i18n/language.ts b/packages/web-ui/src/i18n/language.ts similarity index 100% rename from src/i18n/language.ts rename to packages/web-ui/src/i18n/language.ts diff --git a/src/i18n/localeBackend.ts b/packages/web-ui/src/i18n/localeBackend.ts similarity index 100% rename from src/i18n/localeBackend.ts rename to packages/web-ui/src/i18n/localeBackend.ts diff --git a/src/i18n/locales/de.json b/packages/web-ui/src/i18n/locales/de.json similarity index 98% rename from src/i18n/locales/de.json rename to packages/web-ui/src/i18n/locales/de.json index 23e74f8fe..546b4261a 100644 --- a/src/i18n/locales/de.json +++ b/packages/web-ui/src/i18n/locales/de.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Serverdateien durchsuchen", + "subtitle": "Datei oder Ordner auf dem Tabularis-Host auswählen", + "roots": "Konfigurierte Stammordner", + "empty": "Dieser Ordner ist leer", + "fileName": "Dateiname", + "select": "Auswählen" + }, "toolbar": { "valuePicker": { "open": "Aus Werten wählen", @@ -585,6 +593,8 @@ "appearance": "Darstellung", "localization": "Lokalisierung", "themeSelection": "Themaauswahl", + "importTheme": "Theme importieren", + "exportTheme": "Theme exportieren", "themeMode": "Themenmodus", "themeModeDesc": "Wähle ein festes Thema oder folge dem Hell-/Dunkelmodus des Systems.", "themeModeStatic": "Statisch", @@ -1014,12 +1024,14 @@ "apply": "Anwenden", "restartRequired": "Neustart erforderlich", "restartRequiredDesc": "Tabularis verwendet {{path}} nach einem Neustart.", - "restartNow": "Jetzt neu starten" + "restartNow": "Jetzt neu starten", + "restartServer": "Starte den Tabularis-Server neu, um die Änderung anzuwenden." }, "backup": { "title": "Backup", "directory": "Sicherungsordner", "directoryDesc": "Noch kein Ordner ausgewählt.", + "serverDirectoryDesc": "Serverordnerpfad. Sicherungen werden auf dem Tabularis-Host gespeichert; die manuelle Aktion lädt zusätzlich eine Browserkopie herunter.", "chooseDirectory": "Ordner wählen", "password": "Sicherungspasswort", "passwordDesc": "Sicherungen sind immer verschlüsselt. Das Passwort wird im System-Schlüsselbund gespeichert.", @@ -1151,7 +1163,12 @@ "error": "Update-Fehler", "currentVersion": "Aktuelle Version", "managedByPackageManager": "Updates werden von {{source}} verwaltet", - "managedByPackageManagerDesc": "Verwende deinen Paketmanager, um Tabularis zu aktualisieren." + "managedByPackageManagerDesc": "Verwende deinen Paketmanager, um Tabularis zu aktualisieren.", + "serverManagedTitle": "Serververwaltete Updates", + "serverManagedDesc": "Ein Browser kann die Tabularis-Serverdatei nicht ersetzen. Bitte den Serveradministrator, der Upgrade-Anleitung zu folgen.", + "serverVersion": "Serverversion", + "serverBuild": "Server-Build", + "openServerUpgradeGuide": "Server-Upgrade-Anleitung öffnen" }, "ai": { "assist": "AI Assist", @@ -1190,6 +1207,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", @@ -2149,7 +2167,12 @@ }, "jsonViewer": { "close": "Schließen", - "save": "Speichern" + "save": "Speichern", + "noSession": "Keine Sitzungs-ID angegeben", + "sessionExpired": "Diese JSON-Viewer-Sitzung ist abgelaufen. Kehren Sie zur Quelle zurück und öffnen Sie sie erneut." + }, + "secondaryWindows": { + "sessionExpired": "Diese Sitzung des sekundären Fensters ist abgelaufen. Kehren Sie zur Quelle zurück und öffnen Sie es erneut." }, "jsonCell": { "expand": "JSON-Baum ein-/ausklappen", diff --git a/src/i18n/locales/en.json b/packages/web-ui/src/i18n/locales/en.json similarity index 99% rename from src/i18n/locales/en.json rename to packages/web-ui/src/i18n/locales/en.json index ff896fa61..cac26f916 100644 --- a/src/i18n/locales/en.json +++ b/packages/web-ui/src/i18n/locales/en.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Browse server files", + "subtitle": "Select a file or folder on the Tabularis host", + "roots": "Configured roots", + "empty": "This folder is empty", + "fileName": "File name", + "select": "Select" + }, "toolbar": { "valuePicker": { "open": "Pick from values", @@ -603,6 +611,8 @@ "appearance": "Appearance", "localization": "Localization", "themeSelection": "Theme Selection", + "importTheme": "Import theme", + "exportTheme": "Export theme", "themeMode": "Theme Mode", "themeModeDesc": "Choose a fixed theme, or follow your system's light/dark appearance.", "themeModeStatic": "Static", @@ -1080,12 +1090,14 @@ "apply": "Apply", "restartRequired": "Restart required", "restartRequiredDesc": "Tabularis will use {{path}} after a restart.", - "restartNow": "Restart now" + "restartNow": "Restart now", + "restartServer": "Restart the Tabularis server to apply." }, "backup": { "title": "Backup", "directory": "Backup folder", "directoryDesc": "No folder selected yet.", + "serverDirectoryDesc": "Server folder path. Backups are written on the Tabularis host; the manual action also downloads a browser copy.", "chooseDirectory": "Choose folder", "password": "Backup password", "passwordDesc": "Backups are always encrypted. The password is stored in the system keychain.", @@ -1218,7 +1230,12 @@ "currentVersion": "Current version", "managedByPackageManager": "Updates managed by {{source}}", "managedByPackageManagerDesc": "Use your package manager to update Tabularis.", - "nightlyWarning": "Nightly builds are unstable pre-releases. Only assets built for the nightly channel are installed." + "nightlyWarning": "Nightly builds are unstable pre-releases. Only assets built for the nightly channel are installed.", + "serverManagedTitle": "Server-managed updates", + "serverManagedDesc": "A browser cannot replace the Tabularis server binary. Ask the server administrator to follow the upgrade guide.", + "serverVersion": "Server version", + "serverBuild": "Server build", + "openServerUpgradeGuide": "Open server upgrade guide" }, "ai": { "assist": "AI Assist", @@ -1257,6 +1274,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", @@ -2256,7 +2274,12 @@ }, "jsonViewer": { "close": "Close", - "save": "Save" + "save": "Save", + "noSession": "No session ID provided", + "sessionExpired": "This JSON viewer session expired. Return to the source and open it again." + }, + "secondaryWindows": { + "sessionExpired": "This secondary window session expired. Return to the source and open it again." }, "jsonCell": { "expand": "Toggle inline JSON tree", diff --git a/src/i18n/locales/es.json b/packages/web-ui/src/i18n/locales/es.json similarity index 98% rename from src/i18n/locales/es.json rename to packages/web-ui/src/i18n/locales/es.json index 189b8db8e..64edf5f95 100644 --- a/src/i18n/locales/es.json +++ b/packages/web-ui/src/i18n/locales/es.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Explorar archivos del servidor", + "subtitle": "Selecciona un archivo o carpeta en el host de Tabularis", + "roots": "Rutas configuradas", + "empty": "Esta carpeta está vacía", + "fileName": "Nombre del archivo", + "select": "Seleccionar" + }, "toolbar": { "valuePicker": { "open": "Elegir entre valores", @@ -610,6 +618,8 @@ "appearance": "Apariencia", "localization": "Localización", "themeSelection": "Selección de Tema", + "importTheme": "Importar tema", + "exportTheme": "Exportar tema", "themeMode": "Modo de tema", "themeModeDesc": "Elige un tema fijo o sigue la apariencia clara/oscura del sistema.", "themeModeStatic": "Estático", @@ -1039,12 +1049,14 @@ "apply": "Aplicar", "restartRequired": "Reinicio necesario", "restartRequiredDesc": "Tabularis usará {{path}} después de reiniciar.", - "restartNow": "Reiniciar ahora" + "restartNow": "Reiniciar ahora", + "restartServer": "Reinicia el servidor de Tabularis para aplicar." }, "backup": { "title": "Backup", "directory": "Carpeta de copias", "directoryDesc": "Ninguna carpeta seleccionada.", + "serverDirectoryDesc": "Ruta de carpeta del servidor. Las copias se guardan en el host de Tabularis; la acción manual también descarga una copia en el navegador.", "chooseDirectory": "Elegir carpeta", "password": "Contraseña de copia", "passwordDesc": "Las copias siempre están cifradas. La contraseña se guarda en el llavero del sistema.", @@ -1179,7 +1191,12 @@ "error": "Error de Actualización", "currentVersion": "Versión actual", "managedByPackageManager": "Actualizaciones gestionadas por {{source}}", - "managedByPackageManagerDesc": "Usa tu gestor de paquetes para actualizar Tabularis." + "managedByPackageManagerDesc": "Usa tu gestor de paquetes para actualizar Tabularis.", + "serverManagedTitle": "Actualizaciones gestionadas por el servidor", + "serverManagedDesc": "Un navegador no puede sustituir el binario del servidor Tabularis. Pide al administrador que siga la guía de actualización.", + "serverVersion": "Versión del servidor", + "serverBuild": "Compilación del servidor", + "openServerUpgradeGuide": "Abrir la guía de actualización del servidor" }, "ai": { "assist": "Asistente IA", @@ -1218,6 +1235,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", @@ -2110,7 +2128,12 @@ }, "jsonViewer": { "close": "Cerrar", - "save": "Guardar" + "save": "Guardar", + "noSession": "No se proporcionó un ID de sesión", + "sessionExpired": "Esta sesión del visor JSON ha caducado. Vuelve al origen y ábrela de nuevo." + }, + "secondaryWindows": { + "sessionExpired": "Esta sesión de ventana secundaria ha caducado. Vuelve al origen y ábrela de nuevo." }, "jsonCell": { "expand": "Expandir/contraer árbol JSON", diff --git a/src/i18n/locales/fr.json b/packages/web-ui/src/i18n/locales/fr.json similarity index 98% rename from src/i18n/locales/fr.json rename to packages/web-ui/src/i18n/locales/fr.json index 234804064..346ba690b 100644 --- a/src/i18n/locales/fr.json +++ b/packages/web-ui/src/i18n/locales/fr.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Parcourir les fichiers du serveur", + "subtitle": "Sélectionnez un fichier ou dossier sur l'hôte Tabularis", + "roots": "Racines configurées", + "empty": "Ce dossier est vide", + "fileName": "Nom du fichier", + "select": "Sélectionner" + }, "toolbar": { "valuePicker": { "open": "Choisir parmi les valeurs", @@ -603,6 +611,8 @@ "appearance": "Apparence", "localization": "Localisation", "themeSelection": "Choix du thème", + "importTheme": "Importer un thème", + "exportTheme": "Exporter le thème", "themeMode": "Mode de thème", "themeModeDesc": "Choisissez un thème fixe ou suivez l'apparence claire/sombre du système.", "themeModeStatic": "Statique", @@ -1048,12 +1058,14 @@ "apply": "Appliquer", "restartRequired": "Redémarrage requis", "restartRequiredDesc": "Tabularis utilisera {{path}} après un redémarrage.", - "restartNow": "Redémarrer maintenant" + "restartNow": "Redémarrer maintenant", + "restartServer": "Redémarrez le serveur Tabularis pour appliquer." }, "backup": { "title": "Backup", "directory": "Dossier de sauvegarde", "directoryDesc": "Aucun dossier sélectionné.", + "serverDirectoryDesc": "Chemin du dossier serveur. Les sauvegardes sont écrites sur l’hôte Tabularis ; l’action manuelle télécharge aussi une copie dans le navigateur.", "chooseDirectory": "Choisir un dossier", "password": "Mot de passe de sauvegarde", "passwordDesc": "Les sauvegardes sont toujours chiffrées. Le mot de passe est stocké dans le trousseau du système.", @@ -1188,7 +1200,12 @@ "error": "Erreur de mise à jour", "currentVersion": "Version actuelle", "managedByPackageManager": "Mises à jour gérées par {{source}}", - "managedByPackageManagerDesc": "Utilisez votre gestionnaire de paquets pour mettre à jour Tabularis." + "managedByPackageManagerDesc": "Utilisez votre gestionnaire de paquets pour mettre à jour Tabularis.", + "serverManagedTitle": "Mises à jour gérées par le serveur", + "serverManagedDesc": "Un navigateur ne peut pas remplacer le binaire du serveur Tabularis. Demandez à l’administrateur de suivre le guide de mise à niveau.", + "serverVersion": "Version du serveur", + "serverBuild": "Build du serveur", + "openServerUpgradeGuide": "Ouvrir le guide de mise à niveau du serveur" }, "ai": { "assist": "AI Assist", @@ -1227,6 +1244,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", @@ -2225,7 +2243,12 @@ }, "jsonViewer": { "close": "Fermer", - "save": "Enregistrer" + "save": "Enregistrer", + "noSession": "Aucun identifiant de session fourni", + "sessionExpired": "Cette session du visualiseur JSON a expiré. Revenez à la source et ouvrez-la à nouveau." + }, + "secondaryWindows": { + "sessionExpired": "Cette session de fenêtre secondaire a expiré. Revenez à la source et ouvrez-la à nouveau." }, "jsonCell": { "expand": "Afficher/masquer l'arbre JSON", diff --git a/src/i18n/locales/it.json b/packages/web-ui/src/i18n/locales/it.json similarity index 98% rename from src/i18n/locales/it.json rename to packages/web-ui/src/i18n/locales/it.json index 5554e3574..13af4cc9f 100644 --- a/src/i18n/locales/it.json +++ b/packages/web-ui/src/i18n/locales/it.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Sfoglia i file del server", + "subtitle": "Seleziona un file o una cartella sull'host Tabularis", + "roots": "Percorsi configurati", + "empty": "Questa cartella è vuota", + "fileName": "Nome file", + "select": "Seleziona" + }, "toolbar": { "valuePicker": { "open": "Scegli tra i valori", @@ -617,6 +625,8 @@ "appearance": "Aspetto", "localization": "Localizzazione", "themeSelection": "Selezione Tema", + "importTheme": "Importa tema", + "exportTheme": "Esporta tema", "themeMode": "Modalità tema", "themeModeDesc": "Scegli un tema fisso o segui l'aspetto chiaro/scuro del sistema.", "themeModeStatic": "Statico", @@ -1074,12 +1084,14 @@ "apply": "Applica", "restartRequired": "Riavvio necessario", "restartRequiredDesc": "Tabularis userà {{path}} dopo il riavvio.", - "restartNow": "Riavvia ora" + "restartNow": "Riavvia ora", + "restartServer": "Riavvia il server Tabularis per applicare." }, "backup": { "title": "Backup", "directory": "Cartella di backup", "directoryDesc": "Nessuna cartella selezionata.", + "serverDirectoryDesc": "Percorso della cartella sul server. I backup vengono scritti sull’host Tabularis; l’azione manuale scarica anche una copia nel browser.", "chooseDirectory": "Scegli cartella", "password": "Password di backup", "passwordDesc": "I backup sono sempre cifrati. La password è salvata nel portachiavi di sistema.", @@ -1214,7 +1226,12 @@ "error": "Errore Aggiornamento", "currentVersion": "Versione attuale", "managedByPackageManager": "Aggiornamenti gestiti da {{source}}", - "managedByPackageManagerDesc": "Usa il tuo package manager per aggiornare Tabularis." + "managedByPackageManagerDesc": "Usa il tuo package manager per aggiornare Tabularis.", + "serverManagedTitle": "Aggiornamenti gestiti dal server", + "serverManagedDesc": "Un browser non può sostituire il binario del server Tabularis. Chiedi all’amministratore di seguire la guida all’aggiornamento.", + "serverVersion": "Versione del server", + "serverBuild": "Build del server", + "openServerUpgradeGuide": "Apri la guida all’aggiornamento del server" }, "ai": { "assist": "AI Assist", @@ -1253,6 +1270,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", @@ -2209,7 +2227,12 @@ }, "jsonViewer": { "close": "Chiudi", - "save": "Salva" + "save": "Salva", + "noSession": "Nessun ID sessione fornito", + "sessionExpired": "Questa sessione del visualizzatore JSON è scaduta. Torna all'origine e riaprila." + }, + "secondaryWindows": { + "sessionExpired": "Questa sessione della finestra secondaria è scaduta. Torna all'origine e riaprila." }, "jsonCell": { "expand": "Espandi/comprimi albero JSON", diff --git a/src/i18n/locales/ja.json b/packages/web-ui/src/i18n/locales/ja.json similarity index 98% rename from src/i18n/locales/ja.json rename to packages/web-ui/src/i18n/locales/ja.json index 79129a635..dc1385015 100644 --- a/src/i18n/locales/ja.json +++ b/packages/web-ui/src/i18n/locales/ja.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "サーバーファイルを参照", + "subtitle": "Tabularis ホスト上のファイルまたはフォルダーを選択します", + "roots": "設定済みルート", + "empty": "このフォルダーは空です", + "fileName": "ファイル名", + "select": "選択" + }, "toolbar": { "valuePicker": { "open": "値から選択", @@ -596,6 +604,8 @@ "appearance": "外観", "localization": "ローカライズ", "themeSelection": "テーマ選択", + "importTheme": "テーマをインポート", + "exportTheme": "テーマをエクスポート", "themeMode": "テーマモード", "themeModeDesc": "固定テーマを選ぶか、システムのライト/ダーク表示に従うかを選択します。", "themeModeStatic": "固定", @@ -1028,12 +1038,14 @@ "apply": "適用", "restartRequired": "再起動が必要です", "restartRequiredDesc": "再起動後、Tabularis は {{path}} を使用します。", - "restartNow": "今すぐ再起動" + "restartNow": "今すぐ再起動", + "restartServer": "適用するには Tabularis サーバーを再起動してください。" }, "backup": { "title": "バックアップ", "directory": "バックアップフォルダー", "directoryDesc": "フォルダーが選択されていません。", + "serverDirectoryDesc": "サーバー上のフォルダーパスです。バックアップは Tabularis ホストに保存され、手動実行時にはブラウザーにもコピーがダウンロードされます。", "chooseDirectory": "フォルダーを選択", "password": "バックアップパスワード", "passwordDesc": "バックアップは常に暗号化されます。パスワードはシステムのキーチェーンに保存されます。", @@ -1165,7 +1177,12 @@ "error": "アップデートエラー", "currentVersion": "現在のバージョン", "managedByPackageManager": "アップデートは {{source}} によって管理されています", - "managedByPackageManagerDesc": "Tabularis のアップデートにはパッケージマネージャを使用してください。" + "managedByPackageManagerDesc": "Tabularis のアップデートにはパッケージマネージャを使用してください。", + "serverManagedTitle": "サーバー管理のアップデート", + "serverManagedDesc": "ブラウザから Tabularis サーバーのバイナリを置き換えることはできません。サーバー管理者にアップグレードガイドの手順を依頼してください。", + "serverVersion": "サーバーバージョン", + "serverBuild": "サーバービルド", + "openServerUpgradeGuide": "サーバーアップグレードガイドを開く" }, "ai": { "assist": "AI Assist", @@ -1204,6 +1221,7 @@ "dbNameRequired": "データベース名は必須です", "connectionUriRequiresKeychain": "接続 URI は OS のキーチェーンに保存する必要があります。「パスワードをキーチェーンに保存」を有効にしてください。", "connectionUriRequired": "接続 URI は必須です", + "connectionUriStored": "OS のキーチェーンに保存されています。置き換えるには新しい接続文字列を貼り付けてください。", "connectionString": "?????", "connectionStringPlaceholder": "?: mysql://user:pass@localhost:3306/db", "connectionStringExample": "???????", @@ -2180,6 +2198,15 @@ "expandAll": "すべて展開", "collapseAll": "すべて折りたたむ" }, + "jsonViewer": { + "close": "閉じる", + "save": "保存", + "noSession": "セッション ID が指定されていません", + "sessionExpired": "この JSON ビューアーのセッションは期限切れです。元の画面に戻って、もう一度開いてください。" + }, + "secondaryWindows": { + "sessionExpired": "このサブウィンドウのセッションは期限切れです。元の画面に戻って、もう一度開いてください。" + }, "rowEditor": { "title": "行を編集", "subtitle": "行 #{{row}}", diff --git a/src/i18n/locales/ko.json b/packages/web-ui/src/i18n/locales/ko.json similarity index 98% rename from src/i18n/locales/ko.json rename to packages/web-ui/src/i18n/locales/ko.json index 41d881574..0753806b9 100644 --- a/src/i18n/locales/ko.json +++ b/packages/web-ui/src/i18n/locales/ko.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "서버 파일 찾아보기", + "subtitle": "Tabularis 호스트에서 파일 또는 폴더를 선택하세요", + "roots": "설정된 루트", + "empty": "이 폴더는 비어 있습니다", + "fileName": "파일 이름", + "select": "선택" + }, "toolbar": { "valuePicker": { "open": "값에서 선택", @@ -548,6 +556,8 @@ "appearance": "모양", "localization": "지역화", "themeSelection": "테마 선택", + "importTheme": "테마 가져오기", + "exportTheme": "테마 내보내기", "themeMode": "테마 모드", "themeModeDesc": "고정 테마를 사용하거나 시스템의 라이트/다크 모드를 따릅니다.", "themeModeStatic": "고정", @@ -989,12 +999,14 @@ "apply": "적용", "restartRequired": "재시작 필요", "restartRequiredDesc": "재시작 후 Tabularis는 {{path}}를 사용합니다.", - "restartNow": "지금 재시작" + "restartNow": "지금 재시작", + "restartServer": "적용하려면 Tabularis 서버를 다시 시작하세요." }, "backup": { "title": "백업", "directory": "백업 폴더", "directoryDesc": "아직 폴더가 선택되지 않았습니다.", + "serverDirectoryDesc": "서버 폴더 경로입니다. 백업은 Tabularis 호스트에 저장되며 수동 실행 시 브라우저 사본도 다운로드됩니다.", "chooseDirectory": "폴더 선택", "password": "백업 비밀번호", "passwordDesc": "백업은 항상 암호화됩니다. 비밀번호는 시스템 키체인에 저장됩니다.", @@ -1126,7 +1138,12 @@ "error": "업데이트 오류", "currentVersion": "현재 버전", "managedByPackageManager": "{{source}}(으)로 관리되는 업데이트", - "managedByPackageManagerDesc": "패키지 관리자를 사용해 Tabularis를 업데이트하세요." + "managedByPackageManagerDesc": "패키지 관리자를 사용해 Tabularis를 업데이트하세요.", + "serverManagedTitle": "서버 관리 업데이트", + "serverManagedDesc": "브라우저에서는 Tabularis 서버 바이너리를 교체할 수 없습니다. 서버 관리자에게 업그레이드 가이드를 따르도록 요청하세요.", + "serverVersion": "서버 버전", + "serverBuild": "서버 빌드", + "openServerUpgradeGuide": "서버 업그레이드 가이드 열기" }, "ai": { "assist": "AI 어시스트", @@ -1165,6 +1182,7 @@ "dbNameRequired": "데이터베이스 이름은 필수입니다", "connectionUriRequiresKeychain": "연결 URI는 OS 키체인에 저장해야 합니다. “키체인에 비밀번호 저장”을 활성화하세요.", "connectionUriRequired": "연결 URI는 필수입니다", + "connectionUriStored": "OS 키체인에 저장되어 있습니다. 바꾸려면 새 연결 문자열을 붙여 넣으세요.", "connectionString": "?? ???", "connectionStringPlaceholder": "?: mysql://user:pass@localhost:3306/db", "connectionStringExample": "?? ??? ??", @@ -2159,7 +2177,12 @@ }, "jsonViewer": { "close": "닫기", - "save": "저장" + "save": "저장", + "noSession": "세션 ID가 제공되지 않았습니다", + "sessionExpired": "이 JSON 뷰어 세션이 만료되었습니다. 원본으로 돌아가 다시 여세요." + }, + "secondaryWindows": { + "sessionExpired": "이 보조 창 세션이 만료되었습니다. 원본으로 돌아가 다시 여세요." }, "jsonCell": { "expand": "인라인 JSON 트리 토글", diff --git a/src/i18n/locales/pt-BR.json b/packages/web-ui/src/i18n/locales/pt-BR.json similarity index 99% rename from src/i18n/locales/pt-BR.json rename to packages/web-ui/src/i18n/locales/pt-BR.json index 1edd6a625..34e37c964 100644 --- a/src/i18n/locales/pt-BR.json +++ b/packages/web-ui/src/i18n/locales/pt-BR.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Explorar arquivos do servidor", + "subtitle": "Selecione um arquivo ou pasta no host do Tabularis", + "roots": "Raízes configuradas", + "empty": "Esta pasta está vazia", + "fileName": "Nome do arquivo", + "select": "Selecionar" + }, "toolbar": { "valuePicker": { "open": "Escolher entre os valores", @@ -574,6 +582,8 @@ "appearance": "Aparência", "localization": "Localização", "themeSelection": "Seleção de Tema", + "importTheme": "Importar tema", + "exportTheme": "Exportar tema", "themeMode": "Modo de tema", "themeModeDesc": "Escolha um tema fixo ou siga a aparência clara/escura do sistema.", "themeModeStatic": "Estático", @@ -1028,12 +1038,14 @@ "apply": "Aplicar", "restartRequired": "Reinicialização necessária", "restartRequiredDesc": "O Tabularis usará {{path}} após reiniciar.", - "restartNow": "Reiniciar agora" + "restartNow": "Reiniciar agora", + "restartServer": "Reinicie o servidor do Tabularis para aplicar." }, "backup": { "title": "Backup", "directory": "Pasta de backup", "directoryDesc": "Nenhuma pasta selecionada ainda.", + "serverDirectoryDesc": "Caminho da pasta no servidor. Os backups são gravados no host do Tabularis; a ação manual também baixa uma cópia no navegador.", "chooseDirectory": "Escolher pasta", "password": "Senha do backup", "passwordDesc": "Os backups são sempre criptografados. A senha é armazenada no chaveiro do sistema.", @@ -1169,7 +1181,12 @@ "currentVersion": "Versão atual", "managedByPackageManager": "Atualizações gerenciadas por {{source}}", "managedByPackageManagerDesc": "Use seu gerenciador de pacotes para atualizar o Tabularis.", - "nightlyWarning": "As versões Nightly são pré-lançamentos instáveis. Apenas os artefatos compilados para o canal nightly são instalados." + "nightlyWarning": "As versões Nightly são pré-lançamentos instáveis. Apenas os artefatos compilados para o canal nightly são instalados.", + "serverManagedTitle": "Atualizações gerenciadas pelo servidor", + "serverManagedDesc": "Um navegador não pode substituir o binário do servidor Tabularis. Peça ao administrador para seguir o guia de atualização.", + "serverVersion": "Versão do servidor", + "serverBuild": "Build do servidor", + "openServerUpgradeGuide": "Abrir guia de atualização do servidor" }, "ai": { "assist": "Assistente de IA", @@ -1207,6 +1224,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", @@ -2199,7 +2217,12 @@ }, "jsonViewer": { "close": "Fechar", - "save": "Salvar" + "save": "Salvar", + "noSession": "Nenhum ID de sessão foi fornecido", + "sessionExpired": "Esta sessão do visualizador JSON expirou. Volte à origem e abra-a novamente." + }, + "secondaryWindows": { + "sessionExpired": "Esta sessão da janela secundária expirou. Volte à origem e abra-a novamente." }, "jsonCell": { "expand": "Alternar árvore JSON em linha", diff --git a/src/i18n/locales/ru.json b/packages/web-ui/src/i18n/locales/ru.json similarity index 98% rename from src/i18n/locales/ru.json rename to packages/web-ui/src/i18n/locales/ru.json index 023d51aa1..bd0bcf894 100644 --- a/src/i18n/locales/ru.json +++ b/packages/web-ui/src/i18n/locales/ru.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Обзор файлов сервера", + "subtitle": "Выберите файл или папку на сервере Tabularis", + "roots": "Настроенные корневые каталоги", + "empty": "Эта папка пуста", + "fileName": "Имя файла", + "select": "Выбрать" + }, "toolbar": { "valuePicker": { "open": "Выбрать из значений", @@ -580,6 +588,8 @@ "appearance": "Внешний вид", "localization": "Локализация", "themeSelection": "Выбор темы", + "importTheme": "Импортировать тему", + "exportTheme": "Экспортировать тему", "themeMode": "Режим темы", "themeModeDesc": "Выберите фиксированную тему или следуйте светлому/тёмному оформлению системы.", "themeModeStatic": "Статичная", @@ -1007,12 +1017,14 @@ "apply": "Применить", "restartRequired": "Требуется перезапуск", "restartRequiredDesc": "После перезапуска Tabularis будет использовать {{path}}.", - "restartNow": "Перезапустить сейчас" + "restartNow": "Перезапустить сейчас", + "restartServer": "Перезапустите сервер Tabularis, чтобы применить изменения." }, "backup": { "title": "Бэкап", "directory": "Папка резервных копий", "directoryDesc": "Папка не выбрана.", + "serverDirectoryDesc": "Путь к папке на сервере. Резервные копии сохраняются на хосте Tabularis; при ручном запуске копия также загружается в браузер.", "chooseDirectory": "Выбрать папку", "password": "Пароль резервной копии", "passwordDesc": "Резервные копии всегда зашифрованы. Пароль хранится в системном хранилище ключей.", @@ -1150,7 +1162,12 @@ "error": "Ошибка обновления", "currentVersion": "Текущая версия", "managedByPackageManager": "Обновления управляются через {{source}}", - "managedByPackageManagerDesc": "Для обновления Tabularis используйте менеджер пакетов." + "managedByPackageManagerDesc": "Для обновления Tabularis используйте менеджер пакетов.", + "serverManagedTitle": "Обновления под управлением сервера", + "serverManagedDesc": "Браузер не может заменить бинарный файл сервера Tabularis. Попросите администратора следовать руководству по обновлению.", + "serverVersion": "Версия сервера", + "serverBuild": "Сборка сервера", + "openServerUpgradeGuide": "Открыть руководство по обновлению сервера" }, "ai": { "assist": "AI-помощник", @@ -1189,6 +1206,7 @@ "dbNameRequired": "Название базы данных обязательно", "connectionUriRequiresKeychain": "URI подключения должны храниться в системном хранилище ключей. Включите «Сохранять пароли в Keychain», чтобы продолжить.", "connectionUriRequired": "Требуется URI подключения", + "connectionUriStored": "Сохранено в системной связке ключей. Вставьте новую строку подключения, чтобы заменить её.", "connectionString": "?????? ???????????", "connectionStringPlaceholder": "????????, mysql://user:pass@localhost:3306/db", "connectionStringExample": "?????? ?????? ???????????", @@ -2200,7 +2218,12 @@ }, "jsonViewer": { "close": "Закрыть", - "save": "Сохранить" + "save": "Сохранить", + "noSession": "Идентификатор сеанса не указан", + "sessionExpired": "Сеанс просмотра JSON истёк. Вернитесь к источнику и откройте его снова." + }, + "secondaryWindows": { + "sessionExpired": "Сеанс дополнительного окна истёк. Вернитесь к источнику и откройте его снова." }, "jsonCell": { "expand": "Показать/скрыть JSON-дерево", diff --git a/src/i18n/locales/tl.json b/packages/web-ui/src/i18n/locales/tl.json similarity index 98% rename from src/i18n/locales/tl.json rename to packages/web-ui/src/i18n/locales/tl.json index cfeb35ebe..516bd50b0 100644 --- a/src/i18n/locales/tl.json +++ b/packages/web-ui/src/i18n/locales/tl.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "Mag-browse ng mga file sa server", + "subtitle": "Pumili ng file o folder sa Tabularis host", + "roots": "Mga naka-configure na root", + "empty": "Walang laman ang folder na ito", + "fileName": "Pangalan ng file", + "select": "Piliin" + }, "toolbar": { "valuePicker": { "open": "Pumili mula sa mga value", @@ -603,6 +611,8 @@ "appearance": "Hitsura", "localization": "Lokalization", "themeSelection": "Pagpili ng Theme", + "importTheme": "Mag-import ng theme", + "exportTheme": "Mag-export ng theme", "themeMode": "Mode ng Theme", "themeModeDesc": "Pumili ng nakapirming theme, o sundin ang light/dark na hitsura ng system.", "themeModeStatic": "Static", @@ -1044,12 +1054,14 @@ "apply": "Ilapat", "restartRequired": "Kailangan i-restart", "restartRequiredDesc": "Gagamitin ng Tabularis ang {{path}} pagkatapos ng restart.", - "restartNow": "I-restart ngayon" + "restartNow": "I-restart ngayon", + "restartServer": "I-restart ang Tabularis server para mailapat." }, "backup": { "title": "Backup", "directory": "Folder ng backup", "directoryDesc": "Wala pang napipiling folder.", + "serverDirectoryDesc": "Path ng folder sa server. Isinusulat ang mga backup sa Tabularis host; nagda-download din ang manual na aksyon ng kopya sa browser.", "chooseDirectory": "Pumili ng folder", "password": "Password ng backup", "passwordDesc": "Palaging naka-encrypt ang mga backup. Nakatago ang password sa system keychain.", @@ -1181,7 +1193,12 @@ "error": "Error sa Update", "currentVersion": "Kasalukuyang bersyon", "managedByPackageManager": "Ang mga update ay pinamamahalaan ng {{source}}", - "managedByPackageManagerDesc": "Gamitin ang iyong package manager para i-update ang Tabularis." + "managedByPackageManagerDesc": "Gamitin ang iyong package manager para i-update ang Tabularis.", + "serverManagedTitle": "Mga update na pinamamahalaan ng server", + "serverManagedDesc": "Hindi mapapalitan ng browser ang binary ng Tabularis server. Hilingin sa administrator na sundin ang gabay sa pag-upgrade.", + "serverVersion": "Bersyon ng server", + "serverBuild": "Build ng server", + "openServerUpgradeGuide": "Buksan ang gabay sa pag-upgrade ng server" }, "ai": { "assist": "AI Assist", @@ -1220,6 +1237,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", @@ -2215,7 +2233,12 @@ }, "jsonViewer": { "close": "Isara", - "save": "I-save" + "save": "I-save", + "noSession": "Walang ibinigay na session ID", + "sessionExpired": "Nag-expire ang session ng JSON viewer. Bumalik sa pinagmulan at buksan itong muli." + }, + "secondaryWindows": { + "sessionExpired": "Nag-expire ang session ng pangalawang window. Bumalik sa pinagmulan at buksan itong muli." }, "jsonCell": { "expand": "I-toggle ang inline JSON tree", diff --git a/src/i18n/locales/zh.json b/packages/web-ui/src/i18n/locales/zh.json similarity index 98% rename from src/i18n/locales/zh.json rename to packages/web-ui/src/i18n/locales/zh.json index 969c166e6..7fae28210 100644 --- a/src/i18n/locales/zh.json +++ b/packages/web-ui/src/i18n/locales/zh.json @@ -1,4 +1,12 @@ { + "serverFilePicker": { + "title": "浏览服务器文件", + "subtitle": "在 Tabularis 主机上选择文件或文件夹", + "roots": "已配置的根目录", + "empty": "此文件夹为空", + "fileName": "文件名", + "select": "选择" + }, "toolbar": { "valuePicker": { "open": "从值中选择", @@ -585,6 +593,8 @@ "appearance": "外观", "localization": "本地化", "themeSelection": "主题选择", + "importTheme": "导入主题", + "exportTheme": "导出主题", "themeMode": "主题模式", "themeModeDesc": "选择固定主题,或跟随系统的浅色/深色外观。", "themeModeStatic": "固定", @@ -974,12 +984,14 @@ "apply": "应用", "restartRequired": "需要重启", "restartRequiredDesc": "重启后 Tabularis 将使用 {{path}}。", - "restartNow": "立即重启" + "restartNow": "立即重启", + "restartServer": "重启 Tabularis 服务器以应用更改。" }, "backup": { "title": "备份", "directory": "备份文件夹", "directoryDesc": "尚未选择文件夹。", + "serverDirectoryDesc": "服务器文件夹路径。备份会写入 Tabularis 主机;手动执行时还会在浏览器中下载一份副本。", "chooseDirectory": "选择文件夹", "password": "备份密码", "passwordDesc": "备份始终加密。密码保存在系统钥匙串中。", @@ -1127,7 +1139,12 @@ "error": "更新错误", "currentVersion": "当前版本", "managedByPackageManager": "更新由 {{source}} 管理", - "managedByPackageManagerDesc": "使用您的包管理器更新 Tabularis。" + "managedByPackageManagerDesc": "使用您的包管理器更新 Tabularis。", + "serverManagedTitle": "服务器管理的更新", + "serverManagedDesc": "浏览器无法替换 Tabularis 服务器二进制文件。请让服务器管理员按照升级指南操作。", + "serverVersion": "服务器版本", + "serverBuild": "服务器构建", + "openServerUpgradeGuide": "打开服务器升级指南" }, "ai": { "assist": "AI 辅助", @@ -1166,6 +1183,7 @@ "dbNameRequired": "数据库名称是必需的", "connectionUriRequiresKeychain": "连接 URI 必须保存在操作系统密钥链中。请启用“在密钥链中保存密码”后继续。", "connectionUriRequired": "连接 URI 是必需的", + "connectionUriStored": "已保存在系统钥匙串中。粘贴新的连接字符串即可替换。", "connectionString": "?????", "connectionStringPlaceholder": "?? mysql://user:pass@localhost:3306/db", "connectionStringExample": "???????", @@ -2102,7 +2120,12 @@ }, "jsonViewer": { "close": "关闭", - "save": "保存" + "save": "保存", + "noSession": "未提供会话 ID", + "sessionExpired": "此 JSON 查看器会话已过期。请返回来源并重新打开。" + }, + "secondaryWindows": { + "sessionExpired": "此次级窗口会话已过期。请返回来源并重新打开。" }, "jsonCell": { "expand": "展开/收起 JSON 树", diff --git a/src/i18n/registryLocale.ts b/packages/web-ui/src/i18n/registryLocale.ts similarity index 100% rename from src/i18n/registryLocale.ts rename to packages/web-ui/src/i18n/registryLocale.ts diff --git a/src/index.css b/packages/web-ui/src/index.css similarity index 100% rename from src/index.css rename to packages/web-ui/src/index.css diff --git a/packages/web-ui/src/main.tsx b/packages/web-ui/src/main.tsx new file mode 100644 index 000000000..d0e748a7e --- /dev/null +++ b/packages/web-ui/src/main.tsx @@ -0,0 +1,82 @@ +// Import polyfills first to make Buffer available globally +import '@/polyfills'; + +import React, {Suspense} from 'react'; +import ReactDOM from 'react-dom/client'; +import {App} from '@/App'; +import '@/index.css'; +import '@/i18n/config'; +import {DatabaseProvider} from '@/contexts/DatabaseProvider'; +import {ToastProvider} from '@/contexts/ToastProvider'; +import {SettingsProvider} from '@/contexts/SettingsProvider'; +import {SavedQueriesProvider} from '@/contexts/SavedQueriesProvider'; +import {QueryHistoryProvider} from '@/contexts/QueryHistoryProvider'; +import {EditorProvider} from '@/contexts/EditorProvider'; +import {ThemeProvider} from '@/contexts/ThemeProvider'; +import {UpdateProvider} from '@/contexts/UpdateProvider'; +import {ProductionGuardProvider} from '@/contexts/ProductionGuardContext'; +import {bootstrapTabularisRuntime} from '@/api/bootstrap'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; +import {TauriPlatformCapabilities} from '@/platform/tauriCapabilities'; +import {BrowserPlatformCapabilities} from '@/platform/browserCapabilities'; +import {PlatformCapabilitiesProvider} from '@/contexts/PlatformCapabilitiesProvider'; +import {detectPlatformEnvironment} from '@/platform/environment'; +import {toErrorMessage} from '@/utils/errors'; +import {BrowserCapabilityFallbacks} from '@/components/ui/BrowserCapabilityFallbacks'; +import {registerActivePlatformCapabilities} from '@/platform/activeCapabilities'; +import {LoadingState} from '@/components/ui/LoadingState'; +import {UiStateProvider} from '@/contexts/UiStateProvider'; + +const rootElement = document.getElementById('root') as HTMLElement; +const environment = detectPlatformEnvironment(); + +async function startApplication() { + const {client: tabularisClient, session} = await bootstrapTabularisRuntime(environment); + const platformCapabilities = + environment === 'tauri' + ? new TauriPlatformCapabilities() + : new BrowserPlatformCapabilities( + tabularisClient, + undefined, + session?.capabilities.serverFileBrowser ?? false, + ); + registerActivePlatformCapabilities(platformCapabilities); + + ReactDOM.createRoot(rootElement).render( + + }> + + + + + + + + + + + + + + + + + + + + + + + + + + + + , + ); +} + +void startApplication().catch((error: unknown) => { + console.error('Failed to start Tabularis:', error); + rootElement.textContent = `Unable to start Tabularis: ${toErrorMessage(error)}`; +}); diff --git a/src/monacoLoader.ts b/packages/web-ui/src/monacoLoader.ts similarity index 100% rename from src/monacoLoader.ts rename to packages/web-ui/src/monacoLoader.ts diff --git a/packages/web-ui/src/pages/ConnectionEditorRoute.tsx b/packages/web-ui/src/pages/ConnectionEditorRoute.tsx new file mode 100644 index 000000000..81124e846 --- /dev/null +++ b/packages/web-ui/src/pages/ConnectionEditorRoute.tsx @@ -0,0 +1,55 @@ +import {useEffect, useRef} from 'react'; +import {useNavigate, useParams} from 'react-router-dom'; + +import {EditorErrorBoundary} from '@/components/ui/EditorErrorBoundary'; +import {useDatabase} from '@/hooks/useDatabase'; +import {BROWSER_ROUTES, buildEditorRoute} from '@/routing'; +import {Editor} from './Editor'; + +export function ConnectionEditorRoute() { + const {connectionId} = useParams<{connectionId: string}>(); + const navigate = useNavigate(); + const {activeConnectionId, connect, isConnectionOpen, switchConnection} = useDatabase(); + const handledConnectionIdRef = useRef(null); + const currentRouteConnectionIdRef = useRef(connectionId); + + useEffect(() => { + currentRouteConnectionIdRef.current = connectionId; + }, [connectionId]); + + useEffect(() => { + if (!connectionId) { + if (activeConnectionId) { + navigate(buildEditorRoute(activeConnectionId), {replace: true}); + } else { + navigate(BROWSER_ROUTES.connections, {replace: true}); + } + return; + } + + if (handledConnectionIdRef.current !== connectionId) { + handledConnectionIdRef.current = connectionId; + + if (isConnectionOpen(connectionId)) { + switchConnection(connectionId); + } else { + void connect(connectionId).catch(() => { + if (currentRouteConnectionIdRef.current === connectionId) { + navigate(BROWSER_ROUTES.connections, {replace: true}); + } + }); + } + return; + } + + if (activeConnectionId && activeConnectionId !== connectionId) { + navigate(buildEditorRoute(activeConnectionId), {replace: true}); + } + }, [activeConnectionId, connect, connectionId, isConnectionOpen, navigate, switchConnection]); + + return ( + + + + ); +} diff --git a/src/pages/Connections.tsx b/packages/web-ui/src/pages/Connections.tsx similarity index 98% rename from src/pages/Connections.tsx rename to packages/web-ui/src/pages/Connections.tsx index 50061d1d7..7ddb4a4a7 100644 --- a/src/pages/Connections.tsx +++ b/packages/web-ui/src/pages/Connections.tsx @@ -1,5 +1,4 @@ import {restoreSession} from '@/utils/restoreSession'; -import {getCurrentWindow} from '@tauri-apps/api/window'; import {lazy, Suspense, useState, useEffect, useMemo, useRef, useCallback} from 'react'; import {createPortal} from 'react-dom'; import {useNavigate, useLocation} from 'react-router-dom'; @@ -7,9 +6,6 @@ import {useTranslation} from 'react-i18next'; import {LoadingState} from '@/components/ui/LoadingState'; import {ConfirmModal} from '@/components/modals/ConfirmModal'; import {ExportConnectionsModal, type ExportMode} from '@/components/modals/ExportConnectionsModal'; -import {invoke} from '@tauri-apps/api/core'; -import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; import { Database, Plus, @@ -56,6 +52,10 @@ import {ConnectionErrorBanner} from '@/components/ConnectionErrorBanner'; import {PostgresPluginMigrationBanner} from '@/components/banners/PostgresPluginMigrationBanner'; import {BetaBadge} from '@/components/ui/BetaBadge'; import {useCreateSqliteDatabase} from '@/hooks/useCreateSqliteDatabase'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {saveGeneratedFile} from '@/utils/connectionFiles'; +import {buildEditorRoute} from '@/routing'; import { useBuiltinPostgresMigration, type MigrationOutcome, @@ -64,7 +64,6 @@ import {useConnectionCatalogue} from '@/hooks/useConnectionCatalogue'; import {useToast} from '@/hooks/useToast'; import {useEscapeKey} from '@/hooks/useEscapeKey'; import {buildPluginIssueUrl, resolvePluginRepoUrl} from '@/utils/pluginIssueReport'; -import {openUrl} from '@tauri-apps/plugin-opener'; import {APP_VERSION} from '@/version'; const NewConnectionModal = lazy(() => @@ -83,11 +82,12 @@ const MigrationChecklistModal = lazy(() => })), ); -const windowLabel = getCurrentWindow().label; let autoConnectAttempted = false; export const Connections = () => { const {t} = useTranslation(); + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); const {settings, isLoading: isSettingsLoading} = useSettings(); const navigate = useNavigate(); const location = useLocation(); @@ -243,7 +243,7 @@ export const Connections = () => { error: outcome.error ?? outcome.startupError ?? 'unknown error', migratedFromDriver: builtinId, }); - void openUrl(url); + void platform.openExternalUrl(url); }; if (outcome.status === 'ok') { @@ -328,6 +328,7 @@ export const Connections = () => { undoMigration, catalogueRegistry, installedPlugins, + platform, showToast, t, ], @@ -336,6 +337,8 @@ export const Connections = () => { useEffect(() => { if (autoConnectAttempted) return; // Dedicated connection windows have their own URL-driven restore flow. + // Browser sessions have no native windows; they behave like the main window. + const windowLabel = platform.currentWindowLabel(); if (windowLabel && windowLabel !== 'main') return; if (isSettingsLoading) return; if (connections.length === 0) return; @@ -344,21 +347,25 @@ export const Connections = () => { void (async () => { try { const [openIds, activeId] = await Promise.all([ - invoke('get_last_open_connections'), - invoke('get_last_active_connection'), + client.call('get_last_open_connections', undefined), + client.call('get_last_active_connection', undefined), ]); const toRestore = (openIds ?? []).filter( (id) => connections.some((c) => c.id === id) && !isConnectionOpen(id), ); if (toRestore.length === 0) return; + let foregroundId: string | null = null; await restoreSession({ connectionIds: toRestore, activeId, connect, - onForegroundStart: setConnectingId, + onForegroundStart: (id) => { + foregroundId = id; + setConnectingId(id); + }, onForegroundReady: () => { setConnectingId(null); - navigate('/editor'); + if (foregroundId) navigate(buildEditorRoute(foregroundId)); }, onError: (id, error) => console.error(`Auto-connect to connection ${id} failed:`, error), @@ -370,12 +377,14 @@ export const Connections = () => { } })(); }, [ + client, connections, settings.autoConnectLastConnection, isSettingsLoading, isConnectionOpen, connect, navigate, + platform, ]); // Initialize collapsed groups from saved state @@ -505,22 +514,13 @@ export const Connections = () => { const handleExport = async (mode: ExportMode, password?: string) => { try { - const payload = await invoke('export_connections_payload', { - includeSecrets: mode !== 'noSecrets', + const generated = await client.call('export_connections_file', { + mode, + ...(password ? {password} : {}), connectionIds: exportSelectionOnly && selectedIds.size > 0 ? [...selectedIds] : null, }); - const fileContent = - mode === 'encrypted' - ? await invoke('encrypt_export_payload', {payload, password}) - : payload; - const path = await save({ - defaultPath: 'tabularis-connections.json', - filters: [{name: 'JSON', extensions: ['json']}], - }); - if (path) { - await writeTextFile(path, JSON.stringify(fileContent, null, 2)); - } + await saveGeneratedFile(client, platform, generated); } catch (e) { console.error('Export failed:', e); setError(toErrorMessage(e)); @@ -637,7 +637,7 @@ export const Connections = () => { try { for (const id of ids) { if (isConnectionOpenAnywhere(id)) await disconnect(id); - await invoke('delete_connection', {id}); + await client.call('delete_connection', {id}); } } catch (e) { console.error(e); @@ -687,7 +687,7 @@ export const Connections = () => { setError(null); if (isConnectionOpen(conn.id)) { switchConnection(conn.id); - navigate('/editor'); + navigate(buildEditorRoute(conn.id)); return; } // Open in another window: focus that window instead of opening a duplicate. @@ -698,7 +698,7 @@ export const Connections = () => { setConnectingId(conn.id); try { await connect(conn.id); - navigate('/editor'); + navigate(buildEditorRoute(conn.id)); } catch (e) { setError( `${t('connections.failConnect', {name: conn.name})}\n\nError: ${toErrorMessage(e)}`, @@ -754,7 +754,7 @@ export const Connections = () => { setConfirmModal(null); try { if (isConnectionOpenAnywhere(id)) await disconnect(id); - await invoke('delete_connection', {id}); + await client.call('delete_connection', {id}); void loadConnections(); } catch (e) { console.error(e); @@ -819,9 +819,7 @@ export const Connections = () => { const handleDuplicate = async (id: string) => { try { - const newConn = await invoke('duplicate_connection', { - id, - }); + const newConn = await client.call('duplicate_connection', {id}); await loadConnections(); void openEdit(newConn); } catch (e) { diff --git a/src/pages/Editor.tsx b/packages/web-ui/src/pages/Editor.tsx similarity index 95% rename from src/pages/Editor.tsx rename to packages/web-ui/src/pages/Editor.tsx index 992ed3c87..3d4fd1673 100644 --- a/src/pages/Editor.tsx +++ b/packages/web-ui/src/pages/Editor.tsx @@ -1,3 +1,4 @@ +import {toErrorMessage} from '@/utils/errors'; import {useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo, useId} from 'react'; import {useAutoRefresh} from '@/hooks/useAutoRefresh'; import {hasPendingTableEdits, tableRefreshIdentity} from '@/utils/autoRefresh'; @@ -110,9 +111,6 @@ import { WrapText, } from 'lucide-react'; import {invoke} from '@tauri-apps/api/core'; -import {listen, emit} from '@tauri-apps/api/event'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; -import {open as openFileDialog, save as saveFileDialog} from '@tauri-apps/plugin-dialog'; import {TableToolbar} from '@/components/ui/TableToolbar'; import {DataGrid, type DataGridCommandTarget} from '@/components/ui/DataGrid'; import {MultiResultPanel} from '@/components/ui/MultiResultPanel'; @@ -165,15 +163,18 @@ import { RESULTS_ACTION_EVENT, RESULTS_READY_EVENT, RESULTS_CLOSED_EVENT, - resultsCopyEvent, - resultsSyncEvent, + RESULTS_COPY_EVENT, + RESULTS_SYNC_EVENT, type CopiedRows, type ResultsCopyPayload, type ResultsWindowActionHandlers, - type ResultsReadyPayload, - type ResultsActionEnvelope, - type ResultsClosedPayload, } from '@/utils/resultsWindowSync'; +import type { + ResultsSessionAction, + ResultsSessionClosed, + ResultsSessionRequest, + ResultsSessionSnapshot, +} from '@/platform/secondaryWindowSessions'; import {SqlEditorWrapper} from '@/components/ui/SqlEditorWrapper'; import {NotebookView} from '@/components/notebook/NotebookView'; import {UserManagementView} from '@/components/users/UserManagementView'; @@ -191,12 +192,14 @@ import {useSettings} from '@/hooks/useSettings'; import {useEditor} from '@/hooks/useEditor'; import {useConnectionLayoutContext} from '@/hooks/useConnectionLayoutContext'; import {useKeybindings} from '@/hooks/useKeybindings'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import {openSqlFile, saveSqlFile} from '@/utils/sqlFileTransfer'; +import {useSecondaryWindows} from '@/hooks/useSecondaryWindows'; import type { BatchStatementResult, QueryResult, Tab, PendingInsertion, - TableColumn, ForeignKey, EditorNavigationIntent, EditorNavigationRequest, @@ -218,7 +221,6 @@ import { loadPluginColumnStats, type ColumnStats, type ColumnStatsSupport, - type PluginColumnStats, type PluginColumnStatsFetcher, } from '@/utils/columnStats'; import {getNextSortClause} from '@/utils/tableToolbar'; @@ -235,10 +237,17 @@ import {getTabScrollState, getAdjacentTabIndex, isFocusedPane} from '@/utils/tab import {computeAutoScrollSpeed} from '@/utils/notebookDnd'; import {buildExportFileName} from '@/utils/exportFileName'; import clsx from 'clsx'; - -interface ExportProgress { - rows_processed: number; -} +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import {createRequestId} from '@/api/errors'; +import {downloadGeneratedFile, downloadTextFile} from '@/utils/fileDownloads'; + +const LOADED_ROWS_EXPORT_MIME_TYPES: Record = { + csv: 'text/csv', + json: 'application/json', + ndjson: 'application/x-ndjson', + markdown: 'text/markdown', + html: 'text/html', +}; const CHEVRON_SELECT_STYLE: React.CSSProperties = { backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, @@ -272,6 +281,9 @@ interface EditorProps { } export const Editor = ({commandScopeId}: EditorProps) => { + const client = useTabularisClient(); + const platform = usePlatformCapabilities(); + const {openResultsWindow, closeResultsWindow} = useSecondaryWindows(); const {t} = useTranslation(); const { activeConnectionId, @@ -375,35 +387,37 @@ export const Editor = ({commandScopeId}: EditorProps) => { transactionTabIdsRef.current = transactionTabIds; useEffect(() => { - const unlisten = listen<{session_id: string; in_transaction: boolean}>( - 'session-transaction-state', - (event) => { - const {session_id: sessionId, in_transaction: inTransaction} = event.payload; - setTransactionTabIds((prev) => { - if (prev.has(sessionId) === inTransaction) return prev; - const next = new Set(prev); - if (inTransaction) next.add(sessionId); - else next.delete(sessionId); - return next; - }); - }, - ); + const unlisten = client.subscribe('session-transaction-state', (event) => { + const {session_id: sessionId, in_transaction: inTransaction} = event; + setTransactionTabIds((prev) => { + if (prev.has(sessionId) === inTransaction) return prev; + const next = new Set(prev); + if (inTransaction) next.add(sessionId); + else next.delete(sessionId); + return next; + }); + }); return () => { unlisten.then((f) => f()); }; - }, []); + }, [client]); useEffect(() => { - const unlisten = listen('export_progress', (event) => { - setExportState((prev) => ({ - ...prev, - rowsProcessed: event.payload.rows_processed, - })); - }); + let disposed = false; + let unsubscribe: (() => void) | undefined; + void client + .subscribe('export_progress', ({rows_processed: rowsProcessed}) => { + setExportState((prev) => ({...prev, rowsProcessed})); + }) + .then((stop) => { + if (disposed) stop(); + else unsubscribe = stop; + }); return () => { - unlisten.then((f) => f()); + disposed = true; + unsubscribe?.(); }; - }, []); + }, [client]); const handleTabContextMenu = (e: React.MouseEvent, tabId: string) => { e.preventDefault(); @@ -429,11 +443,11 @@ export const Editor = ({commandScopeId}: EditorProps) => { // Persist the rename to the notebook file too (covers background tabs whose // NotebookView isn't mounted to sync the title automatically). if (tab.type === 'notebook' && tab.notebookId && tab.connectionId) { - renameNotebook(tab.notebookId, tab.connectionId, title).catch((e) => + renameNotebook(tab.notebookId, tab.connectionId, title, client).catch((e) => console.error('Failed to rename notebook:', e), ); } - }, [editingTabId, editingTabTitle, updateTab]); + }, [client, editingTabId, editingTabTitle, updateTab]); const handleConvertToConsole = useCallback( (tabId: string) => { @@ -497,6 +511,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { // Mirror of detachedTabIds for use inside callbacks/refs without re-creating // them or reading stale closures. Kept in sync alongside tabsRef below. const detachedTabIdsRef = useRef(detachedTabIds); + const resultSessionIdsRef = useRef(new Map()); + const resultTabIdsBySessionRef = useRef(new Map()); const isDragging = useRef(false); const rafRef = useRef(null); const editorsRef = useRef[0]>>({}); @@ -600,26 +616,32 @@ export const Editor = ({commandScopeId}: EditorProps) => { const handleOpenSqlFile = useCallback(async () => { try { - const filePath = await openFileDialog({ - multiple: false, - filters: [ - { - name: t('editor.sqlFileFilter'), - extensions: ['sql', 'psql', 'pgsql'], - }, - ], - }); - if (typeof filePath !== 'string') return; - - const query = await invoke('read_sql_file', {path: filePath}); - addTab(createSqlFileTab(filePath, query, isMultiDb ? selectedDatabases[0] : undefined)); + const opened = await openSqlFile(platform, client, [ + { + name: t('editor.sqlFileFilter'), + extensions: ['sql', 'psql', 'pgsql'], + }, + ]); + if (!opened) return; + const schema = isMultiDb ? selectedDatabases[0] : undefined; + addTab( + opened.kind === 'path' + ? createSqlFileTab(opened.path, opened.query, schema) + : { + // An uploaded copy has no host path; saving it downloads a file. + type: 'console', + title: getSqlFileName(opened.name), + query: opened.query, + ...(schema ? {schema} : {}), + }, + ); } catch (error) { showAlert(`${t('editor.openSqlFileError')}: ${String(error)}`, { title: t('common.error'), kind: 'error', }); } - }, [addTab, isMultiDb, selectedDatabases, showAlert, t]); + }, [addTab, client, isMultiDb, platform, selectedDatabases, showAlert, t]); // Save is a no-op on a clean file and on an empty console (which would // otherwise open a Save As dialog for nothing). @@ -631,26 +653,25 @@ export const Editor = ({commandScopeId}: EditorProps) => { const handleSaveSqlFile = useCallback( async (tab: Tab, saveAs = false) => { try { - let filePath = tab.sourceFilePath; - if (saveAs || !filePath) { - const selectedPath = await saveFileDialog({ - defaultPath: filePath ?? tab.title, - filters: [ - { - name: t('editor.sqlFileFilter'), - extensions: ['sql', 'psql', 'pgsql'], - }, - ], - }); - if (typeof selectedPath !== 'string') return; - filePath = selectedPath; - } - const savedQuery = tab.query; - await invoke('write_sql_file', {path: filePath, content: savedQuery}); - updateTab(tab.id, (currentTab) => - savedSqlFileTab(filePath, savedQuery, currentTab.query), - ); + const saved = await saveSqlFile(platform, client, { + query: savedQuery, + title: tab.title, + sourceFilePath: tab.sourceFilePath, + saveAs, + filters: [ + { + name: t('editor.sqlFileFilter'), + extensions: ['sql', 'psql', 'pgsql'], + }, + ], + }); + if (!saved) return; + if (saved.kind === 'path') { + updateTab(tab.id, (currentTab) => + savedSqlFileTab(saved.path, savedQuery, currentTab.query), + ); + } showToast(t('editor.sqlFileSaved'), {kind: 'success'}); } catch (error) { showAlert(`${t('editor.saveSqlFileError')}: ${String(error)}`, { @@ -659,7 +680,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); } }, - [showAlert, showToast, t, updateTab], + [client, platform, showAlert, showToast, t, updateTab], ); const isEditorOpen = !isTableTab && (activeTab?.isEditorOpen ?? activeTab?.type !== 'table'); @@ -699,7 +720,11 @@ export const Editor = ({commandScopeId}: EditorProps) => { } title = `tabularis - ${activeConnectionName} (${dbDisplay}${schemaSuffix})`; } - await invoke('set_window_title', {title}); + if (platform.negotiation.environment === 'browser') { + document.title = title; + } else { + await invoke('set_window_title', {title}); + } } catch (e) { console.error('Failed to update window title', e); } @@ -713,6 +738,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { activeSchema, activeCapabilities, isMultiDb, + platform, ]); // Define updateActiveTab first to be used in handleQueryChange @@ -753,6 +779,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { // two different statements/tables in quick succession) and skip applying // its (now wrong-table) column metadata over the newer run's. const queryGenerationRef = useRef>({}); + const activeQueryRequestIdsRef = useRef>(new Set()); // Stable refs for functions used inside Monaco actions (which capture closures at mount time) const runQueryRef = useRef(null!); const runMultipleQueriesRef = useRef(null!); @@ -1103,21 +1130,23 @@ export const Editor = ({commandScopeId}: EditorProps) => { const isStale = () => !targetId || queryGenerationRef.current[targetId] !== generation; try { const [cols, fks] = await Promise.all([ - invoke('get_columns', { - connectionId: activeConnectionId, - tableName: table, - ...(effectiveSchema ? {schema: effectiveSchema} : {}), - ...(effectiveDatabase ? {database: effectiveDatabase} : {}), - }), - invoke('get_foreign_keys', { + client.call('get_columns', { connectionId: activeConnectionId, tableName: table, ...(effectiveSchema ? {schema: effectiveSchema} : {}), ...(effectiveDatabase ? {database: effectiveDatabase} : {}), - }).catch((e) => { - console.warn('Failed to fetch foreign keys:', e); - return [] as ForeignKey[]; }), + client + .call('get_foreign_keys', { + connectionId: activeConnectionId, + tableName: table, + ...(effectiveSchema ? {schema: effectiveSchema} : {}), + ...(effectiveDatabase ? {database: effectiveDatabase} : {}), + }) + .catch((e) => { + console.warn('Failed to fetch foreign keys:', e); + return [] as ForeignKey[]; + }), ]); if (isStale()) return; const pks = cols.filter((c) => c.is_pk).map((c) => c.name); @@ -1150,18 +1179,30 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); } }, - [activeConnectionId, activeTabId, updateTab, activeSchema], + [client, activeConnectionId, activeTabId, updateTab, activeSchema], ); const stopQuery = useCallback(async () => { if (!activeConnectionId) return; + const requestIds = [...activeQueryRequestIdsRef.current]; try { - await invoke('cancel_query', {connectionId: activeConnectionId}); + if (requestIds.length === 0) { + await client.call('cancel_query', {connectionId: activeConnectionId}); + } else { + await Promise.allSettled( + requestIds.map((queryRequestId) => + client.call('cancel_query', { + connectionId: activeConnectionId, + queryRequestId, + }), + ), + ); + } updateActiveTab({isLoading: false}); } catch (e) { console.error('Failed to stop:', e); } - }, [activeConnectionId, updateActiveTab]); + }, [client, activeConnectionId, updateActiveTab]); const runQuery = useCallback( async ( @@ -1350,6 +1391,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { ); const start = performance.now(); + const queryRequestId = createRequestId(); + activeQueryRequestIdsRef.current.add(queryRequestId); try { // Per-tab page size (falling back to the global Result Page Size) @@ -1359,18 +1402,22 @@ export const Editor = ({commandScopeId}: EditorProps) => { pageSizeOverride ?? targetTab.pageSize, settings.resultPageSize, ); - const res = await invoke('execute_query', { - connectionId: targetConnectionId, - query: textToRun, - limit: pageSize, - page: pageNum, - // One statement at a time is how a transaction is driven: BEGIN, - // the changes, a verifying SELECT, COMMIT. Without the session the - // run would land on a different pooled connection each time. - sessionId: targetTabId, - ...(schema ? {schema} : {}), - ...(targetTab?.database ? {database: targetTab.database} : {}), - }); + const res = await client.call( + 'execute_query', + { + connectionId: targetConnectionId, + query: textToRun, + limit: pageSize, + page: pageNum, + // One statement at a time is how a transaction is driven: BEGIN, + // the changes, a verifying SELECT, COMMIT. Without the session the + // run would land on a different pooled connection each time. + sessionId: targetTabId, + ...(schema ? {schema} : {}), + ...(targetTab?.database ? {database: targetTab.database} : {}), + }, + {requestId: queryRequestId, cancellationId: queryRequestId}, + ); const end = performance.now(); const latestTab = tabsRef.current.find((tab) => tab.id === targetTabId); if (backgroundRefresh && (!latestTab || !canApplyRefresh(latestTab))) @@ -1540,18 +1587,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { ? {} : { ...(backgroundRefresh - ? { - autoRefreshError: - typeof err === 'string' - ? err - : t('editor.queryFailed'), - } - : { - error: - typeof err === 'string' - ? err - : t('editor.queryFailed'), - }), + ? {autoRefreshError: toErrorMessage(err)} + : {error: toErrorMessage(err)}), isLoading: false, }, ); @@ -1579,11 +1616,12 @@ export const Editor = ({commandScopeId}: EditorProps) => { null, 'error', null, - typeof err === 'string' ? err : t('editor.queryFailed'), + toErrorMessage(err), historyDb, ); } } finally { + activeQueryRequestIdsRef.current.delete(queryRequestId); if (queryGenerationRef.current[targetTabId] === generation) { updateTab(targetTabId, {isLoading: false, isAutoRefreshing: false}); } @@ -1596,6 +1634,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { : execute(); }, [ + client, clearEntryScrollTops, activeConnectionId, updateTab, @@ -1735,12 +1774,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { // events from any other batch executing concurrently. const batchId = `batch-${targetTabId}-${performance.now()}`; // Registered before `invoke` so no early statement event is missed. - const unlisten = await listen<{ - batch_id: string; - index: number; - statement: BatchStatementResult; - }>('batch-statement-complete', (event) => { - const p = event.payload; + const unlisten = await client.subscribe('batch-statement-complete', (p) => { if (p.batch_id !== batchId || applied.has(p.index)) return; applied.add(p.index); applyStatement(p.index, p.statement); @@ -1751,19 +1785,25 @@ export const Editor = ({commandScopeId}: EditorProps) => { // TEMP TABLE). const batchStart = performance.now(); let batchResults: BatchStatementResult[]; + const queryRequestId = createRequestId(); + activeQueryRequestIdsRef.current.add(queryRequestId); try { - batchResults = await invoke('execute_query_batch', { - connectionId: activeConnectionId, - queries: entries.map((e) => e.query), - limit: pageSize, - page: 1, - batchId, - // The tab is the session: a transaction it leaves open keeps - // this tab's connection so the next run continues it. - sessionId: targetTabId, - ...(schema ? {schema} : {}), - ...(targetTab?.database ? {database: targetTab.database} : {}), - }); + batchResults = await client.call( + 'execute_query_batch', + { + connectionId: activeConnectionId, + queries: entries.map((e) => e.query), + limit: pageSize, + page: 1, + batchId, + // The tab is the session: a transaction it leaves open keeps + // this tab's connection so the next run continues it. + sessionId: targetTabId, + ...(schema ? {schema} : {}), + ...(targetTab?.database ? {database: targetTab.database} : {}), + }, + {requestId: queryRequestId, cancellationId: queryRequestId}, + ); } catch (err) { unlisten(); // Batch-level failure (e.g. connection acquisition, cancellation): @@ -1782,7 +1822,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { }), }, }); - const message = typeof err === 'string' ? err : t('editor.queryFailed'); + const message = toErrorMessage(err); entries.forEach((entry, idx) => { if (applied.has(idx)) return; if (shouldRecordHistory) { @@ -1803,6 +1843,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); updateTab(targetTabId, {isLoading: false}); return; + } finally { + activeQueryRequestIdsRef.current.delete(queryRequestId); } unlisten(); @@ -1845,6 +1887,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); }, [ + client, clearEntryScrollTops, activeConnectionId, updateTab, @@ -1937,19 +1980,23 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); } + const queryRequestId = createRequestId(); + activeQueryRequestIdsRef.current.add(queryRequestId); try { const start = performance.now(); - const res = await invoke('execute_query', { - connectionId: activeConnectionId, - query: entry.query, - limit: pageSize, - page: pageNum, - // Paging within the tab has to read through the tab's own - // transaction, or it shows pre-transaction rows. - sessionId: targetTabId, - ...(schema ? {schema} : {}), - ...(currentTab?.database ? {database: currentTab.database} : {}), - }); + const res = await client.call( + 'execute_query', + { + connectionId: activeConnectionId, + query: entry.query, + sessionId: targetTabId, + limit: pageSize, + page: pageNum, + ...(schema ? {schema} : {}), + ...(currentTab?.database ? {database: currentTab.database} : {}), + }, + {requestId: queryRequestId, cancellationId: queryRequestId}, + ); const end = performance.now(); const latestTab = tabsRef.current.find((t) => t.id === targetTabId); @@ -1982,14 +2029,16 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (latestTab?.results) { updateTab(targetTabId, { results: updateResultEntry(latestTab.results, entryId, { - error: typeof err === 'string' ? err : t('editor.queryFailed'), + error: toErrorMessage(err), isLoading: false, }), }); } + } finally { + activeQueryRequestIdsRef.current.delete(queryRequestId); } }, - [activeConnectionId, updateTab, settings.resultPageSize, activeSchema, t], + [client, activeConnectionId, updateTab, settings.resultPageSize, activeSchema], ); const handlePageSizeChange = useCallback( @@ -2045,10 +2094,10 @@ export const Editor = ({commandScopeId}: EditorProps) => { const schedule = getAutoRefreshSchedule(tab.id); const execute = async () => { try { - const total = await invoke('count_query', { + const total = await client.call('count_query', { connectionId: tab.connectionId, query: countTarget, - schema: tab.schema ?? activeSchema, + schema: tab.schema ?? activeSchema ?? undefined, database: tab.database, // Inside a transaction, count what the tab sees, uncommitted rows included. sessionId: transactionTabIdsRef.current.has(tab.id) ? tab.id : undefined, @@ -2075,6 +2124,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { activeDriver, activeCapabilities, updateTab, + client, getAutoRefreshSchedule, ], ); @@ -2083,29 +2133,37 @@ export const Editor = ({commandScopeId}: EditorProps) => { const handleDetachResults = useCallback(async () => { if (!activeTab) return; const tabId = activeTab.id; + const sessionId = crypto.randomUUID(); + resultSessionIdsRef.current.set(tabId, sessionId); + resultTabIdsBySessionRef.current.set(sessionId, tabId); try { - await invoke('open_results_window', { - tabId, - title: `${activeTab.title} — Query Results`, - }); + await openResultsWindow(sessionId, `${activeTab.title} — Query Results`); setDetachedTabIds((prev) => new Set(prev).add(tabId)); } catch (e) { + resultSessionIdsRef.current.delete(tabId); + resultTabIdsBySessionRef.current.delete(sessionId); console.error('Failed to detach results', e); } - }, [activeTab]); + }, [activeTab, openResultsWindow]); - const handleReattachResults = useCallback(async (tabId: string) => { - try { - await invoke('close_results_window', {tabId}); - } catch (e) { - console.error('Failed to close results window', e); - } - setDetachedTabIds((prev) => { - const next = new Set(prev); - next.delete(tabId); - return next; - }); - }, []); + const handleReattachResults = useCallback( + async (tabId: string) => { + const sessionId = resultSessionIdsRef.current.get(tabId) ?? tabId; + try { + await closeResultsWindow(sessionId); + } catch (e) { + console.error('Failed to close results window', e); + } + resultSessionIdsRef.current.delete(tabId); + resultTabIdsBySessionRef.current.delete(sessionId); + setDetachedTabIds((prev) => { + const next = new Set(prev); + next.delete(tabId); + return next; + }); + }, + [closeResultsWindow], + ); // Push each detached tab's result state to its window whenever the tabs // change. @@ -2113,19 +2171,28 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (detachedTabIds.size === 0) return; for (const id of detachedTabIds) { const tab = tabs.find((t) => t.id === id); - if (tab) { - emit( - resultsSyncEvent(id), - buildSyncPayload(tab, { + const sessionId = resultSessionIdsRef.current.get(id); + if (tab && sessionId) { + void platform.publishRouteEvent(RESULTS_SYNC_EVENT, { + sessionId, + payload: buildSyncPayload(tab, { connectionId: activeConnectionId, copyFormat, csvDelimiter, csvIncludeHeaders, }), - ); + }); } } - }, [tabs, detachedTabIds, activeConnectionId, copyFormat, csvDelimiter, csvIncludeHeaders]); + }, [ + tabs, + detachedTabIds, + activeConnectionId, + copyFormat, + csvDelimiter, + csvIncludeHeaders, + platform, + ]); // If a detached tab is closed in the main window, close its orphaned window. // Closing the window emits RESULTS_CLOSED_EVENT, whose listener owns pruning @@ -2133,12 +2200,13 @@ export const Editor = ({commandScopeId}: EditorProps) => { useEffect(() => { for (const id of detachedTabIds) { if (!tabs.some((t) => t.id === id)) { - invoke('close_results_window', {tabId: id}).catch(() => {}); + const sessionId = resultSessionIdsRef.current.get(id) ?? id; + void closeResultsWindow(sessionId).catch(() => {}); } } - }, [tabs, detachedTabIds]); + }, [closeResultsWindow, tabs, detachedTabIds]); - // Re-runs a query without pagination and formats the full result set for the + // Reads every query page and formats the full result set for the // clipboard. Returns null when there is nothing to copy. const fetchAllRows = useCallback( async ( @@ -2153,33 +2221,46 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (!activeConnectionId || columns.length === 0 || !query.trim()) { return null; } - const totalRows = result?.pagination?.total_rows; - - const res = await invoke('execute_query', { - connectionId: activeConnectionId, - query, - // When the total is unknown (no row count requested yet), fall back to - // a large practical cap; the toast reports the actual rows fetched. - limit: totalRows ?? 1_000_000, - page: 1, - // Copying every row must see what the tab's own transaction sees. - sessionId, - ...(schema ? {schema} : {}), - // Nested multi-db (Postgres): without this, "Copy All Rows" on a - // secondary database silently re-queries the primary — the same - // database-routing bug class as findings #1/#5/#6. - ...(database ? {database} : {}), - }); - const text = formatRowsForCopy(res.rows, res.columns ?? columns, copyFormat, { + const rows: unknown[][] = []; + let fetchedColumns = columns; + let page = 1; + let limit = 10_000; + while (true) { + const res = await client.call('execute_query', { + connectionId: activeConnectionId, + query, + limit, + page, + // Copying every row must see what the tab's own transaction sees. + sessionId, + ...(schema ? {schema} : {}), + ...(database ? {database} : {}), + }); + if (page === 1) fetchedColumns = res.columns ?? columns; + rows.push(...res.rows); + if (!res.pagination?.has_more || res.rows.length === 0) break; + // The server may clamp our limit. Use its actual size for subsequent + // offsets so copying never skips rows, including with unknown totals. + limit = res.pagination.page_size; + page += 1; + } + const text = formatRowsForCopy(rows, fetchedColumns, copyFormat, { withHeaders: true, csvIncludeHeaders, csvDelimiter, tableName, driver: activeCapabilities, }); - return {text, count: res.rows.length}; + return {text, count: rows.length}; }, - [activeConnectionId, activeCapabilities, copyFormat, csvDelimiter, csvIncludeHeaders], + [ + client, + activeConnectionId, + activeCapabilities, + copyFormat, + csvDelimiter, + csvIncludeHeaders, + ], ); // Schema resolution mirrors runQuery so the full fetch targets the same @@ -2278,18 +2359,19 @@ export const Editor = ({commandScopeId}: EditorProps) => { // the window stuck on "Loading…". Each handler self-guards (action via // detachedTabIdsRef, ready via the tabsRef lookup, closed via prev.has). useEffect(() => { - const emitSyncFor = (tabId: string) => { - const tab = tabsRef.current.find((t) => t.id === tabId); + const emitSyncFor = (sessionId: string) => { + const tabId = resultTabIdsBySessionRef.current.get(sessionId); + const tab = tabsRef.current.find((candidate) => candidate.id === tabId); if (tab) { - emit( - resultsSyncEvent(tabId), - buildSyncPayload(tab, { + void platform.publishRouteEvent(RESULTS_SYNC_EVENT, { + sessionId, + payload: buildSyncPayload(tab, { connectionId: activeConnectionId, copyFormat, csvDelimiter, csvIncludeHeaders, }), - ); + }); } }; @@ -2303,11 +2385,11 @@ export const Editor = ({commandScopeId}: EditorProps) => { try { const copied = await rows; if (!copied) return; - payload = copied; + payload = {tabId, ...copied}; } catch (e) { - payload = {error: String(e)}; + payload = {tabId, error: String(e)}; } - emit(resultsCopyEvent(tabId), payload); + void platform.publishRouteEvent(RESULTS_COPY_EVENT, payload); }; return { onRunQueryPage: (query, page) => runQuery(query, page, tabId), @@ -2384,25 +2466,35 @@ export const Editor = ({commandScopeId}: EditorProps) => { }; }; - const readyP = listen(RESULTS_READY_EVENT, (event) => - emitSyncFor(event.payload.tabId), + const readyP = platform.subscribeRouteEvent( + RESULTS_READY_EVENT, + ({sessionId}) => emitSyncFor(sessionId), + ); + const actionP = platform.subscribeRouteEvent( + RESULTS_ACTION_EVENT, + ({sessionId, action}) => { + const tabId = resultTabIdsBySessionRef.current.get(sessionId); + // Only honor actions for sessions we actually have detached — defense + // in depth against events arriving for an expired route. + if (!tabId || !detachedTabIdsRef.current.has(tabId)) return; + applyAction(action, makeHandlers(tabId)); + }, + ); + const closedP = platform.subscribeRouteEvent( + RESULTS_CLOSED_EVENT, + ({sessionId}) => { + const closedId = resultTabIdsBySessionRef.current.get(sessionId); + if (!closedId) return; + resultTabIdsBySessionRef.current.delete(sessionId); + resultSessionIdsRef.current.delete(closedId); + setDetachedTabIds((prev) => { + if (!prev.has(closedId)) return prev; + const next = new Set(prev); + next.delete(closedId); + return next; + }); + }, ); - const actionP = listen(RESULTS_ACTION_EVENT, (event) => { - // Only honor actions for tabs we actually have detached — defense in - // depth against events arriving for a reattached/unknown tab. - const {tabId, action} = event.payload; - if (!detachedTabIdsRef.current.has(tabId)) return; - applyAction(action, makeHandlers(tabId)); - }); - const closedP = listen(RESULTS_CLOSED_EVENT, (event) => { - const closedId = event.payload.tabId; - setDetachedTabIds((prev) => { - if (!prev.has(closedId)) return prev; - const next = new Set(prev); - next.delete(closedId); - return next; - }); - }); return () => { readyP.then((u) => u()); @@ -2420,6 +2512,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { fetchTabAllRows, fetchEntryAllRows, updateTab, + platform, ]); // Keep the Run button honest about its target: with no selection a pasted @@ -2923,7 +3016,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { async (sql: string, signal?: AbortSignal): Promise => { const result = await runOnActiveTableTab( (tab, schema) => - invoke('execute_query', { + client.call('execute_query', { connectionId: tab.connectionId, query: sql, sessionId: tab.id, @@ -2935,7 +3028,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (!result) throw new Error('The values query did not run'); return result; }, - [runOnActiveTableTab], + [client, runOnActiveTableTab], ); // The plugin's own column statistics (issue #1137), in the tab's database. @@ -2943,14 +3036,14 @@ export const Editor = ({commandScopeId}: EditorProps) => { async (request, signal) => (await runOnActiveTableTab( (tab) => - invoke('get_column_stats', { + client.call('get_column_stats', { connectionId: tab.connectionId, request, ...(tab.database ? {database: tab.database} : {}), }), signal, )) ?? null, - [runOnActiveTableTab], + [client, runOnActiveTableTab], ); const handleForeignKeyShowPanel = useCallback( @@ -3710,7 +3803,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { // activeSchema) so a nested multi-db tab on a non-default schema fetches // columns from the right one. const tabSchema = activeTab?.schema ?? activeSchema; - const columns = await invoke('get_columns', { + const columns = await client.call('get_columns', { connectionId: activeConnectionId, tableName: activeTab.activeTable, ...(tabSchema ? {schema: tabSchema} : {}), @@ -3822,6 +3915,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); } }, [ + client, activeConnectionId, activeTab, updateTab, @@ -3892,7 +3986,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { // connection-level activeSchema) so a nested multi-db tab on a // non-default schema validates against the right columns. const tabSchema = activeTab?.schema ?? activeSchema; - const columns = await invoke('get_columns', { + const columns = await client.call('get_columns', { connectionId: activeConnectionId, tableName: activeTable, ...(tabSchema ? {schema: tabSchema} : {}), @@ -3988,7 +4082,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { ...deletions.map(async (pkMap) => { let remaining = countByKey.get(serializePkKey(pkMap)) ?? 1; while (remaining > 0) { - const affected = await invoke('delete_record', { + const affected = await client.call('delete_record', { connectionId: activeConnectionId, table: activeTable, pkMap, @@ -4009,7 +4103,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { } else { promises.push( ...deletions.map((pkMap) => - invoke('delete_record', { + client.call('delete_record', { connectionId: activeConnectionId, table: activeTable, pkMap, @@ -4045,7 +4139,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { ...Array.from(updatesByRow.values()).map(async (row) => { const plan = buildKeylessUpdatePlan(row.pkVal, row.changes); for (const step of plan) { - const affected = await invoke('update_record', { + const affected = await client.call('update_record', { connectionId: activeConnectionId, table: activeTable, pkMap: step.pkMap, @@ -4068,7 +4162,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { } else { promises.push( ...updates.map((u) => - invoke('update_record', { + client.call('update_record', { connectionId: activeConnectionId, table: activeTable, pkMap: u.pkVal, @@ -4085,7 +4179,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (insertions.length > 0) { promises.push( ...insertions.map((insertion) => - invoke('insert_record', { + client.call('insert_record', { connectionId: activeConnectionId, table: activeTable, data: insertion.data, @@ -4151,6 +4245,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { }); } }, [ + client, activeTab, activeConnectionId, updateActiveTab, @@ -4560,7 +4655,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { const cancelExport = useCallback(async () => { if (!activeConnectionId) return; try { - await invoke('cancel_export', {connectionId: activeConnectionId}); + await client.call('cancel_export', {connectionId: activeConnectionId}); setExportState((prev) => ({ ...prev, isOpen: false, @@ -4568,7 +4663,7 @@ export const Editor = ({commandScopeId}: EditorProps) => { } catch (e) { console.error('Failed to cancel export', e); } - }, [activeConnectionId]); + }, [activeConnectionId, client]); const closeExportModal = useCallback(() => { setExportState((prev) => ({...prev, isOpen: false})); @@ -4590,36 +4685,38 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (!activeTab) return; const extension = format === 'markdown' ? 'md' : format; - const filterName = format === 'markdown' ? 'Markdown' : format.toUpperCase(); try { const warningMessage = getLoadedRowsWarning(result); - const filePath = await saveFileDialog({ - filters: [ - { - name: filterName, - extensions: [extension], - }, - ], - defaultPath: buildExportFileName({ - tableName: activeTab.type === 'table' ? activeTab.activeTable : null, - extension, - }), + const fileName = buildExportFileName({ + tableName: activeTab.type === 'table' ? activeTab.activeTable : null, + extension, }); - - if (!filePath) return; - setExportState({ isOpen: true, status: 'exporting', rowsProcessed: result.rows.length, - fileName: filePath.split(/[/\\]/).pop() || filePath, + fileName, errorMessage: undefined, warningMessage, }); setExportMenuOpen(false); - await writeTextFile(filePath, formatResultForExport(result, format, csvDelimiter)); + const downloaded = await downloadTextFile(platform, { + fileName, + contents: formatResultForExport(result, format, csvDelimiter), + mimeType: LOADED_ROWS_EXPORT_MIME_TYPES[format], + filters: [ + { + name: format === 'markdown' ? 'Markdown' : format.toUpperCase(), + extensions: [extension], + }, + ], + }); + if (!downloaded) { + setExportState((prev) => ({...prev, isOpen: false})); + return; + } setExportState((prev) => ({ ...prev, @@ -4634,7 +4731,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { } }; - const handleExportCommon = async (format: ResultExportFormat) => { + // HTML only exports the loaded grid (handleExportHtml), never the streaming exporter. + const handleExportCommon = async (format: Exclude) => { if (!activeTab || !activeConnectionId) return; if (format === 'ndjson') { @@ -4663,26 +4761,30 @@ export const Editor = ({commandScopeId}: EditorProps) => { if (!query || !query.trim()) return; try { - const filePath = await saveFileDialog({ - filters: [ - { - name: format === 'markdown' ? 'Markdown' : format.toUpperCase(), - extensions: [extension], - }, - ], - defaultPath: buildExportFileName({ - tableName: activeTab.type === 'table' ? activeTab.activeTable : null, - extension, - }), + const fileName = buildExportFileName({ + tableName: activeTab.type === 'table' ? activeTab.activeTable : null, + extension, }); - - if (!filePath) return; + const filter = { + name: format === 'markdown' ? 'Markdown' : format.toUpperCase(), + extensions: [extension], + }; + const usesNativeSaveTarget = + platform.negotiation.environment === 'tauri' && + platform.supports('chooseSaveTarget'); + const target = usesNativeSaveTarget + ? await platform.chooseSaveTarget({ + suggestedName: fileName, + filters: [filter], + }) + : null; + if (usesNativeSaveTarget && !target) return; setExportState({ isOpen: true, status: 'exporting', rowsProcessed: 0, - fileName: filePath.split(/[/\\]/).pop() || filePath, // Show only filename + fileName, errorMessage: undefined, warningMessage: undefined, }); @@ -4703,17 +4805,21 @@ export const Editor = ({commandScopeId}: EditorProps) => { ? {database: targetDatabase} : {}; - await invoke('export_query_to_file', { - connectionId: activeConnectionId, - query, - filePath, - format, - csvDelimiter: format === 'csv' ? csvDelimiter : undefined, - ...databaseParam, - // Inside a transaction, export what the tab sees, uncommitted rows included. - sessionId: - activeTab && transactionTabIds.has(activeTab.id) ? activeTab.id : undefined, - }); + const generated = await client.call( + 'export_query_to_file', + { + connectionId: activeConnectionId, + query, + ...(target ? {filePath: target.reference} : {}), + format, + csvDelimiter: format === 'csv' ? csvDelimiter : undefined, + ...databaseParam, + sessionId: + activeTab && transactionTabIds.has(activeTab.id) ? activeTab.id : undefined, + }, + {deadlineMs: 6 * 60 * 60 * 1000}, + ); + await downloadGeneratedFile(client, platform, generated); // Success: update modal state instead of showing toast setExportState((prev) => ({ @@ -4737,44 +4843,8 @@ export const Editor = ({commandScopeId}: EditorProps) => { // Writes the grid already on screen. Never calls the streaming exporter. const handleExportHtml = async () => { - if (!activeTab || !activeConnectionId || !activeExportResult) return; - - try { - const warningMessage = getLoadedRowsWarning(activeExportResult); - - const filePath = await saveFileDialog({ - filters: [{name: 'HTML', extensions: ['html']}], - defaultPath: buildExportFileName({ - tableName: activeTab.type === 'table' ? activeTab.activeTable : null, - extension: 'html', - }), - }); - - if (!filePath) return; - - setExportState({ - isOpen: true, - status: 'exporting', - rowsProcessed: activeExportResult.rows.length, - fileName: filePath.split(/[/\\]/).pop() || filePath, - errorMessage: undefined, - warningMessage, - }); - setExportMenuOpen(false); - - await writeTextFile(filePath, formatResultForExport(activeExportResult, 'html')); - - setExportState((prev) => ({ - ...prev, - status: 'completed', - })); - } catch (e) { - setExportState((prev) => ({ - ...prev, - status: 'error', - errorMessage: String(e), - })); - } + if (!activeConnectionId || !activeExportResult) return; + await handleExportLoadedRows(activeExportResult, 'html'); }; const handleRunDropdownToggle = useCallback(() => { @@ -5115,7 +5185,11 @@ export const Editor = ({commandScopeId}: EditorProps) => { onClick={async () => { if (!activeConnectionId) return; const title = 'Notebook'; - const {notebookId} = await createNotebook(title, activeConnectionId); + const {notebookId} = await createNotebook( + title, + activeConnectionId, + client, + ); addTab({ type: 'notebook', notebookId, diff --git a/packages/web-ui/src/pages/JsonViewerPage.tsx b/packages/web-ui/src/pages/JsonViewerPage.tsx new file mode 100644 index 000000000..a2522503c --- /dev/null +++ b/packages/web-ui/src/pages/JsonViewerPage.tsx @@ -0,0 +1,195 @@ +import {useState, useEffect, useCallback, useRef} from 'react'; +import {useSearchParams} from 'react-router-dom'; +import {useTranslation} from 'react-i18next'; +import {JsonInput} from '@/components/ui/JsonInput'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import { + JSON_VIEWER_SESSION_CLOSED_EVENT, + JSON_VIEWER_SESSION_DATA_EVENT, + JSON_VIEWER_SESSION_EXPIRED_EVENT, + JSON_VIEWER_SESSION_REQUEST_EVENT, + JSON_VIEWER_SESSION_SAVED_EVENT, + type JsonViewerSession, + type JsonViewerSessionClosed, + type JsonViewerSessionData, + type JsonViewerSessionExpired, + type JsonViewerSessionRequest, + type JsonViewerSessionSaved, +} from '@/platform/secondaryWindowSessions'; + +const SESSION_RESPONSE_TIMEOUT_MS = 2_000; + +export const JsonViewerPage = () => { + const {t} = useTranslation(); + const platform = usePlatformCapabilities(); + const [searchParams] = useSearchParams(); + const sessionId = searchParams.get('session') ?? ''; + const completedRef = useRef(false); + + const [session, setSession] = useState(null); + const [currentValue, setCurrentValue] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + if (!sessionId) return; + let cancelled = false; + let timeout: ReturnType | undefined; + let unsubscribers: Array<() => void> = []; + + void (async () => { + try { + unsubscribers = await Promise.all([ + platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_DATA_EVENT, + ({sessionId: receivedId, session: receivedSession}) => { + if (cancelled || receivedId !== sessionId) return; + if (timeout) clearTimeout(timeout); + setError(null); + setSession(receivedSession); + setCurrentValue(receivedSession.value); + }, + ), + platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_EXPIRED_EVENT, + ({sessionId: expiredId}) => { + if (cancelled || expiredId !== sessionId) return; + if (timeout) clearTimeout(timeout); + setError( + t('jsonViewer.sessionExpired', { + defaultValue: + 'This JSON viewer session expired. Return to the source and open it again.', + }), + ); + }, + ), + ]); + if (cancelled) { + for (const unsubscribe of unsubscribers) unsubscribe(); + return; + } + + timeout = setTimeout(() => { + setError( + t('jsonViewer.sessionExpired', { + defaultValue: + 'This JSON viewer session expired. Return to the source and open it again.', + }), + ); + }, SESSION_RESPONSE_TIMEOUT_MS); + await platform.publishRouteEvent( + JSON_VIEWER_SESSION_REQUEST_EVENT, + {sessionId}, + ); + } catch (cause) { + if (!cancelled) setError(String(cause)); + } + })(); + + return () => { + cancelled = true; + if (timeout) clearTimeout(timeout); + for (const unsubscribe of unsubscribers) unsubscribe(); + }; + }, [platform, sessionId, t]); + + const closeSession = useCallback(async () => { + if (sessionId && !completedRef.current) { + completedRef.current = true; + await platform.publishRouteEvent( + JSON_VIEWER_SESSION_CLOSED_EVENT, + {sessionId}, + ); + } + await platform.closeRoute(); + }, [platform, sessionId]); + + const handleSave = useCallback(async () => { + try { + completedRef.current = true; + await platform.publishRouteEvent( + JSON_VIEWER_SESSION_SAVED_EVENT, + {sessionId, value: currentValue}, + ); + await platform.closeRoute(); + } catch (cause) { + completedRef.current = false; + setError(String(cause)); + } + }, [currentValue, platform, sessionId]); + + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') void closeSession(); + }; + const handlePageHide = () => { + if (!sessionId || completedRef.current) return; + completedRef.current = true; + void platform.publishRouteEvent( + JSON_VIEWER_SESSION_CLOSED_EVENT, + {sessionId}, + ); + }; + window.addEventListener('keydown', handleKeyDown); + window.addEventListener('pagehide', handlePageHide); + return () => { + window.removeEventListener('keydown', handleKeyDown); + window.removeEventListener('pagehide', handlePageHide); + }; + }, [closeSession, platform, sessionId]); + + const showSave = session && !session.readOnly; + const displayError = + error ?? + (!sessionId ? t('jsonViewer.noSession', {defaultValue: 'No session ID provided'}) : null); + + return ( +
+
+ {displayError ? ( +

{displayError}

+ ) : session ? ( + + ) : ( +

{t('common.loading')}

+ )} +
+ +
+ {showSave ? ( + <> + + + + ) : ( + + )} +
+
+ ); +}; diff --git a/src/pages/McpPage.tsx b/packages/web-ui/src/pages/McpPage.tsx similarity index 97% rename from src/pages/McpPage.tsx rename to packages/web-ui/src/pages/McpPage.tsx index 3fe006ff4..ca441c3d0 100644 --- a/src/pages/McpPage.tsx +++ b/packages/web-ui/src/pages/McpPage.tsx @@ -1,5 +1,4 @@ import {useCallback, useEffect, useMemo, useState} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import {useTranslation} from 'react-i18next'; import clsx from 'clsx'; import {MonacoEditor as Editor} from '@/components/ui/LazyMonaco'; @@ -17,18 +16,10 @@ import {useAlert} from '@/hooks/useAlert'; import {useCopyFeedback} from '@/hooks/useCopyFeedback'; import {useEditorTheme} from '@/hooks/useEditorTheme'; import {loadMonacoTheme} from '@/themes/themeUtils'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; +import type {McpClientStatus} from '@/types/mcp'; import {getMonacoThemeId} from '@/themes/themeRuntime'; -interface McpClientStatus { - client_id: string; - client_name: string; - installed: boolean; - config_path: string | null; - executable_path: string; - client_type: string; - manual_command?: string | null; -} - type McpPageTab = 'setup' | 'activity' | 'safety'; const ClientIcon = ({clientId, size = 20}: {clientId: string; size?: number}) => { @@ -115,6 +106,7 @@ function McpSetupPanel() { const {t} = useTranslation(); const editorTheme = useEditorTheme(); const {showAlert} = useAlert(); + const client = useTabularisClient(); const [clients, setClients] = useState([]); const [loading, setLoading] = useState(true); const {copied: copiedJson, copy: copyJson} = useCopyFeedback(); @@ -155,7 +147,7 @@ function McpSetupPanel() { const loadStatus = useCallback(async () => { try { setLoading(true); - const res = await invoke('get_mcp_status'); + const res = await client.call('get_mcp_status', undefined); setClients(res); setSelectedClientId((current) => current ?? res[0]?.client_id ?? null); } catch (e) { @@ -163,7 +155,7 @@ function McpSetupPanel() { } finally { setLoading(false); } - }, []); + }, [client]); useEffect(() => { loadStatus(); @@ -171,7 +163,7 @@ function McpSetupPanel() { const handleInstall = async (clientId: string) => { try { - const clientName = await invoke('install_mcp_config', { + const clientName = await client.call('install_mcp_config', { clientId, }); showAlert(t('mcp.successMsg', {client: clientName}), { diff --git a/packages/web-ui/src/pages/PluginInstallRoutePage.tsx b/packages/web-ui/src/pages/PluginInstallRoutePage.tsx new file mode 100644 index 000000000..4cbed44af --- /dev/null +++ b/packages/web-ui/src/pages/PluginInstallRoutePage.tsx @@ -0,0 +1,46 @@ +import {useCallback, useMemo} from 'react'; +import {Navigate, useNavigate, useParams, useSearchParams} from 'react-router-dom'; +import {PluginInstallConfirmModal} from '@/components/modals/PluginInstallConfirmModal'; +import {usePluginInstallConfirmation} from '@/hooks/usePluginInstallConfirmation'; +import {useSettings} from '@/hooks/useSettings'; +import {BROWSER_ROUTES} from '@/routing'; +import {parsePluginInstallRoute} from '@/utils/pluginInstallRoute'; + +/** Browser equivalent of a native tabularis://install deep link. */ +export function PluginInstallRoutePage() { + const {slug} = useParams<{slug: string}>(); + const [searchParams] = useSearchParams(); + const navigate = useNavigate(); + const {settings} = useSettings(); + const {busy, clearError, confirm: confirmInstall, error} = usePluginInstallConfirmation(); + const request = useMemo( + () => parsePluginInstallRoute(slug, searchParams), + [searchParams, slug], + ); + + const closeRoute = useCallback(() => { + clearError(); + navigate(BROWSER_ROUTES.connections, {replace: true}); + }, [clearError, navigate]); + + const confirm = useCallback(async () => { + if (await confirmInstall(request)) closeRoute(); + }, [closeRoute, confirmInstall, request]); + + if (!request) { + return ; + } + + return ( + { + void confirm(); + }} + onCancel={closeRoute} + configuredRegistry={settings.tabulariumRegistryUrl ?? null} + /> + ); +} diff --git a/packages/web-ui/src/pages/ResultsWindowPage.tsx b/packages/web-ui/src/pages/ResultsWindowPage.tsx new file mode 100644 index 000000000..421e2e011 --- /dev/null +++ b/packages/web-ui/src/pages/ResultsWindowPage.tsx @@ -0,0 +1,217 @@ +import {useState, useEffect, useCallback, useRef} from 'react'; +import {useTranslation} from 'react-i18next'; +import {useSearchParams} from 'react-router-dom'; +import {MultiResultPanel} from '@/components/ui/MultiResultPanel'; +import {ResultEntryContent} from '@/components/ui/ResultEntryContent'; +import {useAlert} from '@/hooks/useAlert'; +import {useToast} from '@/hooks/useToast'; +import {copyTextToClipboard} from '@/utils/clipboard'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import { + RESULTS_CLOSE_REQUEST_EVENT, + type ResultsCloseRequest, + type ResultsSessionAction, + type ResultsSessionClosed, + type ResultsSessionRequest, + type ResultsSessionSnapshot, +} from '@/platform/secondaryWindowSessions'; +import { + RESULTS_SYNC_EVENT, + RESULTS_ACTION_EVENT, + RESULTS_READY_EVENT, + RESULTS_CLOSED_EVENT, + RESULTS_COPY_EVENT, + applyCopyResult, + type ResultsCopyPayload, + hasMultiResults, + singleResultToEntry, + type ResultsSyncPayload, + type ResultsWindowAction, +} from '@/utils/resultsWindowSync'; + +const SESSION_RESPONSE_TIMEOUT_MS = 2_000; + +/** + * Detached query results identified by the `session` route parameter. The + * source editor remains the owner of query state; route events provide the same + * snapshot and action contract to native webviews and browser tabs. + */ +export const ResultsWindowPage = () => { + const {t} = useTranslation(); + const platform = usePlatformCapabilities(); + const {showAlert} = useAlert(); + const {showToast} = useToast(); + const [searchParams] = useSearchParams(); + const sessionId = searchParams.get('session') ?? ''; + const [payload, setPayload] = useState(null); + const [expired, setExpired] = useState(false); + const closedRef = useRef(false); + + useEffect(() => { + if (!sessionId) return; + let cancelled = false; + let timeout: ReturnType | undefined; + let unsubscribers: Array<() => void> = []; + + void (async () => { + try { + unsubscribers = await Promise.all([ + platform.subscribeRouteEvent( + RESULTS_SYNC_EVENT, + ({sessionId: receivedId, payload: nextPayload}) => { + if (cancelled || receivedId !== sessionId) return; + if (timeout) clearTimeout(timeout); + setPayload(nextPayload); + }, + ), + platform.subscribeRouteEvent( + RESULTS_CLOSE_REQUEST_EVENT, + ({sessionId: closedSessionId}) => { + if (cancelled || closedSessionId !== sessionId) return; + closedRef.current = true; + void (async () => { + try { + await platform.publishRouteEvent( + RESULTS_CLOSED_EVENT, + {sessionId}, + ); + } finally { + await platform.closeRoute(); + } + })().catch(() => {}); + }, + ), + ]); + if (cancelled) { + for (const unsubscribe of unsubscribers) unsubscribe(); + return; + } + timeout = setTimeout(() => setExpired(true), SESSION_RESPONSE_TIMEOUT_MS); + await platform.publishRouteEvent(RESULTS_READY_EVENT, { + sessionId, + }); + } catch { + if (!cancelled) setExpired(true); + } + })(); + + return () => { + cancelled = true; + if (timeout) clearTimeout(timeout); + for (const unsubscribe of unsubscribers) unsubscribe(); + }; + }, [platform, sessionId]); + + useEffect(() => { + const handlePageHide = () => { + if (!sessionId || closedRef.current) return; + closedRef.current = true; + void platform.publishRouteEvent(RESULTS_CLOSED_EVENT, { + sessionId, + }); + }; + window.addEventListener('pagehide', handlePageHide); + return () => window.removeEventListener('pagehide', handlePageHide); + }, [platform, sessionId]); + + // The source fetches the rows; this window owns the clipboard and feedback. + useEffect(() => { + if (!payload?.tabId) return; + const showError = (error: unknown) => + showAlert(t('common.error') + ': ' + error, { + title: t('common.error'), + kind: 'error', + }); + const unlisten = platform.subscribeRouteEvent( + RESULTS_COPY_EVENT, + (result) => + applyCopyResult(result, payload.tabId, { + onCopied: ({text, count}) => + copyTextToClipboard(text) + .then(() => + showToast(t('dataGrid.copiedRows', {count}), {kind: 'success'}), + ) + .catch(showError), + onError: showError, + }), + ); + return () => { + void unlisten.then((unsubscribe) => unsubscribe()); + }; + }, [platform, payload?.tabId, showAlert, showToast, t]); + + const send = useCallback( + (action: ResultsWindowAction) => { + void platform.publishRouteEvent(RESULTS_ACTION_EVENT, { + sessionId, + action, + }); + }, + [platform, sessionId], + ); + + if (!sessionId || expired) { + return ( +
+ {t('secondaryWindows.sessionExpired', { + defaultValue: + 'This secondary window session expired. Return to the source and open it again.', + })} +
+ ); + } + + if (!payload) { + return ( +
+ {t('common.loading')} +
+ ); + } + + return ( +
+ {hasMultiResults(payload) ? ( + send({type: 'copy-entry-all-rows', entryId})} + onSelectResult={(entryId) => send({type: 'select-result', entryId})} + onRerunEntry={(entryId) => send({type: 'rerun-entry', entryId})} + onPageChange={(entryId, page) => send({type: 'page-change', entryId, page})} + onCloseEntry={(entryId) => send({type: 'close-entry', entryId})} + onCloseOtherEntries={(entryId) => send({type: 'close-other-entries', entryId})} + onCloseEntriesToRight={(entryId) => + send({type: 'close-entries-to-right', entryId}) + } + onCloseEntriesToLeft={(entryId) => + send({type: 'close-entries-to-left', entryId}) + } + onCloseAllEntries={() => send({type: 'close-all-entries'})} + onRenameEntry={(entryId, label) => send({type: 'rename-entry', entryId, label})} + /> + ) : payload.result || payload.error || payload.isLoading ? ( + send({type: 'copy-all-rows'})} + connectionId={payload.connectionId} + copyFormat={payload.copyFormat} + csvDelimiter={payload.csvDelimiter} + csvIncludeHeaders={payload.csvIncludeHeaders} + onPageChange={(page) => + send({type: 'run-query-page', query: payload.query, page}) + } + /> + ) : ( +
+ {t('editor.executePrompt')} +
+ )} +
+ ); +}; diff --git a/src/pages/SchemaDiagramPage.tsx b/packages/web-ui/src/pages/SchemaDiagramPage.tsx similarity index 97% rename from src/pages/SchemaDiagramPage.tsx rename to packages/web-ui/src/pages/SchemaDiagramPage.tsx index a16123c85..7b64b47ea 100644 --- a/src/pages/SchemaDiagramPage.tsx +++ b/packages/web-ui/src/pages/SchemaDiagramPage.tsx @@ -1,6 +1,6 @@ import {useState, useEffect, useCallback} from 'react'; import {useSearchParams} from 'react-router-dom'; -import {invoke} from '@tauri-apps/api/core'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {SchemaDiagram} from '@/components/ui/SchemaDiagram'; import {resolveDiagramSchema} from '@/utils/schemaDiagram'; import {Maximize2, Minimize2, RefreshCw} from 'lucide-react'; @@ -9,6 +9,7 @@ import {DatabaseProvider} from '@/contexts/DatabaseProvider'; import {EditorProvider} from '@/contexts/EditorProvider'; export const SchemaDiagramPage = () => { + const client = useTabularisClient(); const {t} = useTranslation(); const [isFullscreen, setIsFullscreen] = useState(false); const [refreshTrigger, setRefreshTrigger] = useState(0); @@ -44,7 +45,7 @@ export const SchemaDiagramPage = () => { if (!connectionId || !isSchemaCapable) return; setLoadingSchemas(true); try { - const schemas = await invoke('get_schemas', { + const schemas = await client.call('get_schemas', { connectionId, ...(database ? {database} : {}), }); @@ -54,7 +55,7 @@ export const SchemaDiagramPage = () => { } finally { setLoadingSchemas(false); } - }, [connectionId, isSchemaCapable, database]); + }, [client, connectionId, isSchemaCapable, database]); useEffect(() => { fetchSchemas(); diff --git a/src/pages/Settings.tsx b/packages/web-ui/src/pages/Settings.tsx similarity index 100% rename from src/pages/Settings.tsx rename to packages/web-ui/src/pages/Settings.tsx diff --git a/src/pages/TaskManagerPage.tsx b/packages/web-ui/src/pages/TaskManagerPage.tsx similarity index 99% rename from src/pages/TaskManagerPage.tsx rename to packages/web-ui/src/pages/TaskManagerPage.tsx index c79ac4be8..19a2520c2 100644 --- a/src/pages/TaskManagerPage.tsx +++ b/packages/web-ui/src/pages/TaskManagerPage.tsx @@ -1,5 +1,4 @@ import {useState, useCallback} from 'react'; -import {invoke} from '@tauri-apps/api/core'; import {useTranslation} from 'react-i18next'; import { Activity, @@ -23,6 +22,7 @@ import { } from 'lucide-react'; import clsx from 'clsx'; import {useTaskManager} from '@/hooks/useTaskManager'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import { formatBytes, formatCpuPercent, @@ -104,6 +104,7 @@ const KillConfirmModal = ({pluginName, onConfirm, onCancel}: KillConfirmModalPro // --------------------------------------------------------------------------- const TabularisSelfPanel = ({stats}: {stats: TabularisSelfStats}) => { const {t} = useTranslation(); + const client = useTabularisClient(); const [expanded, setExpanded] = useState(false); const [children, setChildren] = useState([]); const [loadingChildren, setLoadingChildren] = useState(false); @@ -112,12 +113,11 @@ const TabularisSelfPanel = ({stats}: {stats: TabularisSelfStats}) => { const fetchChildren = useCallback(async () => { setLoadingChildren(true); try { - const result = await invoke('get_tabularis_children'); - setChildren(result); + setChildren(await client.call('get_tabularis_children', undefined)); } finally { setLoadingChildren(false); } - }, []); + }, [client]); const handleToggle = useCallback(() => { if (!hasChildren) return; diff --git a/src/pages/VisualExplainPage.tsx b/packages/web-ui/src/pages/VisualExplainPage.tsx similarity index 85% rename from src/pages/VisualExplainPage.tsx rename to packages/web-ui/src/pages/VisualExplainPage.tsx index c898a4e4e..4d29625ee 100644 --- a/src/pages/VisualExplainPage.tsx +++ b/packages/web-ui/src/pages/VisualExplainPage.tsx @@ -3,7 +3,6 @@ import {useLocation} from 'react-router-dom'; import {useTranslation} from 'react-i18next'; import {FileJson, FolderOpen, Loader2, RefreshCw} from 'lucide-react'; import {invoke} from '@tauri-apps/api/core'; -import {open as openDialog} from '@tauri-apps/plugin-dialog'; import type {ExplainPlan} from '@tabularis/explain'; import {parseExplain, withSourceLabel} from '@tabularis/explain'; import {VisualExplainView} from '@/components/explain/VisualExplainView'; @@ -11,6 +10,8 @@ import {getExplainFileName, parseExplainFileParam} from '@/utils/explainImport'; import {parseVisualExplainDeepLink} from '@/utils/aiActivity'; import {useSettings} from '@/hooks/useSettings'; import {useExplainPlan} from '@/hooks/useExplainPlan'; +import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; +import type {ChosenInputFile} from '@/platform/capabilities'; export interface VisualExplainPageProps { /// When provided, render in embedded mode: skip the page header, use the @@ -25,15 +26,20 @@ export const VisualExplainPage = ({ compactMode = false, }: VisualExplainPageProps = {}) => { const {t} = useTranslation(); + const platform = usePlatformCapabilities(); const {settings} = useSettings(); const {search} = useLocation(); - const initialParamPath = parseExplainFileParam(search); + const nativeHandoffs = platform.negotiation.environment === 'tauri'; + const initialParamPath = nativeHandoffs ? parseExplainFileParam(search) : null; const deepLink = parseVisualExplainDeepLink(search); const isDeepLink = !!deepLink.query && !!deepLink.connectionId; const [filePath, setFilePath] = useState(initialParamPath); const sourceVersion = useRef(0); const pickerVersion = useRef(0); + // A picked file is re-read through the platform reference on reload: its + // display name is not a loadable path (and a browser has no path at all). + const pickedFile = useRef(null); const { plan, isLoading, @@ -82,9 +88,11 @@ export const VisualExplainPage = ({ await loadFile(initialParamPath); return; } + if (!nativeHandoffs) return; try { const pending = await invoke('get_pending_explain_file'); if (!cancelled && version === source.current && pending) { + pickedFile.current = null; setFilePath(pending); await loadFile(pending); } @@ -104,6 +112,7 @@ export const VisualExplainPage = ({ invalidate(); }; }, [ + nativeHandoffs, initialPlan, initialParamPath, isDeepLink, @@ -115,23 +124,34 @@ export const VisualExplainPage = ({ invalidate, ]); + const loadPickedFile = useCallback( + (selected: ChosenInputFile) => + loadPlan(async () => { + const contents = await platform.readInputFile(selected.reference); + return withSourceLabel( + parseExplain(new TextDecoder().decode(contents)), + selected.name, + ); + }), + [loadPlan, platform], + ); + const handlePickFile = useCallback(async () => { const version = sourceVersion.current; const picker = ++pickerVersion.current; try { - const selected = await openDialog({ - multiple: false, + const selected = await platform.chooseInputFile({ filters: [ {name: 'Explain', extensions: ['json', 'txt']}, {name: 'All files', extensions: ['*']}, ], }); if (version !== sourceVersion.current || picker !== pickerVersion.current) return; - if (typeof selected === 'string' && selected.trim().length > 0) { - ++sourceVersion.current; - setFilePath(selected); - await loadFile(selected); - } + if (!selected) return; + ++sourceVersion.current; + pickedFile.current = selected; + setFilePath(selected.name); + await loadPickedFile(selected); } catch (err) { if (version === sourceVersion.current && picker === pickerVersion.current) { ++sourceVersion.current; @@ -140,14 +160,15 @@ export const VisualExplainPage = ({ }); } } - }, [loadFile, loadPlan]); + }, [loadPickedFile, loadPlan, platform]); const handleReload = useCallback(() => { if (filePath) { ++sourceVersion.current; - void loadFile(filePath); + if (pickedFile.current) void loadPickedFile(pickedFile.current); + else void loadFile(filePath); } - }, [filePath, loadFile]); + }, [filePath, loadFile, loadPickedFile]); const fileLabel = filePath ? getExplainFileName(filePath) : null; const containerClass = compactMode diff --git a/packages/web-ui/src/platform/activeCapabilities.ts b/packages/web-ui/src/platform/activeCapabilities.ts new file mode 100644 index 000000000..34020eb3f --- /dev/null +++ b/packages/web-ui/src/platform/activeCapabilities.ts @@ -0,0 +1,29 @@ +import type {PlatformCapabilities} from './capabilities'; + +let activePlatformCapabilities: PlatformCapabilities | null = null; + +export function registerActivePlatformCapabilities(capabilities: PlatformCapabilities): void { + activePlatformCapabilities = capabilities; +} + +export function getActivePlatformCapabilities(): PlatformCapabilities { + if (!activePlatformCapabilities) { + throw new Error('Platform capabilities have not been registered'); + } + return activePlatformCapabilities; +} + +/** The registered platform, or null before bootstrap (tests, previews). */ +export function getActivePlatformCapabilitiesOrNull(): PlatformCapabilities | null { + return activePlatformCapabilities; +} + +export function writeActiveClipboard(text: string): Promise { + if (activePlatformCapabilities) { + return activePlatformCapabilities.writeClipboard(text); + } + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + return navigator.clipboard.writeText(text); + } + return Promise.reject(new Error('Clipboard access is unavailable')); +} diff --git a/packages/web-ui/src/platform/browserCapabilities.ts b/packages/web-ui/src/platform/browserCapabilities.ts new file mode 100644 index 000000000..cf38e2223 --- /dev/null +++ b/packages/web-ui/src/platform/browserCapabilities.ts @@ -0,0 +1,425 @@ +import type {TabularisClient} from '@/api/client'; +import { + createPlatformCapabilityNegotiation, + PlatformCapabilityPermissionError, + UnsupportedPlatformCapabilityError, + type AttentionLevel, + type BlobRecordRequest, + type ChooseInputFileOptions, + type ChooseSaveTargetOptions, + type ChooseServerPathOptions, + type ChosenInputFile, + type ChosenSaveTarget, + type DownloadFileRequest, + type FetchedBlob, + type NotificationOutcome, + type OpenConnectionRouteRequest, + type OpenRouteRequest, + type PlatformCapabilities, + type PlatformCapabilityName, + type PlatformDialogRequest, + type PlatformCapabilityNegotiation, + type PlatformNotification, + type SystemThemeListener, + type RouteEventHandler, + type UnsubscribeRouteEvent, +} from './capabilities'; +import { + blobPayloadToBytes, + extractBase64Payload, + extractBlobMetadata, + parseBlobUploadRef, +} from '@/utils/blob'; +import {buildConnectionRoute, buildRouteWindowLabel} from '@/routing'; +import {publishBrowserCapabilityFallback} from './browserFallbacks'; +import { + requestBrowserMessage, + requestBrowserSaveTarget, + requestBrowserServerPath, +} from './browserDialogs'; +import {listenForColorSchemeChanges, prefersDarkColorScheme} from './systemColorScheme'; + +function browserCapabilityNegotiation(serverFileBrowser: boolean): PlatformCapabilityNegotiation { + return createPlatformCapabilityNegotiation('browser', { + chooseInputFile: {supported: true, adaptation: 'adapted'}, + chooseSaveTarget: serverFileBrowser + ? {supported: true, adaptation: 'adapted'} + : { + supported: false, + adaptation: 'unsupported', + reason: 'Server file browsing is disabled. Start Tabularis with --server-file-browser-root to enable it.', + }, + chooseServerPath: serverFileBrowser + ? {supported: true, adaptation: 'adapted'} + : { + supported: false, + adaptation: 'unsupported', + reason: 'Server file browsing is disabled. Start Tabularis with --server-file-browser-root to enable it.', + }, + confirm: {supported: true, adaptation: 'adapted'}, + showMessage: {supported: true, adaptation: 'adapted'}, + readClipboard: {supported: true, adaptation: 'adapted'}, + writeClipboard: {supported: true, adaptation: 'adapted'}, + downloadFile: {supported: true, adaptation: 'adapted'}, + openExternalUrl: {supported: true, adaptation: 'adapted'}, + notify: {supported: true, adaptation: 'adapted'}, + openRoute: {supported: true, adaptation: 'adapted'}, + closeRoute: {supported: true, adaptation: 'adapted'}, + requestAttention: {supported: true, adaptation: 'adapted'}, + restartApplication: { + supported: false, + adaptation: 'unsupported', + reason: 'The browser cannot restart the Tabularis server', + }, + openStorageLocation: { + supported: false, + adaptation: 'unsupported', + reason: 'The browser cannot open folders on the Tabularis server', + }, + }); +} + +type BrowserFilePicker = (accept?: string) => Promise; + +export class BrowserPlatformCapabilities implements PlatformCapabilities { + readonly negotiation: PlatformCapabilityNegotiation; + private readonly client: TabularisClient; + private readonly filePicker: BrowserFilePicker; + private readonly inputFiles = new Map(); + + constructor( + client: TabularisClient, + filePicker: BrowserFilePicker = pickFile, + serverFileBrowser = false, + ) { + this.client = client; + this.filePicker = filePicker; + this.negotiation = browserCapabilityNegotiation(serverFileBrowser); + } + + supports(capability: PlatformCapabilityName): boolean { + return this.negotiation.capabilities[capability].supported; + } + + async chooseInputFile(options?: ChooseInputFileOptions): Promise { + const accept = options?.filters + ?.flatMap(({extensions}) => extensions.map((extension) => `.${extension}`)) + .join(','); + const file = await this.filePicker(accept); + if (!file) return null; + const reference = `browser-file:${crypto.randomUUID()}`; + this.inputFiles.set(reference, file); + return {name: file.name, reference}; + } + + chooseSaveTarget(options: ChooseSaveTargetOptions = {}): Promise { + if (!this.supports('chooseSaveTarget')) { + return this.unsupported('chooseSaveTarget'); + } + return requestBrowserSaveTarget(options); + } + + chooseServerPath(options: ChooseServerPathOptions): Promise { + if (!this.supports('chooseServerPath')) { + return this.unsupported('chooseServerPath'); + } + return requestBrowserServerPath(options); + } + + confirm(request: PlatformDialogRequest): Promise { + return Promise.resolve(window.confirm(dialogText(request))); + } + + showMessage(request: PlatformDialogRequest): Promise { + return requestBrowserMessage(request); + } + + async readInputFile(reference: string): Promise { + return new Uint8Array(await (await this.readInputBlob(reference)).arrayBuffer()); + } + + readInputBlob(reference: string): Promise { + const file = this.inputFiles.get(reference); + if (!file) { + return Promise.reject(new Error('Invalid or expired browser file reference')); + } + this.inputFiles.delete(reference); + return Promise.resolve(file); + } + + async chooseConnectionIcon(connectionId: string): Promise { + const file = await pickImageFile(); + if (!file) return null; + const uploadToken = await this.client.uploadConnectionIcon(file); + return this.client.call('save_connection_icon', { + connectionId, + uploadToken, + }); + } + + async chooseBlob(): Promise { + const file = await pickFile(); + return file ? this.client.uploadBlob(file) : null; + } + + previewBlobReference(value: unknown): Promise { + const reference = parseBlobUploadRef(value); + if (!reference?.mimeType.startsWith('image/')) return Promise.resolve(null); + return Promise.resolve(this.client.uploadedBlobUrl(reference.token)); + } + + async fetchBlobReference(value: unknown): Promise { + const reference = parseBlobUploadRef(value); + if (!reference) throw new Error('Invalid browser BLOB upload reference'); + const blob = await this.client.readUploadedBlob(reference.token); + return { + contents: new Uint8Array(await blob.arrayBuffer()), + mimeType: reference.mimeType || blob.type || 'application/octet-stream', + }; + } + + async fetchDatabaseBlob(request: BlobRecordRequest): Promise { + const response = await this.client.call('fetch_blob', request); + if (response.kind === 'download') { + const blob = await this.client.consumeBlobDownload(response.token); + return { + contents: new Uint8Array(await blob.arrayBuffer()), + mimeType: response.mimeType || blob.type || 'application/octet-stream', + }; + } + const metadata = extractBlobMetadata(response.wireValue); + if (!metadata) throw new Error('The backend returned invalid BLOB metadata'); + return { + contents: blobPayloadToBytes( + extractBase64Payload(response.wireValue), + metadata.isBase64, + ), + mimeType: metadata.mimeType, + }; + } + + resolveAppAsset(relativePath: string): Promise { + const match = relativePath.match(/^connection-icons\/([^/\\]+)$/); + if (!match) { + return Promise.reject(new Error('Invalid application asset path')); + } + return Promise.resolve(`/api/v1/assets/connection-icons/${encodeURIComponent(match[1])}`); + } + + async readClipboard(): Promise { + try { + if (!navigator.clipboard?.readText) { + throw new DOMException('Clipboard access is unavailable', 'NotAllowedError'); + } + return await navigator.clipboard.readText(); + } catch (error) { + throw new PlatformCapabilityPermissionError('readClipboard', 'browser', error); + } + } + + async writeClipboard(text: string): Promise { + try { + if (!navigator.clipboard?.writeText) { + throw new DOMException('Clipboard access is unavailable', 'NotAllowedError'); + } + await navigator.clipboard.writeText(text); + } catch (error) { + throw new PlatformCapabilityPermissionError('writeClipboard', 'browser', error); + } + } + + async writeClipboardHtml(html: string, altText: string): Promise { + if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) { + return this.writeClipboard(altText); + } + try { + await navigator.clipboard.write([ + new ClipboardItem({ + 'text/html': new Blob([html], {type: 'text/html'}), + 'text/plain': new Blob([altText], {type: 'text/plain'}), + }), + ]); + } catch (error) { + throw new PlatformCapabilityPermissionError('writeClipboard', 'browser', error); + } + } + + async downloadFile(request: DownloadFileRequest): Promise { + const bytes = new ArrayBuffer(request.contents.byteLength); + new Uint8Array(bytes).set(request.contents); + const blob = new Blob([bytes], { + type: request.mimeType ?? 'application/octet-stream', + }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = request.fileName; + anchor.click(); + URL.revokeObjectURL(url); + return true; + } + + async openExternalUrl(url: string): Promise { + const externalUrl = normalizeExternalUrl(url); + const opened = window.open(externalUrl.href, '_blank', 'noopener,noreferrer'); + if (!opened) { + publishBrowserCapabilityFallback({ + kind: 'external-url', + url: externalUrl.href, + }); + } + } + + async notify(notification: PlatformNotification): Promise { + try { + if (typeof Notification === 'undefined') { + publishBrowserCapabilityFallback({ + kind: 'notification', + ...notification, + }); + return 'permission-denied'; + } + if (Notification.permission === 'default') { + await Notification.requestPermission(); + } + if (Notification.permission === 'granted') { + new Notification(notification.title, {body: notification.body}); + return 'shown'; + } + } catch { + // The in-app fallback below preserves the notification outcome. + } + + publishBrowserCapabilityFallback({ + kind: 'notification', + ...notification, + }); + return 'permission-denied'; + } + + async openRoute(request: OpenRouteRequest): Promise { + if (request.target === 'current') { + window.location.assign(request.route); + } else { + window.open(request.route, '_blank', 'noopener,noreferrer'); + } + } + + async openConnectionRoute(request: OpenConnectionRouteRequest): Promise { + await this.openRoute({ + route: buildConnectionRoute(request.connectionId), + target: 'new', + label: buildRouteWindowLabel('connection-window', request.connectionId), + title: request.title ? `tabularis - ${request.title}` : 'tabularis', + }); + } + + async publishRouteEvent(event: string, payload: T): Promise { + const channel = new BroadcastChannel(routeEventChannelName(event)); + channel.postMessage(payload); + channel.close(); + } + + async subscribeRouteEvent( + event: string, + handler: RouteEventHandler, + ): Promise { + const channel = new BroadcastChannel(routeEventChannelName(event)); + const listener = ({data}: MessageEvent) => handler(data); + channel.addEventListener('message', listener); + return () => { + channel.removeEventListener('message', listener); + channel.close(); + }; + } + + async closeRoute(): Promise { + window.close(); + } + + async requestAttention(_level: AttentionLevel = 'informational'): Promise { + void _level; + window.focus(); + } + + restartApplication(): Promise { + return this.unsupported('restartApplication'); + } + + openStorageLocation(): Promise { + return this.unsupported('openStorageLocation'); + } + + setNativeWindowTheme(): Promise { + // Browser pages have no native window chrome to theme. + return Promise.resolve(); + } + + getSystemIsDark(): Promise { + return Promise.resolve(prefersDarkColorScheme().matches); + } + + listenForSystemThemeChanges(onChange: SystemThemeListener): Promise<() => void> { + return listenForColorSchemeChanges(onChange); + } + + currentWindowLabel(): string { + return 'main'; + } + + private unsupported(capability: PlatformCapabilityName): Promise { + const availability = this.negotiation.capabilities[capability]; + return Promise.reject( + new UnsupportedPlatformCapabilityError( + capability, + 'browser', + availability.supported ? undefined : availability.reason, + ), + ); + } +} + +function dialogText(request: PlatformDialogRequest): string { + return request.title ? `${request.title}\n\n${request.message}` : request.message; +} + +function normalizeExternalUrl(value: string): URL { + const url = new URL(value); + if (!['https:', 'http:', 'mailto:'].includes(url.protocol)) { + throw new Error(`Unsupported external URL protocol: ${url.protocol}`); + } + return url; +} + +function routeEventChannelName(event: string): string { + return `tabularis-route:${event}`; +} + +function pickImageFile(): Promise { + return pickFile('.png,.jpg,.jpeg,.webp,.svg,image/png,image/jpeg,image/webp,image/svg+xml'); +} + +function pickFile(accept?: string): Promise { + return new Promise((resolve) => { + const input = document.createElement('input'); + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + window.removeEventListener('focus', handleWindowFocus); + input.remove(); + resolve(input.files?.item(0) ?? null); + }; + const handleWindowFocus = () => { + window.setTimeout(finish, 0); + }; + + input.type = 'file'; + input.hidden = true; + if (accept) input.accept = accept; + input.addEventListener('change', finish, {once: true}); + window.addEventListener('focus', handleWindowFocus, {once: true}); + document.body.appendChild(input); + input.click(); + }); +} diff --git a/packages/web-ui/src/platform/browserDialogs.ts b/packages/web-ui/src/platform/browserDialogs.ts new file mode 100644 index 000000000..c770ca64d --- /dev/null +++ b/packages/web-ui/src/platform/browserDialogs.ts @@ -0,0 +1,78 @@ +import type { + ChooseSaveTargetOptions, + ChooseServerPathOptions, + ChosenSaveTarget, + PlatformDialogRequest, +} from './capabilities'; + +const SERVER_PATH_EVENT = 'tabularis:browser-server-path'; +const MESSAGE_EVENT = 'tabularis:browser-platform-message'; + +export type BrowserPathPickerOptions = + | ({readonly mode: 'open'} & ChooseServerPathOptions) + | ({readonly mode: 'save'} & ChooseSaveTargetOptions); + +export interface BrowserServerPathRequest { + readonly options: BrowserPathPickerOptions; + readonly resolve: (selection: ChosenSaveTarget | null) => void; + readonly reject: (error: unknown) => void; +} + +export interface BrowserMessageRequest { + readonly request: PlatformDialogRequest; + readonly resolve: () => void; +} + +export function requestBrowserServerPath( + options: ChooseServerPathOptions, +): Promise { + return new Promise((resolve, reject) => { + window.dispatchEvent( + new CustomEvent(SERVER_PATH_EVENT, { + detail: {options: {...options, mode: 'open'}, resolve, reject}, + }), + ); + }); +} + +export function requestBrowserSaveTarget( + options: ChooseSaveTargetOptions, +): Promise { + return new Promise((resolve, reject) => { + window.dispatchEvent( + new CustomEvent(SERVER_PATH_EVENT, { + detail: {options: {...options, mode: 'save'}, resolve, reject}, + }), + ); + }); +} + +export function requestBrowserMessage(request: PlatformDialogRequest): Promise { + return new Promise((resolve) => { + window.dispatchEvent( + new CustomEvent(MESSAGE_EVENT, { + detail: {request, resolve}, + }), + ); + }); +} + +export function subscribeBrowserServerPathRequests( + handler: (request: BrowserServerPathRequest) => void, +): () => void { + const listener = (event: Event) => { + handler((event as CustomEvent).detail); + }; + window.addEventListener(SERVER_PATH_EVENT, listener); + return () => window.removeEventListener(SERVER_PATH_EVENT, listener); +} + +export function subscribeBrowserMessageRequests( + handler: (request: BrowserMessageRequest) => void, +): () => void { + const listener = (event: Event) => { + handler((event as CustomEvent).detail); + }; + window.addEventListener(MESSAGE_EVENT, listener); + return () => window.removeEventListener(MESSAGE_EVENT, listener); +} diff --git a/packages/web-ui/src/platform/browserFallbacks.ts b/packages/web-ui/src/platform/browserFallbacks.ts new file mode 100644 index 000000000..1546c3645 --- /dev/null +++ b/packages/web-ui/src/platform/browserFallbacks.ts @@ -0,0 +1,32 @@ +export const BROWSER_CAPABILITY_FALLBACK_EVENT = 'tabularis:browser-capability-fallback'; + +export type BrowserCapabilityFallback = + | { + readonly kind: 'notification'; + readonly title: string; + readonly body?: string; + } + | { + readonly kind: 'external-url'; + readonly url: string; + }; + +export type BrowserCapabilityFallbackHandler = (fallback: BrowserCapabilityFallback) => void; + +export function publishBrowserCapabilityFallback(fallback: BrowserCapabilityFallback): void { + window.dispatchEvent( + new CustomEvent(BROWSER_CAPABILITY_FALLBACK_EVENT, { + detail: fallback, + }), + ); +} + +export function subscribeBrowserCapabilityFallbacks( + handler: BrowserCapabilityFallbackHandler, +): () => void { + const listener = (event: Event) => { + handler((event as CustomEvent).detail); + }; + window.addEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); + return () => window.removeEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); +} diff --git a/packages/web-ui/src/platform/capabilities.ts b/packages/web-ui/src/platform/capabilities.ts new file mode 100644 index 000000000..57063ff96 --- /dev/null +++ b/packages/web-ui/src/platform/capabilities.ts @@ -0,0 +1,268 @@ +export const PLATFORM_CAPABILITY_NAMES = [ + 'chooseInputFile', + 'chooseSaveTarget', + 'chooseServerPath', + 'confirm', + 'showMessage', + 'readClipboard', + 'writeClipboard', + 'downloadFile', + 'openExternalUrl', + 'notify', + 'openRoute', + 'closeRoute', + 'requestAttention', + 'restartApplication', + 'openStorageLocation', +] as const; + +export type PlatformCapabilityName = (typeof PLATFORM_CAPABILITY_NAMES)[number]; +export type PlatformEnvironment = 'tauri' | 'browser'; +export type CapabilityAdaptation = 'native' | 'adapted'; + +export type PlatformCapabilityAvailability = + | { + readonly supported: true; + readonly adaptation: CapabilityAdaptation; + } + | { + readonly supported: false; + readonly adaptation: 'unsupported'; + readonly reason: string; + }; + +export interface PlatformCapabilityNegotiation { + readonly environment: PlatformEnvironment; + readonly capabilities: Readonly>; +} + +export interface PlatformFileFilter { + readonly name: string; + readonly extensions: readonly string[]; +} + +export interface ChooseInputFileOptions { + readonly title?: string; + readonly filters?: readonly PlatformFileFilter[]; +} + +export interface ChosenInputFile { + readonly name: string; + /** + * An opaque reference understood by the active platform adapter. Shared UI + * code must not interpret this value as a server-side filesystem path. + */ + readonly reference: string; +} + +export interface ChooseSaveTargetOptions { + readonly title?: string; + readonly suggestedName?: string; + readonly filters?: readonly PlatformFileFilter[]; +} + +export interface ChosenSaveTarget { + /** + * An opaque reference understood by the active platform adapter. Shared UI + * code must not interpret this value as a server-side filesystem path. + */ + readonly reference: string; +} + +export interface ChooseServerPathOptions { + readonly kind: 'file' | 'directory'; + readonly title?: string; + readonly filters?: readonly PlatformFileFilter[]; +} + +export type PlatformDialogKind = 'info' | 'warning' | 'error'; + +export interface PlatformDialogRequest { + readonly message: string; + readonly title?: string; + readonly kind?: PlatformDialogKind; +} + +export interface DownloadFileRequest { + readonly fileName: string; + readonly contents: Uint8Array; + readonly mimeType?: string; + readonly title?: string; + readonly filters?: readonly PlatformFileFilter[]; +} + +export interface BlobRecordRequest { + readonly connectionId: string; + readonly table: string; + readonly colName: string; + readonly pkMap: Record; + readonly schema?: string; + readonly database?: string; +} + +export interface FetchedBlob { + readonly contents: Uint8Array; + readonly mimeType: string; +} + +export interface PlatformNotification { + readonly title: string; + readonly body?: string; + readonly sound?: string; +} + +export type NotificationOutcome = 'shown' | 'permission-denied'; + +export interface RouteWindowOptions { + readonly width?: number; + readonly height?: number; + readonly minWidth?: number; + readonly minHeight?: number; +} + +export type OpenRouteRequest = + | { + readonly route: string; + readonly target: 'current'; + } + | { + readonly route: string; + readonly target: 'new'; + readonly label: string; + readonly title?: string; + readonly window?: RouteWindowOptions; + }; + +export interface OpenConnectionRouteRequest { + readonly connectionId: string; + readonly title?: string | null; +} + +export type RouteEventHandler = (payload: T) => void; +export type UnsubscribeRouteEvent = () => void; + +export type AttentionLevel = 'informational' | 'critical'; + +/** Native window chrome theme; null follows the operating system. */ +export type NativeWindowTheme = 'light' | 'dark'; + +export type SystemThemeListener = (isDark: boolean) => void; + +export interface PlatformCapabilities { + readonly negotiation: PlatformCapabilityNegotiation; + + supports(capability: PlatformCapabilityName): boolean; + chooseInputFile(options?: ChooseInputFileOptions): Promise; + chooseSaveTarget(options?: ChooseSaveTargetOptions): Promise; + chooseServerPath(options: ChooseServerPathOptions): Promise; + confirm(request: PlatformDialogRequest): Promise; + showMessage(request: PlatformDialogRequest): Promise; + readInputFile(reference: string): Promise; + readInputBlob(reference: string): Promise; + chooseConnectionIcon(connectionId: string): Promise; + chooseBlob(): Promise; + previewBlobReference(value: unknown): Promise; + fetchBlobReference(value: unknown): Promise; + fetchDatabaseBlob(request: BlobRecordRequest): Promise; + resolveAppAsset(relativePath: string): Promise; + readClipboard(): Promise; + writeClipboard(text: string): Promise; + /** Writes an HTML flavor with `altText` as the plain-text flavor (same capability as writeClipboard). */ + writeClipboardHtml(html: string, altText: string): Promise; + downloadFile(request: DownloadFileRequest): Promise; + openExternalUrl(url: string): Promise; + notify(notification: PlatformNotification): Promise; + openRoute(request: OpenRouteRequest): Promise; + openConnectionRoute(request: OpenConnectionRouteRequest): Promise; + publishRouteEvent(event: string, payload: T): Promise; + subscribeRouteEvent( + event: string, + handler: RouteEventHandler, + ): Promise; + closeRoute(): Promise; + requestAttention(level?: AttentionLevel): Promise; + restartApplication(): Promise; + /** Open the app storage folder in the host file manager (desktop only). */ + openStorageLocation(): Promise; + /** Apply the theme to native window chrome; a no-op where there is none. */ + setNativeWindowTheme(theme: NativeWindowTheme | null): Promise; + getSystemIsDark(): Promise; + /** + * Subscribe to operating-system light/dark changes. The listener is also + * called once with the current mode after subscribing. + */ + listenForSystemThemeChanges(onChange: SystemThemeListener): Promise<() => void>; + /** Label of the hosting window; the browser always reports "main". */ + currentWindowLabel(): string; +} + +export class PlatformCapabilityPermissionError extends Error { + readonly code = 'PLATFORM_CAPABILITY_PERMISSION_DENIED'; + readonly capability: PlatformCapabilityName; + readonly environment: PlatformEnvironment; + + constructor( + capability: PlatformCapabilityName, + environment: PlatformEnvironment, + cause?: unknown, + ) { + super(`${capability} permission was denied in ${environment}`, {cause}); + this.name = 'PlatformCapabilityPermissionError'; + this.capability = capability; + this.environment = environment; + } +} + +export class UnsupportedPlatformCapabilityError extends Error { + readonly code = 'PLATFORM_CAPABILITY_UNSUPPORTED'; + readonly capability: PlatformCapabilityName; + readonly environment: PlatformEnvironment; + + constructor( + capability: PlatformCapabilityName, + environment: PlatformEnvironment, + reason?: string, + ) { + super( + reason + ? `${capability} is not supported in ${environment}: ${reason}` + : `${capability} is not supported in ${environment}`, + ); + this.name = 'UnsupportedPlatformCapabilityError'; + this.capability = capability; + this.environment = environment; + } +} + +export function createPlatformCapabilityNegotiation( + environment: PlatformEnvironment, + capabilities: Partial>, +): PlatformCapabilityNegotiation { + return { + environment, + capabilities: Object.fromEntries( + PLATFORM_CAPABILITY_NAMES.map((capability) => [ + capability, + capabilities[capability] ?? { + supported: false, + adaptation: 'unsupported', + reason: 'The active platform did not advertise this capability', + }, + ]), + ) as Record, + }; +} + +export function requirePlatformCapability( + negotiation: PlatformCapabilityNegotiation, + capability: PlatformCapabilityName, +): void { + const availability = negotiation.capabilities[capability]; + if (!availability.supported) { + throw new UnsupportedPlatformCapabilityError( + capability, + negotiation.environment, + availability.reason, + ); + } +} diff --git a/packages/web-ui/src/platform/dialogs.ts b/packages/web-ui/src/platform/dialogs.ts new file mode 100644 index 000000000..75579f1a4 --- /dev/null +++ b/packages/web-ui/src/platform/dialogs.ts @@ -0,0 +1,84 @@ +import type {PlatformCapabilities, PlatformDialogKind, PlatformFileFilter} from './capabilities'; + +interface ConfirmDialogOptions { + readonly title?: string; + readonly kind?: PlatformDialogKind; +} + +export type PlatformConfirmDialog = ( + message: string, + options?: ConfirmDialogOptions, +) => Promise; + +export function bindPlatformConfirm(platform: PlatformCapabilities): PlatformConfirmDialog { + return (message, options) => confirmPlatformDialog(platform, message, options); +} + +interface ServerPathDialogOptions { + readonly multiple?: false; + readonly title?: string; + readonly directory?: boolean; + readonly filters?: readonly PlatformFileFilter[]; +} + +interface SavePathDialogOptions { + readonly title?: string; + readonly defaultPath?: string; + readonly filters?: readonly PlatformFileFilter[]; +} + +export async function choosePlatformServerPath( + platform: PlatformCapabilities, + options: ServerPathDialogOptions = {}, +): Promise { + if (!platform.supports('chooseServerPath')) { + const availability = platform.negotiation.capabilities.chooseServerPath; + await platform.showMessage({ + message: availability.supported + ? 'Server path selection is unavailable' + : availability.reason, + kind: 'info', + }); + return null; + } + const selected = await platform.chooseServerPath({ + kind: options.directory ? 'directory' : 'file', + ...(options.title ? {title: options.title} : {}), + ...(options.filters ? {filters: options.filters} : {}), + }); + return selected?.reference ?? null; +} + +export async function choosePlatformSavePath( + platform: PlatformCapabilities, + options: SavePathDialogOptions = {}, +): Promise { + if (!platform.supports('chooseSaveTarget')) { + const availability = platform.negotiation.capabilities.chooseSaveTarget; + await platform.showMessage({ + message: availability.supported + ? 'Save target selection is unavailable' + : availability.reason, + kind: 'info', + }); + return null; + } + const selected = await platform.chooseSaveTarget({ + ...(options.title ? {title: options.title} : {}), + ...(options.defaultPath ? {suggestedName: options.defaultPath} : {}), + ...(options.filters ? {filters: options.filters} : {}), + }); + return selected?.reference ?? null; +} + +export function confirmPlatformDialog( + platform: PlatformCapabilities, + message: string, + options?: ConfirmDialogOptions, +): Promise { + return platform.confirm({ + message, + ...(options?.title ? {title: options.title} : {}), + ...(options?.kind ? {kind: options.kind} : {}), + }); +} diff --git a/packages/web-ui/src/platform/environment.ts b/packages/web-ui/src/platform/environment.ts new file mode 100644 index 000000000..e23605ac3 --- /dev/null +++ b/packages/web-ui/src/platform/environment.ts @@ -0,0 +1,9 @@ +import {isTauri} from '@tauri-apps/api/core'; +import type {PlatformEnvironment} from './capabilities'; + +export type TauriRuntimeProbe = () => boolean; + +/** The single runtime-host check used when application composition selects adapters. */ +export function detectPlatformEnvironment(probe: TauriRuntimeProbe = isTauri): PlatformEnvironment { + return probe() ? 'tauri' : 'browser'; +} diff --git a/packages/web-ui/src/platform/secondaryWindowSessions.ts b/packages/web-ui/src/platform/secondaryWindowSessions.ts new file mode 100644 index 000000000..398ddfbe1 --- /dev/null +++ b/packages/web-ui/src/platform/secondaryWindowSessions.ts @@ -0,0 +1,202 @@ +import type {PlatformCapabilities} from './capabilities'; +import {BROWSER_ROUTES} from '@/routing'; +import type {ResultsSyncPayload, ResultsWindowAction} from '@/utils/resultsWindowSync'; + +export const JSON_VIEWER_SESSION_REQUEST_EVENT = 'secondary-window:json-session-request'; +export const JSON_VIEWER_SESSION_DATA_EVENT = 'secondary-window:json-session-data'; +export const JSON_VIEWER_SESSION_SAVED_EVENT = 'secondary-window:json-session-saved'; +export const JSON_VIEWER_SESSION_CLOSED_EVENT = 'secondary-window:json-session-closed'; +export const JSON_VIEWER_SESSION_EXPIRED_EVENT = 'secondary-window:json-session-expired'; +export const RESULTS_CLOSE_REQUEST_EVENT = 'secondary-window:results-close-request'; + +export interface ResultsSessionRequest { + readonly sessionId: string; +} + +export interface ResultsSessionSnapshot { + readonly sessionId: string; + readonly payload: ResultsSyncPayload; +} + +export interface ResultsSessionAction { + readonly sessionId: string; + readonly action: ResultsWindowAction; +} + +export type ResultsCloseRequest = ResultsSessionRequest; +export type ResultsSessionClosed = ResultsSessionRequest; + +export interface JsonViewerSession { + readonly value: unknown; + readonly originalValue: unknown; + readonly columnName: string; + readonly rowLabel?: string | null; + readonly readOnly: boolean; + readonly cellKey?: string | null; +} + +export interface JsonViewerSessionRequest { + readonly sessionId: string; +} + +export interface JsonViewerSessionData { + readonly sessionId: string; + readonly session: JsonViewerSession; +} + +export interface JsonViewerSessionSaved { + readonly sessionId: string; + readonly value: unknown; +} + +export interface JsonViewerSessionClosed { + readonly sessionId: string; +} + +export type JsonViewerSessionExpired = JsonViewerSessionRequest; +export type JsonViewerSavedHandler = (value: unknown) => void; + +export interface JsonViewerSessionHostOptions { + readonly createSessionId?: () => string; +} + +interface HostedJsonViewerSession { + session: JsonViewerSession; + onSaved?: JsonViewerSavedHandler; + onClosed?: () => void; +} + +export class JsonViewerSessionHost { + private readonly platform: PlatformCapabilities; + private readonly createSessionId: () => string; + private readonly sessions = new Map(); + private readonly cellSessions = new Map(); + private readonly ready: Promise; + private unsubscribers: Array<() => void> = []; + + constructor(platform: PlatformCapabilities, options: JsonViewerSessionHostOptions = {}) { + this.platform = platform; + this.createSessionId = options.createSessionId ?? (() => crypto.randomUUID()); + this.ready = this.subscribe(); + } + + async open( + session: JsonViewerSession, + onSaved?: JsonViewerSavedHandler, + onClosed?: () => void, + ): Promise { + await this.ready; + + const existingSessionId = session.cellKey + ? this.cellSessions.get(session.cellKey) + : undefined; + const sessionId = existingSessionId ?? this.createSessionId(); + const existingSession = existingSessionId + ? this.sessions.get(existingSessionId) + : undefined; + + const hostedSession: HostedJsonViewerSession = { + session: existingSession ? {...existingSession.session, value: session.value} : session, + onSaved: onSaved ?? existingSession?.onSaved, + onClosed: onClosed ?? existingSession?.onClosed, + }; + this.sessions.set(sessionId, hostedSession); + if (session.cellKey) this.cellSessions.set(session.cellKey, sessionId); + + try { + await this.platform.openRoute({ + route: `${BROWSER_ROUTES.jsonViewer}?session=${encodeURIComponent(sessionId)}`, + target: 'new', + label: `json-viewer-${sessionId}`, + title: buildJsonViewerTitle(session), + window: { + width: 900, + height: 700, + minWidth: 600, + minHeight: 400, + }, + }); + if (onClosed && existingSession?.onClosed !== onClosed) { + existingSession?.onClosed?.(); + } + return sessionId; + } catch (cause) { + if (existingSession) { + this.sessions.set(sessionId, existingSession); + onClosed?.(); + } else this.remove(sessionId, session.cellKey); + throw cause; + } + } + + async dispose(): Promise { + await this.ready; + for (const unsubscribe of this.unsubscribers) unsubscribe(); + this.unsubscribers = []; + for (const hosted of this.sessions.values()) hosted.onClosed?.(); + this.sessions.clear(); + this.cellSessions.clear(); + } + + private async subscribe(): Promise { + this.unsubscribers = await Promise.all([ + this.platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_REQUEST_EVENT, + ({sessionId}) => { + const hosted = this.sessions.get(sessionId); + // Other windows share this bus; only the owner can answer. The viewer + // times out if its owner has gone away. + if (hosted) { + void this.platform.publishRouteEvent( + JSON_VIEWER_SESSION_DATA_EVENT, + {sessionId, session: hosted.session}, + ); + } + }, + ), + this.platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_SAVED_EVENT, + ({sessionId, value}) => { + const hosted = this.sessions.get(sessionId); + if (!hosted) return; + hosted.onSaved?.(value); + this.remove(sessionId, hosted.session.cellKey); + }, + ), + this.platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_CLOSED_EVENT, + ({sessionId}) => { + const hosted = this.sessions.get(sessionId); + if (hosted) this.remove(sessionId, hosted.session.cellKey); + }, + ), + ]); + } + + private remove(sessionId: string, cellKey?: string | null): void { + const hosted = this.sessions.get(sessionId); + this.sessions.delete(sessionId); + hosted?.onClosed?.(); + if (cellKey && this.cellSessions.get(cellKey) === sessionId) { + this.cellSessions.delete(cellKey); + } + } +} + +const hosts = new WeakMap(); + +export function getJsonViewerSessionHost(platform: PlatformCapabilities): JsonViewerSessionHost { + const existing = hosts.get(platform); + if (existing) return existing; + const host = new JsonViewerSessionHost(platform); + hosts.set(platform, host); + return host; +} + +function buildJsonViewerTitle(session: JsonViewerSession): string { + const column = session.columnName.trim(); + const row = session.rowLabel?.trim(); + if (column && row) return `${column} · ${row} — JSON Viewer`; + if (column) return `${column} — JSON Viewer`; + return 'JSON Viewer'; +} diff --git a/packages/web-ui/src/platform/systemColorScheme.ts b/packages/web-ui/src/platform/systemColorScheme.ts new file mode 100644 index 000000000..5cec405a3 --- /dev/null +++ b/packages/web-ui/src/platform/systemColorScheme.ts @@ -0,0 +1,17 @@ +import type {SystemThemeListener} from './capabilities'; + +export function prefersDarkColorScheme(): MediaQueryList { + return window.matchMedia('(prefers-color-scheme: dark)'); +} + +/** Media-query based system theme subscription shared by every adapter. */ +export async function listenForColorSchemeChanges( + onChange: SystemThemeListener, +): Promise<() => void> { + const mediaQuery = prefersDarkColorScheme(); + const handleChange = (event: MediaQueryListEvent) => onChange(event.matches); + mediaQuery.addEventListener('change', handleChange); + await Promise.resolve(); + onChange(mediaQuery.matches); + return () => mediaQuery.removeEventListener('change', handleChange); +} diff --git a/packages/web-ui/src/platform/tauriCapabilities.ts b/packages/web-ui/src/platform/tauriCapabilities.ts new file mode 100644 index 000000000..63b8133ad --- /dev/null +++ b/packages/web-ui/src/platform/tauriCapabilities.ts @@ -0,0 +1,547 @@ +import {convertFileSrc, invoke} from '@tauri-apps/api/core'; +import {emit, listen} from '@tauri-apps/api/event'; +import {join} from '@tauri-apps/api/path'; +import { + ask as askDialog, + message as messageDialog, + open as openDialog, + save as saveDialog, + type OpenDialogOptions, + type SaveDialogOptions, +} from '@tauri-apps/plugin-dialog'; +import {readFile, writeFile} from '@tauri-apps/plugin-fs'; +import {openUrl} from '@tauri-apps/plugin-opener'; +import {readText, writeHtml, writeText} from '@tauri-apps/plugin-clipboard-manager'; +import { + isPermissionGranted, + requestPermission, + sendNotification, +} from '@tauri-apps/plugin-notification'; +import {UserAttentionType, getCurrentWindow} from '@tauri-apps/api/window'; +import {WebviewWindow} from '@tauri-apps/api/webviewWindow'; +import { + PLATFORM_CAPABILITY_NAMES, + createPlatformCapabilityNegotiation, + requirePlatformCapability, + type AttentionLevel, + type BlobRecordRequest, + type ChooseInputFileOptions, + type ChooseSaveTargetOptions, + type ChooseServerPathOptions, + type ChosenInputFile, + type ChosenSaveTarget, + type DownloadFileRequest, + type NativeWindowTheme, + type FetchedBlob, + type NotificationOutcome, + type OpenConnectionRouteRequest, + type OpenRouteRequest, + type PlatformCapabilities, + type PlatformCapabilityNegotiation, + type PlatformDialogRequest, + type PlatformNotification, + type RouteEventHandler, + type SystemThemeListener, + type UnsubscribeRouteEvent, +} from './capabilities'; +import type {BlobFetchResponse} from '@/api/contract'; +import { + blobPayloadToBytes, + extractBase64Payload, + extractBlobMetadata, + parseBlobFileRef, +} from '@/utils/blob'; +import {isLinuxDesktop} from '@/utils/systemTheme'; +import {listenForColorSchemeChanges, prefersDarkColorScheme} from './systemColorScheme'; + +export interface TauriPlatformOperations { + chooseInputPath(options?: ChooseInputFileOptions): Promise; + chooseSavePath(options?: ChooseSaveTargetOptions): Promise; + chooseServerPath(options: ChooseServerPathOptions): Promise; + confirmDialog(request: PlatformDialogRequest): Promise; + showMessageDialog(request: PlatformDialogRequest): Promise; + readClipboardText(): Promise; + writeClipboardText(text: string): Promise; + writeClipboardHtml(html: string, altText: string): Promise; + writeFileContents(reference: string, contents: Uint8Array): Promise; + readFileContents(reference: string): Promise; + openUrl(url: string): Promise; + isNotificationPermissionGranted(): Promise; + requestNotificationPermission(): Promise; + sendNotification(notification: PlatformNotification): void; + openRoute(request: OpenRouteRequest): Promise; + openConnectionRoute(request: OpenConnectionRouteRequest): Promise; + publishRouteEvent(event: string, payload: T): Promise; + subscribeRouteEvent( + event: string, + handler: RouteEventHandler, + ): Promise; + closeRoute(): Promise; + requestAttention(level: AttentionLevel): Promise; + restartApplication(): Promise; + openStorageLocation(): Promise; + setNativeWindowTheme(theme: NativeWindowTheme | null): Promise; + getSystemIsDark(): Promise; + listenForSystemThemeChanges(onChange: SystemThemeListener): Promise<() => void>; + currentWindowLabel(): string; + getAppDataDir(): Promise; +} + +let appDataDirPromise: Promise | null = null; + +/** + * Absolute data directory as resolved by the backend, honouring a custom + * storage location. Cached for the page lifetime: the folder cannot change + * without a restart. Prefer this over `appDataDir()` from the Tauri path API, + * which only knows the platform default. + */ +export function getTauriAppDataDir(): Promise { + if (!appDataDirPromise) { + appDataDirPromise = invoke('get_app_data_dir').catch((e: unknown) => { + appDataDirPromise = null; + throw e; + }); + } + return appDataDirPromise; +} + +/** Test hook: forget the cached directory. */ +export function resetAppDataDirCache(): void { + appDataDirPromise = null; +} + +export const getTauriSystemIsDark = async (): Promise => { + if (isLinuxDesktop()) { + try { + const portalTheme = await invoke<'dark' | 'light' | null>('get_linux_system_theme'); + if (portalTheme) return portalTheme === 'dark'; + } catch { + /* Desktops without a portal use fallbacks. */ + } + } + try { + const nativeTheme = await getCurrentWindow().theme(); + if (nativeTheme) return nativeTheme === 'dark'; + } catch { + /* Previews do not expose the native window API. */ + } + return prefersDarkColorScheme().matches; +}; + +export const listenForTauriSystemThemeChanges = async ( + onChange: SystemThemeListener, +): Promise<() => void> => { + if (isLinuxDesktop()) { + let disposed = false; + let revision = 0; + const refresh = async () => { + const request = ++revision; + const isDark = await getTauriSystemIsDark(); + if (!disposed && request === revision) onChange(isDark); + }; + const mediaQuery = prefersDarkColorScheme(); + const handleChange = () => { + void refresh(); + }; + mediaQuery.addEventListener('change', handleChange); + let stopPortal: (() => void) | undefined; + try { + stopPortal = await listen('linux-system-theme-changed', handleChange); + } catch { + /* Keep the media-query fallback. */ + } + await refresh(); + return () => { + disposed = true; + stopPortal?.(); + mediaQuery.removeEventListener('change', handleChange); + }; + } + try { + let disposed = false; + let revision = 0; + const stopNative = await getCurrentWindow().onThemeChanged(({payload}) => { + const request = ++revision; + if (payload === null) { + void getTauriSystemIsDark().then((isDark) => { + if (!disposed && request === revision) onChange(isDark); + }); + } else { + onChange(payload === 'dark'); + } + }); + // A user may enable follow-system after the OS changed in static mode. + // Subscribe before reading and never let a stale read override an event. + const request = ++revision; + const isDark = await getTauriSystemIsDark(); + if (!disposed && request === revision) onChange(isDark); + return () => { + disposed = true; + stopNative(); + }; + } catch { + return listenForColorSchemeChanges(onChange); + } +}; + +const toDialogFilters = (filters: ChooseInputFileOptions['filters']) => + filters?.map(({name, extensions}) => ({ + name, + extensions: [...extensions], + })); + +const openTauriRoute = async (request: OpenRouteRequest): Promise => { + if (request.target === 'current') { + globalThis.location.assign(request.route); + return; + } + + const existingWindow = await WebviewWindow.getByLabel(request.label); + if (existingWindow) { + await existingWindow.show(); + await existingWindow.unminimize(); + await existingWindow.setFocus(); + return; + } + + const routeWindow = new WebviewWindow(request.label, { + url: request.route, + ...(request.title ? {title: request.title} : {}), + ...(request.window?.width ? {width: request.window.width} : {}), + ...(request.window?.height ? {height: request.window.height} : {}), + ...(request.window?.minWidth ? {minWidth: request.window.minWidth} : {}), + ...(request.window?.minHeight ? {minHeight: request.window.minHeight} : {}), + }); + + await new Promise((resolve, reject) => { + const fail = (error: unknown) => { + reject( + error instanceof Error + ? error + : new Error(`Failed to open route: ${String(error)}`), + ); + }; + + void routeWindow.once('tauri://created', () => resolve()).catch(fail); + void routeWindow.once('tauri://error', ({payload}) => fail(payload)).catch(fail); + }); +}; + +const defaultTauriOperations: TauriPlatformOperations = { + chooseInputPath: (options) => { + const dialogOptions: OpenDialogOptions = { + multiple: false, + directory: false, + ...(options?.title ? {title: options.title} : {}), + ...(options?.filters ? {filters: toDialogFilters(options.filters)} : {}), + }; + return openDialog(dialogOptions); + }, + chooseSavePath: (options) => { + const dialogOptions: SaveDialogOptions = { + ...(options?.title ? {title: options.title} : {}), + ...(options?.suggestedName ? {defaultPath: options.suggestedName} : {}), + ...(options?.filters ? {filters: toDialogFilters(options.filters)} : {}), + }; + return saveDialog(dialogOptions); + }, + chooseServerPath: (options) => + openDialog({ + multiple: false, + directory: options.kind === 'directory', + ...(options.title ? {title: options.title} : {}), + ...(options.filters ? {filters: toDialogFilters(options.filters)} : {}), + }), + confirmDialog: ({message, title, kind}) => + askDialog(message, { + ...(title ? {title} : {}), + ...(kind ? {kind} : {}), + }), + showMessageDialog: async ({message, title, kind}) => { + await messageDialog(message, { + ...(title ? {title} : {}), + ...(kind ? {kind} : {}), + }); + }, + readClipboardText: readText, + writeClipboardText: writeText, + writeClipboardHtml: writeHtml, + writeFileContents: writeFile, + readFileContents: readFile, + openUrl, + isNotificationPermissionGranted: isPermissionGranted, + requestNotificationPermission: requestPermission, + sendNotification, + openRoute: openTauriRoute, + openConnectionRoute: ({connectionId, title}) => + invoke('open_connection_window', { + connectionId, + title: title ?? null, + }), + publishRouteEvent: (event, payload) => emit(event, payload), + subscribeRouteEvent: async (event: string, handler: RouteEventHandler) => + listen(event, ({payload}) => handler(payload)), + closeRoute: () => getCurrentWindow().close(), + requestAttention: (level) => + getCurrentWindow().requestUserAttention( + level === 'critical' ? UserAttentionType.Critical : UserAttentionType.Informational, + ), + restartApplication: () => invoke('relaunch_app'), + openStorageLocation: () => invoke('open_storage_location'), + setNativeWindowTheme: (theme) => getCurrentWindow().setTheme(theme), + getSystemIsDark: getTauriSystemIsDark, + listenForSystemThemeChanges: listenForTauriSystemThemeChanges, + currentWindowLabel: () => getCurrentWindow().label, + getAppDataDir: getTauriAppDataDir, +}; + +const nativeCapabilityAvailability = Object.fromEntries( + PLATFORM_CAPABILITY_NAMES.map((capability) => [ + capability, + {supported: true, adaptation: 'native'} as const, + ]), +); + +export const TAURI_PLATFORM_CAPABILITY_NEGOTIATION = createPlatformCapabilityNegotiation( + 'tauri', + nativeCapabilityAvailability, +); + +const copyToArrayBuffer = (contents: Uint8Array): ArrayBuffer => { + const copy = new ArrayBuffer(contents.byteLength); + new Uint8Array(copy).set(contents); + return copy; +}; + +const selectedFileName = (reference: string): string => { + const segments = reference.split(/[\\/]/); + return segments.at(-1) || reference; +}; + +export class TauriPlatformCapabilities implements PlatformCapabilities { + readonly negotiation: PlatformCapabilityNegotiation; + private readonly operations: TauriPlatformOperations; + + constructor( + operations: TauriPlatformOperations = defaultTauriOperations, + negotiation: PlatformCapabilityNegotiation = TAURI_PLATFORM_CAPABILITY_NEGOTIATION, + ) { + this.operations = operations; + this.negotiation = negotiation; + } + + supports(capability: keyof PlatformCapabilityNegotiation['capabilities']): boolean { + return this.negotiation.capabilities[capability].supported; + } + + async chooseInputFile(options?: ChooseInputFileOptions): Promise { + this.require('chooseInputFile'); + const selected = await this.operations.chooseInputPath(options); + // The dialog is single-select: anything but a non-blank path (a cancelled + // dialog, a blank value or an unexpected multi-selection) selects nothing. + return typeof selected === 'string' && selected.trim().length > 0 + ? {name: selectedFileName(selected), reference: selected} + : null; + } + + async chooseSaveTarget(options?: ChooseSaveTargetOptions): Promise { + this.require('chooseSaveTarget'); + const reference = await this.operations.chooseSavePath(options); + return reference ? {reference} : null; + } + + async chooseServerPath(options: ChooseServerPathOptions): Promise { + this.require('chooseServerPath'); + const reference = await this.operations.chooseServerPath(options); + return reference ? {reference} : null; + } + + async confirm(request: PlatformDialogRequest): Promise { + this.require('confirm'); + return this.operations.confirmDialog(request); + } + + async showMessage(request: PlatformDialogRequest): Promise { + this.require('showMessage'); + await this.operations.showMessageDialog(request); + } + + readInputFile(reference: string): Promise { + this.require('chooseInputFile'); + return this.operations.readFileContents(reference); + } + + async readInputBlob(reference: string): Promise { + return new Blob([copyToArrayBuffer(await this.readInputFile(reference))]); + } + + async chooseConnectionIcon(connectionId: string): Promise { + const selected = await this.chooseInputFile({ + filters: [ + { + name: 'Image', + extensions: ['png', 'jpg', 'jpeg', 'webp', 'svg'], + }, + ], + }); + if (!selected) return null; + return invoke('save_connection_icon', { + connectionId, + sourcePath: selected.reference, + }); + } + + async chooseBlob(): Promise { + const selected = await this.chooseInputFile(); + if (!selected) return null; + return invoke('load_blob_from_file', { + filePath: selected.reference, + }); + } + + async previewBlobReference(value: unknown): Promise { + const reference = parseBlobFileRef(value); + if (!reference?.mimeType.startsWith('image/')) return null; + return invoke('read_file_as_data_url', { + filePath: reference.filePath, + }); + } + + async fetchBlobReference(value: unknown): Promise { + const reference = parseBlobFileRef(value); + if (!reference) throw new Error('Invalid desktop BLOB file reference'); + return { + contents: await this.operations.readFileContents(reference.filePath), + mimeType: reference.mimeType, + }; + } + + async fetchDatabaseBlob(request: BlobRecordRequest): Promise { + const response = await invoke('fetch_blob', {...request}); + if (response.kind !== 'inline') { + throw new Error('The desktop BLOB command returned a browser download token'); + } + const metadata = extractBlobMetadata(response.wireValue); + if (!metadata) throw new Error('The backend returned invalid BLOB metadata'); + return { + contents: blobPayloadToBytes( + extractBase64Payload(response.wireValue), + metadata.isBase64, + ), + mimeType: metadata.mimeType, + }; + } + + async resolveAppAsset(relativePath: string): Promise { + return convertFileSrc(await join(await this.operations.getAppDataDir(), relativePath)); + } + + async readClipboard(): Promise { + this.require('readClipboard'); + return this.operations.readClipboardText(); + } + + async writeClipboard(text: string): Promise { + this.require('writeClipboard'); + await this.operations.writeClipboardText(text); + } + + async writeClipboardHtml(html: string, altText: string): Promise { + this.require('writeClipboard'); + await this.operations.writeClipboardHtml(html, altText); + } + + async downloadFile(request: DownloadFileRequest): Promise { + this.require('downloadFile'); + const reference = await this.operations.chooseSavePath({ + title: request.title, + suggestedName: request.fileName, + filters: request.filters, + }); + if (!reference) return false; + + await this.operations.writeFileContents(reference, request.contents); + return true; + } + + async openExternalUrl(url: string): Promise { + this.require('openExternalUrl'); + await this.operations.openUrl(url); + } + + async notify(notification: PlatformNotification): Promise { + this.require('notify'); + let permissionGranted = await this.operations.isNotificationPermissionGranted(); + if (!permissionGranted) { + permissionGranted = + (await this.operations.requestNotificationPermission()) === 'granted'; + } + if (!permissionGranted) return 'permission-denied'; + + this.operations.sendNotification(notification); + return 'shown'; + } + + async openRoute(request: OpenRouteRequest): Promise { + this.require('openRoute'); + await this.operations.openRoute(request); + } + + async openConnectionRoute(request: OpenConnectionRouteRequest): Promise { + this.require('openRoute'); + await this.operations.openConnectionRoute(request); + } + + async publishRouteEvent(event: string, payload: T): Promise { + this.require('openRoute'); + await this.operations.publishRouteEvent(event, payload); + } + + async subscribeRouteEvent( + event: string, + handler: RouteEventHandler, + ): Promise { + this.require('openRoute'); + return this.operations.subscribeRouteEvent(event, handler); + } + + async closeRoute(): Promise { + this.require('closeRoute'); + await this.operations.closeRoute(); + } + + async requestAttention(level: AttentionLevel = 'informational'): Promise { + this.require('requestAttention'); + await this.operations.requestAttention(level); + } + + async restartApplication(): Promise { + this.require('restartApplication'); + await this.operations.restartApplication(); + } + + async openStorageLocation(): Promise { + this.require('openStorageLocation'); + await this.operations.openStorageLocation(); + } + + setNativeWindowTheme(theme: NativeWindowTheme | null): Promise { + return this.operations.setNativeWindowTheme(theme); + } + + getSystemIsDark(): Promise { + return this.operations.getSystemIsDark(); + } + + listenForSystemThemeChanges(onChange: SystemThemeListener): Promise<() => void> { + return this.operations.listenForSystemThemeChanges(onChange); + } + + currentWindowLabel(): string { + return this.operations.currentWindowLabel(); + } + + private require(capability: keyof PlatformCapabilityNegotiation['capabilities']): void { + requirePlatformCapability(this.negotiation, capability); + } +} diff --git a/src/pluginApi.ts b/packages/web-ui/src/pluginApi.ts similarity index 94% rename from src/pluginApi.ts rename to packages/web-ui/src/pluginApi.ts index ce7db5460..7ead2bd6b 100644 --- a/src/pluginApi.ts +++ b/packages/web-ui/src/pluginApi.ts @@ -21,6 +21,8 @@ export { export type {SlotComponentProps, SlotContext, SlotName} from './types/pluginSlots'; export type {PluginModalOptions} from './contexts/PluginModalContext'; +export {API_VERSION} from './pluginApiVersion'; + // Slot registration helper — must be exposed via __TABULARIS_API__ so plugin // IIFE bundles that externalize @tabularis/plugin-api can call defineSlot(). export function defineSlot( diff --git a/packages/web-ui/src/pluginApiVersion.ts b/packages/web-ui/src/pluginApiVersion.ts new file mode 100644 index 000000000..f8a30dfb6 --- /dev/null +++ b/packages/web-ui/src/pluginApiVersion.ts @@ -0,0 +1,5 @@ +/** + * Host contract version exposed to installed plugin UI bundles. + * Keep in sync with packages/plugin-api/src/version.ts. + */ +export const API_VERSION = '0.1.1'; diff --git a/src/polyfills.ts b/packages/web-ui/src/polyfills.ts similarity index 100% rename from src/polyfills.ts rename to packages/web-ui/src/polyfills.ts diff --git a/packages/web-ui/src/routing.ts b/packages/web-ui/src/routing.ts new file mode 100644 index 000000000..f5b94253b --- /dev/null +++ b/packages/web-ui/src/routing.ts @@ -0,0 +1,73 @@ +export const WEB_UI_BASE_PATH = '/'; + +export const BROWSER_ROUTES = { + root: '/', + connections: '/connections', + editor: '/editor', + connectionEditor: '/connections/:connectionId/editor', + mcp: '/mcp', + settings: '/settings', + schemaDiagram: '/schema-diagram', + taskManager: '/task-manager', + visualExplain: '/visual-explain', + jsonViewer: '/json-viewer', + resultsWindow: '/results-window', + pluginInstall: '/install/:slug', +} as const; + +export const BROWSER_ROUTE_PATHS = Object.values(BROWSER_ROUTES); + +export interface SchemaDiagramRouteParams { + readonly connectionId: string; + readonly connectionName: string; + readonly databaseName: string; + readonly database?: string; + readonly schema?: string; + readonly focusTable?: string; +} + +export function buildConnectionRoute(connectionId: string): string { + return `${BROWSER_ROUTES.connections}?connect=${encodeURIComponent(connectionId)}&standalone=connection`; +} + +export function buildEditorRoute(connectionId: string): string { + return `/connections/${encodeURIComponent(connectionId)}/editor`; +} + +export function isEditorRoute(pathname: string): boolean { + return pathname === BROWSER_ROUTES.editor || /^\/connections\/[^/]+\/editor\/?$/.test(pathname); +} + +export function buildResultsWindowRoute(sessionId: string): string { + return `${BROWSER_ROUTES.resultsWindow}?session=${encodeURIComponent(sessionId)}`; +} + +export function buildSchemaDiagramRoute(params: SchemaDiagramRouteParams): string { + const search = new URLSearchParams({ + connectionId: params.connectionId, + connectionName: params.connectionName, + databaseName: params.databaseName, + }); + if (params.database) search.set('database', params.database); + if (params.schema) search.set('schema', params.schema); + if (params.focusTable) search.set('focusTable', params.focusTable); + return `${BROWSER_ROUTES.schemaDiagram}?${search.toString()}`; +} + +export function buildVisualExplainRoute(connectionId: string, query: string): string { + return `${BROWSER_ROUTES.visualExplain}?connection=${encodeURIComponent( + connectionId, + )}&query=${base64UrlEncode(query)}`; +} + +export function buildRouteWindowLabel(prefix: string, ...parts: string[]): string { + const suffix = parts.join(':').replace(/[^a-zA-Z0-9_-]/g, '_'); + return `${prefix}-${suffix}`; +} + +function base64UrlEncode(value: string): string { + const bytes = new TextEncoder().encode(value); + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} diff --git a/src/schemas/theme-bases-v1.json b/packages/web-ui/src/schemas/theme-bases-v1.json similarity index 100% rename from src/schemas/theme-bases-v1.json rename to packages/web-ui/src/schemas/theme-bases-v1.json diff --git a/src/schemas/theme-definition-v1.json b/packages/web-ui/src/schemas/theme-definition-v1.json similarity index 100% rename from src/schemas/theme-definition-v1.json rename to packages/web-ui/src/schemas/theme-definition-v1.json diff --git a/src/schemas/theme-limits-v1.json b/packages/web-ui/src/schemas/theme-limits-v1.json similarity index 100% rename from src/schemas/theme-limits-v1.json rename to packages/web-ui/src/schemas/theme-limits-v1.json diff --git a/src/schemas/theme-package-v1.json b/packages/web-ui/src/schemas/theme-package-v1.json similarity index 100% rename from src/schemas/theme-package-v1.json rename to packages/web-ui/src/schemas/theme-package-v1.json diff --git a/src/schemas/theme-registry-extensions-v1.json b/packages/web-ui/src/schemas/theme-registry-extensions-v1.json similarity index 100% rename from src/schemas/theme-registry-extensions-v1.json rename to packages/web-ui/src/schemas/theme-registry-extensions-v1.json diff --git a/src/schemas/theme-snapshot-v1.json b/packages/web-ui/src/schemas/theme-snapshot-v1.json similarity index 100% rename from src/schemas/theme-snapshot-v1.json rename to packages/web-ui/src/schemas/theme-snapshot-v1.json diff --git a/src/themes/builtin-themes.json b/packages/web-ui/src/themes/builtin-themes.json similarity index 100% rename from src/themes/builtin-themes.json rename to packages/web-ui/src/themes/builtin-themes.json diff --git a/src/themes/colorUtils.ts b/packages/web-ui/src/themes/colorUtils.ts similarity index 100% rename from src/themes/colorUtils.ts rename to packages/web-ui/src/themes/colorUtils.ts diff --git a/src/themes/monaco/Dracula.json b/packages/web-ui/src/themes/monaco/Dracula.json similarity index 100% rename from src/themes/monaco/Dracula.json rename to packages/web-ui/src/themes/monaco/Dracula.json diff --git a/src/themes/monaco/GitHub Dark.json b/packages/web-ui/src/themes/monaco/GitHub Dark.json similarity index 100% rename from src/themes/monaco/GitHub Dark.json rename to packages/web-ui/src/themes/monaco/GitHub Dark.json diff --git a/src/themes/monaco/GitHub Light.json b/packages/web-ui/src/themes/monaco/GitHub Light.json similarity index 100% rename from src/themes/monaco/GitHub Light.json rename to packages/web-ui/src/themes/monaco/GitHub Light.json diff --git a/src/themes/monaco/Gruvbox Material Dark.json b/packages/web-ui/src/themes/monaco/Gruvbox Material Dark.json similarity index 100% rename from src/themes/monaco/Gruvbox Material Dark.json rename to packages/web-ui/src/themes/monaco/Gruvbox Material Dark.json diff --git a/src/themes/monaco/Gruvbox Material Light.json b/packages/web-ui/src/themes/monaco/Gruvbox Material Light.json similarity index 100% rename from src/themes/monaco/Gruvbox Material Light.json rename to packages/web-ui/src/themes/monaco/Gruvbox Material Light.json diff --git a/src/themes/monaco/Monokai.json b/packages/web-ui/src/themes/monaco/Monokai.json similarity index 100% rename from src/themes/monaco/Monokai.json rename to packages/web-ui/src/themes/monaco/Monokai.json diff --git a/src/themes/monaco/Night Owl.json b/packages/web-ui/src/themes/monaco/Night Owl.json similarity index 100% rename from src/themes/monaco/Night Owl.json rename to packages/web-ui/src/themes/monaco/Night Owl.json diff --git a/src/themes/monaco/Nord.json b/packages/web-ui/src/themes/monaco/Nord.json similarity index 100% rename from src/themes/monaco/Nord.json rename to packages/web-ui/src/themes/monaco/Nord.json diff --git a/src/themes/monaco/One Dark Pro.json b/packages/web-ui/src/themes/monaco/One Dark Pro.json similarity index 100% rename from src/themes/monaco/One Dark Pro.json rename to packages/web-ui/src/themes/monaco/One Dark Pro.json diff --git a/src/themes/monaco/Solarized-dark.json b/packages/web-ui/src/themes/monaco/Solarized-dark.json similarity index 100% rename from src/themes/monaco/Solarized-dark.json rename to packages/web-ui/src/themes/monaco/Solarized-dark.json diff --git a/src/themes/monaco/Solarized-light.json b/packages/web-ui/src/themes/monaco/Solarized-light.json similarity index 100% rename from src/themes/monaco/Solarized-light.json rename to packages/web-ui/src/themes/monaco/Solarized-light.json diff --git a/src/themes/monaco/Tomorrow-Night-Eighties.json b/packages/web-ui/src/themes/monaco/Tomorrow-Night-Eighties.json similarity index 100% rename from src/themes/monaco/Tomorrow-Night-Eighties.json rename to packages/web-ui/src/themes/monaco/Tomorrow-Night-Eighties.json diff --git a/src/themes/presets/dracula.ts b/packages/web-ui/src/themes/presets/dracula.ts similarity index 100% rename from src/themes/presets/dracula.ts rename to packages/web-ui/src/themes/presets/dracula.ts diff --git a/src/themes/presets/githubDark.ts b/packages/web-ui/src/themes/presets/githubDark.ts similarity index 100% rename from src/themes/presets/githubDark.ts rename to packages/web-ui/src/themes/presets/githubDark.ts diff --git a/src/themes/presets/gruvboxDark.ts b/packages/web-ui/src/themes/presets/gruvboxDark.ts similarity index 100% rename from src/themes/presets/gruvboxDark.ts rename to packages/web-ui/src/themes/presets/gruvboxDark.ts diff --git a/src/themes/presets/gruvboxLight.ts b/packages/web-ui/src/themes/presets/gruvboxLight.ts similarity index 100% rename from src/themes/presets/gruvboxLight.ts rename to packages/web-ui/src/themes/presets/gruvboxLight.ts diff --git a/src/themes/presets/highContrast.ts b/packages/web-ui/src/themes/presets/highContrast.ts similarity index 100% rename from src/themes/presets/highContrast.ts rename to packages/web-ui/src/themes/presets/highContrast.ts diff --git a/src/themes/presets/monokai.ts b/packages/web-ui/src/themes/presets/monokai.ts similarity index 100% rename from src/themes/presets/monokai.ts rename to packages/web-ui/src/themes/presets/monokai.ts diff --git a/src/themes/presets/nord.ts b/packages/web-ui/src/themes/presets/nord.ts similarity index 100% rename from src/themes/presets/nord.ts rename to packages/web-ui/src/themes/presets/nord.ts diff --git a/src/themes/presets/oneDarkPro.ts b/packages/web-ui/src/themes/presets/oneDarkPro.ts similarity index 100% rename from src/themes/presets/oneDarkPro.ts rename to packages/web-ui/src/themes/presets/oneDarkPro.ts diff --git a/src/themes/presets/solarizedDark.ts b/packages/web-ui/src/themes/presets/solarizedDark.ts similarity index 100% rename from src/themes/presets/solarizedDark.ts rename to packages/web-ui/src/themes/presets/solarizedDark.ts diff --git a/src/themes/presets/solarizedLight.ts b/packages/web-ui/src/themes/presets/solarizedLight.ts similarity index 100% rename from src/themes/presets/solarizedLight.ts rename to packages/web-ui/src/themes/presets/solarizedLight.ts diff --git a/src/themes/presets/tabularisDark.ts b/packages/web-ui/src/themes/presets/tabularisDark.ts similarity index 100% rename from src/themes/presets/tabularisDark.ts rename to packages/web-ui/src/themes/presets/tabularisDark.ts diff --git a/src/themes/presets/tabularisLight.ts b/packages/web-ui/src/themes/presets/tabularisLight.ts similarity index 100% rename from src/themes/presets/tabularisLight.ts rename to packages/web-ui/src/themes/presets/tabularisLight.ts diff --git a/src/themes/themeRegistry.ts b/packages/web-ui/src/themes/themeRegistry.ts similarity index 100% rename from src/themes/themeRegistry.ts rename to packages/web-ui/src/themes/themeRegistry.ts diff --git a/src/themes/themeRuntime.ts b/packages/web-ui/src/themes/themeRuntime.ts similarity index 100% rename from src/themes/themeRuntime.ts rename to packages/web-ui/src/themes/themeRuntime.ts diff --git a/src/themes/themeUtils.ts b/packages/web-ui/src/themes/themeUtils.ts similarity index 100% rename from src/themes/themeUtils.ts rename to packages/web-ui/src/themes/themeUtils.ts diff --git a/src/types/ai.ts b/packages/web-ui/src/types/ai.ts similarity index 80% rename from src/types/ai.ts rename to packages/web-ui/src/types/ai.ts index c267dbc88..b0822838f 100644 --- a/src/types/ai.ts +++ b/packages/web-ui/src/types/ai.ts @@ -3,6 +3,40 @@ export type AiQueryKind = 'select' | 'write' | 'ddl' | 'unknown'; +export interface AiKeyStatus { + configured: boolean; + fromEnv: boolean; +} + +export type AiProviderModels = Record; + +export interface AiGenerateRequest { + provider: string; + model: string; + prompt: string; + schema: string; +} + +export interface AiExplainRequest { + provider: string; + model: string; + query: string; + language: string; +} + +export interface AiNameRequest { + provider: string; + model: string; + query: string; +} + +export interface AiTableNameRequest { + provider: string; + model: string; + headers: string[]; + sample_rows: string[][]; +} + export type AiActivityStatus = 'success' | 'blocked_readonly' | 'blocked_pending_approval' | 'denied' | 'error' | 'timeout'; diff --git a/src/types/askpass.ts b/packages/web-ui/src/types/askpass.ts similarity index 100% rename from src/types/askpass.ts rename to packages/web-ui/src/types/askpass.ts diff --git a/src/types/chatgpt.ts b/packages/web-ui/src/types/chatgpt.ts similarity index 100% rename from src/types/chatgpt.ts rename to packages/web-ui/src/types/chatgpt.ts diff --git a/src/types/commands.ts b/packages/web-ui/src/types/commands.ts similarity index 100% rename from src/types/commands.ts rename to packages/web-ui/src/types/commands.ts diff --git a/src/types/connectionImport.ts b/packages/web-ui/src/types/connectionImport.ts similarity index 100% rename from src/types/connectionImport.ts rename to packages/web-ui/src/types/connectionImport.ts diff --git a/src/types/dataTypes.ts b/packages/web-ui/src/types/dataTypes.ts similarity index 100% rename from src/types/dataTypes.ts rename to packages/web-ui/src/types/dataTypes.ts diff --git a/src/types/databaseBackup.ts b/packages/web-ui/src/types/databaseBackup.ts similarity index 100% rename from src/types/databaseBackup.ts rename to packages/web-ui/src/types/databaseBackup.ts diff --git a/src/types/databaseObjects.ts b/packages/web-ui/src/types/databaseObjects.ts similarity index 100% rename from src/types/databaseObjects.ts rename to packages/web-ui/src/types/databaseObjects.ts diff --git a/src/types/editor.ts b/packages/web-ui/src/types/editor.ts similarity index 99% rename from src/types/editor.ts rename to packages/web-ui/src/types/editor.ts index faf197b51..0ff0c3328 100644 --- a/src/types/editor.ts +++ b/packages/web-ui/src/types/editor.ts @@ -142,7 +142,7 @@ export interface Tab { } export interface EditorPreferences { - tabs: Tab[]; + tabs: Array>; active_tab_id: string | null; } diff --git a/packages/web-ui/src/types/mcp.ts b/packages/web-ui/src/types/mcp.ts new file mode 100644 index 000000000..f6f6471f8 --- /dev/null +++ b/packages/web-ui/src/types/mcp.ts @@ -0,0 +1,9 @@ +export interface McpClientStatus { + client_id: string; + client_name: string; + installed: boolean; + config_path: string | null; + executable_path: string; + client_type: 'file' | 'command'; + manual_command?: string | null; +} diff --git a/src/types/notebook.ts b/packages/web-ui/src/types/notebook.ts similarity index 100% rename from src/types/notebook.ts rename to packages/web-ui/src/types/notebook.ts diff --git a/packages/web-ui/src/types/operations.ts b/packages/web-ui/src/types/operations.ts new file mode 100644 index 000000000..f162140be --- /dev/null +++ b/packages/web-ui/src/types/operations.ts @@ -0,0 +1,59 @@ +export interface LogEntry { + timestamp: string; + level: string; + message: string; + target?: string | null; +} + +export interface LogSettings { + enabled: boolean; + max_size: number; + current_count: number; +} + +export interface ChildProcessInfo { + pid: number; + cpu_percent: number; + memory_bytes: number; + disk_read_bytes: number; + disk_write_bytes: number; +} + +export interface ProcessInfo { + plugin_id: string; + plugin_name: string; + pid: number | null; + cpu_percent: number; + memory_bytes: number; + disk_read_bytes: number; + disk_write_bytes: number; + status: 'running' | 'stopped' | 'unknown'; + children: ChildProcessInfo[]; +} + +export interface TabularisChildProcess { + pid: number; + name: string; + cpu_percent: number; + memory_bytes: number; +} + +export interface TabularisSelfStats { + pid: number; + cpu_percent: number; + self_memory_bytes: number; + total_memory_bytes: number; + disk_read_bytes: number; + disk_write_bytes: number; + child_count: number; +} + +export interface SystemStats { + cpu_percent: number; + memory_used: number; + memory_total: number; + disk_read_bytes: number; + disk_write_bytes: number; + process_count: number; + tabularis: TabularisSelfStats | null; +} diff --git a/src/types/palette.ts b/packages/web-ui/src/types/palette.ts similarity index 100% rename from src/types/palette.ts rename to packages/web-ui/src/types/palette.ts diff --git a/src/types/pluginSlots.ts b/packages/web-ui/src/types/pluginSlots.ts similarity index 98% rename from src/types/pluginSlots.ts rename to packages/web-ui/src/types/pluginSlots.ts index 01af1eaaf..0c4f95462 100644 --- a/src/types/pluginSlots.ts +++ b/packages/web-ui/src/types/pluginSlots.ts @@ -107,6 +107,8 @@ export interface UIExtensionDeclaration { order?: number; /** If set, the contribution is only active when context.driver matches this value */ driver?: string; + /** @tabularis/plugin-api version used to build the bundle */ + api_version?: string; } /** diff --git a/src/types/plugins.ts b/packages/web-ui/src/types/plugins.ts similarity index 97% rename from src/types/plugins.ts rename to packages/web-ui/src/types/plugins.ts index 35021483a..ba9e42a08 100644 --- a/src/types/plugins.ts +++ b/packages/web-ui/src/types/plugins.ts @@ -148,6 +148,12 @@ export interface SqlSyntaxDescriptor { functions?: string[]; } +/** Non-fatal plugin warning queued by the host, e.g. a runtime version mismatch. */ +export interface PluginRuntimeWarning { + plugin_id: string; + message: string; +} + /** Effective metadata for one connection. The registered manifest stays static. */ export interface ConnectionMetadata { capabilities: DriverCapabilities; @@ -249,6 +255,8 @@ export interface UIExtensionManifestEntry { order?: number; /** If set, the contribution is only active when context.driver matches this value. */ driver?: string; + /** @tabularis/plugin-api version used to build this bundle. */ + api_version?: string; } /** @@ -314,3 +322,8 @@ export interface InstalledPluginInfo { version: string; description: string; } + +export interface PluginLoadError { + plugin_id: string; + error: string; +} diff --git a/src/types/proxy.ts b/packages/web-ui/src/types/proxy.ts similarity index 100% rename from src/types/proxy.ts rename to packages/web-ui/src/types/proxy.ts diff --git a/src/types/queryHistory.ts b/packages/web-ui/src/types/queryHistory.ts similarity index 100% rename from src/types/queryHistory.ts rename to packages/web-ui/src/types/queryHistory.ts diff --git a/src/types/schema.ts b/packages/web-ui/src/types/schema.ts similarity index 100% rename from src/types/schema.ts rename to packages/web-ui/src/types/schema.ts diff --git a/src/types/sidebar.ts b/packages/web-ui/src/types/sidebar.ts similarity index 100% rename from src/types/sidebar.ts rename to packages/web-ui/src/types/sidebar.ts diff --git a/src/types/tags.ts b/packages/web-ui/src/types/tags.ts similarity index 100% rename from src/types/tags.ts rename to packages/web-ui/src/types/tags.ts diff --git a/src/types/theme.ts b/packages/web-ui/src/types/theme.ts similarity index 100% rename from src/types/theme.ts rename to packages/web-ui/src/types/theme.ts diff --git a/src/types/themeCatalog.ts b/packages/web-ui/src/types/themeCatalog.ts similarity index 71% rename from src/types/themeCatalog.ts rename to packages/web-ui/src/types/themeCatalog.ts index 9948b29a5..7a26d3067 100644 --- a/src/types/themeCatalog.ts +++ b/packages/web-ui/src/types/themeCatalog.ts @@ -2,6 +2,7 @@ import type {Theme, MonacoThemeDefinition} from './theme'; import type { ResolvedThemeContribution, ThemeContributionContext, + ThemePackageManifestV1, ThemePackageMode, } from './themePackage'; @@ -14,6 +15,17 @@ export interface NativeThemeContribution extends ThemeContributionContext { editor?: MonacoThemeDefinition | null; } +/** Validated local archive, returned before the user confirms the install. */ +export interface LocalThemePreview { + digest: string; + manifest: ThemePackageManifestV1; + variants: NativeThemeContribution[]; +} +/** A committed package operation; warnings describe deferred cleanup only. */ +export interface ThemeCommit { + warnings: string[]; +} + export interface ThemeCatalogIssue { location: string; message: string; diff --git a/src/types/themePackage.ts b/packages/web-ui/src/types/themePackage.ts similarity index 100% rename from src/types/themePackage.ts rename to packages/web-ui/src/types/themePackage.ts diff --git a/src/types/wkx.d.ts b/packages/web-ui/src/types/wkx.d.ts similarity index 100% rename from src/types/wkx.d.ts rename to packages/web-ui/src/types/wkx.d.ts diff --git a/src/utils/aiActivity.ts b/packages/web-ui/src/utils/aiActivity.ts similarity index 100% rename from src/utils/aiActivity.ts rename to packages/web-ui/src/utils/aiActivity.ts diff --git a/src/utils/aiDefaults.ts b/packages/web-ui/src/utils/aiDefaults.ts similarity index 62% rename from src/utils/aiDefaults.ts rename to packages/web-ui/src/utils/aiDefaults.ts index 03070abe7..a1b7c005b 100644 --- a/src/utils/aiDefaults.ts +++ b/packages/web-ui/src/utils/aiDefaults.ts @@ -1,9 +1,11 @@ -import {invoke} from '@tauri-apps/api/core'; +import type {TabularisClient} from '@/api/client'; import type {Settings} from '@/contexts/SettingsContext'; /** Optional AI discovery must not hold up settings hydration or reconnection. */ -export async function detectAiDefaults(settings: Settings): Promise> { - // ChatGPT discovers account models on demand and resolves an empty model natively. +export async function detectAiDefaults( + client: TabularisClient, + settings: Settings, +): Promise> { if ( !settings.aiEnabled || settings.aiProvider === 'chatgpt' || @@ -14,14 +16,12 @@ export async function detectAiDefaults(settings: Settings): Promise - invoke('check_ai_key', {provider}).catch(() => false), - ), + providers.map((provider) => client.call('check_ai_key', {provider}).catch(() => false)), ); provider = providers.find((_, index) => available[index]) ?? null; } if (!provider) return {}; if (settings.aiModel) return {aiProvider: provider}; - const models = await invoke>('get_ai_models', {forceRefresh: false}); + const models = await client.call('get_ai_models', {forceRefresh: false}); return {aiProvider: provider, aiModel: models[provider]?.[0] ?? null}; } diff --git a/src/utils/anchoredPopover.ts b/packages/web-ui/src/utils/anchoredPopover.ts similarity index 100% rename from src/utils/anchoredPopover.ts rename to packages/web-ui/src/utils/anchoredPopover.ts diff --git a/src/utils/approvalExplain.ts b/packages/web-ui/src/utils/approvalExplain.ts similarity index 100% rename from src/utils/approvalExplain.ts rename to packages/web-ui/src/utils/approvalExplain.ts diff --git a/src/utils/asyncResource.ts b/packages/web-ui/src/utils/asyncResource.ts similarity index 100% rename from src/utils/asyncResource.ts rename to packages/web-ui/src/utils/asyncResource.ts diff --git a/src/utils/autoRefresh.ts b/packages/web-ui/src/utils/autoRefresh.ts similarity index 100% rename from src/utils/autoRefresh.ts rename to packages/web-ui/src/utils/autoRefresh.ts diff --git a/src/utils/autocomplete.ts b/packages/web-ui/src/utils/autocomplete.ts similarity index 98% rename from src/utils/autocomplete.ts rename to packages/web-ui/src/utils/autocomplete.ts index 452bf422d..eda77d096 100644 --- a/src/utils/autocomplete.ts +++ b/packages/web-ui/src/utils/autocomplete.ts @@ -1,7 +1,7 @@ import type {Monaco} from '@monaco-editor/react'; -import {invoke} from '@tauri-apps/api/core'; import type {TableInfo} from '@/contexts/DatabaseContext'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; +import type {TypedCommandCaller} from '@/api/contract'; import {formatSqlIdentifier, getQuoteChar, quoteIdentifier} from './identifiers'; import {getCurrentStatement, parseTablesFromQuery, type ParsedTableRef} from './sqlAnalysis'; import { @@ -139,7 +139,12 @@ const cleanupCache = () => { } }; -const getTableColumns = async (connectionId: string, tableName: string, schema?: string | null) => { +const getTableColumns = async ( + client: TypedCommandCaller, + connectionId: string, + tableName: string, + schema?: string | null, +) => { if (!connectionId || !tableName) return []; const cacheKey = schema @@ -153,7 +158,7 @@ const getTableColumns = async (connectionId: string, tableName: string, schema?: } try { - const cols = await invoke>('get_columns', { + const cols = await client.call('get_columns', { connectionId, tableName, ...(schema ? {schema} : {}), @@ -211,6 +216,7 @@ export const registerSqlAutocomplete = ( tables: TableInfo[], schema?: string | null, driver?: string | PluginManifest | DriverCapabilities | null, + client?: TypedCommandCaller, keywordCase: AutocompleteKeywordCase = 'match', ) => { // Declared `sql_syntax` keywords and functions join the shared list. @@ -238,7 +244,7 @@ export const registerSqlAutocomplete = ( }, position: {lineNumber: number; column: number}, ) => { - if (!connectionId) return {suggestions: []}; + if (!connectionId || !client) return {suggestions: []}; const wordUntil = model.getWordUntilPosition(position); const typedPrefix = wordUntil.word ?? ''; @@ -465,7 +471,9 @@ export const registerSqlAutocomplete = ( } const colArrays = await Promise.all( - dotTables.map((t) => getTableColumns(connectionId, t.name, t.schema ?? schema)), + dotTables.map((t) => + getTableColumns(client, connectionId, t.name, t.schema ?? schema), + ), ); const seen = new Set(); const columns = colArrays @@ -593,7 +601,7 @@ export const registerSqlAutocomplete = ( const results = await Promise.all( matchingTables.map((t) => - getTableColumns(connectionId, t.name, t.schema ?? schema), + getTableColumns(client, connectionId, t.name, t.schema ?? schema), ), ); diff --git a/src/utils/blob.ts b/packages/web-ui/src/utils/blob.ts similarity index 88% rename from src/utils/blob.ts rename to packages/web-ui/src/utils/blob.ts index c8554d99e..3bc09d923 100644 --- a/src/utils/blob.ts +++ b/packages/web-ui/src/utils/blob.ts @@ -16,12 +16,15 @@ export const BLOB_TEXT_LENGTH_THRESHOLD = 65_535; /** * Returns true if the value is in the canonical BLOB wire format - * ("BLOB:..." or "BLOB_FILE_REF:...") produced by the backend. + * ("BLOB:...", "BLOB_FILE_REF:...", or "BLOB_UPLOAD_REF:...") + * produced by the backend or an authenticated browser upload. */ export function isBlobWireFormat(value: unknown): boolean { if (value === null || value === undefined) return false; const s = String(value); - return s.startsWith('BLOB:') || s.startsWith('BLOB_FILE_REF:'); + return ( + s.startsWith('BLOB:') || s.startsWith('BLOB_FILE_REF:') || s.startsWith('BLOB_UPLOAD_REF:') + ); } /** @@ -110,6 +113,7 @@ export interface BlobMetadata { * Expected wire formats: * - "BLOB:::" * - "BLOB_FILE_REF:::" + * - "BLOB_UPLOAD_REF:::" * * Returns null for null/undefined values. * Returns a text/plain metadata object for plain-text strings that are not @@ -123,23 +127,18 @@ export function extractBlobMetadata(value: unknown): BlobMetadata | null { const stringValue = String(value); - // Handle BLOB_FILE_REF format: "BLOB_FILE_REF:::" - if (stringValue.startsWith('BLOB_FILE_REF:')) { - const firstColon = 14; // right after "BLOB_FILE_REF:" - const secondColon = stringValue.indexOf(':', firstColon); - const thirdColon = stringValue.indexOf(':', secondColon + 1); - if (secondColon !== -1 && thirdColon !== -1) { - const size = parseInt(stringValue.substring(firstColon, secondColon), 10); - const mimeType = stringValue.substring(secondColon + 1, thirdColon); - - return { - mimeType, - size, - formattedSize: formatBlobSize(size), - isBase64: false, // It's a file reference, not base64 - isTruncated: false, // File refs are never truncated - }; - } + // File and upload references contain metadata but never expose their bytes. + const reference = + parseBlobReference(stringValue, 'BLOB_FILE_REF:') ?? + parseBlobReference(stringValue, 'BLOB_UPLOAD_REF:'); + if (reference) { + return { + mimeType: reference.mimeType, + size: reference.size, + formattedSize: formatBlobSize(reference.size), + isBase64: false, + isTruncated: false, + }; } // Canonical wire format: "BLOB:::" @@ -188,20 +187,35 @@ export function extractBlobMetadata(value: unknown): BlobMetadata | null { export function parseBlobFileRef( value: unknown, ): {size: number; mimeType: string; filePath: string} | null { - const stringValue = String(value ?? ''); - if (!stringValue.startsWith('BLOB_FILE_REF:')) { - return null; - } - const firstColon = 14; // right after "BLOB_FILE_REF:" - const secondColon = stringValue.indexOf(':', firstColon); - const thirdColon = stringValue.indexOf(':', secondColon + 1); - if (secondColon === -1 || thirdColon === -1) { + const parsed = parseBlobReference(String(value ?? ''), 'BLOB_FILE_REF:'); + return parsed + ? {size: parsed.size, mimeType: parsed.mimeType, filePath: parsed.reference} + : null; +} + +export function parseBlobUploadRef( + value: unknown, +): {size: number; mimeType: string; token: string} | null { + const parsed = parseBlobReference(String(value ?? ''), 'BLOB_UPLOAD_REF:'); + return parsed ? {size: parsed.size, mimeType: parsed.mimeType, token: parsed.reference} : null; +} + +function parseBlobReference( + value: string, + prefix: 'BLOB_FILE_REF:' | 'BLOB_UPLOAD_REF:', +): {size: number; mimeType: string; reference: string} | null { + if (!value.startsWith(prefix)) return null; + const firstColon = prefix.length; + const secondColon = value.indexOf(':', firstColon); + const thirdColon = value.indexOf(':', secondColon + 1); + if (secondColon === -1 || thirdColon === -1) return null; + const size = Number.parseInt(value.substring(firstColon, secondColon), 10); + const mimeType = value.substring(secondColon + 1, thirdColon); + const reference = value.substring(thirdColon + 1); + if (!Number.isSafeInteger(size) || size < 0 || !mimeType || !reference) { return null; } - const size = parseInt(stringValue.substring(firstColon, secondColon), 10); - const mimeType = stringValue.substring(secondColon + 1, thirdColon); - const filePath = stringValue.substring(thirdColon + 1); - return {size, mimeType, filePath}; + return {size, mimeType, reference}; } /** diff --git a/src/utils/builtInCommands.ts b/packages/web-ui/src/utils/builtInCommands.ts similarity index 100% rename from src/utils/builtInCommands.ts rename to packages/web-ui/src/utils/builtInCommands.ts diff --git a/src/utils/bulkCellEdit.ts b/packages/web-ui/src/utils/bulkCellEdit.ts similarity index 100% rename from src/utils/bulkCellEdit.ts rename to packages/web-ui/src/utils/bulkCellEdit.ts diff --git a/src/utils/cellValueFilter.ts b/packages/web-ui/src/utils/cellValueFilter.ts similarity index 100% rename from src/utils/cellValueFilter.ts rename to packages/web-ui/src/utils/cellValueFilter.ts diff --git a/src/utils/changelog.ts b/packages/web-ui/src/utils/changelog.ts similarity index 100% rename from src/utils/changelog.ts rename to packages/web-ui/src/utils/changelog.ts diff --git a/src/utils/clipboard.ts b/packages/web-ui/src/utils/clipboard.ts similarity index 98% rename from src/utils/clipboard.ts rename to packages/web-ui/src/utils/clipboard.ts index 31311c8fb..930d38e0c 100644 --- a/src/utils/clipboard.ts +++ b/packages/web-ui/src/utils/clipboard.ts @@ -1,4 +1,5 @@ import {formatCellValue} from './dataGrid'; +import {writeActiveClipboard} from '@/platform/activeCapabilities'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; import {quoteSqlString, sqlBooleanLiteral, stringEscapeStyle} from './sqlLiteral'; import {escapeHtml} from './escape'; @@ -244,7 +245,7 @@ export async function copyTextToClipboard( onError?: (error: unknown) => void, ): Promise { try { - await navigator.clipboard.writeText(text); + await writeActiveClipboard(text); } catch (e) { console.error('Copy failed:', e); if (onError) { diff --git a/src/utils/clipboardParser.ts b/packages/web-ui/src/utils/clipboardParser.ts similarity index 100% rename from src/utils/clipboardParser.ts rename to packages/web-ui/src/utils/clipboardParser.ts diff --git a/src/utils/closedTabs.ts b/packages/web-ui/src/utils/closedTabs.ts similarity index 100% rename from src/utils/closedTabs.ts rename to packages/web-ui/src/utils/closedTabs.ts diff --git a/src/utils/columnMasking.ts b/packages/web-ui/src/utils/columnMasking.ts similarity index 100% rename from src/utils/columnMasking.ts rename to packages/web-ui/src/utils/columnMasking.ts diff --git a/src/utils/columnStats.ts b/packages/web-ui/src/utils/columnStats.ts similarity index 100% rename from src/utils/columnStats.ts rename to packages/web-ui/src/utils/columnStats.ts diff --git a/src/utils/columnTypes.ts b/packages/web-ui/src/utils/columnTypes.ts similarity index 100% rename from src/utils/columnTypes.ts rename to packages/web-ui/src/utils/columnTypes.ts diff --git a/src/utils/commandScopeStore.ts b/packages/web-ui/src/utils/commandScopeStore.ts similarity index 100% rename from src/utils/commandScopeStore.ts rename to packages/web-ui/src/utils/commandScopeStore.ts diff --git a/src/utils/commandTable.ts b/packages/web-ui/src/utils/commandTable.ts similarity index 91% rename from src/utils/commandTable.ts rename to packages/web-ui/src/utils/commandTable.ts index 0134ee476..afc2cd4c0 100644 --- a/src/utils/commandTable.ts +++ b/packages/web-ui/src/utils/commandTable.ts @@ -1,3 +1,4 @@ +import {isEditorRoute} from '@/routing'; import type {TableTarget} from '@/types/databaseObjects'; import type {Tab} from '@/types/editor'; @@ -15,7 +16,7 @@ export function resolveCommandTable({ pathname, }: ResolveCommandTableOptions): TableTarget | null { if ( - pathname !== '/editor' || + !isEditorRoute(pathname) || activeConnectionId === null || activeTab?.type !== 'table' || activeTab.activeTable === null diff --git a/src/utils/connectionCatalogue.ts b/packages/web-ui/src/utils/connectionCatalogue.ts similarity index 100% rename from src/utils/connectionCatalogue.ts rename to packages/web-ui/src/utils/connectionCatalogue.ts diff --git a/src/utils/connectionCommandItems.ts b/packages/web-ui/src/utils/connectionCommandItems.ts similarity index 100% rename from src/utils/connectionCommandItems.ts rename to packages/web-ui/src/utils/connectionCommandItems.ts diff --git a/src/utils/connectionErrors.ts b/packages/web-ui/src/utils/connectionErrors.ts similarity index 100% rename from src/utils/connectionErrors.ts rename to packages/web-ui/src/utils/connectionErrors.ts diff --git a/packages/web-ui/src/utils/connectionFiles.ts b/packages/web-ui/src/utils/connectionFiles.ts new file mode 100644 index 000000000..c1cc2f1de --- /dev/null +++ b/packages/web-ui/src/utils/connectionFiles.ts @@ -0,0 +1,49 @@ +import type {TabularisClient} from '@/api/client'; +import type {ConnectionImportFile, GeneratedFile} from '@/api/contract'; +import type {ChosenInputFile, PlatformCapabilities} from '@/platform/capabilities'; + +const CONNECTION_IMPORT_PURPOSE = 'connection-import'; + +export async function prepareConnectionImportFile( + client: TabularisClient, + platform: PlatformCapabilities, + file: ChosenInputFile, + preparedContents?: Uint8Array, +): Promise { + if (platform.negotiation.environment === 'tauri') { + return {kind: 'serverPath', path: file.reference}; + } + + const contents = preparedContents ?? (await platform.readInputFile(file.reference)); + const metadata = await client.uploadFile({ + contents: new Blob([copyToArrayBuffer(contents)], { + type: 'application/octet-stream', + }), + fileName: file.name, + purpose: CONNECTION_IMPORT_PURPOSE, + }); + return {kind: 'upload', token: metadata.token}; +} + +export async function saveGeneratedFile( + client: TabularisClient, + platform: PlatformCapabilities, + generated: GeneratedFile, +): Promise { + const contents = + generated.kind === 'inline' + ? new TextEncoder().encode(generated.contents) + : new Uint8Array(await (await client.consumeDownload(generated.token)).arrayBuffer()); + + return platform.downloadFile({ + fileName: generated.fileName, + mimeType: generated.mimeType, + contents, + }); +} + +function copyToArrayBuffer(contents: Uint8Array): ArrayBuffer { + const copy = new ArrayBuffer(contents.byteLength); + new Uint8Array(copy).set(contents); + return copy; +} diff --git a/src/utils/connectionIconPack.ts b/packages/web-ui/src/utils/connectionIconPack.ts similarity index 100% rename from src/utils/connectionIconPack.ts rename to packages/web-ui/src/utils/connectionIconPack.ts diff --git a/src/utils/connectionLayout.ts b/packages/web-ui/src/utils/connectionLayout.ts similarity index 100% rename from src/utils/connectionLayout.ts rename to packages/web-ui/src/utils/connectionLayout.ts diff --git a/src/utils/connectionManager.ts b/packages/web-ui/src/utils/connectionManager.ts similarity index 100% rename from src/utils/connectionManager.ts rename to packages/web-ui/src/utils/connectionManager.ts diff --git a/src/utils/connectionMetadata.ts b/packages/web-ui/src/utils/connectionMetadata.ts similarity index 100% rename from src/utils/connectionMetadata.ts rename to packages/web-ui/src/utils/connectionMetadata.ts diff --git a/src/utils/connectionStringParser.ts b/packages/web-ui/src/utils/connectionStringParser.ts similarity index 100% rename from src/utils/connectionStringParser.ts rename to packages/web-ui/src/utils/connectionStringParser.ts diff --git a/src/utils/connectionTest.ts b/packages/web-ui/src/utils/connectionTest.ts similarity index 100% rename from src/utils/connectionTest.ts rename to packages/web-ui/src/utils/connectionTest.ts diff --git a/src/utils/connections.ts b/packages/web-ui/src/utils/connections.ts similarity index 100% rename from src/utils/connections.ts rename to packages/web-ui/src/utils/connections.ts diff --git a/src/utils/contextMenu.ts b/packages/web-ui/src/utils/contextMenu.ts similarity index 100% rename from src/utils/contextMenu.ts rename to packages/web-ui/src/utils/contextMenu.ts diff --git a/src/utils/createTable.ts b/packages/web-ui/src/utils/createTable.ts similarity index 100% rename from src/utils/createTable.ts rename to packages/web-ui/src/utils/createTable.ts diff --git a/src/utils/credentials.ts b/packages/web-ui/src/utils/credentials.ts similarity index 88% rename from src/utils/credentials.ts rename to packages/web-ui/src/utils/credentials.ts index 768502578..d56ed10b3 100644 --- a/src/utils/credentials.ts +++ b/packages/web-ui/src/utils/credentials.ts @@ -1,4 +1,4 @@ -import {invoke} from '@tauri-apps/api/core'; +import type {TypedCommandCaller} from '@/api/contract'; interface ConnectionParams { driver: string; @@ -37,9 +37,8 @@ export interface SavedConnectionWithCredentials { } export async function fetchConnectionWithCredentials( + client: Pick, id: string, ): Promise { - return await invoke('get_connection_by_id', { - id, - }); + return client.call('get_connection_by_id', {id}); } diff --git a/src/utils/dataGrid.ts b/packages/web-ui/src/utils/dataGrid.ts similarity index 100% rename from src/utils/dataGrid.ts rename to packages/web-ui/src/utils/dataGrid.ts diff --git a/src/utils/dataGridCell.tsx b/packages/web-ui/src/utils/dataGridCell.tsx similarity index 100% rename from src/utils/dataGridCell.tsx rename to packages/web-ui/src/utils/dataGridCell.tsx diff --git a/packages/web-ui/src/utils/dataImportFile.ts b/packages/web-ui/src/utils/dataImportFile.ts new file mode 100644 index 000000000..cd2ac21e0 --- /dev/null +++ b/packages/web-ui/src/utils/dataImportFile.ts @@ -0,0 +1,29 @@ +import type {ChosenInputFile, PlatformCapabilities} from '@/platform/capabilities'; + +export const DATA_IMPORT_FILE_LIMIT = 20 * 1024 * 1024; +export const DATA_IMPORT_EXTENSIONS = ['csv', 'tsv', 'json', 'md']; + +export class DataImportFileError extends Error { + readonly code: 'tooLarge' | 'unsupported' | 'notFile'; + + constructor(code: DataImportFileError['code']) { + super(code); + this.code = code; + } +} + +/** Read supported text through the active platform's opaque file reference. */ +export async function readDataImportFile( + file: ChosenInputFile, + platform: Pick, +): Promise { + const extension = file.name.split('.').pop()?.toLowerCase(); + if (!extension || !DATA_IMPORT_EXTENSIONS.includes(extension)) { + throw new DataImportFileError('unsupported'); + } + const bytes = await platform.readInputFile(file.reference); + if (bytes.byteLength > DATA_IMPORT_FILE_LIMIT) { + throw new DataImportFileError('tooLarge'); + } + return new TextDecoder().decode(bytes); +} diff --git a/src/utils/database.ts b/packages/web-ui/src/utils/database.ts similarity index 100% rename from src/utils/database.ts rename to packages/web-ui/src/utils/database.ts diff --git a/src/utils/databaseBackup.ts b/packages/web-ui/src/utils/databaseBackup.ts similarity index 100% rename from src/utils/databaseBackup.ts rename to packages/web-ui/src/utils/databaseBackup.ts diff --git a/src/utils/databaseObjectActions.ts b/packages/web-ui/src/utils/databaseObjectActions.ts similarity index 95% rename from src/utils/databaseObjectActions.ts rename to packages/web-ui/src/utils/databaseObjectActions.ts index 8840e7e3a..7b82ad683 100644 --- a/src/utils/databaseObjectActions.ts +++ b/packages/web-ui/src/utils/databaseObjectActions.ts @@ -1,5 +1,4 @@ -import {invoke} from '@tauri-apps/api/core'; - +import type {TypedCommandCaller} from '@/api/contract'; import type { ConsoleEditorNavigationRequest, DefinitionEditorNavigationRequest, @@ -265,8 +264,11 @@ export function createDefinitionRequest({ }; } -export function loadRoutineDefinition(target: RoutineDefinitionTarget): Promise { - return invoke('get_routine_definition', { +export function loadRoutineDefinition( + client: Pick, + target: RoutineDefinitionTarget, +): Promise { + return client.call('get_routine_definition', { connectionId: target.connectionId, routineName: target.routineName, routineType: target.routineType, @@ -281,8 +283,11 @@ export function loadRoutineDefinition(target: RoutineDefinitionTarget): Promise< }); } -export function loadTriggerDefinition(target: TriggerDefinitionTarget): Promise { - return invoke('get_trigger_definition', { +export function loadTriggerDefinition( + client: Pick, + target: TriggerDefinitionTarget, +): Promise { + return client.call('get_trigger_definition', { connectionId: target.connectionId, triggerName: target.triggerName, tableName: target.tableName, diff --git a/packages/web-ui/src/utils/databaseTransfers.ts b/packages/web-ui/src/utils/databaseTransfers.ts new file mode 100644 index 000000000..d076da90e --- /dev/null +++ b/packages/web-ui/src/utils/databaseTransfers.ts @@ -0,0 +1,56 @@ +import type {TabularisClient} from '@/api/client'; +import type {DatabaseDumpRequest} from '@/api/contract'; +import type {ChosenInputFile, PlatformCapabilities} from '@/platform/capabilities'; +import {saveGeneratedFile} from './connectionFiles'; + +const DATABASE_IMPORT_PURPOSE = 'database-import'; +const DATABASE_JOB_DEADLINE_MS = 6 * 60 * 60 * 1_000; + +export type PreparedDatabaseImportSource = {filePath: string} | {uploadToken: string}; + +export async function prepareDatabaseImportSource( + client: TabularisClient, + platform: PlatformCapabilities, + file: ChosenInputFile, +): Promise { + if (platform.negotiation.environment === 'tauri') { + return {filePath: file.reference}; + } + + const metadata = await client.uploadFile({ + contents: await platform.readInputBlob(file.reference), + fileName: file.name, + purpose: DATABASE_IMPORT_PURPOSE, + }); + return {uploadToken: metadata.token}; +} + +export async function runDatabaseDump( + client: TabularisClient, + platform: PlatformCapabilities, + request: DatabaseDumpRequest, + suggestedName: string, +): Promise { + let commandRequest = request; + if (platform.negotiation.environment === 'tauri') { + const target = await platform.chooseSaveTarget({ + suggestedName, + filters: [{name: 'SQL File', extensions: ['sql']}], + }); + if (!target) return false; + commandRequest = {...request, filePath: target.reference}; + } + + const generated = await client.call('dump_database', commandRequest, { + deadlineMs: DATABASE_JOB_DEADLINE_MS, + cancellationId: crypto.randomUUID(), + }); + if (!generated) return true; + if (platform.negotiation.environment === 'browser' && generated.kind === 'download') { + await client.requestDownload(generated.token); + return true; + } + return saveGeneratedFile(client, platform, generated); +} + +export const DATABASE_TRANSFER_DEADLINE_MS = DATABASE_JOB_DEADLINE_MS; diff --git a/src/utils/dateGroups.ts b/packages/web-ui/src/utils/dateGroups.ts similarity index 100% rename from src/utils/dateGroups.ts rename to packages/web-ui/src/utils/dateGroups.ts diff --git a/src/utils/dateInput.ts b/packages/web-ui/src/utils/dateInput.ts similarity index 100% rename from src/utils/dateInput.ts rename to packages/web-ui/src/utils/dateInput.ts diff --git a/src/utils/derivedTables.ts b/packages/web-ui/src/utils/derivedTables.ts similarity index 100% rename from src/utils/derivedTables.ts rename to packages/web-ui/src/utils/derivedTables.ts diff --git a/src/utils/dragState.ts b/packages/web-ui/src/utils/dragState.ts similarity index 100% rename from src/utils/dragState.ts rename to packages/web-ui/src/utils/dragState.ts diff --git a/src/utils/driverCapabilities.ts b/packages/web-ui/src/utils/driverCapabilities.ts similarity index 100% rename from src/utils/driverCapabilities.ts rename to packages/web-ui/src/utils/driverCapabilities.ts diff --git a/src/utils/driverIcons.tsx b/packages/web-ui/src/utils/driverIcons.tsx similarity index 100% rename from src/utils/driverIcons.tsx rename to packages/web-ui/src/utils/driverIcons.tsx diff --git a/src/utils/driverUI.tsx b/packages/web-ui/src/utils/driverUI.tsx similarity index 100% rename from src/utils/driverUI.tsx rename to packages/web-ui/src/utils/driverUI.tsx diff --git a/src/utils/dropTable.ts b/packages/web-ui/src/utils/dropTable.ts similarity index 100% rename from src/utils/dropTable.ts rename to packages/web-ui/src/utils/dropTable.ts diff --git a/src/utils/dropdownPosition.ts b/packages/web-ui/src/utils/dropdownPosition.ts similarity index 100% rename from src/utils/dropdownPosition.ts rename to packages/web-ui/src/utils/dropdownPosition.ts diff --git a/src/utils/dumpUtils.ts b/packages/web-ui/src/utils/dumpUtils.ts similarity index 100% rename from src/utils/dumpUtils.ts rename to packages/web-ui/src/utils/dumpUtils.ts diff --git a/src/utils/editor.ts b/packages/web-ui/src/utils/editor.ts similarity index 95% rename from src/utils/editor.ts rename to packages/web-ui/src/utils/editor.ts index 7c6ae2532..8cfe9750c 100644 --- a/src/utils/editor.ts +++ b/packages/web-ui/src/utils/editor.ts @@ -1,7 +1,7 @@ -import type {Tab, SchemaCache, TableSchema, EditorPreferences} from '@/types/editor'; +import type {Tab, SchemaCache, TableSchema} from '@/types/editor'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; import {quoteTableRef} from './identifiers'; -import {invoke} from '@tauri-apps/api/core'; +import type {TypedCommandCaller} from '@/api/contract'; import {cleanTabForStorage, restoreTabFromStorage} from './tabCleaner'; import {filterTabsByConnection, getActiveTabForConnection} from './tabFilters'; @@ -17,14 +17,13 @@ export function generateTabId(): string { } export async function loadEditorPreferences( + client: TypedCommandCaller, connectionId: string | null, ): Promise<{tabs: Tab[]; activeTabId: string | null}> { if (!connectionId) return {tabs: [], activeTabId: null}; try { - const prefs = await invoke('load_editor_preferences', { - connectionId, - }); + const prefs = await client.call('load_editor_preferences', {connectionId}); const tabs = (prefs?.tabs || []).map(restoreTabFromStorage); return {tabs, activeTabId: prefs?.active_tab_id || null}; } catch (e) { @@ -34,16 +33,23 @@ export async function loadEditorPreferences( } /** @deprecated Use loadEditorPreferences instead */ -export async function loadTabsFromStorage(connectionId: string | null): Promise { - return (await loadEditorPreferences(connectionId)).tabs; +export async function loadTabsFromStorage( + client: TypedCommandCaller, + connectionId: string | null, +): Promise { + return (await loadEditorPreferences(client, connectionId)).tabs; } /** @deprecated Use loadEditorPreferences instead */ -export async function loadActiveTabId(connectionId: string | null): Promise { - return (await loadEditorPreferences(connectionId)).activeTabId; +export async function loadActiveTabId( + client: TypedCommandCaller, + connectionId: string | null, +): Promise { + return (await loadEditorPreferences(client, connectionId)).activeTabId; } export async function saveTabsToStorage( + client: TypedCommandCaller, connectionId: string, tabs: Tab[], activeTabId: string | null, @@ -52,7 +58,7 @@ export async function saveTabsToStorage( // Clean tabs before saving: remove temporary data like results, errors, etc. const cleanedTabs = tabs.map(cleanTabForStorage); - await invoke('save_editor_preferences', { + await client.call('save_editor_preferences', { connectionId, preferences: { tabs: cleanedTabs, diff --git a/src/utils/editorCommands.ts b/packages/web-ui/src/utils/editorCommands.ts similarity index 100% rename from src/utils/editorCommands.ts rename to packages/web-ui/src/utils/editorCommands.ts diff --git a/src/utils/editorFontSize.ts b/packages/web-ui/src/utils/editorFontSize.ts similarity index 100% rename from src/utils/editorFontSize.ts rename to packages/web-ui/src/utils/editorFontSize.ts diff --git a/src/utils/editorNavigation.ts b/packages/web-ui/src/utils/editorNavigation.ts similarity index 100% rename from src/utils/editorNavigation.ts rename to packages/web-ui/src/utils/editorNavigation.ts diff --git a/src/utils/environment.ts b/packages/web-ui/src/utils/environment.ts similarity index 100% rename from src/utils/environment.ts rename to packages/web-ui/src/utils/environment.ts diff --git a/src/utils/errors.ts b/packages/web-ui/src/utils/errors.ts similarity index 100% rename from src/utils/errors.ts rename to packages/web-ui/src/utils/errors.ts diff --git a/src/utils/escape.ts b/packages/web-ui/src/utils/escape.ts similarity index 100% rename from src/utils/escape.ts rename to packages/web-ui/src/utils/escape.ts diff --git a/src/utils/explainImport.ts b/packages/web-ui/src/utils/explainImport.ts similarity index 100% rename from src/utils/explainImport.ts rename to packages/web-ui/src/utils/explainImport.ts diff --git a/src/utils/explainRaw.ts b/packages/web-ui/src/utils/explainRaw.ts similarity index 84% rename from src/utils/explainRaw.ts rename to packages/web-ui/src/utils/explainRaw.ts index dfae0ad5d..0bbfe7010 100644 --- a/src/utils/explainRaw.ts +++ b/packages/web-ui/src/utils/explainRaw.ts @@ -7,8 +7,8 @@ * a one-line XML document readable without touching the parsed plan. */ -import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {downloadTextFile} from './fileDownloads'; export type RawExplainLanguage = 'json' | 'xml' | 'plaintext'; @@ -82,31 +82,28 @@ export function getRawExplainFileOptions(raw: string): RawExplainFileDialogOptio }; } -export interface SaveRawExplainDependencies { - saveDialog?: (options: RawExplainFileDialogOptions) => Promise; - writeFile?: (path: string, content: string) => Promise; -} +const RAW_EXPLAIN_MIME_TYPES: Record = { + json: 'application/json', + xml: 'application/xml', + plaintext: 'text/plain', +}; /** - * Prompt the user for a destination file and write the raw EXPLAIN output. - * Returns true when successfully saved, or false when the user cancelled the dialog. - * Throws when dialog prompt or file writing fails. + * Save the raw EXPLAIN output unmodified through the platform download + * (native save dialog on desktop, browser download on the web). + * Returns false when the user cancelled; throws when saving fails. */ -export async function saveRawExplainOutput( +export function saveRawExplainOutput( + platform: PlatformCapabilities, raw: string, - deps: SaveRawExplainDependencies = {}, ): Promise { - const saveDialog = deps.saveDialog ?? save; - const writeFile = deps.writeFile ?? writeTextFile; - - const options = getRawExplainFileOptions(raw); - const path = await saveDialog(options); - if (!path) { - return false; - } - - await writeFile(path, raw); - return true; + const {defaultPath, filters} = getRawExplainFileOptions(raw); + return downloadTextFile(platform, { + fileName: defaultPath, + contents: raw, + mimeType: RAW_EXPLAIN_MIME_TYPES[detectRawExplainLanguage(raw)], + filters, + }); } /** diff --git a/src/utils/explainTableExport.ts b/packages/web-ui/src/utils/explainTableExport.ts similarity index 83% rename from src/utils/explainTableExport.ts rename to packages/web-ui/src/utils/explainTableExport.ts index cb4087040..26b49c0d1 100644 --- a/src/utils/explainTableExport.ts +++ b/packages/web-ui/src/utils/explainTableExport.ts @@ -1,8 +1,8 @@ import type {ExplainPlan, ExplainMetrics} from '@tabularis/explain'; import {getExplainTableRows, formatRatio} from '@tabularis/explain'; -import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; +import type {PlatformCapabilities} from '@/platform/capabilities'; import {csvField} from './clipboard'; +import {downloadTextFile} from './fileDownloads'; export const EXPLAIN_TABLE_CSV_HEADERS = [ 'index', @@ -65,24 +65,19 @@ export function formatExplainTableCsv( } /** - * Open the native Tauri save-file dialog and save the complete EXPLAIN table as CSV. + * Save the complete EXPLAIN table as CSV through the platform download. * Returns true if saved successfully, or false if cancelled by the user. */ -export async function saveExplainTableCsv( +export function saveExplainTableCsv( + platform: PlatformCapabilities, plan: ExplainPlan, metrics?: ExplainMetrics, defaultPath = 'explain-plan.csv', ): Promise { - const filePath = await save({ - defaultPath, + return downloadTextFile(platform, { + fileName: defaultPath, + contents: formatExplainTableCsv(plan, {metrics}), + mimeType: 'text/csv', filters: [{name: 'CSV', extensions: ['csv']}], }); - - if (!filePath) { - return false; - } - - const csv = formatExplainTableCsv(plan, {metrics}); - await writeTextFile(filePath, csv); - return true; } diff --git a/src/utils/exportFileName.ts b/packages/web-ui/src/utils/exportFileName.ts similarity index 100% rename from src/utils/exportFileName.ts rename to packages/web-ui/src/utils/exportFileName.ts diff --git a/packages/web-ui/src/utils/fileDownloads.ts b/packages/web-ui/src/utils/fileDownloads.ts new file mode 100644 index 000000000..d19c48f1d --- /dev/null +++ b/packages/web-ui/src/utils/fileDownloads.ts @@ -0,0 +1,41 @@ +import type {TabularisClient} from '@/api/client'; +import type {GeneratedFile} from '@/api/contract'; +import type {PlatformCapabilities, PlatformFileFilter} from '@/platform/capabilities'; + +interface TextDownloadRequest { + fileName: string; + contents: string; + mimeType: string; + title?: string; + filters?: readonly PlatformFileFilter[]; +} + +export async function downloadGeneratedFile( + client: TabularisClient, + platform: PlatformCapabilities, + file: GeneratedFile | null, +): Promise { + if (!file) return true; + if (file.kind === 'download') { + await client.requestDownload(file.token); + return true; + } + return downloadTextFile(platform, { + fileName: file.fileName, + contents: file.contents, + mimeType: file.mimeType, + }); +} + +export function downloadTextFile( + platform: PlatformCapabilities, + request: TextDownloadRequest, +): Promise { + return platform.downloadFile({ + fileName: request.fileName, + contents: new TextEncoder().encode(request.contents), + mimeType: request.mimeType, + title: request.title, + filters: request.filters, + }); +} diff --git a/src/utils/filterBar.ts b/packages/web-ui/src/utils/filterBar.ts similarity index 100% rename from src/utils/filterBar.ts rename to packages/web-ui/src/utils/filterBar.ts diff --git a/src/utils/findUnsupportedFeatures.ts b/packages/web-ui/src/utils/findUnsupportedFeatures.ts similarity index 100% rename from src/utils/findUnsupportedFeatures.ts rename to packages/web-ui/src/utils/findUnsupportedFeatures.ts diff --git a/src/utils/foreignKeys.ts b/packages/web-ui/src/utils/foreignKeys.ts similarity index 100% rename from src/utils/foreignKeys.ts rename to packages/web-ui/src/utils/foreignKeys.ts diff --git a/src/utils/formatTime.ts b/packages/web-ui/src/utils/formatTime.ts similarity index 100% rename from src/utils/formatTime.ts rename to packages/web-ui/src/utils/formatTime.ts diff --git a/src/utils/fsPath.ts b/packages/web-ui/src/utils/fsPath.ts similarity index 100% rename from src/utils/fsPath.ts rename to packages/web-ui/src/utils/fsPath.ts diff --git a/src/utils/fuzzy.ts b/packages/web-ui/src/utils/fuzzy.ts similarity index 100% rename from src/utils/fuzzy.ts rename to packages/web-ui/src/utils/fuzzy.ts diff --git a/src/utils/geometry.ts b/packages/web-ui/src/utils/geometry.ts similarity index 100% rename from src/utils/geometry.ts rename to packages/web-ui/src/utils/geometry.ts diff --git a/src/utils/geometryInput.ts b/packages/web-ui/src/utils/geometryInput.ts similarity index 100% rename from src/utils/geometryInput.ts rename to packages/web-ui/src/utils/geometryInput.ts diff --git a/src/utils/graphLayout.ts b/packages/web-ui/src/utils/graphLayout.ts similarity index 100% rename from src/utils/graphLayout.ts rename to packages/web-ui/src/utils/graphLayout.ts diff --git a/src/utils/gridUndo.ts b/packages/web-ui/src/utils/gridUndo.ts similarity index 100% rename from src/utils/gridUndo.ts rename to packages/web-ui/src/utils/gridUndo.ts diff --git a/src/utils/groupTree.ts b/packages/web-ui/src/utils/groupTree.ts similarity index 100% rename from src/utils/groupTree.ts rename to packages/web-ui/src/utils/groupTree.ts diff --git a/src/utils/identifiers.ts b/packages/web-ui/src/utils/identifiers.ts similarity index 100% rename from src/utils/identifiers.ts rename to packages/web-ui/src/utils/identifiers.ts diff --git a/src/utils/indexes.ts b/packages/web-ui/src/utils/indexes.ts similarity index 100% rename from src/utils/indexes.ts rename to packages/web-ui/src/utils/indexes.ts diff --git a/src/utils/json.ts b/packages/web-ui/src/utils/json.ts similarity index 100% rename from src/utils/json.ts rename to packages/web-ui/src/utils/json.ts diff --git a/src/utils/jsonHighlight.ts b/packages/web-ui/src/utils/jsonHighlight.ts similarity index 100% rename from src/utils/jsonHighlight.ts rename to packages/web-ui/src/utils/jsonHighlight.ts diff --git a/src/utils/jsonTree.ts b/packages/web-ui/src/utils/jsonTree.ts similarity index 100% rename from src/utils/jsonTree.ts rename to packages/web-ui/src/utils/jsonTree.ts diff --git a/src/utils/jsonValueDecorators.ts b/packages/web-ui/src/utils/jsonValueDecorators.ts similarity index 100% rename from src/utils/jsonValueDecorators.ts rename to packages/web-ui/src/utils/jsonValueDecorators.ts diff --git a/src/utils/k8s.ts b/packages/web-ui/src/utils/k8s.ts similarity index 67% rename from src/utils/k8s.ts rename to packages/web-ui/src/utils/k8s.ts index 808ae7eb6..3ed7223a1 100644 --- a/src/utils/k8s.ts +++ b/packages/web-ui/src/utils/k8s.ts @@ -3,34 +3,20 @@ * Manages kubectl port-forward tunnel configurations */ -import {invoke} from '@tauri-apps/api/core'; - -export interface K8sConnection { - id: string; - name: string; - context: string; - namespace: string; - resource_type: 'service' | 'pod'; - resource_name: string; - port: number; - kubectl_path?: string; - kubeconfig_path?: string; -} +import {TauriTransport} from '@/api/transports/tauriTransport'; +import type { + K8sCommandOptions, + K8sConnection, + K8sConnectionInput, + TypedCommandCaller, +} from '@/api/contract'; -export interface K8sConnectionInput { - name: string; - context: string; - namespace: string; - resource_type: string; - resource_name: string; - port: number; - kubectl_path?: string; - kubeconfig_path?: string; -} +export type {K8sCommandOptions, K8sConnection, K8sConnectionInput} from '@/api/contract'; + +const legacyTauriClient = new TauriTransport(); -export interface K8sCommandOptions { - kubectl_path?: string; - kubeconfig_path?: string; +function commandClient(client?: TypedCommandCaller): TypedCommandCaller { + return client ?? legacyTauriClient; } export type K8sPathValidationKind = 'kubectl' | 'kubeconfig'; @@ -50,9 +36,9 @@ function toK8sCommandPayload(options?: K8sCommandOptions): { /** * Load all saved K8s connections */ -export async function loadK8sConnections(): Promise { +export async function loadK8sConnections(client?: TypedCommandCaller): Promise { try { - return await invoke('get_k8s_connections'); + return await commandClient(client).call('get_k8s_connections', undefined); } catch (error) { console.error('Failed to load K8s connections:', error); return []; @@ -62,8 +48,11 @@ export async function loadK8sConnections(): Promise { /** * Save a new K8s connection */ -export async function saveK8sConnection(k8s: K8sConnectionInput): Promise { - return await invoke('save_k8s_connection', {k8s}); +export async function saveK8sConnection( + k8s: K8sConnectionInput, + client?: TypedCommandCaller, +): Promise { + return await commandClient(client).call('save_k8s_connection', {k8s}); } /** @@ -72,15 +61,16 @@ export async function saveK8sConnection(k8s: K8sConnectionInput): Promise { - return await invoke('update_k8s_connection', {id, k8s}); + return await commandClient(client).call('update_k8s_connection', {id, k8s}); } /** * Delete a K8s connection */ -export async function deleteK8sConnection(id: string): Promise { - await invoke('delete_k8s_connection', {id}); +export async function deleteK8sConnection(id: string, client?: TypedCommandCaller): Promise { + await commandClient(client).call('delete_k8s_connection', {id}); } /** @@ -89,9 +79,10 @@ export async function deleteK8sConnection(id: string): Promise { export async function testK8sConnection( context: string, namespace: string, - options?: K8sCommandOptions, + options: K8sCommandOptions | undefined, + client?: TypedCommandCaller, ): Promise { - return await invoke('test_k8s_connection_cmd', { + return await commandClient(client).call('test_k8s_connection_cmd', { context, namespace, ...toK8sCommandPayload(options), @@ -101,11 +92,15 @@ export async function testK8sConnection( /** * List available kubectl contexts */ -export async function getK8sContexts(options?: K8sCommandOptions): Promise { +export async function getK8sContexts( + options: K8sCommandOptions | undefined, + client?: TypedCommandCaller, +): Promise { const payload = toK8sCommandPayload(options); - return Object.keys(payload).length === 0 - ? await invoke('get_k8s_contexts_cmd') - : await invoke('get_k8s_contexts_cmd', payload); + return commandClient(client).call( + 'get_k8s_contexts_cmd', + Object.keys(payload).length === 0 ? undefined : payload, + ); } /** @@ -113,9 +108,10 @@ export async function getK8sContexts(options?: K8sCommandOptions): Promise { - return await invoke('get_k8s_namespaces_cmd', { + return await commandClient(client).call('get_k8s_namespaces_cmd', { context, ...toK8sCommandPayload(options), }); @@ -128,9 +124,10 @@ export async function getK8sResources( context: string, namespace: string, resourceType: string, - options?: K8sCommandOptions, + options: K8sCommandOptions | undefined, + client?: TypedCommandCaller, ): Promise { - return await invoke('get_k8s_resources_cmd', { + return await commandClient(client).call('get_k8s_resources_cmd', { context, namespace, resourceType, @@ -146,9 +143,10 @@ export async function getK8sResourcePorts( namespace: string, resourceType: string, resourceName: string, - options?: K8sCommandOptions, + options: K8sCommandOptions | undefined, + client?: TypedCommandCaller, ): Promise { - return await invoke('get_k8s_resource_ports_cmd', { + return await commandClient(client).call('get_k8s_resource_ports_cmd', { context, namespace, resourceType, @@ -160,8 +158,12 @@ export async function getK8sResourcePorts( /** * Validate an advanced K8s path override. */ -export async function validateK8sPath(path: string, kind: K8sPathValidationKind): Promise { - await invoke('validate_k8s_path_cmd', {path, kind}); +export async function validateK8sPath( + path: string, + kind: K8sPathValidationKind, + client?: TypedCommandCaller, +): Promise { + await commandClient(client).call('validate_k8s_path_cmd', {path, kind}); } /** diff --git a/src/utils/keybindings.ts b/packages/web-ui/src/utils/keybindings.ts similarity index 100% rename from src/utils/keybindings.ts rename to packages/web-ui/src/utils/keybindings.ts diff --git a/src/utils/keyboardEvents.ts b/packages/web-ui/src/utils/keyboardEvents.ts similarity index 100% rename from src/utils/keyboardEvents.ts rename to packages/web-ui/src/utils/keyboardEvents.ts diff --git a/src/utils/localThemePlugins.ts b/packages/web-ui/src/utils/localThemePlugins.ts similarity index 100% rename from src/utils/localThemePlugins.ts rename to packages/web-ui/src/utils/localThemePlugins.ts diff --git a/src/utils/mcpApprovalAttention.ts b/packages/web-ui/src/utils/mcpApprovalAttention.ts similarity index 92% rename from src/utils/mcpApprovalAttention.ts rename to packages/web-ui/src/utils/mcpApprovalAttention.ts index 4b4814dd7..1b6d8f3c0 100644 --- a/src/utils/mcpApprovalAttention.ts +++ b/packages/web-ui/src/utils/mcpApprovalAttention.ts @@ -1,9 +1,5 @@ import {UserAttentionType, getCurrentWindow} from '@tauri-apps/api/window'; -import { - isPermissionGranted, - requestPermission, - sendNotification, -} from '@tauri-apps/plugin-notification'; +import type {PlatformCapabilities} from '@/platform/capabilities'; export interface ApprovalNotificationContent { title: string; @@ -189,22 +185,17 @@ function approvalNotificationSound(): string | undefined { return platform.toUpperCase().includes('LINUX') ? LINUX_NOTIFICATION_SOUND : undefined; } -export async function notifyApprovalRequest(content: ApprovalNotificationContent): Promise { - let permissionGranted = await isPermissionGranted().catch(() => false); - if (!permissionGranted) { - const permission = await requestPermission().catch(() => 'denied' as const); - permissionGranted = permission === 'granted'; - } - +export async function notifyApprovalRequest( + content: ApprovalNotificationContent, + platform: Pick, +): Promise { const sound = approvalNotificationSound(); - if (permissionGranted) { - sendNotification({ - title: content.title, - body: content.body, - ...(sound ? {sound} : {}), - }); - } + await platform.notify({ + title: content.title, + body: content.body, + ...(sound ? {sound} : {}), + }); // When the OS notification carries the sound (Linux) we skip the in-page tone // to avoid a double alert; elsewhere the Web Audio tone is the alert. diff --git a/src/utils/monaco.ts b/packages/web-ui/src/utils/monaco.ts similarity index 100% rename from src/utils/monaco.ts rename to packages/web-ui/src/utils/monaco.ts diff --git a/src/utils/monacoInputArea.ts b/packages/web-ui/src/utils/monacoInputArea.ts similarity index 100% rename from src/utils/monacoInputArea.ts rename to packages/web-ui/src/utils/monacoInputArea.ts diff --git a/src/utils/multiResult.ts b/packages/web-ui/src/utils/multiResult.ts similarity index 100% rename from src/utils/multiResult.ts rename to packages/web-ui/src/utils/multiResult.ts diff --git a/src/utils/newConsole.ts b/packages/web-ui/src/utils/newConsole.ts similarity index 100% rename from src/utils/newConsole.ts rename to packages/web-ui/src/utils/newConsole.ts diff --git a/src/utils/notebook.ts b/packages/web-ui/src/utils/notebook.ts similarity index 100% rename from src/utils/notebook.ts rename to packages/web-ui/src/utils/notebook.ts diff --git a/src/utils/notebookChart.ts b/packages/web-ui/src/utils/notebookChart.ts similarity index 100% rename from src/utils/notebookChart.ts rename to packages/web-ui/src/utils/notebookChart.ts diff --git a/src/utils/notebookDnd.ts b/packages/web-ui/src/utils/notebookDnd.ts similarity index 100% rename from src/utils/notebookDnd.ts rename to packages/web-ui/src/utils/notebookDnd.ts diff --git a/src/utils/notebookFile.ts b/packages/web-ui/src/utils/notebookFile.ts similarity index 100% rename from src/utils/notebookFile.ts rename to packages/web-ui/src/utils/notebookFile.ts diff --git a/src/utils/notebookHistory.ts b/packages/web-ui/src/utils/notebookHistory.ts similarity index 100% rename from src/utils/notebookHistory.ts rename to packages/web-ui/src/utils/notebookHistory.ts diff --git a/src/utils/notebookHtmlExport.ts b/packages/web-ui/src/utils/notebookHtmlExport.ts similarity index 100% rename from src/utils/notebookHtmlExport.ts rename to packages/web-ui/src/utils/notebookHtmlExport.ts diff --git a/src/utils/notebookOutline.ts b/packages/web-ui/src/utils/notebookOutline.ts similarity index 100% rename from src/utils/notebookOutline.ts rename to packages/web-ui/src/utils/notebookOutline.ts diff --git a/src/utils/notebookParams.ts b/packages/web-ui/src/utils/notebookParams.ts similarity index 100% rename from src/utils/notebookParams.ts rename to packages/web-ui/src/utils/notebookParams.ts diff --git a/src/utils/notebookRunAll.ts b/packages/web-ui/src/utils/notebookRunAll.ts similarity index 100% rename from src/utils/notebookRunAll.ts rename to packages/web-ui/src/utils/notebookRunAll.ts diff --git a/src/utils/notebookStore.ts b/packages/web-ui/src/utils/notebookStore.ts similarity index 83% rename from src/utils/notebookStore.ts rename to packages/web-ui/src/utils/notebookStore.ts index 26bef6ac4..6e8bd4db0 100644 --- a/src/utils/notebookStore.ts +++ b/packages/web-ui/src/utils/notebookStore.ts @@ -1,4 +1,4 @@ -import {invoke} from '@tauri-apps/api/core'; +import type {TypedCommandCaller} from '@/api/contract'; import type {NotebookMetadata, NotebookState} from '@/types/notebook'; import {createDefaultNotebookState} from './notebook'; import {serializeNotebook, deserializeNotebook} from './notebookFile'; @@ -25,6 +25,7 @@ const titleCache = new Map(); // every save/load/delete needs the owning connection id. It is captured when a // notebook is created or loaded and read back from here for autosaves. const connectionIdCache = new Map(); +const clientCache = new Map(); const saveTimers = new Map>(); function generateNotebookId(): string { @@ -46,13 +47,14 @@ function serializeForDisk(notebookId: string, state: NotebookState): string { } /** Persist a notebook, or skip (with a warning) if its connection is unknown. */ -function persist(notebookId: string, content: string): Promise { +function persist(notebookId: string, content: string): Promise { const connectionId = connectionIdCache.get(notebookId); - if (!connectionId) { - console.error(`Cannot save notebook ${notebookId}: unknown connection`); + const client = clientCache.get(notebookId); + if (!connectionId || !client) { + console.error(`Cannot save notebook ${notebookId}: unknown connection or client`); return Promise.resolve(); } - return invoke('save_notebook', {connectionId, notebookId, content}); + return client.call('save_notebook', {connectionId, notebookId, content}); } /** Flush a single pending save immediately. */ @@ -116,13 +118,15 @@ export function setNotebookTitle(notebookId: string, title: string): void { export async function loadNotebook( notebookId: string, connectionId: string, + client: TypedCommandCaller, ): Promise { connectionIdCache.set(notebookId, connectionId); + clientCache.set(notebookId, client); const cached = cache.get(notebookId); if (cached) return cached; - const content = await invoke('load_notebook', { + const content = await client.call('load_notebook', { connectionId, notebookId, }); @@ -145,16 +149,18 @@ export async function loadNotebook( export async function createNotebook( title: string, connectionId: string, + client: TypedCommandCaller, ): Promise<{notebookId: string; state: NotebookState}> { const notebookId = generateNotebookId(); const state = createDefaultNotebookState(); titleCache.set(notebookId, title); connectionIdCache.set(notebookId, connectionId); + clientCache.set(notebookId, client); cache.set(notebookId, state); const content = serializeForDisk(notebookId, state); - await invoke('create_notebook', {connectionId, notebookId, content}); + await client.call('create_notebook', {connectionId, notebookId, content}); notifyNotebooksChanged(); return {notebookId, state}; @@ -165,22 +171,28 @@ export async function createNotebookFromState( title: string, state: NotebookState, connectionId: string, + client: TypedCommandCaller, ): Promise<{notebookId: string}> { const notebookId = generateNotebookId(); titleCache.set(notebookId, title); connectionIdCache.set(notebookId, connectionId); + clientCache.set(notebookId, client); cache.set(notebookId, state); const content = serializeForDisk(notebookId, state); - await invoke('create_notebook', {connectionId, notebookId, content}); + await client.call('create_notebook', {connectionId, notebookId, content}); notifyNotebooksChanged(); return {notebookId}; } /** Delete a notebook file and evict from cache. */ -export async function deleteNotebook(notebookId: string, connectionId: string): Promise { +export async function deleteNotebook( + notebookId: string, + connectionId: string, + client: TypedCommandCaller, +): Promise { const timer = saveTimers.get(notebookId); if (timer) { clearTimeout(timer); @@ -189,13 +201,17 @@ export async function deleteNotebook(notebookId: string, connectionId: string): cache.delete(notebookId); titleCache.delete(notebookId); connectionIdCache.delete(notebookId); - await invoke('delete_notebook', {connectionId, notebookId}); + clientCache.delete(notebookId); + await client.call('delete_notebook', {connectionId, notebookId}); notifyNotebooksChanged(); } /** List saved notebooks for a connection (metadata only, read from disk). */ -export async function listNotebooks(connectionId: string): Promise { - return invoke('list_notebooks', {connectionId}); +export async function listNotebooks( + connectionId: string, + client: TypedCommandCaller, +): Promise { + return client.call('list_notebooks', {connectionId}); } /** Rename a saved notebook. Patches the file (and cache, if currently open). */ @@ -203,8 +219,10 @@ export async function renameNotebook( notebookId: string, connectionId: string, title: string, + client: TypedCommandCaller, ): Promise { connectionIdCache.set(notebookId, connectionId); + clientCache.set(notebookId, client); if (cache.has(notebookId)) { // Open notebook: update the cached title and flush the full file so a // pending autosave can't clobber the new title. @@ -213,7 +231,7 @@ export async function renameNotebook( notifyNotebooksChanged(); return; } - await invoke('rename_notebook', {connectionId, notebookId, title}); + await client.call('rename_notebook', {connectionId, notebookId, title}); notifyNotebooksChanged(); } @@ -223,6 +241,7 @@ export async function evictFromCache(notebookId: string): Promise { cache.delete(notebookId); titleCache.delete(notebookId); connectionIdCache.delete(notebookId); + clientCache.delete(notebookId); } /** Flush all pending saves immediately (on app close). */ @@ -238,4 +257,5 @@ export function _resetForTesting(): void { cache.clear(); titleCache.clear(); connectionIdCache.clear(); + clientCache.clear(); } diff --git a/packages/web-ui/src/utils/notebookTransfer.ts b/packages/web-ui/src/utils/notebookTransfer.ts new file mode 100644 index 000000000..109e00081 --- /dev/null +++ b/packages/web-ui/src/utils/notebookTransfer.ts @@ -0,0 +1,58 @@ +import type {PlatformCapabilities} from '@/platform/capabilities'; +import type {NotebookState} from '@/types/notebook'; +import {deserializeNotebook, serializeNotebook} from './notebookFile'; +import {exportNotebookToHtml} from './notebookHtmlExport'; + +const NOTEBOOK_FILTER = [{name: 'Tabularis Notebook', extensions: ['tabularis-notebook']}] as const; +const HTML_FILTER = [{name: 'HTML', extensions: ['html']}] as const; +const encoder = new TextEncoder(); +const decoder = new TextDecoder('utf-8', {fatal: true}); + +export interface ImportedNotebook { + readonly title: string; + readonly state: NotebookState; +} + +export async function chooseNotebookImport( + platform: PlatformCapabilities, +): Promise { + const selected = await platform.chooseInputFile({filters: NOTEBOOK_FILTER}); + if (!selected) return null; + const contents = await platform.readInputFile(selected.reference); + const {title, cells, params, stopOnError} = deserializeNotebook(decoder.decode(contents)); + return { + title, + state: {cells, params, stopOnError}, + }; +} + +export function downloadNotebook( + platform: PlatformCapabilities, + title: string, + state: NotebookState, +): Promise { + const notebook = serializeNotebook(title, state.cells, state.params, state.stopOnError); + return platform.downloadFile({ + fileName: `${safeFileName(title)}.tabularis-notebook`, + contents: encoder.encode(JSON.stringify(notebook, null, 2)), + mimeType: 'application/json', + filters: NOTEBOOK_FILTER, + }); +} + +export function downloadNotebookHtml( + platform: PlatformCapabilities, + title: string, + state: NotebookState, +): Promise { + return platform.downloadFile({ + fileName: `${safeFileName(title)}.html`, + contents: encoder.encode(exportNotebookToHtml(title, state.cells)), + mimeType: 'text/html;charset=utf-8', + filters: HTML_FILTER, + }); +} + +function safeFileName(title: string): string { + return title.replace(/[^a-zA-Z0-9_-]/g, '_') || 'Notebook'; +} diff --git a/src/utils/notebookUndo.ts b/packages/web-ui/src/utils/notebookUndo.ts similarity index 100% rename from src/utils/notebookUndo.ts rename to packages/web-ui/src/utils/notebookUndo.ts diff --git a/src/utils/notebookVariables.ts b/packages/web-ui/src/utils/notebookVariables.ts similarity index 100% rename from src/utils/notebookVariables.ts rename to packages/web-ui/src/utils/notebookVariables.ts diff --git a/src/utils/number.ts b/packages/web-ui/src/utils/number.ts similarity index 100% rename from src/utils/number.ts rename to packages/web-ui/src/utils/number.ts diff --git a/src/utils/objectNameCopy.ts b/packages/web-ui/src/utils/objectNameCopy.ts similarity index 100% rename from src/utils/objectNameCopy.ts rename to packages/web-ui/src/utils/objectNameCopy.ts diff --git a/src/utils/objectPaletteItems.ts b/packages/web-ui/src/utils/objectPaletteItems.ts similarity index 100% rename from src/utils/objectPaletteItems.ts rename to packages/web-ui/src/utils/objectPaletteItems.ts diff --git a/src/utils/openSourceLibraries.ts b/packages/web-ui/src/utils/openSourceLibraries.ts similarity index 100% rename from src/utils/openSourceLibraries.ts rename to packages/web-ui/src/utils/openSourceLibraries.ts diff --git a/src/utils/paletteItems.ts b/packages/web-ui/src/utils/paletteItems.ts similarity index 100% rename from src/utils/paletteItems.ts rename to packages/web-ui/src/utils/paletteItems.ts diff --git a/src/utils/pendingInsertions.ts b/packages/web-ui/src/utils/pendingInsertions.ts similarity index 100% rename from src/utils/pendingInsertions.ts rename to packages/web-ui/src/utils/pendingInsertions.ts diff --git a/packages/web-ui/src/utils/pluginApiCompatibility.ts b/packages/web-ui/src/utils/pluginApiCompatibility.ts new file mode 100644 index 000000000..111c3245e --- /dev/null +++ b/packages/web-ui/src/utils/pluginApiCompatibility.ts @@ -0,0 +1,35 @@ +interface SemanticVersion { + readonly major: number; + readonly minor: number; + readonly patch: number; +} + +const SEMANTIC_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +function parseSemanticVersion(value: string): SemanticVersion | null { + const match = SEMANTIC_VERSION.exec(value); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + }; +} + +function compareVersions(left: SemanticVersion, right: SemanticVersion): number { + return left.major - right.major || left.minor - right.minor || left.patch - right.patch; +} + +/** + * Check whether a host can execute a bundle built for the declared plugin API. + * Legacy entries without a declaration remain supported. During the unstable + * 0.x line, minor versions are treated as compatibility boundaries. + */ +export function isPluginApiCompatible(hostVersion: string, requiredVersion?: string): boolean { + if (requiredVersion === undefined) return true; + const host = parseSemanticVersion(hostVersion); + const required = parseSemanticVersion(requiredVersion); + if (!host || !required || host.major !== required.major) return false; + if (host.major === 0 && host.minor !== required.minor) return false; + return compareVersions(host, required) >= 0; +} diff --git a/src/utils/pluginConfig.ts b/packages/web-ui/src/utils/pluginConfig.ts similarity index 100% rename from src/utils/pluginConfig.ts rename to packages/web-ui/src/utils/pluginConfig.ts diff --git a/src/utils/pluginExplainLoader.ts b/packages/web-ui/src/utils/pluginExplainLoader.ts similarity index 96% rename from src/utils/pluginExplainLoader.ts rename to packages/web-ui/src/utils/pluginExplainLoader.ts index bebad1ba6..408d41351 100644 --- a/src/utils/pluginExplainLoader.ts +++ b/packages/web-ui/src/utils/pluginExplainLoader.ts @@ -1,10 +1,10 @@ -import {invoke} from '@tauri-apps/api/core'; import * as explainApi from '@tabularis/explain'; import type {RegisteredExplainParser} from '@tabularis/explain'; import type {ExplainParserManifestEntry, PluginManifest} from '@/types/plugins'; type ContinueLoading = () => boolean; +type ReadPluginAsset = (pluginId: string, assetPath: string) => Promise; function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null; @@ -71,6 +71,7 @@ function evaluateBundle(source: string): unknown { */ export async function loadPluginExplainParsers( manifest: PluginManifest, + readAsset: ReadPluginAsset, shouldContinue: ContinueLoading = () => true, ): Promise { if (!manifest.explain_parsers?.length) return []; @@ -96,10 +97,7 @@ export async function loadPluginExplainParsers( let rawExports: unknown; try { - const source = await invoke('read_plugin_file', { - pluginId: manifest.id, - filePath: modulePath, - }); + const source = await readAsset(manifest.id, modulePath); if (!shouldContinue()) break; rawExports = evaluateBundle(source); } catch (error) { diff --git a/packages/web-ui/src/utils/pluginInstallRoute.ts b/packages/web-ui/src/utils/pluginInstallRoute.ts new file mode 100644 index 000000000..e4100129f --- /dev/null +++ b/packages/web-ui/src/utils/pluginInstallRoute.ts @@ -0,0 +1,53 @@ +import type {PluginInstallRequest} from '@/api/pluginLifecycle'; +import {BROWSER_ROUTES} from '@/routing'; + +const PLUGIN_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/; + +export function buildPluginInstallRoute(request: PluginInstallRequest): string { + const normalized = normalizePluginInstallRequest(request); + if (!normalized) throw new Error('Invalid plugin install route request'); + + const search = new URLSearchParams(); + if (normalized.version) search.set('version', normalized.version); + if (normalized.registry) search.set('registry', normalized.registry); + const query = search.toString(); + const path = BROWSER_ROUTES.pluginInstall.replace(':slug', encodeURIComponent(normalized.slug)); + return query ? `${path}?${query}` : path; +} + +export function parsePluginInstallRoute( + slug: string | undefined, + search: URLSearchParams, +): PluginInstallRequest | null { + return normalizePluginInstallRequest({ + slug: slug ?? '', + version: search.get('version'), + registry: search.get('registry'), + }); +} + +function normalizePluginInstallRequest(request: PluginInstallRequest): PluginInstallRequest | null { + if (!PLUGIN_SLUG_PATTERN.test(request.slug)) return null; + + const registry = normalizeRegistryUrl(request.registry); + if (request.registry && !registry) return null; + + return { + slug: request.slug, + version: request.version?.trim() || null, + registry, + }; +} + +function normalizeRegistryUrl(value: string | null | undefined): string | null { + if (!value) return null; + + try { + const url = new URL(value); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + if (url.username || url.password || url.search || url.hash) return null; + return url.toString().replace(/\/+$/, ''); + } catch { + return null; + } +} diff --git a/src/utils/pluginIssueReport.ts b/packages/web-ui/src/utils/pluginIssueReport.ts similarity index 100% rename from src/utils/pluginIssueReport.ts rename to packages/web-ui/src/utils/pluginIssueReport.ts diff --git a/src/utils/pluginModuleLoader.ts b/packages/web-ui/src/utils/pluginModuleLoader.ts similarity index 100% rename from src/utils/pluginModuleLoader.ts rename to packages/web-ui/src/utils/pluginModuleLoader.ts diff --git a/src/utils/pluginPresentation.ts b/packages/web-ui/src/utils/pluginPresentation.ts similarity index 100% rename from src/utils/pluginPresentation.ts rename to packages/web-ui/src/utils/pluginPresentation.ts diff --git a/src/utils/pluginReadme.ts b/packages/web-ui/src/utils/pluginReadme.ts similarity index 100% rename from src/utils/pluginReadme.ts rename to packages/web-ui/src/utils/pluginReadme.ts diff --git a/src/utils/pluginUpdates.ts b/packages/web-ui/src/utils/pluginUpdates.ts similarity index 100% rename from src/utils/pluginUpdates.ts rename to packages/web-ui/src/utils/pluginUpdates.ts diff --git a/src/utils/pluginVersions.ts b/packages/web-ui/src/utils/pluginVersions.ts similarity index 100% rename from src/utils/pluginVersions.ts rename to packages/web-ui/src/utils/pluginVersions.ts diff --git a/src/utils/plugins.ts b/packages/web-ui/src/utils/plugins.ts similarity index 100% rename from src/utils/plugins.ts rename to packages/web-ui/src/utils/plugins.ts diff --git a/src/utils/pointerDrag.ts b/packages/web-ui/src/utils/pointerDrag.ts similarity index 100% rename from src/utils/pointerDrag.ts rename to packages/web-ui/src/utils/pointerDrag.ts diff --git a/src/utils/queryBuilderLayout.ts b/packages/web-ui/src/utils/queryBuilderLayout.ts similarity index 100% rename from src/utils/queryBuilderLayout.ts rename to packages/web-ui/src/utils/queryBuilderLayout.ts diff --git a/src/utils/queryGuard.ts b/packages/web-ui/src/utils/queryGuard.ts similarity index 100% rename from src/utils/queryGuard.ts rename to packages/web-ui/src/utils/queryGuard.ts diff --git a/src/utils/queryHistoryDetails.ts b/packages/web-ui/src/utils/queryHistoryDetails.ts similarity index 100% rename from src/utils/queryHistoryDetails.ts rename to packages/web-ui/src/utils/queryHistoryDetails.ts diff --git a/src/utils/queryHistoryFilter.ts b/packages/web-ui/src/utils/queryHistoryFilter.ts similarity index 100% rename from src/utils/queryHistoryFilter.ts rename to packages/web-ui/src/utils/queryHistoryFilter.ts diff --git a/src/utils/queryNotification.ts b/packages/web-ui/src/utils/queryNotification.ts similarity index 72% rename from src/utils/queryNotification.ts rename to packages/web-ui/src/utils/queryNotification.ts index 3b05a586f..da718a623 100644 --- a/src/utils/queryNotification.ts +++ b/packages/web-ui/src/utils/queryNotification.ts @@ -1,9 +1,4 @@ -import {getCurrentWindow} from '@tauri-apps/api/window'; -import { - isPermissionGranted, - requestPermission, - sendNotification, -} from '@tauri-apps/plugin-notification'; +import {getActivePlatformCapabilitiesOrNull} from '@/platform/activeCapabilities'; export const DEFAULT_NOTIFY_THRESHOLD_SEC = 20; @@ -44,9 +39,11 @@ interface NotifyQueryFinishedOptions { export async function notifyQueryFinished(opts: NotifyQueryFinishedOptions): Promise { try { + const platform = getActivePlatformCapabilitiesOrNull(); + if (!platform) return; let windowFocused: boolean; try { - windowFocused = await getCurrentWindow().isFocused(); + windowFocused = document.hasFocus(); } catch { // The focus probe rejecting must not suppress the notification: treat // the window as unfocused so a long query still reports its result. @@ -61,17 +58,7 @@ export async function notifyQueryFinished(opts: NotifyQueryFinishedOptions): Pro }); if (!shouldNotify) return; - let permissionGranted = await isPermissionGranted().catch(() => false); - if (!permissionGranted) { - const permission = await requestPermission().catch(() => 'denied' as const); - permissionGranted = permission === 'granted'; - } - if (!permissionGranted) return; - - sendNotification({ - title: opts.content.title, - body: opts.content.body, - }); + await platform.notify(opts.content); } catch { // A notification problem must never break query execution. } diff --git a/src/utils/queryParameters.ts b/packages/web-ui/src/utils/queryParameters.ts similarity index 100% rename from src/utils/queryParameters.ts rename to packages/web-ui/src/utils/queryParameters.ts diff --git a/src/utils/quickNavigator.ts b/packages/web-ui/src/utils/quickNavigator.ts similarity index 100% rename from src/utils/quickNavigator.ts rename to packages/web-ui/src/utils/quickNavigator.ts diff --git a/src/utils/restoreSession.ts b/packages/web-ui/src/utils/restoreSession.ts similarity index 100% rename from src/utils/restoreSession.ts rename to packages/web-ui/src/utils/restoreSession.ts diff --git a/src/utils/resultExport.ts b/packages/web-ui/src/utils/resultExport.ts similarity index 100% rename from src/utils/resultExport.ts rename to packages/web-ui/src/utils/resultExport.ts diff --git a/src/utils/resultPresentation.ts b/packages/web-ui/src/utils/resultPresentation.ts similarity index 100% rename from src/utils/resultPresentation.ts rename to packages/web-ui/src/utils/resultPresentation.ts diff --git a/src/utils/resultsWindowSync.ts b/packages/web-ui/src/utils/resultsWindowSync.ts similarity index 94% rename from src/utils/resultsWindowSync.ts rename to packages/web-ui/src/utils/resultsWindowSync.ts index 5b9c2c129..537473e27 100644 --- a/src/utils/resultsWindowSync.ts +++ b/packages/web-ui/src/utils/resultsWindowSync.ts @@ -9,6 +9,8 @@ import type {QueryResult, QueryResultEntry, Tab} from '@/types/editor'; * module avoids event-name / payload drift between the two windows. */ +export const RESULTS_SYNC_EVENT = 'results-window:sync'; +export const RESULTS_COPY_EVENT = 'results-window:copy'; export const RESULTS_ACTION_EVENT = 'results-window:action'; export const RESULTS_READY_EVENT = 'results-window:ready'; export const RESULTS_CLOSED_EVENT = 'results-window:closed'; @@ -70,7 +72,7 @@ export interface CopiedRows { /** Copy-all result the main window sends back to the detached window that * asked for it. The detached window writes the clipboard itself, so the write * and its toast happen in the focused window. */ -export type ResultsCopyPayload = CopiedRows | {error: string}; +export type ResultsCopyPayload = ({tabId: string} & CopiedRows) | {tabId: string; error: string}; /** Actions the detached window forwards to the main window. */ export type ResultsWindowAction = @@ -155,14 +157,17 @@ export function singleResultToEntry(payload: ResultsSyncPayload): QueryResultEnt }; } -/** Route a copy-all result to the copied or error handler. */ +/** Route a copy-all result to the detached window bound to `tabId`. Results + * for other tabs are ignored: every detached window receives every event. */ export function applyCopyResult( payload: ResultsCopyPayload, + tabId: string, handlers: { onCopied: (rows: CopiedRows) => void; onError: (error: string) => void; }, ): void { + if (payload.tabId !== tabId) return; if ('error' in payload) { handlers.onError(payload.error); } else { diff --git a/src/utils/routineCall.ts b/packages/web-ui/src/utils/routineCall.ts similarity index 100% rename from src/utils/routineCall.ts rename to packages/web-ui/src/utils/routineCall.ts diff --git a/src/utils/routines.ts b/packages/web-ui/src/utils/routines.ts similarity index 100% rename from src/utils/routines.ts rename to packages/web-ui/src/utils/routines.ts diff --git a/src/utils/rowIdentity.ts b/packages/web-ui/src/utils/rowIdentity.ts similarity index 100% rename from src/utils/rowIdentity.ts rename to packages/web-ui/src/utils/rowIdentity.ts diff --git a/src/utils/runTarget.ts b/packages/web-ui/src/utils/runTarget.ts similarity index 100% rename from src/utils/runTarget.ts rename to packages/web-ui/src/utils/runTarget.ts diff --git a/src/utils/savedQueryFolders.ts b/packages/web-ui/src/utils/savedQueryFolders.ts similarity index 100% rename from src/utils/savedQueryFolders.ts rename to packages/web-ui/src/utils/savedQueryFolders.ts diff --git a/src/utils/savedQueryNames.ts b/packages/web-ui/src/utils/savedQueryNames.ts similarity index 100% rename from src/utils/savedQueryNames.ts rename to packages/web-ui/src/utils/savedQueryNames.ts diff --git a/src/utils/savedQuerySearch.ts b/packages/web-ui/src/utils/savedQuerySearch.ts similarity index 100% rename from src/utils/savedQuerySearch.ts rename to packages/web-ui/src/utils/savedQuerySearch.ts diff --git a/src/utils/schema.ts b/packages/web-ui/src/utils/schema.ts similarity index 100% rename from src/utils/schema.ts rename to packages/web-ui/src/utils/schema.ts diff --git a/src/utils/schemaDiagram.ts b/packages/web-ui/src/utils/schemaDiagram.ts similarity index 100% rename from src/utils/schemaDiagram.ts rename to packages/web-ui/src/utils/schemaDiagram.ts diff --git a/src/utils/schemaExport.ts b/packages/web-ui/src/utils/schemaExport.ts similarity index 100% rename from src/utils/schemaExport.ts rename to packages/web-ui/src/utils/schemaExport.ts diff --git a/src/utils/settings.ts b/packages/web-ui/src/utils/settings.ts similarity index 98% rename from src/utils/settings.ts rename to packages/web-ui/src/utils/settings.ts index 65d94a441..d8ff34ecc 100644 --- a/src/utils/settings.ts +++ b/packages/web-ui/src/utils/settings.ts @@ -259,7 +259,7 @@ export interface RoadmapItem { url?: string; } -// roadmap.json sits at the repository root, outside the '@/' alias: CI rewrites it. +// roadmap.json lives at the repository root, outside the source alias. // eslint-disable-next-line no-restricted-imports -import roadmapData from '../../roadmap.json'; +import roadmapData from '../../../../roadmap.json'; export const ROADMAP: readonly RoadmapItem[] = roadmapData; diff --git a/src/utils/settingsUI.ts b/packages/web-ui/src/utils/settingsUI.ts similarity index 100% rename from src/utils/settingsUI.ts rename to packages/web-ui/src/utils/settingsUI.ts diff --git a/src/utils/sidebarTableItem.ts b/packages/web-ui/src/utils/sidebarTableItem.ts similarity index 100% rename from src/utils/sidebarTableItem.ts rename to packages/web-ui/src/utils/sidebarTableItem.ts diff --git a/src/utils/sql.ts b/packages/web-ui/src/utils/sql.ts similarity index 100% rename from src/utils/sql.ts rename to packages/web-ui/src/utils/sql.ts diff --git a/src/utils/sqlAnalysis.ts b/packages/web-ui/src/utils/sqlAnalysis.ts similarity index 100% rename from src/utils/sqlAnalysis.ts rename to packages/web-ui/src/utils/sqlAnalysis.ts diff --git a/src/utils/sqlContext.ts b/packages/web-ui/src/utils/sqlContext.ts similarity index 100% rename from src/utils/sqlContext.ts rename to packages/web-ui/src/utils/sqlContext.ts diff --git a/src/utils/sqlFile.ts b/packages/web-ui/src/utils/sqlFile.ts similarity index 100% rename from src/utils/sqlFile.ts rename to packages/web-ui/src/utils/sqlFile.ts diff --git a/packages/web-ui/src/utils/sqlFileTransfer.ts b/packages/web-ui/src/utils/sqlFileTransfer.ts new file mode 100644 index 000000000..a841a8827 --- /dev/null +++ b/packages/web-ui/src/utils/sqlFileTransfer.ts @@ -0,0 +1,77 @@ +import type {TabularisClient} from '@/api/client'; +import type {PlatformCapabilities, PlatformFileFilter} from '@/platform/capabilities'; +import {choosePlatformSavePath, choosePlatformServerPath} from '@/platform/dialogs'; +import {getSqlFileName} from './sqlFile'; + +type SqlFileClient = Pick; + +export type OpenedSqlFile = + /** A host (desktop) or server (browser) path the tab can be saved back to. */ + | {readonly kind: 'path'; readonly path: string; readonly query: string} + /** A browser upload: there is no path to write back to. */ + | {readonly kind: 'upload'; readonly name: string; readonly query: string}; + +export type SavedSqlFile = + {readonly kind: 'path'; readonly path: string} | {readonly kind: 'download'}; + +/** + * Pick and read a SQL file. Desktop uses the native dialog, browsers use the + * server file picker when the server exposes one and fall back to an upload. + */ +export async function openSqlFile( + platform: PlatformCapabilities, + client: SqlFileClient, + filters: readonly PlatformFileFilter[], +): Promise { + if (!platform.supports('chooseServerPath')) { + const selected = await platform.chooseInputFile({filters}); + if (!selected) return null; + const query = new TextDecoder().decode(await platform.readInputFile(selected.reference)); + return {kind: 'upload', name: selected.name, query}; + } + + const path = await choosePlatformServerPath(platform, {filters}); + if (!path) return null; + return {kind: 'path', path, query: await client.call('read_sql_file', {path})}; +} + +interface SaveSqlFileRequest { + readonly query: string; + readonly title: string; + readonly sourceFilePath?: string; + readonly saveAs?: boolean; + readonly filters: readonly PlatformFileFilter[]; +} + +/** + * Write a SQL tab to its file, asking for a target when it has none (or on + * "save as"). Browsers without server file browsing download the file. + */ +export async function saveSqlFile( + platform: PlatformCapabilities, + client: SqlFileClient, + {query, title, sourceFilePath, saveAs = false, filters}: SaveSqlFileRequest, +): Promise { + if (!platform.supports('chooseSaveTarget')) { + const fileName = getSqlFileName(sourceFilePath ?? title); + const saved = await platform.downloadFile({ + fileName: /\.(sql|psql|pgsql)$/i.test(fileName) ? fileName : `${fileName}.sql`, + contents: new TextEncoder().encode(query), + mimeType: 'application/sql', + filters, + }); + return saved ? {kind: 'download'} : null; + } + + let path = sourceFilePath; + if (saveAs || !path) { + const selected = await choosePlatformSavePath(platform, { + defaultPath: path ?? title, + filters, + }); + if (!selected) return null; + path = selected; + } + await client.call('write_sql_file', {path, content: query}); + return {kind: 'path', path}; +} diff --git a/src/utils/sqlFoldPreview.ts b/packages/web-ui/src/utils/sqlFoldPreview.ts similarity index 100% rename from src/utils/sqlFoldPreview.ts rename to packages/web-ui/src/utils/sqlFoldPreview.ts diff --git a/src/utils/sqlFolding.ts b/packages/web-ui/src/utils/sqlFolding.ts similarity index 100% rename from src/utils/sqlFolding.ts rename to packages/web-ui/src/utils/sqlFolding.ts diff --git a/src/utils/sqlFormat.ts b/packages/web-ui/src/utils/sqlFormat.ts similarity index 100% rename from src/utils/sqlFormat.ts rename to packages/web-ui/src/utils/sqlFormat.ts diff --git a/src/utils/sqlGenerator.ts b/packages/web-ui/src/utils/sqlGenerator.ts similarity index 100% rename from src/utils/sqlGenerator.ts rename to packages/web-ui/src/utils/sqlGenerator.ts diff --git a/src/utils/sqlHighlight.tsx b/packages/web-ui/src/utils/sqlHighlight.tsx similarity index 100% rename from src/utils/sqlHighlight.tsx rename to packages/web-ui/src/utils/sqlHighlight.tsx diff --git a/src/utils/sqlInvisibleCharacters.ts b/packages/web-ui/src/utils/sqlInvisibleCharacters.ts similarity index 100% rename from src/utils/sqlInvisibleCharacters.ts rename to packages/web-ui/src/utils/sqlInvisibleCharacters.ts diff --git a/src/utils/sqlLiteral.ts b/packages/web-ui/src/utils/sqlLiteral.ts similarity index 100% rename from src/utils/sqlLiteral.ts rename to packages/web-ui/src/utils/sqlLiteral.ts diff --git a/src/utils/sqlSplitter/classify.ts b/packages/web-ui/src/utils/sqlSplitter/classify.ts similarity index 100% rename from src/utils/sqlSplitter/classify.ts rename to packages/web-ui/src/utils/sqlSplitter/classify.ts diff --git a/src/utils/sqlSplitter/index.ts b/packages/web-ui/src/utils/sqlSplitter/index.ts similarity index 100% rename from src/utils/sqlSplitter/index.ts rename to packages/web-ui/src/utils/sqlSplitter/index.ts diff --git a/src/utils/sqlSplitter/nonCodeSpans.ts b/packages/web-ui/src/utils/sqlSplitter/nonCodeSpans.ts similarity index 100% rename from src/utils/sqlSplitter/nonCodeSpans.ts rename to packages/web-ui/src/utils/sqlSplitter/nonCodeSpans.ts diff --git a/src/utils/sqlSplitter/scriptBlocks.ts b/packages/web-ui/src/utils/sqlSplitter/scriptBlocks.ts similarity index 100% rename from src/utils/sqlSplitter/scriptBlocks.ts rename to packages/web-ui/src/utils/sqlSplitter/scriptBlocks.ts diff --git a/src/utils/sqlSplitter/splitter.ts b/packages/web-ui/src/utils/sqlSplitter/splitter.ts similarity index 100% rename from src/utils/sqlSplitter/splitter.ts rename to packages/web-ui/src/utils/sqlSplitter/splitter.ts diff --git a/src/utils/sqlSplitter/statementAt.ts b/packages/web-ui/src/utils/sqlSplitter/statementAt.ts similarity index 100% rename from src/utils/sqlSplitter/statementAt.ts rename to packages/web-ui/src/utils/sqlSplitter/statementAt.ts diff --git a/src/utils/sqlSplitter/tokenizer.ts b/packages/web-ui/src/utils/sqlSplitter/tokenizer.ts similarity index 100% rename from src/utils/sqlSplitter/tokenizer.ts rename to packages/web-ui/src/utils/sqlSplitter/tokenizer.ts diff --git a/src/utils/sqlSyntax.ts b/packages/web-ui/src/utils/sqlSyntax.ts similarity index 100% rename from src/utils/sqlSyntax.ts rename to packages/web-ui/src/utils/sqlSyntax.ts diff --git a/src/utils/ssh.ts b/packages/web-ui/src/utils/ssh.ts similarity index 70% rename from src/utils/ssh.ts rename to packages/web-ui/src/utils/ssh.ts index d11052c1b..608c9f581 100644 --- a/src/utils/ssh.ts +++ b/packages/web-ui/src/utils/ssh.ts @@ -3,28 +3,23 @@ * Extracted for testability and reusability */ -import {invoke} from '@tauri-apps/api/core'; - -export interface SshConnection { - id: string; - name: string; - host: string; - port: number; - user: string; - auth_type?: 'password' | 'ssh_key'; - password?: string; - key_file?: string; - key_passphrase?: string; - allow_passphrase_prompt?: boolean; - save_in_keychain?: boolean; +import type {SshConnection, SshConnectionInput, TypedCommandCaller} from '@/api/contract'; +import {TauriTransport} from '@/api/transports/tauriTransport'; + +export type {SshConnection, SshConnectionInput} from '@/api/contract'; + +const legacyTauriClient = new TauriTransport(); + +function commandClient(client?: TypedCommandCaller): TypedCommandCaller { + return client ?? legacyTauriClient; } /** * Load all SSH connections */ -export async function loadSshConnections(): Promise { +export async function loadSshConnections(client?: TypedCommandCaller): Promise { try { - return await invoke('get_ssh_connections'); + return await commandClient(client).call('get_ssh_connections', undefined); } catch (error) { console.error('Failed to load SSH connections:', error); return []; @@ -58,9 +53,10 @@ function normalizeSshParams(ssh: Partial): Partial */ export async function saveSshConnection( name: string, - ssh: Partial, + ssh: SshConnectionInput, + client?: TypedCommandCaller, ): Promise { - return await invoke('save_ssh_connection', { + return await commandClient(client).call('save_ssh_connection', { name, ssh: normalizeSshParams(ssh), }); @@ -72,9 +68,10 @@ export async function saveSshConnection( export async function updateSshConnection( id: string, name: string, - ssh: Partial, + ssh: SshConnectionInput, + client?: TypedCommandCaller, ): Promise { - return await invoke('update_ssh_connection', { + return await commandClient(client).call('update_ssh_connection', { id, name, ssh: normalizeSshParams(ssh), @@ -84,8 +81,8 @@ export async function updateSshConnection( /** * Delete an SSH connection */ -export async function deleteSshConnection(id: string): Promise { - await invoke('delete_ssh_connection', {id}); +export async function deleteSshConnection(id: string, client?: TypedCommandCaller): Promise { + await commandClient(client).call('delete_ssh_connection', {id}); } /** @@ -99,15 +96,20 @@ export async function deleteSshConnection(id: string): Promise { export async function testSshConnection( ssh: Partial, options: {dbConnectionId?: string; progressId?: string} = {}, + client?: TypedCommandCaller, ): Promise { - return await invoke('test_ssh_connection', { - ssh: { - ...normalizeSshParams(ssh), - connection_id: ssh.id, - db_connection_id: options.dbConnectionId, - progress_id: options.progressId, + return await commandClient(client).call( + 'test_ssh_connection', + { + ssh: { + ...normalizeSshParams(ssh), + connection_id: ssh.id, + db_connection_id: options.dbConnectionId, + progress_id: options.progressId, + }, }, - }); + {deadlineMs: 180_000}, + ); } /** diff --git a/src/utils/sslMode.ts b/packages/web-ui/src/utils/sslMode.ts similarity index 100% rename from src/utils/sslMode.ts rename to packages/web-ui/src/utils/sslMode.ts diff --git a/src/utils/ssm.ts b/packages/web-ui/src/utils/ssm.ts similarity index 79% rename from src/utils/ssm.ts rename to packages/web-ui/src/utils/ssm.ts index f73c0e9ae..7187fe90e 100644 --- a/src/utils/ssm.ts +++ b/packages/web-ui/src/utils/ssm.ts @@ -3,9 +3,9 @@ * Manages `aws ssm start-session` port-forwarding tunnels. */ -import {invoke} from '@tauri-apps/api/core'; +import type {TabularisClient} from '@/api/client'; -export interface SsmTestParams extends Record { +export interface SsmTestParams { target: string; profile?: string; region?: string; @@ -18,8 +18,11 @@ export interface SsmTestParams extends Record { * Test an SSM connection by opening a real port-forwarding session and * closing it again. */ -export async function testSsmConnection(params: SsmTestParams): Promise { - return await invoke('test_ssm_connection_cmd', params); +export async function testSsmConnection( + client: TabularisClient, + params: SsmTestParams, +): Promise { + return await client.call('test_ssm_connection_cmd', params); } const LOOPBACK_HOSTS = new Set(['', 'localhost', '127.0.0.1', '::1']); diff --git a/src/utils/startupConfig.ts b/packages/web-ui/src/utils/startupConfig.ts similarity index 66% rename from src/utils/startupConfig.ts rename to packages/web-ui/src/utils/startupConfig.ts index 088bfcbf1..480173d70 100644 --- a/src/utils/startupConfig.ts +++ b/packages/web-ui/src/utils/startupConfig.ts @@ -1,4 +1,4 @@ -import {invoke} from '@tauri-apps/api/core'; +import type {TabularisClient} from '@/api/client'; import type {Settings} from '@/contexts/SettingsContext'; type StartupConfig = Partial & { @@ -11,8 +11,8 @@ type StartupConfig = Partial & { let pending: Promise | undefined; /** Share simultaneous boot reads without retaining a stale config after boot. */ -export function loadStartupConfig(): Promise { - pending ??= invoke('get_config').finally(() => { +export function loadStartupConfig(client: TabularisClient): Promise { + pending ??= client.call('get_config', undefined).finally(() => { pending = undefined; }); return pending; diff --git a/src/utils/storageLocation.ts b/packages/web-ui/src/utils/storageLocation.ts similarity index 63% rename from src/utils/storageLocation.ts rename to packages/web-ui/src/utils/storageLocation.ts index 3dc0d0382..42b923176 100644 --- a/src/utils/storageLocation.ts +++ b/packages/web-ui/src/utils/storageLocation.ts @@ -1,5 +1,3 @@ -import {invoke} from '@tauri-apps/api/core'; - /** Where the folder in use was resolved from (mirrors the Rust enum). */ export type StorageLocationSource = 'default' | 'custom' | 'env'; @@ -38,26 +36,3 @@ export function pendingPathOf(info: StorageLocationInfo): string | null { if (!info.restartRequired) return null; return info.customPath ?? info.defaultPath; } - -let appDataDirPromise: Promise | null = null; - -/** - * Absolute data directory as resolved by the backend, honouring a custom - * storage location. Cached for the page lifetime: the folder cannot change - * without a restart. Prefer this over `appDataDir()` from the Tauri path API, - * which only knows the platform default. - */ -export function getAppDataDir(): Promise { - if (!appDataDirPromise) { - appDataDirPromise = invoke('get_app_data_dir').catch((e: unknown) => { - appDataDirPromise = null; - throw e; - }); - } - return appDataDirPromise; -} - -/** Test hook: forget the cached directory. */ -export function resetAppDataDirCache(): void { - appDataDirPromise = null; -} diff --git a/src/utils/stripSqlComments.ts b/packages/web-ui/src/utils/stripSqlComments.ts similarity index 100% rename from src/utils/stripSqlComments.ts rename to packages/web-ui/src/utils/stripSqlComments.ts diff --git a/packages/web-ui/src/utils/supportPrompt.ts b/packages/web-ui/src/utils/supportPrompt.ts new file mode 100644 index 000000000..b54406160 --- /dev/null +++ b/packages/web-ui/src/utils/supportPrompt.ts @@ -0,0 +1,20 @@ +import {UI_STATE_KEYS, uiStateStore} from '@/utils/uiStateStore'; + +export const SUPPORT_PROMPT_DISMISSED_KEY = UI_STATE_KEYS.supportPromptDismissed.key; + +export function isSupportPromptDismissed(): boolean { + return uiStateStore.get(SUPPORT_PROMPT_DISMISSED_KEY, false) === true; +} + +/** Persist before notifying subscribers, so a failed write does not hide the prompt. */ +export function dismissSupportPrompt(): Promise { + return uiStateStore.commit(SUPPORT_PROMPT_DISMISSED_KEY, true); +} + +/** + * Keep both modal instances in sync. The shared store also follows + * `ui-state://changed`, so other windows and browser sessions update too. + */ +export function subscribeToSupportPrompt(onChange: () => void): () => void { + return uiStateStore.subscribe(onChange); +} diff --git a/src/utils/systemTheme.ts b/packages/web-ui/src/utils/systemTheme.ts similarity index 100% rename from src/utils/systemTheme.ts rename to packages/web-ui/src/utils/systemTheme.ts diff --git a/src/utils/tabCleaner.ts b/packages/web-ui/src/utils/tabCleaner.ts similarity index 100% rename from src/utils/tabCleaner.ts rename to packages/web-ui/src/utils/tabCleaner.ts diff --git a/src/utils/tabDnd.ts b/packages/web-ui/src/utils/tabDnd.ts similarity index 100% rename from src/utils/tabDnd.ts rename to packages/web-ui/src/utils/tabDnd.ts diff --git a/src/utils/tabFilters.ts b/packages/web-ui/src/utils/tabFilters.ts similarity index 100% rename from src/utils/tabFilters.ts rename to packages/web-ui/src/utils/tabFilters.ts diff --git a/src/utils/tabScroll.ts b/packages/web-ui/src/utils/tabScroll.ts similarity index 100% rename from src/utils/tabScroll.ts rename to packages/web-ui/src/utils/tabScroll.ts diff --git a/src/utils/tableQueryTemplates.ts b/packages/web-ui/src/utils/tableQueryTemplates.ts similarity index 89% rename from src/utils/tableQueryTemplates.ts rename to packages/web-ui/src/utils/tableQueryTemplates.ts index 46644e65b..a012eb8d3 100644 --- a/src/utils/tableQueryTemplates.ts +++ b/packages/web-ui/src/utils/tableQueryTemplates.ts @@ -1,4 +1,4 @@ -import {invoke} from '@tauri-apps/api/core'; +import type {TabularisClient} from '@/api/client'; export type TableQueryTab = 'select-all' | 'select-fields' | 'update' | 'delete'; export type TableQueryTemplates = Partial>; @@ -14,6 +14,7 @@ export interface TableQueryTemplateRequest { /** Only call for opted-in drivers. A null response selects the legacy template; * errors must propagate instead of silently substituting another dialect. */ export async function loadTableQueryTemplates( + client: Pick, connectionId: string, table: string, schema: string | undefined, @@ -30,7 +31,7 @@ export async function loadTableQueryTemplates( columns: tab === 'select-fields' || tab === 'update' ? columns : [], limit: tab === 'select-fields' ? 100 : null, }; - const sql = await invoke('get_table_query_template', { + const sql = await client.call('get_table_query_template', { connectionId, request, database, diff --git a/src/utils/tableToolbar.ts b/packages/web-ui/src/utils/tableToolbar.ts similarity index 100% rename from src/utils/tableToolbar.ts rename to packages/web-ui/src/utils/tableToolbar.ts diff --git a/src/utils/taskManager.ts b/packages/web-ui/src/utils/taskManager.ts similarity index 70% rename from src/utils/taskManager.ts rename to packages/web-ui/src/utils/taskManager.ts index aa4c7e3fa..6f294bb38 100644 --- a/src/utils/taskManager.ts +++ b/packages/web-ui/src/utils/taskManager.ts @@ -1,50 +1,12 @@ -export interface ChildProcessInfo { - pid: number; - cpu_percent: number; - memory_bytes: number; - disk_read_bytes: number; - disk_write_bytes: number; -} - -export interface ProcessInfo { - plugin_id: string; - plugin_name: string; - pid: number | null; - cpu_percent: number; - memory_bytes: number; - disk_read_bytes: number; - disk_write_bytes: number; - status: 'running' | 'stopped' | 'unknown'; - children: ChildProcessInfo[]; -} - -export interface TabularisChildProcess { - pid: number; - name: string; - cpu_percent: number; - memory_bytes: number; -} +import type {ProcessInfo} from '@/types/operations'; -export interface TabularisSelfStats { - pid: number; - cpu_percent: number; - self_memory_bytes: number; - total_memory_bytes: number; - disk_read_bytes: number; - disk_write_bytes: number; - child_count: number; - // children are fetched on-demand via get_tabularis_children -} - -export interface SystemStats { - cpu_percent: number; - memory_used: number; - memory_total: number; - disk_read_bytes: number; - disk_write_bytes: number; - process_count: number; - tabularis: TabularisSelfStats | null; -} +export type { + ChildProcessInfo, + ProcessInfo, + SystemStats, + TabularisChildProcess, + TabularisSelfStats, +} from '@/types/operations'; export type ProcessSortKey = keyof Pick< ProcessInfo, diff --git a/src/utils/text.ts b/packages/web-ui/src/utils/text.ts similarity index 100% rename from src/utils/text.ts rename to packages/web-ui/src/utils/text.ts diff --git a/src/utils/themeArchive.ts b/packages/web-ui/src/utils/themeArchive.ts similarity index 100% rename from src/utils/themeArchive.ts rename to packages/web-ui/src/utils/themeArchive.ts diff --git a/src/utils/themeBoot.ts b/packages/web-ui/src/utils/themeBoot.ts similarity index 100% rename from src/utils/themeBoot.ts rename to packages/web-ui/src/utils/themeBoot.ts diff --git a/src/utils/themeCatalog.ts b/packages/web-ui/src/utils/themeCatalog.ts similarity index 100% rename from src/utils/themeCatalog.ts rename to packages/web-ui/src/utils/themeCatalog.ts diff --git a/src/utils/themeColor.ts b/packages/web-ui/src/utils/themeColor.ts similarity index 100% rename from src/utils/themeColor.ts rename to packages/web-ui/src/utils/themeColor.ts diff --git a/src/utils/themeContrast.ts b/packages/web-ui/src/utils/themeContrast.ts similarity index 100% rename from src/utils/themeContrast.ts rename to packages/web-ui/src/utils/themeContrast.ts diff --git a/src/utils/themeDefinitionEditing.ts b/packages/web-ui/src/utils/themeDefinitionEditing.ts similarity index 100% rename from src/utils/themeDefinitionEditing.ts rename to packages/web-ui/src/utils/themeDefinitionEditing.ts diff --git a/src/utils/themeDiscovery.ts b/packages/web-ui/src/utils/themeDiscovery.ts similarity index 100% rename from src/utils/themeDiscovery.ts rename to packages/web-ui/src/utils/themeDiscovery.ts diff --git a/src/utils/themeManagement.ts b/packages/web-ui/src/utils/themeManagement.ts similarity index 100% rename from src/utils/themeManagement.ts rename to packages/web-ui/src/utils/themeManagement.ts diff --git a/src/utils/themePackageExport.ts b/packages/web-ui/src/utils/themePackageExport.ts similarity index 100% rename from src/utils/themePackageExport.ts rename to packages/web-ui/src/utils/themePackageExport.ts diff --git a/src/utils/themePackageIdentity.ts b/packages/web-ui/src/utils/themePackageIdentity.ts similarity index 100% rename from src/utils/themePackageIdentity.ts rename to packages/web-ui/src/utils/themePackageIdentity.ts diff --git a/src/utils/themePackageValidation.ts b/packages/web-ui/src/utils/themePackageValidation.ts similarity index 100% rename from src/utils/themePackageValidation.ts rename to packages/web-ui/src/utils/themePackageValidation.ts diff --git a/src/utils/themeReadme.ts b/packages/web-ui/src/utils/themeReadme.ts similarity index 100% rename from src/utils/themeReadme.ts rename to packages/web-ui/src/utils/themeReadme.ts diff --git a/src/utils/themeResolver.ts b/packages/web-ui/src/utils/themeResolver.ts similarity index 100% rename from src/utils/themeResolver.ts rename to packages/web-ui/src/utils/themeResolver.ts diff --git a/packages/web-ui/src/utils/themeSystemEvents.ts b/packages/web-ui/src/utils/themeSystemEvents.ts new file mode 100644 index 000000000..3acd0f208 --- /dev/null +++ b/packages/web-ui/src/utils/themeSystemEvents.ts @@ -0,0 +1,18 @@ +import {getActivePlatformCapabilitiesOrNull} from '@/platform/activeCapabilities'; +import type {SystemThemeListener} from '@/platform/capabilities'; +import {listenForColorSchemeChanges, prefersDarkColorScheme} from '@/platform/systemColorScheme'; + +/** Current OS light/dark mode as reported by the active platform. */ +export const getSystemIsDark = (): Promise => { + const platform = getActivePlatformCapabilitiesOrNull(); + return platform + ? platform.getSystemIsDark() + : Promise.resolve(prefersDarkColorScheme().matches); +}; + +export const listenForSystemThemeChanges = (onChange: SystemThemeListener): Promise<() => void> => { + const platform = getActivePlatformCapabilitiesOrNull(); + return platform + ? platform.listenForSystemThemeChanges(onChange) + : listenForColorSchemeChanges(onChange); +}; diff --git a/src/utils/tones.ts b/packages/web-ui/src/utils/tones.ts similarity index 100% rename from src/utils/tones.ts rename to packages/web-ui/src/utils/tones.ts diff --git a/src/utils/triggerSql.ts b/packages/web-ui/src/utils/triggerSql.ts similarity index 100% rename from src/utils/triggerSql.ts rename to packages/web-ui/src/utils/triggerSql.ts diff --git a/packages/web-ui/src/utils/uiStateStore.ts b/packages/web-ui/src/utils/uiStateStore.ts new file mode 100644 index 000000000..3d4932d37 --- /dev/null +++ b/packages/web-ui/src/utils/uiStateStore.ts @@ -0,0 +1,314 @@ +import type {TabularisClient} from '@/api/client'; + +/** + * UI state shared by every host (desktop windows and browser sessions). + * + * Values live in the backend SQLite store (`get_ui_state` / `set_ui_state`), + * so a sidebar width chosen on the desktop is also used in the browser. This + * module keeps an in-memory copy so components can read synchronously. + */ +export interface UiStateKeyDefinition { + key: string; + /** Converts the value an older version kept in localStorage. */ + parseLegacy: (raw: string) => T | undefined; + /** + * Mirror the value in localStorage so the first paint uses it before the + * backend answers. Only layout values need this: a sidebar that starts at + * the default width and then snaps to the saved one is a visible jump. + */ + firstPaintCache?: boolean; +} + +const parseWidth = (raw: string): number | undefined => { + const parsed = Number.parseInt(raw, 10); + return Number.isNaN(parsed) ? undefined : parsed; +}; + +const parseTrue = (raw: string): boolean | undefined => (raw === 'true' ? true : undefined); + +export const UI_STATE_KEYS = { + sidebarWidth: { + key: 'tabularis_sidebar_width', + parseLegacy: parseWidth, + firstPaintCache: true, + }, + rowEditorSidebarWidth: { + key: 'tabularis_row_editor_sidebar_width', + parseLegacy: parseWidth, + firstPaintCache: true, + }, + lastSeenVersion: { + key: 'tabularis_last_seen_version', + parseLegacy: (raw: string) => (raw ? raw : undefined), + }, + supportPromptDismissed: { + key: 'tabularis_support_prompt_dismissed', + parseLegacy: parseTrue, + }, + discordCalloutDismissed: { + key: 'tabularis:discord-callout-v2-dismissed', + parseLegacy: parseTrue, + }, +} satisfies Record>; + +const DEFINITIONS: UiStateKeyDefinition[] = Object.values(UI_STATE_KEYS); + +/** One localStorage entry holds every first-paint value. */ +export const UI_STATE_CACHE_KEY = 'tabularis:ui-state-cache'; + +interface SetOptions { + /** Coalesce rapid writes (e.g. while dragging a resize handle). */ + debounceMs?: number; +} + +type Listener = () => void; + +function safeStorage(): Storage | null { + try { + return typeof window === 'undefined' ? null : window.localStorage; + } catch { + return null; + } +} + +export class UiStateStore { + private readonly values = new Map(); + private readonly listeners = new Set(); + private readonly timers = new Map>(); + private readonly pending = new Map(); + /** Keys changed locally since the current load started. */ + private readonly dirty = new Set(); + private readonly definitions: UiStateKeyDefinition[]; + private client: TabularisClient | null = null; + private ready = false; + private generation = 0; + + constructor(definitions: UiStateKeyDefinition[] = DEFINITIONS) { + this.definitions = definitions; + this.readFirstPaintCache(); + } + + get(key: string, fallback: T): T { + return this.values.has(key) ? (this.values.get(key) as T) : fallback; + } + + isReady(): boolean { + return this.ready; + } + + subscribe(listener: Listener): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + /** Updates immediately and writes to the backend in the background. */ + set(key: string, value: unknown, options: SetOptions = {}): void { + if (Object.is(this.values.get(key), value)) return; + this.dirty.add(key); + this.applyLocal(key, value); + const existing = this.timers.get(key); + if (existing) clearTimeout(existing); + this.timers.delete(key); + if (options.debounceMs && options.debounceMs > 0) { + this.pending.set(key, value); + this.timers.set( + key, + setTimeout(() => { + this.timers.delete(key); + this.pending.delete(key); + void this.write(key, value).catch(logWriteFailure(key)); + }, options.debounceMs), + ); + return; + } + this.pending.delete(key); + void this.write(key, value).catch(logWriteFailure(key)); + } + + /** Writes to the backend first and only then updates subscribers. */ + async commit(key: string, value: unknown): Promise { + await this.write(key, value); + this.dirty.add(key); + this.applyLocal(key, value); + } + + /** Forgets every value and the attached client, then re-reads the cache. */ + reset(): void { + for (const timer of this.timers.values()) clearTimeout(timer); + this.timers.clear(); + this.pending.clear(); + this.dirty.clear(); + this.values.clear(); + this.client = null; + this.ready = false; + this.generation += 1; + this.readFirstPaintCache(); + this.notify(); + } + + /** Sends debounced writes now (e.g. before the page unloads). */ + flush(): void { + for (const [key, timer] of this.timers) { + clearTimeout(timer); + const value = this.pending.get(key); + this.pending.delete(key); + void this.write(key, value).catch(logWriteFailure(key)); + } + this.timers.clear(); + } + + /** + * Loads the shared values, migrates values older versions kept in + * localStorage and follows changes made by other windows or sessions. + */ + attach(client: TabularisClient): () => void { + const generation = ++this.generation; + this.client = client; + this.dirty.clear(); + let unsubscribe: (() => void) | undefined; + let disposed = false; + + void client + .subscribe('ui-state://changed', ({key, value}) => { + if (generation !== this.generation) return; + if (this.timers.has(key)) return; // a newer local write is on its way + this.applyLocal(key, value); + }) + .then((stop) => { + if (disposed) stop(); + else unsubscribe = stop; + }) + .catch((error: unknown) => { + console.warn('Failed to follow shared UI state changes:', error); + }); + + void this.load(client, generation); + + return () => { + disposed = true; + unsubscribe?.(); + this.flush(); + if (generation === this.generation) this.client = null; + }; + } + + private async load(client: TabularisClient, generation: number): Promise { + const keys = this.definitions.map((definition) => definition.key); + let remote: Readonly> | null = null; + try { + remote = await client.call('get_ui_state', {keys}); + } catch (error) { + console.warn('Failed to load shared UI state; using local values:', error); + } + if (generation !== this.generation) return; + + const storage = safeStorage(); + for (const definition of this.definitions) { + const {key} = definition; + if (this.dirty.has(key)) continue; + const remoteValue = remote?.[key]; + if (remoteValue !== undefined && remoteValue !== null) { + this.applyLocal(key, remoteValue); + removeLegacy(storage, key); + continue; + } + if (!remote) continue; + // The backend has no value yet: migrate the one this host already had. + const legacy = readLegacy(storage, definition); + const local = legacy !== undefined ? legacy : this.values.get(key); + if (local === undefined) continue; + this.applyLocal(key, local); + try { + await client.call('set_ui_state', {key, value: local}); + removeLegacy(storage, key); + } catch (error) { + console.warn(`Failed to migrate UI state "${key}":`, error); + } + } + + this.ready = true; + this.notify(); + } + + private async write(key: string, value: unknown): Promise { + const client = this.client; + if (!client) return; + if (value === undefined || value === null) { + await client.call('delete_ui_state', {key}); + } else { + await client.call('set_ui_state', {key, value}); + } + } + + private applyLocal(key: string, value: unknown): void { + if (value === undefined || value === null) this.values.delete(key); + else this.values.set(key, value); + this.writeFirstPaintCache(); + this.notify(); + } + + private notify(): void { + for (const listener of [...this.listeners]) listener(); + } + + private readFirstPaintCache(): void { + const storage = safeStorage(); + if (!storage) return; + let cached: Record = {}; + try { + const raw = storage.getItem(UI_STATE_CACHE_KEY); + if (raw) cached = JSON.parse(raw) as Record; + } catch { + cached = {}; + } + for (const definition of this.definitions) { + if (!definition.firstPaintCache) continue; + const value = cached[definition.key] ?? readLegacy(storage, definition); + if (value !== undefined) this.values.set(definition.key, value); + } + } + + private writeFirstPaintCache(): void { + const storage = safeStorage(); + if (!storage) return; + const cached: Record = {}; + for (const definition of this.definitions) { + if (definition.firstPaintCache && this.values.has(definition.key)) { + cached[definition.key] = this.values.get(definition.key); + } + } + try { + storage.setItem(UI_STATE_CACHE_KEY, JSON.stringify(cached)); + } catch { + // The cache only avoids a layout jump; the backend keeps the value. + } + } +} + +function readLegacy(storage: Storage | null, definition: UiStateKeyDefinition): unknown { + if (!storage) return undefined; + try { + const raw = storage.getItem(definition.key); + return raw === null ? undefined : definition.parseLegacy(raw); + } catch { + return undefined; + } +} + +function removeLegacy(storage: Storage | null, key: string): void { + try { + storage?.removeItem(key); + } catch { + // Harmless: the backend value wins on every later start. + } +} + +function logWriteFailure(key: string) { + return (error: unknown) => { + console.warn(`Failed to save UI state "${key}":`, error); + }; +} + +export const uiStateStore = new UiStateStore(); diff --git a/src/utils/versionCompare.ts b/packages/web-ui/src/utils/versionCompare.ts similarity index 100% rename from src/utils/versionCompare.ts rename to packages/web-ui/src/utils/versionCompare.ts diff --git a/src/utils/visualQuery.ts b/packages/web-ui/src/utils/visualQuery.ts similarity index 100% rename from src/utils/visualQuery.ts rename to packages/web-ui/src/utils/visualQuery.ts diff --git a/src/utils/vsCodeThemeImport.ts b/packages/web-ui/src/utils/vsCodeThemeImport.ts similarity index 100% rename from src/utils/vsCodeThemeImport.ts rename to packages/web-ui/src/utils/vsCodeThemeImport.ts diff --git a/src/version.ts b/packages/web-ui/src/version.ts similarity index 100% rename from src/version.ts rename to packages/web-ui/src/version.ts diff --git a/src/workers/layoutWorker.ts b/packages/web-ui/src/workers/layoutWorker.ts similarity index 100% rename from src/workers/layoutWorker.ts rename to packages/web-ui/src/workers/layoutWorker.ts diff --git a/packages/web-ui/tests/api/bootstrap.test.ts b/packages/web-ui/tests/api/bootstrap.test.ts new file mode 100644 index 000000000..57caa27fe --- /dev/null +++ b/packages/web-ui/tests/api/bootstrap.test.ts @@ -0,0 +1,97 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisTransport} from '@/api/client'; +import {bootstrapTabularisClient, bootstrapTabularisRuntime} from '@/api/bootstrap'; +import type {SessionNegotiation} from '@/api/session'; + +const transport = (): TabularisTransport => + ({ + call: vi.fn().mockResolvedValue(true), + callUnmigrated: vi.fn(), + subscribe: vi.fn(), + emit: vi.fn(), + }) as unknown as TabularisTransport; + +const session: SessionNegotiation = { + apiVersion: 'v1', + serverVersion: '0.20.0', + serverBuild: { + target: 'linux-x86_64', + profile: 'release', + commit: 'abc1234', + }, + authenticated: true, + csrfToken: 'csrf-token', + access: { + remote: false, + authorizationLevel: 'local-admin', + highRiskCapabilities: true, + }, + capabilities: { + rpc: true, + events: true, + uploads: false, + downloads: false, + pluginAssets: false, + mcpHostConfiguration: true, + serverFileBrowser: false, + nativeUpdater: false, + }, + queryResponsePolicy: { + maxRowsPerPage: 10_000, + maxResponseBytes: 16_777_216, + streaming: false, + }, +}; + +describe('bootstrapTabularisClient', () => { + it('selects Tauri without starting a browser session', async () => { + const tauriTransport = transport(); + const createTauriTransport = vi.fn(() => tauriTransport); + const createHttpTransport = vi.fn(); + + const client = await bootstrapTabularisClient('tauri', { + createTauriTransport, + createHttpTransport, + }); + + await expect(client.call('is_debug_mode', undefined)).resolves.toBe(true); + expect(createTauriTransport).toHaveBeenCalledOnce(); + expect(createHttpTransport).not.toHaveBeenCalled(); + }); + + it('negotiates the browser session before returning the client', async () => { + const browserTransport = Object.assign(transport(), { + initialize: vi.fn().mockResolvedValue(session), + }); + const createTauriTransport = vi.fn(); + const createHttpTransport = vi.fn(() => browserTransport); + + const client = await bootstrapTabularisClient('browser', { + createTauriTransport, + createHttpTransport, + }); + + expect(browserTransport.initialize).toHaveBeenCalledOnce(); + expect(createHttpTransport).toHaveBeenCalledOnce(); + expect(createTauriTransport).not.toHaveBeenCalled(); + await expect(client.call('is_debug_mode', undefined)).resolves.toBe(true); + }); + + it('retains negotiated server build information for browser providers', async () => { + const browserTransport = Object.assign(transport(), { + initialize: vi.fn().mockResolvedValue(session), + }); + + const runtime = await bootstrapTabularisRuntime('browser', { + createHttpTransport: () => browserTransport, + }); + + expect(runtime.session).toEqual(session); + expect(runtime.session?.capabilities.nativeUpdater).toBe(false); + expect(runtime.session?.serverBuild).toEqual({ + target: 'linux-x86_64', + profile: 'release', + commit: 'abc1234', + }); + }); +}); diff --git a/packages/web-ui/tests/api/client.test.ts b/packages/web-ui/tests/api/client.test.ts new file mode 100644 index 000000000..c18d829f7 --- /dev/null +++ b/packages/web-ui/tests/api/client.test.ts @@ -0,0 +1,106 @@ +import {describe, expect, it, vi} from 'vitest'; +import {TabularisClient, type TabularisTransport} from '@/api/client'; +import type {RequestId} from '@/api/errors'; + +const createTransport = () => + ({ + call: vi.fn(), + callUnmigrated: vi.fn(), + subscribe: vi.fn(), + emit: vi.fn(), + }) as unknown as TabularisTransport; + +describe('TabularisClient', () => { + it('delegates typed and unmigrated commands to its transport', async () => { + const transport = createTransport(); + const client = new TabularisClient(transport); + const requestId = 'request-1' as RequestId; + + vi.mocked(transport.call).mockResolvedValueOnce(true); + vi.mocked(transport.callUnmigrated).mockResolvedValueOnce({value: 1}); + + await expect(client.call('is_debug_mode', undefined, {requestId})).resolves.toBe(true); + await expect( + client.callUnmigrated( + 'legacy_command', + {enabled: true}, + { + task: 'WEB-050', + callSite: 'src/example.ts:1', + reason: 'Awaiting its command-group migration', + }, + {requestId}, + ), + ).resolves.toEqual({value: 1}); + + expect(transport.call).toHaveBeenCalledWith('is_debug_mode', undefined, { + requestId, + }); + expect(transport.callUnmigrated).toHaveBeenCalledWith( + 'legacy_command', + {enabled: true}, + { + task: 'WEB-050', + callSite: 'src/example.ts:1', + reason: 'Awaiting its command-group migration', + }, + {requestId}, + ); + }); + + it('delegates plugin asset reads to transport adapters', async () => { + const transport = createTransport(); + transport.readPluginAsset = vi.fn().mockResolvedValue('plugin source'); + const client = new TabularisClient(transport); + + await expect(client.readPluginAsset('plugin-id', 'ui/index.js')).resolves.toBe( + 'plugin source', + ); + expect(transport.readPluginAsset).toHaveBeenCalledWith('plugin-id', 'ui/index.js'); + }); + + it('delegates streamed browser downloads to transport adapters', async () => { + const transport = createTransport(); + transport.requestDownload = vi.fn().mockResolvedValue(undefined); + const client = new TabularisClient(transport); + + await expect(client.requestDownload('download-token')).resolves.toBeUndefined(); + expect(transport.requestDownload).toHaveBeenCalledWith('download-token'); + }); + + it('delegates browser BLOB transfers to transport adapters', async () => { + const upload = new Blob([new Uint8Array([0, 1, 2, 3])]); + const download = new Blob([new Uint8Array([3, 2, 1, 0])]); + const transport = createTransport(); + transport.uploadBlob = vi + .fn() + .mockResolvedValue('BLOB_UPLOAD_REF:4:application/octet-stream:token'); + transport.uploadedBlobUrl = vi.fn().mockReturnValue('/api/v1/uploads/blobs/token'); + transport.readUploadedBlob = vi.fn().mockResolvedValue(upload); + transport.consumeBlobDownload = vi.fn().mockResolvedValue(download); + const client = new TabularisClient(transport); + + await expect(client.uploadBlob(upload)).resolves.toContain('BLOB_UPLOAD_REF:'); + expect(client.uploadedBlobUrl('token')).toBe('/api/v1/uploads/blobs/token'); + await expect(client.readUploadedBlob('token')).resolves.toBe(upload); + await expect(client.consumeBlobDownload('download-token')).resolves.toBe(download); + }); + + it('delegates subscriptions and emitted events to its transport', async () => { + const transport = createTransport(); + const client = new TabularisClient(transport); + const handler = vi.fn(); + const unsubscribe = vi.fn(); + const payload = ['connection-1']; + + vi.mocked(transport.subscribe).mockResolvedValueOnce(unsubscribe); + + await expect(client.subscribe('connections:active-changed', handler)).resolves.toBe( + unsubscribe, + ); + await client.emit('connections:active-changed', payload); + + expect(transport.subscribe).toHaveBeenCalledWith('connections:active-changed', handler); + expect(transport.emit).toHaveBeenCalledWith('connections:active-changed', payload); + }); +}); diff --git a/packages/web-ui/tests/api/contract.type-test.ts b/packages/web-ui/tests/api/contract.type-test.ts new file mode 100644 index 000000000..aa28eba4f --- /dev/null +++ b/packages/web-ui/tests/api/contract.type-test.ts @@ -0,0 +1,369 @@ +import type { + CommandAuthorization, + CommandRequest, + CommandResponse, + TypedCommandCaller, +} from '@/api/contract'; +import type {EventEnvelope, EventSubscriber} from '@/api/events'; +import type {RpcFailure} from '@/api/errors'; +import type {QueryResult} from '@/types/editor'; + +function assertCommandContract(caller: TypedCommandCaller): void { + const debugMode: Promise = caller.call('is_debug_mode', undefined, { + requestId: 'request-1', + deadlineMs: 30_000, + cancellationId: 'startup-debug', + }); + const sshProfiles = caller.call('get_ssh_connections', undefined); + const askpassResponse = caller.call('respond_ssh_askpass', { + id: 7, + response: null, + }); + const queryResult: Promise = caller.call( + 'execute_query', + { + connectionId: 'connection-1', + query: 'SELECT 1', + limit: 100, + page: 1, + }, + {requestId: 'query-request-1', cancellationId: 'query-request-1'}, + ); + const explainResult = caller.call('explain_query_plan', { + connectionId: 'connection-1', + query: 'SELECT 1', + analyze: false, + }); + const cancellation = caller.call('cancel_query', { + connectionId: 'connection-1', + queryRequestId: 'query-request-1', + }); + const columns = caller.call('get_columns', { + connectionId: 'connection-1', + tableName: 'users', + schema: 'public', + }); + const materializedViewDefinition: Promise = caller.call( + 'get_materialized_view_definition', + { + connectionId: 'connection-1', + viewName: 'active_users', + schema: 'public', + }, + ); + const selectedSchemas: Promise = caller.call('get_selected_schemas', { + connectionId: 'connection-1', + }); + const updatedRows: Promise = caller.call('update_record', { + connectionId: 'connection-1', + table: 'files', + pkMap: {id: 1}, + colName: 'payload', + newVal: 'BLOB:4:application/octet-stream:AAECAw==', + }); + const blob = caller.call('fetch_blob', { + connectionId: 'connection-1', + table: 'files', + pkMap: {id: 1}, + colName: 'payload', + }); + const viewDefinition: Promise = caller.call('get_view_definition', { + connectionId: 'connection-1', + viewName: 'active_users', + schema: 'public', + }); + const passwordChange: Promise = caller.call('set_db_user_password', { + connectionId: 'connection-1', + user: 'app', + host: '%', + password: 'write-only-secret', + }); + const config = caller.call('get_config', undefined); + const savedConfig: Promise = caller.call('save_config', { + config: {language: 'en', formatterTabWidth: 2}, + }); + const editorPreferences = caller.call('load_editor_preferences', { + connectionId: 'connection-1', + }); + const sessionSelection: Promise = caller.call('get_last_open_connections', undefined); + const savedQueries = caller.call('get_saved_queries', { + connectionId: 'connection-1', + }); + const history = caller.call('get_query_history', { + connectionId: 'connection-1', + }); + const deletedSavedQuery: Promise = caller.call('delete_saved_query', { + connectionId: 'connection-1', + id: 'saved-query-1', + }); + const notebookContent: Promise = caller.call('load_notebook', { + connectionId: 'connection-1', + notebookId: 'notebook-1', + }); + const savedNotebook: Promise = caller.call('save_notebook', { + connectionId: 'connection-1', + notebookId: 'notebook-1', + content: '{}', + }); + const notebooks = caller.call('list_notebooks', { + connectionId: 'connection-1', + }); + const pluginRegistry = caller.call('fetch_plugin_registry', undefined); + const pluginInstall: Promise = caller.call('install_plugin', { + pluginId: 'postgres-driver', + version: '1.2.3', + registryUrl: 'https://registry.example/api', + }); + const pluginCancellation: Promise = caller.call('cancel_plugin_install', { + pluginId: 'postgres-driver', + }); + const pluginReadme = caller.call('fetch_plugin_readme', { + slug: 'postgres-driver', + locale: 'en', + }); + const pluginRestart: Promise = caller.call('restart_plugin_process', { + pluginId: 'postgres-driver', + }); + const mcpStatus = caller.call('get_mcp_status', undefined); + const installedMcpClient: Promise = caller.call('install_mcp_config', { + clientId: 'claude', + }); + const logs = caller.call('get_logs', { + request: {limit: 100, level_filter: 'ERROR'}, + }); + const logSettings = caller.call('get_log_settings', undefined); + const processes = caller.call('get_process_list', undefined); + const systemStats = caller.call('get_system_stats', undefined); + const childProcesses = caller.call('get_tabularis_children', undefined); + const clearedLogs: Promise = caller.call('clear_logs', undefined); + const toggledLogging: Promise = caller.call('set_log_enabled', { + enabled: true, + }); + const resizedLogBuffer: Promise = caller.call('set_log_max_size', { + maxSize: 1000, + }); + + const themeCatalog = caller.call('get_theme_catalog', undefined); + const uploadedThemePreview = caller.call('preview_local_theme_package', { + uploadToken: 'upload-1', + }); + const serverThemeInstall = caller.call('install_local_theme_package', { + path: '/srv/themes/nord.zip', + packageName: 'acme/nord', + expectedDigest: 'digest', + }); + const uiState: Promise>> = caller.call('get_ui_state', { + keys: ['tabularis_sidebar_width'], + }); + const savedUiState: Promise = caller.call('set_ui_state', { + key: 'tabularis_sidebar_width', + value: 320, + }); + const sqlFile: Promise = caller.call('read_sql_file', { + path: '/srv/sql/report.sql', + }); + // @ts-expect-error A local archive is either uploaded or a server path, never both. + caller.call('preview_local_theme_package', {path: '/a.zip', uploadToken: 't'}); + // @ts-expect-error UI state writes need a key. + caller.call('set_ui_state', {value: 1}); + + // @ts-expect-error Log limits must be numeric. + caller.call('get_logs', {request: {limit: '100'}}); + // @ts-expect-error Plugin identifiers are required for lifecycle mutations. + caller.call('install_plugin', {version: '1.2.3'}); + // @ts-expect-error Notebook operations require explicit connection scoping. + caller.call('load_notebook', {notebookId: 'notebook-1'}); + // @ts-expect-error Saved-query mutations require explicit connection scoping. + caller.call('delete_saved_query', {id: 'saved-query-1'}); + // @ts-expect-error execute_query requires a connection id. + caller.call('execute_query', {query: 'SELECT 1'}); + // @ts-expect-error Unknown commands must use the tracked escape hatch. + caller.call('get_unmigrated_data', undefined); + // @ts-expect-error The response of execute_query is not a string. + const wrongResponse: Promise = caller.call('execute_query', { + connectionId: 'connection-1', + query: 'SELECT 1', + }); + + const unmigratedResult: Promise = caller.callUnmigrated( + 'get_unmigrated_data', + {connectionId: 'connection-1'}, + { + task: 'WEB-050', + callSite: 'src/example.ts:10', + reason: 'The command has not been added to CommandMap yet.', + }, + ); + caller.callUnmigrated( + // @ts-expect-error Migrated commands cannot bypass their typed contract. + 'execute_query', + {}, + { + task: 'WEB-050', + callSite: 'src/example.ts:20', + reason: 'Invalid bypass attempt.', + }, + ); + // @ts-expect-error Every unmigrated call must include tracking metadata. + caller.callUnmigrated('get_unmigrated_data', {}); + + void [ + debugMode, + sshProfiles, + askpassResponse, + queryResult, + columns, + materializedViewDefinition, + selectedSchemas, + updatedRows, + blob, + viewDefinition, + passwordChange, + config, + savedConfig, + editorPreferences, + sessionSelection, + savedQueries, + history, + deletedSavedQuery, + notebookContent, + savedNotebook, + notebooks, + pluginRegistry, + pluginInstall, + pluginCancellation, + pluginReadme, + pluginRestart, + mcpStatus, + installedMcpClient, + logs, + logSettings, + processes, + systemStats, + childProcesses, + clearedLogs, + toggledLogging, + resizedLogBuffer, + explainResult, + cancellation, + wrongResponse, + unmigratedResult, + themeCatalog, + uploadedThemePreview, + serverThemeInstall, + uiState, + savedUiState, + sqlFile, + ]; +} + +function assertEventContract(subscriber: EventSubscriber): void { + subscriber.subscribe('database-dropped', (payload) => { + const connectionId: string = payload.connectionId; + const database: string = payload.database; + void [connectionId, database]; + }); + + subscriber.subscribe('ssh-askpass://request', (payload) => { + const id: number = payload.id; + const prompt: string = payload.prompt; + void [id, prompt]; + }); + + subscriber.subscribe('query-status', (payload) => { + const requestId: string = payload.requestId; + const status: 'started' | 'completed' | 'failed' = payload.status; + void [requestId, status]; + }); + + subscriber.subscribe('ui-state://changed', (payload) => { + const key: string = payload.key; + void key; + }); + subscriber.subscribe('theme-catalog-changed', () => undefined); + + // @ts-expect-error database-dropped does not carry a batch id. + subscriber.subscribe('database-dropped', (payload) => payload.batch_id); + // @ts-expect-error Unknown event names are rejected. + subscriber.subscribe('untracked-event', () => undefined); +} + +type ExecuteQueryRequest = CommandRequest<'execute_query'>; +type ExecuteQueryResponse = CommandResponse<'execute_query'>; +type DatabaseDroppedEnvelope = EventEnvelope<'database-dropped'>; + +const executeQueryAuthorization: CommandAuthorization<'execute_query'> = 'database'; +const sshAuthorization: CommandAuthorization<'get_ssh_connections'> = 'local-admin'; +const askpassAuthorization: CommandAuthorization<'respond_ssh_askpass'> = 'sensitive'; +const passwordAuthorization: CommandAuthorization<'set_db_user_password'> = 'sensitive'; +const userListAuthorization: CommandAuthorization<'get_db_users'> = 'sensitive'; +const configAuthorization: CommandAuthorization<'get_config'> = 'local-admin'; +const editorPreferencesAuthorization: CommandAuthorization<'load_editor_preferences'> = 'database'; +const sessionSelectionAuthorization: CommandAuthorization<'get_last_open_connections'> = 'session'; +const savedQueryAuthorization: CommandAuthorization<'save_query'> = 'database'; +const queryHistoryAuthorization: CommandAuthorization<'get_query_history'> = 'database'; +const notebookAuthorization: CommandAuthorization<'save_notebook'> = 'database'; +const pluginInstallAuthorization: CommandAuthorization<'install_plugin'> = 'local-admin'; +const mcpAuthorization: CommandAuthorization<'install_mcp_config'> = 'local-admin'; +const logReadAuthorization: CommandAuthorization<'get_logs'> = 'sensitive'; +const clearLogsAuthorization: CommandAuthorization<'clear_logs'> = 'local-admin'; +const taskStatsAuthorization: CommandAuthorization<'get_system_stats'> = 'sensitive'; +const themeCatalogAuthorization: CommandAuthorization<'get_theme_catalog'> = 'session'; +const themeImportAuthorization: CommandAuthorization<'import_theme'> = 'local-admin'; +const proxySecretAuthorization: CommandAuthorization<'set_proxy_password'> = 'sensitive'; +const uiStateAuthorization: CommandAuthorization<'set_ui_state'> = 'session'; +// @ts-expect-error Personal theme writes change host files. +const wrongThemeAuthorization: CommandAuthorization<'create_personal_theme'> = 'session'; +// @ts-expect-error Plugin installation is never a plain session operation. +const wrongPluginAuthorization: CommandAuthorization<'install_plugin'> = 'session'; +// @ts-expect-error execute_query is not a local-admin operation. +const wrongAuthorization: CommandAuthorization<'execute_query'> = 'local-admin'; +const rpcFailure: RpcFailure = { + ok: false, + error: { + code: 'QUERY_FAILED', + message: 'Query failed', + details: null, + requestId: 'request-1', + }, +}; +const failureWithoutRequestId: RpcFailure = { + ok: false, + // @ts-expect-error Errors must expose the request id used for diagnostics. + error: { + code: 'QUERY_FAILED', + message: 'Query failed', + details: null, + }, +}; + +void assertCommandContract; +void assertEventContract; +void (null as unknown as ExecuteQueryRequest); +void (null as unknown as ExecuteQueryResponse); +void (null as unknown as DatabaseDroppedEnvelope); +void executeQueryAuthorization; +void sshAuthorization; +void askpassAuthorization; +void passwordAuthorization; +void userListAuthorization; +void configAuthorization; +void editorPreferencesAuthorization; +void sessionSelectionAuthorization; +void savedQueryAuthorization; +void queryHistoryAuthorization; +void notebookAuthorization; +void pluginInstallAuthorization; +void mcpAuthorization; +void logReadAuthorization; +void clearLogsAuthorization; +void taskStatsAuthorization; +void wrongPluginAuthorization; +void wrongAuthorization; +void rpcFailure; +void failureWithoutRequestId; +void themeCatalogAuthorization; +void themeImportAuthorization; +void proxySecretAuthorization; +void uiStateAuthorization; +void wrongThemeAuthorization; diff --git a/packages/web-ui/tests/api/contract/transportContract.ts b/packages/web-ui/tests/api/contract/transportContract.ts new file mode 100644 index 000000000..81d3f515b --- /dev/null +++ b/packages/web-ui/tests/api/contract/transportContract.ts @@ -0,0 +1,1680 @@ +import {createServer, type IncomingMessage, type ServerResponse} from 'node:http'; +import type {AddressInfo} from 'node:net'; +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import type {TabularisTransport} from '@/api/client'; + +const QUERY_RESULT = { + columns: ['value'], + rows: [[1]], + affected_rows: 0, + truncated: false, + pagination: { + page: 1, + page_size: 100, + total_rows: null, + has_more: false, + }, +}; + +const PLUGIN_MANIFEST = { + id: 'postgres-driver', + name: 'PostgreSQL Driver', + version: '1.2.3', + description: 'Contract plugin', + default_port: 5432, + is_builtin: false, + capabilities: { + schemas: true, + views: true, + routines: true, + file_based: false, + folder_based: false, + identifier_quote: '"', + alter_primary_key: false, + }, +}; + +const PLUGIN_REGISTRY_ENTRY = { + id: 'postgres-driver', + name: 'PostgreSQL Driver', + description: 'Contract plugin', + author: 'Tabularis', + homepage: 'https://example.com/postgres-driver', + latest_version: '1.2.3', + releases: [ + { + version: '1.2.3', + min_tabularis_version: null, + platform_supported: true, + }, + ], + installed_version: null, + update_available: false, + platform_supported: true, +}; + +const SESSION = { + apiVersion: 'v1', + serverVersion: 'contract-fixture', + serverBuild: { + target: 'test-contract', + profile: 'debug', + commit: null, + }, + authenticated: true, + csrfToken: 'contract-csrf-token', + access: { + remote: false, + authorizationLevel: 'local-admin', + highRiskCapabilities: true, + }, + capabilities: { + rpc: true, + events: false, + uploads: false, + downloads: false, + pluginAssets: false, + mcpHostConfiguration: true, + serverFileBrowser: false, + nativeUpdater: false, + }, + queryResponsePolicy: { + maxRowsPerPage: 10_000, + maxResponseBytes: 16_777_216, + streaming: false, + }, +}; + +interface TransportContractHarness { + readonly transport: TabularisTransport; + readonly close?: () => Promise | void; +} + +interface LiveWebContractServer { + readonly baseUrl: string; + readonly close: () => Promise; +} + +type CreateTransportContractHarness = () => + Promise | TransportContractHarness; + +export function defineTransportContractSuite( + adapterName: string, + serializationFixture: unknown, + createHarness: CreateTransportContractHarness, +): void { + describe(`${adapterName} transport contract`, () => { + let harness: TransportContractHarness; + + beforeAll(async () => { + harness = await createHarness(); + }); + + afterAll(async () => { + await harness.close?.(); + }); + + it('preserves typed requests and responses', async () => { + await expect( + harness.transport.call('is_debug_mode', undefined, { + requestId: 'contract-debug-request', + }), + ).resolves.toBe(true); + }); + + it('preserves connection and tunnel profile contracts', async () => { + await expect( + harness.transport.call('get_connections_with_groups', undefined), + ).resolves.toEqual({groups: [], connections: []}); + await expect(harness.transport.call('get_ssh_connections', undefined)).resolves.toEqual( + [], + ); + await expect(harness.transport.call('get_k8s_connections', undefined)).resolves.toEqual( + [], + ); + }); + + it('preserves connection file and backup contracts', async () => { + await expect( + harness.transport.call('export_connections_file', { + mode: 'noSecrets', + connectionIds: ['connection-fixture'], + }), + ).resolves.toEqual({ + kind: 'inline', + fileName: 'tabularis-connections.json', + mimeType: 'application/json', + contents: '{"version":1}', + }); + await expect( + harness.transport.call('list_connection_import_sources', undefined), + ).resolves.toEqual([]); + await expect( + harness.transport.call('get_connections_backup_status', undefined), + ).resolves.toEqual({ + passwordSet: true, + targetPasswordSet: true, + lastBackupAt: null, + targetKind: 'serverDirectory', + targetDisplay: '/srv/tabularis/backups', + }); + await expect( + harness.transport.call('set_connections_backup_password', { + password: 'backup-password', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('run_connections_backup', undefined), + ).resolves.toEqual({ + serverLocation: '/srv/tabularis/backups/tabularis-backup.json', + targetKind: 'serverDirectory', + download: null, + }); + }); + + it('preserves generic export contracts', async () => { + await expect( + harness.transport.call('export_query_to_file', { + connectionId: 'query-export-fixture', + query: 'SELECT 1 AS value', + format: 'csv', + csvDelimiter: ';', + }), + ).resolves.toEqual({ + kind: 'download', + fileName: 'result.csv', + mimeType: 'text/csv', + token: 'query-export-download-token', + size: 14, + }); + await expect( + harness.transport.call('cancel_export', { + connectionId: 'query-export-fixture', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('export_ai_activity_json', undefined), + ).resolves.toBe('{"id":"activity-1"}\n'); + await expect(harness.transport.call('export_ai_activity_csv', undefined)).resolves.toBe( + 'id,status\nactivity-1,success\n', + ); + await expect( + harness.transport.call('export_ai_session_as_notebook', { + sessionId: 'ai-session-fixture', + }), + ).resolves.toMatchObject({title: 'AI session'}); + await expect(harness.transport.call('export_logs', {})).resolves.toEqual({ + kind: 'download', + fileName: 'tabularis-logs.log', + mimeType: 'text/plain', + token: 'logs-download-token', + size: 64, + }); + }); + + it('preserves AI, activity, and approval contracts without returning keys', async () => { + await expect( + harness.transport.call('set_ai_key', { + provider: 'openai', + key: 'write-only-contract-key', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('check_ai_key_status', {provider: 'openai'}), + ).resolves.toEqual({configured: true, fromEnv: false}); + await expect( + harness.transport.call('get_ai_models', {forceRefresh: false}), + ).resolves.toEqual({openai: ['gpt-contract']}); + await expect( + harness.transport.call('generate_ai_query', { + req: { + provider: 'openai', + model: 'gpt-contract', + prompt: 'Select one', + schema: 'table values(id integer)', + }, + }), + ).resolves.toBe('SELECT 1'); + await expect( + harness.transport.call('get_ai_activity', {filter: {status: 'success'}}), + ).resolves.toEqual([]); + await expect( + harness.transport.call('list_pending_approvals', undefined), + ).resolves.toEqual([]); + await expect( + harness.transport.call('decide_pending_approval', { + approvalId: 'approval-contract', + decision: 'deny', + reason: 'contract fixture', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('delete_ai_key', {provider: 'openai'}), + ).resolves.toBeNull(); + }); + + it('preserves local-admin MCP host configuration contracts', async () => { + await expect(harness.transport.call('get_mcp_status', undefined)).resolves.toEqual([ + { + client_id: 'claude', + client_name: 'Claude Desktop', + installed: false, + config_path: '/home/test/.config/Claude/claude_desktop_config.json', + executable_path: '/usr/bin/tabularis', + client_type: 'file', + manual_command: null, + }, + ]); + await expect( + harness.transport.call('install_mcp_config', {clientId: 'claude'}), + ).resolves.toBe('Claude Desktop'); + }); + + it('preserves local-admin plugin lifecycle contracts', async () => { + await expect( + harness.transport.call('fetch_plugin_registry', undefined), + ).resolves.toEqual([PLUGIN_REGISTRY_ENTRY]); + await expect( + harness.transport.call('fetch_tabularium_plugin_preview', { + slug: 'postgres-driver', + registryUrl: null, + version: '1.2.3', + }), + ).resolves.toEqual({ + ...PLUGIN_REGISTRY_ENTRY, + install_action: 'install', + signature: 'verified', + }); + await expect( + harness.transport.call('fetch_plugin_readme', { + slug: 'postgres-driver', + locale: 'en', + registryUrl: null, + }), + ).resolves.toEqual({ + html: '

Contract plugin

', + locale: 'en', + available_locales: ['en'], + documentation_url: null, + repo_url: 'https://example.com/postgres-driver', + }); + await expect( + harness.transport.call('get_installed_plugins', undefined), + ).resolves.toEqual([]); + await expect( + harness.transport.call('get_plugin_manifest', { + pluginId: 'postgres-driver', + }), + ).resolves.toEqual(PLUGIN_MANIFEST); + await expect( + harness.transport.call('get_plugin_startup_errors', undefined), + ).resolves.toEqual([]); + await expect( + harness.transport.call('cancel_plugin_install', { + pluginId: 'postgres-driver', + }), + ).resolves.toBe(true); + + await expect( + harness.transport.call('install_plugin', { + pluginId: 'postgres-driver', + version: '1.2.3', + registryUrl: 'https://registry.example/api', + }), + ).resolves.toBeNull(); + + for (const command of [ + 'disable_plugin', + 'enable_plugin', + 'kill_plugin_process', + 'restart_plugin_process', + 'uninstall_plugin', + ] as const) { + await expect( + harness.transport.call(command, {pluginId: 'postgres-driver'}), + ).resolves.toBeNull(); + } + }); + + it('preserves logs and task manager contracts', async () => { + await expect( + harness.transport.call('get_logs', { + request: {limit: 100, level_filter: 'ERROR'}, + }), + ).resolves.toEqual([ + { + timestamp: '2026-08-22 09:00:00.000', + level: 'ERROR', + message: 'Contract log', + target: 'contract', + }, + ]); + await expect(harness.transport.call('get_log_settings', undefined)).resolves.toEqual({ + enabled: true, + max_size: 1000, + current_count: 1, + }); + await expect(harness.transport.call('get_process_list', undefined)).resolves.toEqual([ + { + plugin_id: 'postgres-driver', + plugin_name: 'PostgreSQL Driver', + pid: 4100, + cpu_percent: 1.5, + memory_bytes: 2048, + disk_read_bytes: 128, + disk_write_bytes: 64, + status: 'running', + children: [], + }, + ]); + await expect(harness.transport.call('get_system_stats', undefined)).resolves.toEqual({ + cpu_percent: 12.5, + memory_used: 4096, + memory_total: 8192, + disk_read_bytes: 256, + disk_write_bytes: 128, + process_count: 4, + tabularis: null, + }); + await expect( + harness.transport.call('get_tabularis_children', undefined), + ).resolves.toEqual([ + { + pid: 4200, + name: 'tabularis-plugin', + cpu_percent: 0.5, + memory_bytes: 1024, + }, + ]); + + await expect( + harness.transport.call('set_log_enabled', {enabled: false}), + ).resolves.toBeNull(); + await expect( + harness.transport.call('set_log_max_size', {maxSize: 500}), + ).resolves.toBeNull(); + await expect(harness.transport.call('clear_logs', undefined)).resolves.toBeNull(); + }); + + it('preserves database dump and import job contracts', async () => { + await expect( + harness.transport.call('dump_database', { + connectionId: 'database-transfer-fixture', + options: {structure: true, data: true, tables: ['users']}, + schema: 'public', + }), + ).resolves.toEqual({ + kind: 'download', + fileName: 'database-transfer-fixture.sql', + mimeType: 'application/sql', + token: 'database-transfer-download-token', + size: 128, + }); + await expect( + harness.transport.call('import_database', { + connectionId: 'database-transfer-fixture', + uploadToken: 'database-transfer-upload-token', + schema: 'public', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('cancel_dump', { + connectionId: 'database-transfer-fixture', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('cancel_import', { + connectionId: 'database-transfer-fixture', + }), + ).resolves.toBeNull(); + }); + + it('preserves metadata explorer contracts', async () => { + await expect( + harness.transport.call('get_tables', { + connectionId: 'metadata-fixture', + schema: 'public', + }), + ).resolves.toEqual([{name: 'users', schema: 'public'}]); + await expect( + harness.transport.call('get_columns', { + connectionId: 'metadata-fixture', + tableName: 'users', + schema: 'public', + }), + ).resolves.toEqual([ + { + name: 'id', + data_type: 'integer', + is_pk: true, + is_nullable: false, + is_auto_increment: true, + }, + ]); + await expect( + harness.transport.call('get_selected_schemas', { + connectionId: 'metadata-fixture', + }), + ).resolves.toEqual(['public']); + }); + + it('preserves shared UI state and theme catalog contracts', async () => { + await expect( + harness.transport.call('get_ui_state', { + keys: ['tabularis_sidebar_width'], + }), + ).resolves.toEqual({tabularis_sidebar_width: 320}); + await expect( + harness.transport.call('set_ui_state', { + key: 'tabularis_sidebar_width', + value: 280, + }), + ).resolves.toBeNull(); + await expect(harness.transport.call('get_theme_catalog', undefined)).resolves.toEqual({ + themes: [], + issues: [], + }); + }); + + it('preserves database object and user-management contracts', async () => { + await expect( + harness.transport.call('get_view_definition', { + connectionId: 'object-fixture', + viewName: 'active_users', + schema: 'public', + }), + ).resolves.toBe('SELECT id FROM users WHERE active = 1'); + await expect( + harness.transport.call('get_routine_parameters', { + connectionId: 'object-fixture', + routineName: 'refresh_users', + schema: 'public', + }), + ).resolves.toEqual([ + { + name: 'batch_size', + data_type: 'integer', + mode: 'IN', + ordinal_position: 1, + }, + ]); + await expect( + harness.transport.call('get_trigger_definition', { + connectionId: 'object-fixture', + triggerName: 'audit_users', + tableName: 'users', + schema: 'public', + }), + ).resolves.toBe('CREATE TRIGGER audit_users AFTER UPDATE ON users'); + await expect( + harness.transport.call('get_create_index_sql', { + connectionId: 'object-fixture', + table: 'users', + indexName: 'idx_users_email', + columns: ['email'], + isUnique: true, + schema: 'public', + }), + ).resolves.toEqual([ + 'CREATE UNIQUE INDEX "idx_users_email" ON "public"."users" ("email")', + ]); + await expect( + harness.transport.call('get_db_users', { + connectionId: 'object-fixture', + }), + ).resolves.toEqual([{user: 'app', host: '%', locked: false}]); + await expect( + harness.transport.call('apply_db_user_privileges', { + connectionId: 'object-fixture', + user: 'app', + host: '%', + database: 'app_db', + table: null, + privileges: ['SELECT'], + grant: true, + }), + ).resolves.toBeNull(); + }); + + it('preserves query execution contracts and request-scoped cancellation', async () => { + await expect( + harness.transport.call( + 'execute_query', + { + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + limit: 100, + page: 1, + }, + {requestId: 'query-request-1', cancellationId: 'query-request-1'}, + ), + ).resolves.toEqual(QUERY_RESULT); + await expect( + harness.transport.call('execute_query_batch', { + connectionId: 'query-fixture', + queries: ['SELECT 1 AS value'], + limit: 100, + page: 1, + batchId: 'batch-contract-1', + }), + ).resolves.toEqual([{result: QUERY_RESULT, error: null, execution_time_ms: 1}]); + await expect( + harness.transport.call('count_query', { + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + }), + ).resolves.toBe(1); + await expect( + harness.transport.call('get_server_now', { + connectionId: 'query-fixture', + }), + ).resolves.toBe('2026-08-22 00:00:00'); + await expect( + harness.transport.call('explain_query_plan', { + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + analyze: false, + }), + ).resolves.toEqual({ + kind: 'raw', + raw: { + engine: 'sqlite', + format: 'sqlite-eqp-rows', + payload: '[]', + original_query: 'SELECT 1 AS value', + }, + }); + await expect( + harness.transport.call('cancel_query', { + connectionId: 'query-fixture', + queryRequestId: 'query-request-1', + }), + ).resolves.toBeNull(); + }); + + it('preserves saved query and query history contracts', async () => { + const savedQuery = { + id: 'saved-query-1', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'app', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }; + await expect( + harness.transport.call('get_saved_queries', { + connectionId: 'saved-query-fixture', + }), + ).resolves.toEqual([savedQuery]); + await expect( + harness.transport.call('save_query', { + connectionId: 'saved-query-fixture', + name: savedQuery.name, + sql: savedQuery.sql, + database: 'app', + }), + ).resolves.toEqual(savedQuery); + await expect( + harness.transport.call('update_saved_query', { + connectionId: 'saved-query-fixture', + id: savedQuery.id, + name: 'Recently active users', + sql: savedQuery.sql, + database: 'analytics', + }), + ).resolves.toEqual({ + ...savedQuery, + name: 'Recently active users', + database: 'analytics', + }); + await expect( + harness.transport.call('delete_saved_query', { + connectionId: 'saved-query-fixture', + id: savedQuery.id, + }), + ).resolves.toBeNull(); + + const historyEntry = { + id: 'history-1', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success' as const, + rowsAffected: 1, + error: null, + database: 'app', + }; + await expect( + harness.transport.call('get_query_history', { + connectionId: 'saved-query-fixture', + }), + ).resolves.toEqual({ + entries: [historyEntry], + recoveredBackupPath: null, + }); + await expect( + harness.transport.call('add_query_history_entry', { + connectionId: 'saved-query-fixture', + sql: historyEntry.sql, + executedAt: historyEntry.executedAt, + executionTimeMs: historyEntry.executionTimeMs, + status: historyEntry.status, + rowsAffected: historyEntry.rowsAffected, + error: null, + database: 'app', + }), + ).resolves.toEqual(historyEntry); + await expect( + harness.transport.call('delete_query_history_entry', { + connectionId: 'saved-query-fixture', + id: historyEntry.id, + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('clear_query_history', { + connectionId: 'saved-query-fixture', + }), + ).resolves.toBeNull(); + }); + + it('preserves notebook CRUD contracts and file format content', async () => { + const notebook = { + version: 2, + title: 'Revenue', + createdAt: '2026-08-22T00:00:00Z', + connectionId: 'notebook-fixture', + cells: [{type: 'sql', content: 'SELECT 42', name: 'Answer'}], + }; + const content = JSON.stringify(notebook); + const target = { + connectionId: 'notebook-fixture', + notebookId: 'notebook-1', + }; + + await expect( + harness.transport.call('create_notebook', {...target, content}), + ).resolves.toBeNull(); + await expect( + harness.transport.call('save_notebook', {...target, content}), + ).resolves.toBeNull(); + await expect(harness.transport.call('load_notebook', target)).resolves.toBe(content); + await expect( + harness.transport.call('rename_notebook', { + ...target, + title: 'Revenue 2026', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('list_notebooks', { + connectionId: target.connectionId, + }), + ).resolves.toEqual([ + { + id: target.notebookId, + title: 'Revenue 2026', + createdAt: notebook.createdAt, + updatedAt: '2026-08-22T00:01:00Z', + }, + ]); + await expect(harness.transport.call('delete_notebook', target)).resolves.toBeNull(); + }); + + it('preserves data editing and blob contracts', async () => { + const locator = { + connectionId: 'record-fixture', + table: 'files', + database: 'main', + schema: 'public', + }; + await expect( + harness.transport.call('insert_record', { + ...locator, + data: {id: 1, name: 'before', payload: null}, + }), + ).resolves.toBe(1); + await expect( + harness.transport.call('update_record', { + ...locator, + pkMap: {id: 1}, + colName: 'name', + newVal: 'after', + }), + ).resolves.toBe(1); + await expect( + harness.transport.call('fetch_blob', { + ...locator, + pkMap: {id: 1}, + colName: 'payload', + }), + ).resolves.toEqual({ + kind: 'inline', + wireValue: 'BLOB:4:application/octet-stream:AAECAw==', + }); + await expect( + harness.transport.call('delete_record', { + ...locator, + pkMap: {id: 1}, + }), + ).resolves.toBe(1); + }); + + it('preserves settings and session preference contracts', async () => { + await expect(harness.transport.call('get_config', undefined)).resolves.toEqual({ + theme: 'tabularis-dark', + resultPageSize: 500, + }); + await expect( + harness.transport.call('save_config', { + config: {language: 'en', resultPageSize: 250}, + }), + ).resolves.toBeNull(); + await expect(harness.transport.call('get_keybindings', undefined)).resolves.toEqual({ + 'editor.run': { + mac: {key: 'Enter', metaKey: true}, + win: {key: 'Enter', ctrlKey: true}, + }, + }); + await expect( + harness.transport.call('save_keybindings', {keybindings: {}}), + ).resolves.toBeNull(); + await expect(harness.transport.call('get_all_themes', undefined)).resolves.toEqual([]); + await expect(harness.transport.call('get_system_prompt', undefined)).resolves.toBe( + 'Generate SQL only', + ); + await expect( + harness.transport.call('save_system_prompt', {prompt: 'Generate safe SQL'}), + ).resolves.toBeNull(); + await expect(harness.transport.call('reset_system_prompt', undefined)).resolves.toBe( + 'Generate SQL only', + ); + await expect( + harness.transport.call('load_editor_preferences', { + connectionId: 'preference-fixture', + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('save_editor_preferences', { + connectionId: 'preference-fixture', + preferences: {tabs: [], active_tab_id: null}, + }), + ).resolves.toBeNull(); + await expect( + harness.transport.call('get_last_open_connections', undefined), + ).resolves.toEqual(['preference-fixture']); + await expect( + harness.transport.call('set_last_active_connection', { + connectionId: 'preference-fixture', + }), + ).resolves.toBeNull(); + }); + + it('preserves complex JSON serialization without coercion', async () => { + const result = await harness.transport.callUnmigrated( + 'contract_serialization_fixture', + {fixture: 'complex-query-result'}, + { + task: 'WEB-043', + callSite: 'packages/web-ui/tests/api/contract/transportContract.ts:58', + reason: 'Test-only command for transport serialization parity', + }, + {requestId: 'contract-serialization-request'}, + ); + + expect(result).toEqual(serializationFixture); + }); + + it('normalizes failures to the shared error contract', async () => { + const error = await harness.transport + .call( + 'cancel_query', + {connectionId: 'missing-connection'}, + {requestId: 'contract-error-request'}, + ) + .catch((caught: unknown) => caught); + + expect(error).toMatchObject({ + name: 'TabularisClientError', + message: 'No running query found', + details: null, + requestId: 'contract-error-request', + }); + expect(error).toHaveProperty('code'); + }); + }); +} + +export async function createLiveWebContractServer( + serializationFixture: unknown, +): Promise { + const server = createServer((request, response) => { + void handleRequest(request, response, serializationFixture); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + server.off('error', reject); + resolve(); + }); + }); + + const address = server.address() as AddressInfo | null; + if (!address) { + server.close(); + throw new Error('The live contract server did not expose an address'); + } + + return { + baseUrl: `http://127.0.0.1:${address.port}`, + close: () => + new Promise((resolve, reject) => { + server.close((error) => { + if (error) reject(error); + else resolve(); + }); + }), + }; +} + +async function handleRequest( + request: IncomingMessage, + response: ServerResponse, + serializationFixture: unknown, +): Promise { + if (request.method === 'GET' && request.url === '/api/v1/session') { + sendJson(response, 200, SESSION, 'contract-session-request'); + return; + } + + const command = request.url?.match(/^\/api\/v1\/rpc\/([^/?]+)$/)?.[1]; + if (request.method !== 'POST' || !command) { + sendJson(response, 404, {error: 'not found'}, 'contract-not-found'); + return; + } + + const requestId = headerValue(request, 'x-request-id') ?? 'missing-request-id'; + if ( + headerValue(request, 'content-type') !== 'application/json' || + headerValue(request, 'x-tabularis-csrf') !== SESSION.csrfToken + ) { + sendFailure(response, 400, 'INVALID_HEADERS', 'Invalid RPC headers', requestId); + return; + } + + const body = await readBody(request); + if (command === 'is_debug_mode' && body === 'null') { + sendSuccess(response, true, requestId); + return; + } + if (command === 'get_connections_with_groups' && body === 'null') { + sendSuccess(response, {groups: [], connections: []}, requestId); + return; + } + if ( + (command === 'get_ssh_connections' || command === 'get_k8s_connections') && + body === 'null' + ) { + sendSuccess(response, [], requestId); + return; + } + if ( + command === 'get_tables' && + body === JSON.stringify({connectionId: 'metadata-fixture', schema: 'public'}) + ) { + sendSuccess(response, [{name: 'users', schema: 'public'}], requestId); + return; + } + if ( + command === 'get_columns' && + body === + JSON.stringify({ + connectionId: 'metadata-fixture', + tableName: 'users', + schema: 'public', + }) + ) { + sendSuccess( + response, + [ + { + name: 'id', + data_type: 'integer', + is_pk: true, + is_nullable: false, + is_auto_increment: true, + }, + ], + requestId, + ); + return; + } + if ( + command === 'get_selected_schemas' && + body === JSON.stringify({connectionId: 'metadata-fixture'}) + ) { + sendSuccess(response, ['public'], requestId); + return; + } + if ( + command === 'get_ui_state' && + body === JSON.stringify({keys: ['tabularis_sidebar_width']}) + ) { + sendSuccess(response, {tabularis_sidebar_width: 320}, requestId); + return; + } + if ( + command === 'set_ui_state' && + body === JSON.stringify({key: 'tabularis_sidebar_width', value: 280}) + ) { + sendSuccess(response, null, requestId); + return; + } + if (command === 'get_theme_catalog' && body === 'null') { + sendSuccess(response, {themes: [], issues: []}, requestId); + return; + } + const notebookContent = JSON.stringify({ + version: 2, + title: 'Revenue', + createdAt: '2026-08-22T00:00:00Z', + connectionId: 'notebook-fixture', + cells: [{type: 'sql', content: 'SELECT 42', name: 'Answer'}], + }); + const notebookTarget = { + connectionId: 'notebook-fixture', + notebookId: 'notebook-1', + }; + const queryRequests: Record = { + create_notebook: { + request: {...notebookTarget, content: notebookContent}, + response: null, + }, + save_notebook: { + request: {...notebookTarget, content: notebookContent}, + response: null, + }, + load_notebook: { + request: notebookTarget, + response: notebookContent, + }, + rename_notebook: { + request: {...notebookTarget, title: 'Revenue 2026'}, + response: null, + }, + list_notebooks: { + request: {connectionId: 'notebook-fixture'}, + response: [ + { + id: 'notebook-1', + title: 'Revenue 2026', + createdAt: '2026-08-22T00:00:00Z', + updatedAt: '2026-08-22T00:01:00Z', + }, + ], + }, + delete_notebook: { + request: notebookTarget, + response: null, + }, + export_connections_file: { + request: {mode: 'noSecrets', connectionIds: ['connection-fixture']}, + response: { + kind: 'inline', + fileName: 'tabularis-connections.json', + mimeType: 'application/json', + contents: '{"version":1}', + }, + }, + list_connection_import_sources: {request: null, response: []}, + get_connections_backup_status: { + request: null, + response: { + passwordSet: true, + targetPasswordSet: true, + lastBackupAt: null, + targetKind: 'serverDirectory', + targetDisplay: '/srv/tabularis/backups', + }, + }, + set_connections_backup_password: { + request: {password: 'backup-password'}, + response: null, + }, + run_connections_backup: { + request: null, + response: { + serverLocation: '/srv/tabularis/backups/tabularis-backup.json', + targetKind: 'serverDirectory', + download: null, + }, + }, + export_query_to_file: { + request: { + connectionId: 'query-export-fixture', + query: 'SELECT 1 AS value', + format: 'csv', + csvDelimiter: ';', + }, + response: { + kind: 'download', + fileName: 'result.csv', + mimeType: 'text/csv', + token: 'query-export-download-token', + size: 14, + }, + }, + cancel_export: { + request: {connectionId: 'query-export-fixture'}, + response: null, + }, + export_ai_activity_json: { + request: null, + response: '{"id":"activity-1"}\n', + }, + export_ai_activity_csv: { + request: null, + response: 'id,status\nactivity-1,success\n', + }, + export_ai_session_as_notebook: { + request: {sessionId: 'ai-session-fixture'}, + response: {title: 'AI session', cells: []}, + }, + export_logs: { + request: {}, + response: { + kind: 'download', + fileName: 'tabularis-logs.log', + mimeType: 'text/plain', + token: 'logs-download-token', + size: 64, + }, + }, + set_ai_key: { + request: {provider: 'openai', key: 'write-only-contract-key'}, + response: null, + }, + check_ai_key_status: { + request: {provider: 'openai'}, + response: {configured: true, fromEnv: false}, + }, + get_ai_models: { + request: {forceRefresh: false}, + response: {openai: ['gpt-contract']}, + }, + generate_ai_query: { + request: { + req: { + provider: 'openai', + model: 'gpt-contract', + prompt: 'Select one', + schema: 'table values(id integer)', + }, + }, + response: 'SELECT 1', + }, + get_ai_activity: { + request: {filter: {status: 'success'}}, + response: [], + }, + list_pending_approvals: {request: null, response: []}, + decide_pending_approval: { + request: { + approvalId: 'approval-contract', + decision: 'deny', + reason: 'contract fixture', + }, + response: null, + }, + delete_ai_key: { + request: {provider: 'openai'}, + response: null, + }, + get_mcp_status: { + request: null, + response: [ + { + client_id: 'claude', + client_name: 'Claude Desktop', + installed: false, + config_path: '/home/test/.config/Claude/claude_desktop_config.json', + executable_path: '/usr/bin/tabularis', + client_type: 'file', + manual_command: null, + }, + ], + }, + install_mcp_config: { + request: {clientId: 'claude'}, + response: 'Claude Desktop', + }, + fetch_plugin_registry: { + request: null, + response: [PLUGIN_REGISTRY_ENTRY], + }, + fetch_tabularium_plugin_preview: { + request: { + slug: 'postgres-driver', + registryUrl: null, + version: '1.2.3', + }, + response: { + ...PLUGIN_REGISTRY_ENTRY, + install_action: 'install', + signature: 'verified', + }, + }, + fetch_plugin_readme: { + request: { + slug: 'postgres-driver', + locale: 'en', + registryUrl: null, + }, + response: { + html: '

Contract plugin

', + locale: 'en', + available_locales: ['en'], + documentation_url: null, + repo_url: 'https://example.com/postgres-driver', + }, + }, + get_installed_plugins: {request: null, response: []}, + get_plugin_manifest: { + request: {pluginId: 'postgres-driver'}, + response: PLUGIN_MANIFEST, + }, + get_plugin_startup_errors: {request: null, response: []}, + cancel_plugin_install: { + request: {pluginId: 'postgres-driver'}, + response: true, + }, + install_plugin: { + request: { + pluginId: 'postgres-driver', + version: '1.2.3', + registryUrl: 'https://registry.example/api', + }, + response: null, + }, + disable_plugin: { + request: {pluginId: 'postgres-driver'}, + response: null, + }, + enable_plugin: { + request: {pluginId: 'postgres-driver'}, + response: null, + }, + kill_plugin_process: { + request: {pluginId: 'postgres-driver'}, + response: null, + }, + restart_plugin_process: { + request: {pluginId: 'postgres-driver'}, + response: null, + }, + uninstall_plugin: { + request: {pluginId: 'postgres-driver'}, + response: null, + }, + get_logs: { + request: {request: {limit: 100, level_filter: 'ERROR'}}, + response: [ + { + timestamp: '2026-08-22 09:00:00.000', + level: 'ERROR', + message: 'Contract log', + target: 'contract', + }, + ], + }, + get_log_settings: { + request: null, + response: {enabled: true, max_size: 1000, current_count: 1}, + }, + get_process_list: { + request: null, + response: [ + { + plugin_id: 'postgres-driver', + plugin_name: 'PostgreSQL Driver', + pid: 4100, + cpu_percent: 1.5, + memory_bytes: 2048, + disk_read_bytes: 128, + disk_write_bytes: 64, + status: 'running', + children: [], + }, + ], + }, + get_system_stats: { + request: null, + response: { + cpu_percent: 12.5, + memory_used: 4096, + memory_total: 8192, + disk_read_bytes: 256, + disk_write_bytes: 128, + process_count: 4, + tabularis: null, + }, + }, + get_tabularis_children: { + request: null, + response: [ + { + pid: 4200, + name: 'tabularis-plugin', + cpu_percent: 0.5, + memory_bytes: 1024, + }, + ], + }, + set_log_enabled: {request: {enabled: false}, response: null}, + set_log_max_size: {request: {maxSize: 500}, response: null}, + clear_logs: {request: null, response: null}, + dump_database: { + request: { + connectionId: 'database-transfer-fixture', + options: {structure: true, data: true, tables: ['users']}, + schema: 'public', + }, + response: { + kind: 'download', + fileName: 'database-transfer-fixture.sql', + mimeType: 'application/sql', + token: 'database-transfer-download-token', + size: 128, + }, + }, + import_database: { + request: { + connectionId: 'database-transfer-fixture', + uploadToken: 'database-transfer-upload-token', + schema: 'public', + }, + response: null, + }, + cancel_dump: { + request: {connectionId: 'database-transfer-fixture'}, + response: null, + }, + cancel_import: { + request: {connectionId: 'database-transfer-fixture'}, + response: null, + }, + get_saved_queries: { + request: {connectionId: 'saved-query-fixture'}, + response: [ + { + id: 'saved-query-1', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'app', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }, + ], + }, + save_query: { + request: { + connectionId: 'saved-query-fixture', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + database: 'app', + }, + response: { + id: 'saved-query-1', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'app', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }, + }, + update_saved_query: { + request: { + connectionId: 'saved-query-fixture', + id: 'saved-query-1', + name: 'Recently active users', + sql: 'SELECT * FROM users WHERE active = 1', + database: 'analytics', + }, + response: { + id: 'saved-query-1', + name: 'Recently active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'analytics', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }, + }, + delete_saved_query: { + request: {connectionId: 'saved-query-fixture', id: 'saved-query-1'}, + response: null, + }, + get_query_history: { + request: {connectionId: 'saved-query-fixture'}, + response: { + entries: [ + { + id: 'history-1', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success', + rowsAffected: 1, + error: null, + database: 'app', + }, + ], + recoveredBackupPath: null, + }, + }, + add_query_history_entry: { + request: { + connectionId: 'saved-query-fixture', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success', + rowsAffected: 1, + error: null, + database: 'app', + }, + response: { + id: 'history-1', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success', + rowsAffected: 1, + error: null, + database: 'app', + }, + }, + delete_query_history_entry: { + request: {connectionId: 'saved-query-fixture', id: 'history-1'}, + response: null, + }, + clear_query_history: { + request: {connectionId: 'saved-query-fixture'}, + response: null, + }, + get_config: { + request: null, + response: {theme: 'tabularis-dark', resultPageSize: 500}, + }, + save_config: { + request: {config: {language: 'en', resultPageSize: 250}}, + response: null, + }, + get_keybindings: { + request: null, + response: { + 'editor.run': { + mac: {key: 'Enter', metaKey: true}, + win: {key: 'Enter', ctrlKey: true}, + }, + }, + }, + save_keybindings: {request: {keybindings: {}}, response: null}, + get_all_themes: {request: null, response: []}, + get_system_prompt: {request: null, response: 'Generate SQL only'}, + save_system_prompt: { + request: {prompt: 'Generate safe SQL'}, + response: null, + }, + reset_system_prompt: {request: null, response: 'Generate SQL only'}, + load_editor_preferences: { + request: {connectionId: 'preference-fixture'}, + response: null, + }, + save_editor_preferences: { + request: { + connectionId: 'preference-fixture', + preferences: {tabs: [], active_tab_id: null}, + }, + response: null, + }, + get_last_open_connections: { + request: null, + response: ['preference-fixture'], + }, + set_last_active_connection: { + request: {connectionId: 'preference-fixture'}, + response: null, + }, + get_view_definition: { + request: { + connectionId: 'object-fixture', + viewName: 'active_users', + schema: 'public', + }, + response: 'SELECT id FROM users WHERE active = 1', + }, + get_routine_parameters: { + request: { + connectionId: 'object-fixture', + routineName: 'refresh_users', + schema: 'public', + }, + response: [ + { + name: 'batch_size', + data_type: 'integer', + mode: 'IN', + ordinal_position: 1, + }, + ], + }, + get_trigger_definition: { + request: { + connectionId: 'object-fixture', + triggerName: 'audit_users', + tableName: 'users', + schema: 'public', + }, + response: 'CREATE TRIGGER audit_users AFTER UPDATE ON users', + }, + get_create_index_sql: { + request: { + connectionId: 'object-fixture', + table: 'users', + indexName: 'idx_users_email', + columns: ['email'], + isUnique: true, + schema: 'public', + }, + response: ['CREATE UNIQUE INDEX "idx_users_email" ON "public"."users" ("email")'], + }, + get_db_users: { + request: {connectionId: 'object-fixture'}, + response: [{user: 'app', host: '%', locked: false}], + }, + apply_db_user_privileges: { + request: { + connectionId: 'object-fixture', + user: 'app', + host: '%', + database: 'app_db', + table: null, + privileges: ['SELECT'], + grant: true, + }, + response: null, + }, + insert_record: { + request: { + connectionId: 'record-fixture', + table: 'files', + database: 'main', + schema: 'public', + data: {id: 1, name: 'before', payload: null}, + }, + response: 1, + }, + update_record: { + request: { + connectionId: 'record-fixture', + table: 'files', + database: 'main', + schema: 'public', + pkMap: {id: 1}, + colName: 'name', + newVal: 'after', + }, + response: 1, + }, + fetch_blob: { + request: { + connectionId: 'record-fixture', + table: 'files', + database: 'main', + schema: 'public', + pkMap: {id: 1}, + colName: 'payload', + }, + response: { + kind: 'inline', + wireValue: 'BLOB:4:application/octet-stream:AAECAw==', + }, + }, + delete_record: { + request: { + connectionId: 'record-fixture', + table: 'files', + database: 'main', + schema: 'public', + pkMap: {id: 1}, + }, + response: 1, + }, + execute_query: { + request: { + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + limit: 100, + page: 1, + }, + response: QUERY_RESULT, + }, + execute_query_batch: { + request: { + connectionId: 'query-fixture', + queries: ['SELECT 1 AS value'], + limit: 100, + page: 1, + batchId: 'batch-contract-1', + }, + response: [{result: QUERY_RESULT, error: null, execution_time_ms: 1}], + }, + count_query: { + request: {connectionId: 'query-fixture', query: 'SELECT 1 AS value'}, + response: 1, + }, + get_server_now: { + request: {connectionId: 'query-fixture'}, + response: '2026-08-22 00:00:00', + }, + explain_query_plan: { + request: { + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + analyze: false, + }, + response: { + kind: 'raw', + raw: { + engine: 'sqlite', + format: 'sqlite-eqp-rows', + payload: '[]', + original_query: 'SELECT 1 AS value', + }, + }, + }, + cancel_query: { + request: { + connectionId: 'query-fixture', + queryRequestId: 'query-request-1', + }, + response: null, + }, + }; + const queryFixture = queryRequests[command] as + {request: unknown; response: unknown} | undefined; + if (queryFixture && body === JSON.stringify(queryFixture.request)) { + sendSuccess(response, queryFixture.response, requestId); + return; + } + if ( + command === 'contract_serialization_fixture' && + body === JSON.stringify({fixture: 'complex-query-result'}) + ) { + sendSuccess(response, serializationFixture, requestId); + return; + } + if ( + command === 'cancel_query' && + body === JSON.stringify({connectionId: 'missing-connection'}) + ) { + sendFailure( + response, + 409, + 'QUERY_CANCELLATION_FAILED', + 'No running query found', + requestId, + ); + return; + } + + sendFailure(response, 400, 'CONTRACT_DRIFT', 'Unexpected RPC request', requestId); +} + +function sendSuccess(response: ServerResponse, data: unknown, requestId: string): void { + sendJson(response, 200, {ok: true, data}, requestId); +} + +function sendFailure( + response: ServerResponse, + status: number, + code: string, + message: string, + requestId: string, +): void { + sendJson( + response, + status, + {ok: false, error: {code, message, details: null, requestId}}, + requestId, + ); +} + +function sendJson( + response: ServerResponse, + status: number, + body: unknown, + requestId: string, +): void { + response.writeHead(status, { + 'content-type': 'application/json', + 'x-request-id': requestId, + }); + response.end(JSON.stringify(body)); +} + +function headerValue(request: IncomingMessage, name: string): string | undefined { + const value = request.headers[name]; + return Array.isArray(value) ? value[0] : value; +} + +async function readBody(request: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of request) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + return Buffer.concat(chunks).toString('utf8'); +} diff --git a/packages/web-ui/tests/api/dualTransportContract.test.ts b/packages/web-ui/tests/api/dualTransportContract.test.ts new file mode 100644 index 000000000..f8a18b499 --- /dev/null +++ b/packages/web-ui/tests/api/dualTransportContract.test.ts @@ -0,0 +1,555 @@ +import {invoke} from '@tauri-apps/api/core'; +import {expect, vi} from 'vitest'; +import {HttpTransport} from '@/api/transports/httpTransport'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import serializationFixture from '../fixtures/transportSerialization.json'; +import { + createLiveWebContractServer, + defineTransportContractSuite, +} from './contract/transportContract'; + +defineTransportContractSuite('Tauri adapter mock', serializationFixture, async () => { + vi.mocked(invoke).mockImplementation(async (command, request) => { + if (command === 'is_debug_mode') { + expect(request).toBeUndefined(); + return true; + } + if (command === 'get_connections_with_groups') { + expect(request).toBeUndefined(); + return {groups: [], connections: []}; + } + if (command === 'get_ssh_connections' || command === 'get_k8s_connections') { + expect(request).toBeUndefined(); + return []; + } + if (command === 'export_connections_file') { + expect(request).toEqual({ + mode: 'noSecrets', + connectionIds: ['connection-fixture'], + }); + return { + kind: 'inline', + fileName: 'tabularis-connections.json', + mimeType: 'application/json', + contents: '{"version":1}', + }; + } + if (command === 'list_connection_import_sources') return []; + if (command === 'get_connections_backup_status') { + return { + passwordSet: true, + targetPasswordSet: true, + lastBackupAt: null, + targetKind: 'serverDirectory', + targetDisplay: '/srv/tabularis/backups', + }; + } + if (command === 'set_connections_backup_password') return null; + if (command === 'run_connections_backup') { + return { + serverLocation: '/srv/tabularis/backups/tabularis-backup.json', + targetKind: 'serverDirectory', + download: null, + }; + } + if (command === 'export_query_to_file') { + expect(request).toEqual({ + connectionId: 'query-export-fixture', + query: 'SELECT 1 AS value', + format: 'csv', + csvDelimiter: ';', + }); + return { + kind: 'download', + fileName: 'result.csv', + mimeType: 'text/csv', + token: 'query-export-download-token', + size: 14, + }; + } + if (command === 'cancel_export') return null; + if (command === 'export_ai_activity_json') { + return '{"id":"activity-1"}\n'; + } + if (command === 'export_ai_activity_csv') { + return 'id,status\nactivity-1,success\n'; + } + if (command === 'export_ai_session_as_notebook') { + return {title: 'AI session', cells: []}; + } + if (command === 'export_logs') { + return { + kind: 'download', + fileName: 'tabularis-logs.log', + mimeType: 'text/plain', + token: 'logs-download-token', + size: 64, + }; + } + if (command === 'set_ai_key' || command === 'delete_ai_key') return null; + if (command === 'check_ai_key_status') { + return {configured: true, fromEnv: false}; + } + if (command === 'get_ai_models') return {openai: ['gpt-contract']}; + if (command === 'generate_ai_query') return 'SELECT 1'; + if (command === 'get_ai_activity' || command === 'list_pending_approvals') { + return []; + } + if (command === 'decide_pending_approval') return null; + if (command === 'get_mcp_status') { + expect(request).toBeUndefined(); + return [ + { + client_id: 'claude', + client_name: 'Claude Desktop', + installed: false, + config_path: '/home/test/.config/Claude/claude_desktop_config.json', + executable_path: '/usr/bin/tabularis', + client_type: 'file', + manual_command: null, + }, + ]; + } + if (command === 'install_mcp_config') { + expect(request).toEqual({clientId: 'claude'}); + return 'Claude Desktop'; + } + if (command === 'fetch_plugin_registry') { + return [ + { + id: 'postgres-driver', + name: 'PostgreSQL Driver', + description: 'Contract plugin', + author: 'Tabularis', + homepage: 'https://example.com/postgres-driver', + latest_version: '1.2.3', + releases: [ + { + version: '1.2.3', + min_tabularis_version: null, + platform_supported: true, + }, + ], + installed_version: null, + update_available: false, + platform_supported: true, + }, + ]; + } + if (command === 'fetch_tabularium_plugin_preview') { + return { + id: 'postgres-driver', + name: 'PostgreSQL Driver', + description: 'Contract plugin', + author: 'Tabularis', + homepage: 'https://example.com/postgres-driver', + latest_version: '1.2.3', + releases: [ + { + version: '1.2.3', + min_tabularis_version: null, + platform_supported: true, + }, + ], + installed_version: null, + update_available: false, + platform_supported: true, + install_action: 'install', + signature: 'verified', + }; + } + if (command === 'fetch_plugin_readme') { + return { + html: '

Contract plugin

', + locale: 'en', + available_locales: ['en'], + documentation_url: null, + repo_url: 'https://example.com/postgres-driver', + }; + } + if (command === 'get_plugin_manifest') { + return { + id: 'postgres-driver', + name: 'PostgreSQL Driver', + version: '1.2.3', + description: 'Contract plugin', + default_port: 5432, + is_builtin: false, + capabilities: { + schemas: true, + views: true, + routines: true, + file_based: false, + folder_based: false, + identifier_quote: '"', + alter_primary_key: false, + }, + }; + } + if (command === 'get_installed_plugins' || command === 'get_plugin_startup_errors') { + return []; + } + if (command === 'cancel_plugin_install') return true; + if ( + command === 'install_plugin' || + command === 'disable_plugin' || + command === 'enable_plugin' || + command === 'kill_plugin_process' || + command === 'restart_plugin_process' || + command === 'uninstall_plugin' + ) { + return null; + } + if (command === 'get_logs') { + expect(request).toEqual({ + request: {limit: 100, level_filter: 'ERROR'}, + }); + return [ + { + timestamp: '2026-08-22 09:00:00.000', + level: 'ERROR', + message: 'Contract log', + target: 'contract', + }, + ]; + } + if (command === 'get_log_settings') { + return {enabled: true, max_size: 1000, current_count: 1}; + } + if (command === 'get_process_list') { + return [ + { + plugin_id: 'postgres-driver', + plugin_name: 'PostgreSQL Driver', + pid: 4100, + cpu_percent: 1.5, + memory_bytes: 2048, + disk_read_bytes: 128, + disk_write_bytes: 64, + status: 'running', + children: [], + }, + ]; + } + if (command === 'get_system_stats') { + return { + cpu_percent: 12.5, + memory_used: 4096, + memory_total: 8192, + disk_read_bytes: 256, + disk_write_bytes: 128, + process_count: 4, + tabularis: null, + }; + } + if (command === 'get_tabularis_children') { + return [ + { + pid: 4200, + name: 'tabularis-plugin', + cpu_percent: 0.5, + memory_bytes: 1024, + }, + ]; + } + if ( + command === 'set_log_enabled' || + command === 'set_log_max_size' || + command === 'clear_logs' + ) { + return null; + } + if (command === 'dump_database') { + expect(request).toEqual({ + connectionId: 'database-transfer-fixture', + options: {structure: true, data: true, tables: ['users']}, + schema: 'public', + }); + return { + kind: 'download', + fileName: 'database-transfer-fixture.sql', + mimeType: 'application/sql', + token: 'database-transfer-download-token', + size: 128, + }; + } + if (command === 'import_database') { + expect(request).toEqual({ + connectionId: 'database-transfer-fixture', + uploadToken: 'database-transfer-upload-token', + schema: 'public', + }); + return null; + } + if (command === 'cancel_dump' || command === 'cancel_import') { + expect(request).toEqual({connectionId: 'database-transfer-fixture'}); + return null; + } + if (command === 'get_tables') { + expect(request).toEqual({ + connectionId: 'metadata-fixture', + schema: 'public', + }); + return [{name: 'users', schema: 'public'}]; + } + if (command === 'get_columns') { + expect(request).toEqual({ + connectionId: 'metadata-fixture', + tableName: 'users', + schema: 'public', + }); + return [ + { + name: 'id', + data_type: 'integer', + is_pk: true, + is_nullable: false, + is_auto_increment: true, + }, + ]; + } + if (command === 'get_selected_schemas') { + expect(request).toEqual({connectionId: 'metadata-fixture'}); + return ['public']; + } + if (command === 'get_ui_state') { + expect(request).toEqual({keys: ['tabularis_sidebar_width']}); + return {tabularis_sidebar_width: 320}; + } + if (command === 'set_ui_state') { + expect(request).toEqual({key: 'tabularis_sidebar_width', value: 280}); + return null; + } + if (command === 'get_theme_catalog') { + expect(request).toBeUndefined(); + return {themes: [], issues: []}; + } + if (command === 'create_notebook' || command === 'save_notebook') { + return null; + } + if (command === 'load_notebook') { + return JSON.stringify({ + version: 2, + title: 'Revenue', + createdAt: '2026-08-22T00:00:00Z', + connectionId: 'notebook-fixture', + cells: [{type: 'sql', content: 'SELECT 42', name: 'Answer'}], + }); + } + if (command === 'rename_notebook' || command === 'delete_notebook') { + return null; + } + if (command === 'list_notebooks') { + return [ + { + id: 'notebook-1', + title: 'Revenue 2026', + createdAt: '2026-08-22T00:00:00Z', + updatedAt: '2026-08-22T00:01:00Z', + }, + ]; + } + if (command === 'get_saved_queries') { + return [ + { + id: 'saved-query-1', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'app', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }, + ]; + } + if (command === 'save_query') { + return { + id: 'saved-query-1', + name: 'Active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'app', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }; + } + if (command === 'update_saved_query') { + return { + id: 'saved-query-1', + name: 'Recently active users', + sql: 'SELECT * FROM users WHERE active = 1', + connection_id: 'saved-query-fixture', + database: 'analytics', + created_at: '2026-08-22T00:00:00Z', + updated_at: '2026-08-22T00:00:00Z', + }; + } + if (command === 'delete_saved_query') return null; + if (command === 'get_query_history') { + return { + entries: [ + { + id: 'history-1', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success', + rowsAffected: 1, + error: null, + database: 'app', + }, + ], + recoveredBackupPath: null, + }; + } + if (command === 'add_query_history_entry') { + return { + id: 'history-1', + sql: 'SELECT 1', + executedAt: '2026-08-22T00:00:00Z', + executionTimeMs: 2.5, + status: 'success', + rowsAffected: 1, + error: null, + database: 'app', + }; + } + if (command === 'delete_query_history_entry' || command === 'clear_query_history') { + return null; + } + if (command === 'get_config') { + expect(request).toBeUndefined(); + return {theme: 'tabularis-dark', resultPageSize: 500}; + } + if (command === 'save_config') return null; + if (command === 'get_keybindings') { + return { + 'editor.run': { + mac: {key: 'Enter', metaKey: true}, + win: {key: 'Enter', ctrlKey: true}, + }, + }; + } + if (command === 'save_keybindings') return null; + if (command === 'get_all_themes') return []; + if (command === 'get_system_prompt' || command === 'reset_system_prompt') { + return 'Generate SQL only'; + } + if (command === 'save_system_prompt') return null; + if (command === 'load_editor_preferences') return null; + if (command === 'save_editor_preferences') return null; + if (command === 'get_last_open_connections') { + return ['preference-fixture']; + } + if (command === 'set_last_active_connection') return null; + if (command === 'get_view_definition') { + return 'SELECT id FROM users WHERE active = 1'; + } + if (command === 'get_routine_parameters') { + return [ + { + name: 'batch_size', + data_type: 'integer', + mode: 'IN', + ordinal_position: 1, + }, + ]; + } + if (command === 'get_trigger_definition') { + return 'CREATE TRIGGER audit_users AFTER UPDATE ON users'; + } + if (command === 'get_create_index_sql') { + return ['CREATE UNIQUE INDEX "idx_users_email" ON "public"."users" ("email")']; + } + if (command === 'get_db_users') { + return [{user: 'app', host: '%', locked: false}]; + } + if (command === 'apply_db_user_privileges') return null; + if ( + command === 'insert_record' || + command === 'update_record' || + command === 'delete_record' + ) { + return 1; + } + if (command === 'fetch_blob') { + return { + kind: 'inline', + wireValue: 'BLOB:4:application/octet-stream:AAECAw==', + }; + } + if (command === 'execute_query') { + expect(request).toEqual({ + connectionId: 'query-fixture', + query: 'SELECT 1 AS value', + limit: 100, + page: 1, + }); + return { + columns: ['value'], + rows: [[1]], + affected_rows: 0, + truncated: false, + pagination: { + page: 1, + page_size: 100, + total_rows: null, + has_more: false, + }, + }; + } + if (command === 'execute_query_batch') { + return [ + { + result: { + columns: ['value'], + rows: [[1]], + affected_rows: 0, + truncated: false, + pagination: { + page: 1, + page_size: 100, + total_rows: null, + has_more: false, + }, + }, + error: null, + execution_time_ms: 1, + }, + ]; + } + if (command === 'count_query') return 1; + if (command === 'get_server_now') return '2026-08-22 00:00:00'; + if (command === 'explain_query_plan') { + return { + kind: 'raw', + raw: { + engine: 'sqlite', + format: 'sqlite-eqp-rows', + payload: '[]', + original_query: 'SELECT 1 AS value', + }, + }; + } + if (command === 'contract_serialization_fixture') { + expect(request).toEqual({fixture: 'complex-query-result'}); + return serializationFixture; + } + if (command === 'cancel_query') { + if ('queryRequestId' in (request as Record)) return null; + expect(request).toEqual({connectionId: 'missing-connection'}); + throw new Error('No running query found'); + } + throw new Error(`Unexpected Tauri command: ${command}`); + }); + + return {transport: new TauriTransport()}; +}); + +defineTransportContractSuite('live web server', serializationFixture, async () => { + const server = await createLiveWebContractServer(serializationFixture); + return { + transport: new HttpTransport({baseUrl: server.baseUrl}), + close: server.close, + }; +}); diff --git a/packages/web-ui/tests/api/representativeSlice.test.ts b/packages/web-ui/tests/api/representativeSlice.test.ts new file mode 100644 index 000000000..735991309 --- /dev/null +++ b/packages/web-ui/tests/api/representativeSlice.test.ts @@ -0,0 +1,152 @@ +import {readFileSync, readdirSync} from 'node:fs'; +import {extname, join, relative} from 'node:path'; +import {invoke} from '@tauri-apps/api/core'; +import {listen, type EventCallback} from '@tauri-apps/api/event'; +import ts from 'typescript'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; + +vi.mock('@tauri-apps/api/event', () => ({ + emit: vi.fn(), + listen: vi.fn(), +})); + +const SOURCE_ROOT = join(process.cwd(), 'packages/web-ui/src'); +const MIGRATED_COMMANDS = new Set([ + 'is_debug_mode', + 'get_connections', + 'test_connection', + 'get_tables', + 'execute_query', + 'cancel_query', +]); +const MIGRATED_EVENTS = new Set(['batch-statement-complete', 'connection-test-progress']); + +interface DirectTauriCall { + api: 'invoke' | 'listen'; + name: string; + file: string; + line: number; +} + +function sourceFiles(directory: string): string[] { + return readdirSync(directory, {withFileTypes: true}).flatMap((entry) => { + const path = join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(path); + return ['.ts', '.tsx'].includes(extname(entry.name)) ? [path] : []; + }); +} + +function findDirectTauriCalls(): DirectTauriCall[] { + return sourceFiles(SOURCE_ROOT).flatMap((file) => { + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true, + file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS, + ); + const calls: DirectTauriCall[] = []; + + const visit = (node: ts.Node) => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + (node.expression.text === 'invoke' || node.expression.text === 'listen') + ) { + const argument = node.arguments[0]; + if (argument && ts.isStringLiteralLike(argument)) { + const names = + node.expression.text === 'invoke' ? MIGRATED_COMMANDS : MIGRATED_EVENTS; + if (names.has(argument.text)) { + const {line} = source.getLineAndCharacterOfPosition(node.getStart(source)); + calls.push({ + api: node.expression.text, + name: argument.text, + file: relative(process.cwd(), file), + line: line + 1, + }); + } + } + } + ts.forEachChild(node, visit); + }; + + visit(source); + return calls; + }); +} + +describe('WEB-013 representative transport slice', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('has no direct Tauri calls for migrated commands and events', () => { + expect(findDirectTauriCalls()).toEqual([]); + }, 15_000); + + it('preserves requests, responses, errors, cancellation, and events', async () => { + const client = new TabularisClient(new TauriTransport()); + const queryResult = {columns: ['value'], rows: [[1]], affected_rows: 0}; + + vi.mocked(invoke) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce('Connection successful') + .mockResolvedValueOnce([{name: 'users'}]) + .mockResolvedValueOnce(queryResult) + .mockRejectedValueOnce(new Error('query failed')) + .mockResolvedValueOnce(undefined); + + await expect(client.call('is_debug_mode', undefined)).resolves.toBe(true); + await expect(client.call('get_connections', undefined)).resolves.toEqual([]); + await expect( + client.call('test_connection', { + request: {params: {driver: 'sqlite', database: 'test.db'}}, + }), + ).resolves.toBe('Connection successful'); + await expect(client.call('get_tables', {connectionId: 'connection-1'})).resolves.toEqual([ + {name: 'users'}, + ]); + await expect( + client.call('execute_query', { + connectionId: 'connection-1', + query: 'SELECT 1', + }), + ).resolves.toEqual(queryResult); + await expect( + client.call('execute_query', { + connectionId: 'connection-1', + query: 'INVALID', + }), + ).rejects.toThrow('query failed'); + await expect( + client.call('cancel_query', {connectionId: 'connection-1'}), + ).resolves.toBeUndefined(); + + const handler = vi.fn(); + const unlisten = vi.fn(); + let callback: + | EventCallback<{ + batch_id: string; + index: number; + statement: {query: string; result: typeof queryResult; error: null}; + }> + | undefined; + vi.mocked(listen).mockImplementationOnce((_event, eventHandler) => { + callback = eventHandler as typeof callback; + return Promise.resolve(unlisten); + }); + + await expect(client.subscribe('batch-statement-complete', handler)).resolves.toBe(unlisten); + const payload = { + batch_id: 'batch-1', + index: 0, + statement: {query: 'SELECT 1', result: queryResult, error: null}, + }; + callback?.({event: 'batch-statement-complete', id: 1, payload}); + expect(handler).toHaveBeenCalledWith(payload); + }); +}); diff --git a/packages/web-ui/tests/api/transports/httpTransport.test.ts b/packages/web-ui/tests/api/transports/httpTransport.test.ts new file mode 100644 index 000000000..a75c6aca5 --- /dev/null +++ b/packages/web-ui/tests/api/transports/httpTransport.test.ts @@ -0,0 +1,966 @@ +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {TabularisClientError} from '@/api/errors'; +import {HttpTransport, type WebSocketLike} from '@/api/transports/httpTransport'; + +const SESSION = { + apiVersion: 'v1', + serverVersion: '0.20.0', + serverBuild: { + target: 'linux-x86_64', + profile: 'release', + commit: 'abc1234', + }, + authenticated: true, + csrfToken: 'csrf-token', + access: { + remote: false, + authorizationLevel: 'local-admin', + highRiskCapabilities: true, + }, + capabilities: { + rpc: true, + events: true, + uploads: false, + downloads: false, + pluginAssets: false, + mcpHostConfiguration: true, + serverFileBrowser: false, + nativeUpdater: false, + }, + queryResponsePolicy: { + maxRowsPerPage: 10_000, + maxResponseBytes: 16_777_216, + streaming: false, + }, +}; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: {'content-type': 'application/json'}, + }); +} + +class FakeWebSocket implements WebSocketLike { + readyState = 0; + onopen: ((event: Event) => void) | null = null; + onmessage: ((event: MessageEvent) => void) | null = null; + onerror: ((event: Event) => void) | null = null; + onclose: ((event: CloseEvent) => void) | null = null; + readonly sent: string[] = []; + acknowledgeSubscriptions = true; + + send(data: string): void { + this.sent.push(data); + const message = JSON.parse(data) as {type: string; events: string[]}; + if (this.acknowledgeSubscriptions && message.type === 'subscribe') { + this.message({type: 'subscribed', events: message.events, replayed: 0}); + } + } + + close(): void { + this.readyState = 3; + } + + open(): void { + this.readyState = 1; + this.onopen?.(new Event('open')); + } + + message(value: unknown): void { + this.onmessage?.(new MessageEvent('message', {data: JSON.stringify(value)})); + } + + disconnect(): void { + this.readyState = 3; + this.onclose?.(new CloseEvent('close')); + } +} + +describe('HttpTransport', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('bootstraps one cookie-backed session and performs typed RPC calls', async () => { + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce(jsonResponse({ok: true, data: true})); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + + await expect(transport.initialize()).resolves.toEqual(SESSION); + await expect( + transport.call('is_debug_mode', undefined, { + requestId: 'request-1', + deadlineMs: 1500, + cancellationId: 'startup-debug', + }), + ).resolves.toBe(true); + + expect(fetchRequest).toHaveBeenCalledTimes(2); + expect(fetchRequest.mock.calls[0]).toEqual([ + 'http://127.0.0.1:8080/api/v1/session', + expect.objectContaining({credentials: 'same-origin', cache: 'no-store'}), + ]); + const [rpcUrl, rpcInit] = fetchRequest.mock.calls[1]; + const headers = new Headers(rpcInit?.headers); + expect(rpcUrl).toBe('http://127.0.0.1:8080/api/v1/rpc/is_debug_mode'); + expect(rpcInit?.body).toBe('null'); + expect(headers.get('content-type')).toBe('application/json'); + expect(headers.get('x-tabularis-csrf')).toBe('csrf-token'); + expect(headers.get('x-request-id')).toBe('request-1'); + expect(headers.get('x-tabularis-deadline-ms')).toBe('1500'); + expect(headers.get('x-tabularis-cancellation-id')).toBe('startup-debug'); + }); + + it('rejects a browser session that advertises native binary updates', async () => { + const transport = new HttpTransport({ + fetch: vi.fn().mockResolvedValueOnce( + jsonResponse({ + ...SESSION, + capabilities: {...SESSION.capabilities, nativeUpdater: true}, + }), + ), + }); + + await expect(transport.initialize()).rejects.toMatchObject({ + code: 'INVALID_SESSION_RESPONSE', + }); + }); + + it('rejects an unknown remote authorization policy', async () => { + const transport = new HttpTransport({ + fetch: vi.fn().mockResolvedValueOnce( + jsonResponse({ + ...SESSION, + access: {...SESSION.access, authorizationLevel: 'super-admin'}, + }), + ), + }); + + await expect(transport.initialize()).rejects.toMatchObject({ + code: 'INVALID_SESSION_RESPONSE', + }); + }); + + it('loads authenticated plugin assets when advertised by the server', async () => { + const pluginSession = { + ...SESSION, + capabilities: {...SESSION.capabilities, pluginAssets: true}, + }; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(pluginSession)) + .mockResolvedValueOnce( + new Response('window.pluginLoaded = true;', { + headers: {'content-type': 'text/javascript'}, + }), + ); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + + await expect(transport.readPluginAsset('my plugin', 'ui/dist/index.js')).resolves.toBe( + 'window.pluginLoaded = true;', + ); + + expect(fetchRequest.mock.calls[1]?.[0]).toBe( + 'http://127.0.0.1:8080/api/v1/assets/plugins/my%20plugin/ui/dist/index.js', + ); + expect(fetchRequest.mock.calls[1]?.[1]).toEqual( + expect.objectContaining({method: 'GET', credentials: 'same-origin'}), + ); + }); + + it('rejects plugin asset reads when the capability is unavailable', async () => { + const transport = new HttpTransport({ + fetch: vi.fn().mockResolvedValueOnce(jsonResponse(SESSION)), + }); + + await expect(transport.readPluginAsset('plugin', 'ui/index.js')).rejects.toMatchObject({ + code: 'PLUGIN_ASSETS_UNAVAILABLE', + }); + }); + + it('uploads connection icons with the authenticated session', async () => { + const uploadSession = { + ...SESSION, + capabilities: {...SESSION.capabilities, uploads: true}, + }; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(uploadSession)) + .mockResolvedValueOnce(jsonResponse({token: 'opaque-upload-token'}, 201)); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + const icon = new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { + type: 'image/png', + }); + + await expect(transport.uploadConnectionIcon(icon)).resolves.toBe('opaque-upload-token'); + + const [url, request] = fetchRequest.mock.calls[1]; + const headers = new Headers(request?.headers); + expect(url).toBe('http://127.0.0.1:8080/api/v1/uploads/connection-icons'); + expect(request?.body).toBe(icon); + expect(headers.get('content-type')).toBe('image/png'); + expect(headers.get('x-tabularis-csrf')).toBe('csrf-token'); + }); + + it('streams purpose-bound generic uploads and consumes token downloads', async () => { + const transferSession = { + ...SESSION, + capabilities: { + ...SESSION.capabilities, + uploads: true, + downloads: true, + }, + }; + const metadata = { + token: 'opaque-file-token', + fileName: 'report.csv', + mimeType: 'text/csv', + size: 7, + expiresAt: '2026-08-22T05:30:00Z', + }; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(transferSession)) + .mockResolvedValueOnce(jsonResponse(metadata, 201)) + .mockResolvedValueOnce( + new Response('a,b\n1,2', {headers: {'content-type': 'text/csv'}}), + ); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + const contents = new Blob(['a,b\n1,2'], {type: 'text/csv'}); + + await expect( + transport.uploadFile({ + contents, + fileName: '../report.csv', + purpose: 'connection-import', + }), + ).resolves.toEqual(metadata); + await expect( + transport.consumeDownload('opaque-file-token').then((file) => file.text()), + ).resolves.toBe('a,b\n1,2'); + + const [uploadUrl, uploadRequest] = fetchRequest.mock.calls[1]; + const uploadHeaders = new Headers(uploadRequest?.headers); + expect(uploadUrl).toBe('http://127.0.0.1:8080/api/v1/uploads'); + expect(uploadRequest?.body).toBe(contents); + expect(uploadHeaders.get('x-tabularis-file-name')).toBe('..%2Freport.csv'); + expect(uploadHeaders.get('x-tabularis-purpose')).toBe('connection-import'); + const [downloadUrl] = fetchRequest.mock.calls[2]; + expect(downloadUrl).toBe('http://127.0.0.1:8080/api/v1/downloads/opaque-file-token'); + }); + + it('hands generic downloads directly to the browser without buffering', async () => { + const transferSession = { + ...SESSION, + capabilities: {...SESSION.capabilities, downloads: true}, + }; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(transferSession)); + const startDownload = vi.fn(); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + startDownload, + }); + + await expect(transport.requestDownload('opaque file token')).resolves.toBeUndefined(); + + expect(startDownload).toHaveBeenCalledWith( + 'http://127.0.0.1:8080/api/v1/downloads/opaque%20file%20token', + ); + expect(fetchRequest).toHaveBeenCalledTimes(1); + }); + + it('uploads BLOBs and consumes single-use downloads with the authenticated session', async () => { + const transferSession = { + ...SESSION, + capabilities: { + ...SESSION.capabilities, + uploads: true, + downloads: true, + }, + }; + const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(transferSession)) + .mockResolvedValueOnce( + jsonResponse( + { + value: 'BLOB_UPLOAD_REF:4:image/png:00000000-0000-4000-8000-000000000000', + }, + 201, + ), + ) + .mockResolvedValueOnce( + new Response(bytes, { + headers: {'content-type': 'image/png'}, + }), + ) + .mockResolvedValueOnce( + new Response(bytes, { + headers: {'content-type': 'image/png'}, + }), + ); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + const file = new Blob([bytes], {type: 'image/png'}); + + await expect(transport.uploadBlob(file)).resolves.toBe( + 'BLOB_UPLOAD_REF:4:image/png:00000000-0000-4000-8000-000000000000', + ); + expect(transport.uploadedBlobUrl('00000000-0000-4000-8000-000000000000')).toBe( + 'http://127.0.0.1:8080/api/v1/uploads/blobs/00000000-0000-4000-8000-000000000000', + ); + const uploaded = await transport.readUploadedBlob('00000000-0000-4000-8000-000000000000'); + expect(new Uint8Array(await uploaded.arrayBuffer())).toEqual(bytes); + const downloaded = await transport.consumeBlobDownload( + '11111111-1111-4111-8111-111111111111', + ); + expect(downloaded.type).toBe('image/png'); + expect(new Uint8Array(await downloaded.arrayBuffer())).toEqual(bytes); + + const [uploadUrl, uploadRequest] = fetchRequest.mock.calls[1]; + expect(uploadUrl).toBe('http://127.0.0.1:8080/api/v1/uploads/blobs'); + expect(uploadRequest?.body).toBe(file); + const [uploadReadUrl, uploadReadRequest] = fetchRequest.mock.calls[2]; + expect(uploadReadUrl).toBe( + 'http://127.0.0.1:8080/api/v1/uploads/blobs/00000000-0000-4000-8000-000000000000', + ); + expect(uploadReadRequest).toEqual( + expect.objectContaining({method: 'GET', credentials: 'same-origin'}), + ); + const [downloadUrl, downloadRequest] = fetchRequest.mock.calls[3]; + expect(downloadUrl).toBe( + 'http://127.0.0.1:8080/api/v1/downloads/11111111-1111-4111-8111-111111111111', + ); + expect(downloadRequest).toEqual( + expect.objectContaining({method: 'GET', credentials: 'same-origin'}), + ); + }); + + it('normalizes RPC envelopes and network failures', async () => { + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce( + jsonResponse( + { + ok: false, + error: { + code: 'QUERY_CANCELLATION_FAILED', + message: 'No active query', + details: {connectionId: 'connection-1'}, + requestId: 'request-server', + }, + }, + 409, + ), + ) + .mockRejectedValueOnce(new TypeError('Failed to fetch')); + const transport = new HttpTransport({fetch: fetchRequest}); + + const rpcError = await transport + .call('cancel_query', {connectionId: 'connection-1'}) + .catch((error: unknown) => error); + expect(rpcError).toBeInstanceOf(TabularisClientError); + expect(rpcError).toMatchObject({ + code: 'QUERY_CANCELLATION_FAILED', + message: 'No active query', + details: {connectionId: 'connection-1'}, + requestId: 'request-server', + }); + + const networkError = await transport + .call('is_debug_mode', undefined, {requestId: 'request-network'}) + .catch((error: unknown) => error); + expect(networkError).toMatchObject({ + code: 'NETWORK_ERROR', + message: 'Failed to fetch', + requestId: 'request-network', + }); + }); + + it('renews a rejected session and sends the next call with the new CSRF token', async () => { + const renewed = {...SESSION, csrfToken: 'renewed-csrf'}; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce(new Response(null, {status: 401})) + .mockResolvedValueOnce(jsonResponse(renewed)) + .mockResolvedValueOnce(jsonResponse({ok: true, data: false})); + const openLogin = vi.fn(); + const transport = new HttpTransport({fetch: fetchRequest, openLogin}); + + await expect(transport.call('is_debug_mode', undefined)).rejects.toMatchObject({ + code: 'SESSION_EXPIRED', + }); + await expect(transport.call('is_debug_mode', undefined)).resolves.toBe(false); + const lastHeaders = new Headers(fetchRequest.mock.calls[3][1]?.headers); + expect(lastHeaders.get('x-tabularis-csrf')).toBe('renewed-csrf'); + expect(openLogin).not.toHaveBeenCalled(); + }); + + it('treats an empty 403 as a stale CSRF token but keeps JSON 403 errors', async () => { + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce( + jsonResponse( + { + ok: false, + error: { + code: 'FORBIDDEN', + message: 'Denied', + details: null, + requestId: 'r', + }, + }, + 403, + ), + ) + .mockResolvedValueOnce(new Response(null, {status: 403})) + .mockResolvedValueOnce(jsonResponse(SESSION)); + const transport = new HttpTransport({fetch: fetchRequest}); + + await expect(transport.call('is_debug_mode', undefined)).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + await expect(transport.call('is_debug_mode', undefined)).rejects.toMatchObject({ + code: 'SESSION_EXPIRED', + }); + expect(fetchRequest).toHaveBeenCalledTimes(4); + }); + + it('sends the browser to the login form when a password session expired', async () => { + const loginPage = new Response('', { + status: 200, + headers: {'content-type': 'text/html'}, + }); + Object.defineProperty(loginPage, 'redirected', {value: true}); + Object.defineProperty(loginPage, 'url', {value: 'http://localhost/login'}); + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce(new Response(null, {status: 401})) + .mockResolvedValueOnce(loginPage); + const openLogin = vi.fn(); + const transport = new HttpTransport({ + baseUrl: 'http://localhost', + fetch: fetchRequest, + openLogin, + }); + + await expect(transport.call('is_debug_mode', undefined)).rejects.toMatchObject({ + code: 'LOGIN_REQUIRED', + }); + expect(openLogin).toHaveBeenCalledWith('http://localhost/login'); + }); + + it.each(['file', 'icon', 'blob'] as const)( + 'renews an expired %s upload session without retrying the upload', + async (kind) => { + const session = {...SESSION, capabilities: {...SESSION.capabilities, uploads: true}}; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(session)) + .mockResolvedValueOnce(new Response(null, {status: 401})) + .mockResolvedValueOnce(jsonResponse({...session, csrfToken: 'fresh-csrf'})); + const transport = new HttpTransport({fetch: fetchRequest}); + const file = new Blob(['{}']); + const upload = + kind === 'file' + ? transport.uploadFile({ + fileName: 'notebook.json', + purpose: 'notebook-import', + contents: file, + }) + : kind === 'icon' + ? transport.uploadConnectionIcon(file) + : transport.uploadBlob(file); + await expect(upload).rejects.toMatchObject({code: 'SESSION_EXPIRED'}); + expect((await transport.initialize()).csrfToken).toBe('fresh-csrf'); + expect(fetchRequest).toHaveBeenCalledTimes(3); + }, + ); + + it('redirects an expired download session to password login instead of returning HTML', async () => { + const session = {...SESSION, capabilities: {...SESSION.capabilities, downloads: true}}; + const loginPage = () => { + const response = new Response('Login', { + headers: {'content-type': 'text/html'}, + }); + Object.defineProperties(response, { + redirected: {value: true}, + url: {value: 'http://localhost/login'}, + }); + return response; + }; + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(session)) + .mockResolvedValueOnce(loginPage()) + .mockResolvedValueOnce(loginPage()); + const openLogin = vi.fn(); + const transport = new HttpTransport({ + baseUrl: 'http://localhost', + fetch: fetchRequest, + openLogin, + }); + await expect(transport.consumeDownload('expired-token')).rejects.toMatchObject({ + code: 'LOGIN_REQUIRED', + }); + expect(openLogin).toHaveBeenCalledWith('http://localhost/login'); + }); + + it('accepts new event sequences after a server restart without an RPC call', async () => { + vi.useFakeTimers(); + const sockets: FakeWebSocket[] = []; + let negotiations = 0; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => + jsonResponse({ + ...SESSION, + csrfToken: `csrf-${++negotiations}`, + }), + ), + reconnectDelayMs: 100, + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + }); + const handler = vi.fn(); + await transport.initialize(); + const subscribed = transport.subscribe('connection-health-failed', handler); + await Promise.resolve(); + sockets[0].open(); + const unsubscribe = await subscribed; + const event = { + type: 'event', + event: 'connection-health-failed', + payload: {connectionId: 'one', error: 'offline'}, + }; + sockets[0].message({...event, sequence: 100}); + sockets[0].disconnect(); + await vi.advanceTimersByTimeAsync(100); + sockets[1].open(); + sockets[1].message({...event, sequence: 1}); + expect(handler).toHaveBeenCalledTimes(2); + expect((await transport.initialize()).csrfToken).toBe('csrf-2'); + unsubscribe(); + }); + + it('does not reopen a socket when all handlers leave during session refresh', async () => { + vi.useFakeTimers(); + const sockets: FakeWebSocket[] = []; + let finishRefresh!: (response: Response) => void; + const refresh = new Promise((resolve) => { + finishRefresh = resolve; + }); + const transport = new HttpTransport({ + fetch: vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockReturnValueOnce(refresh), + reconnectDelayMs: 100, + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + }); + await transport.initialize(); + const subscribed = transport.subscribe('connection-health-failed', vi.fn()); + await Promise.resolve(); + sockets[0].open(); + const unsubscribe = await subscribed; + sockets[0].disconnect(); + await vi.advanceTimersByTimeAsync(100); + unsubscribe(); + finishRefresh(jsonResponse(SESSION)); + await vi.advanceTimersByTimeAsync(0); + expect(sockets).toHaveLength(1); + }); + + it('uses the same RPC path for tracked unmigrated commands', async () => { + const fetchRequest = vi + .fn() + .mockResolvedValueOnce(jsonResponse(SESSION)) + .mockResolvedValueOnce(jsonResponse({ok: true, data: {value: 1}})); + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + }); + + await expect( + transport.callUnmigrated( + 'legacy_command', + {enabled: true}, + { + task: 'WEB-050', + callSite: 'src/example.ts:1', + reason: 'Awaiting command migration', + }, + ), + ).resolves.toEqual({value: 1}); + + expect(fetchRequest.mock.calls[1]?.[0]).toBe( + 'http://127.0.0.1:8080/api/v1/rpc/legacy_command', + ); + }); + + it('rejects restricted SSH and AI subscriptions individually while retaining database events across reconnect', async () => { + vi.useFakeTimers(); + const sockets: FakeWebSocket[] = []; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => + jsonResponse({ + ...SESSION, + access: { + remote: true, + authorizationLevel: 'database', + highRiskCapabilities: false, + }, + }), + ), + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + reconnectDelayMs: 100, + }); + await transport.initialize(); + const health = vi.fn(); + const transaction = vi.fn(); + const subscriptions = Promise.allSettled([ + transport.subscribe('ssh-askpass://request', vi.fn()), + transport.subscribe('connection-health-failed', health), + transport.subscribe('ai://activity', vi.fn()), + transport.subscribe('session-transaction-state', transaction), + ]); + await Promise.resolve(); + sockets[0].open(); + const results = await subscriptions; + expect(results.map((result) => result.status)).toEqual([ + 'rejected', + 'fulfilled', + 'rejected', + 'fulfilled', + ]); + expect(results[0]).toMatchObject({reason: {code: 'EVENT_FORBIDDEN'}}); + expect(JSON.parse(sockets[0].sent[0])).toEqual({ + type: 'subscribe', + events: ['connection-health-failed', 'session-transaction-state'], + }); + sockets[0].message({ + type: 'event', + event: 'connection-health-failed', + sequence: 1, + payload: {connectionId: 'a', error: 'offline'}, + }); + expect(health).toHaveBeenCalledWith({connectionId: 'a', error: 'offline'}); + sockets[0].disconnect(); + await vi.advanceTimersByTimeAsync(100); + sockets[1].open(); + expect(JSON.parse(sockets[1].sent[0])).toEqual({ + type: 'subscribe', + events: ['connection-health-failed', 'session-transaction-state'], + since: 1, + }); + sockets[1].message({ + type: 'event', + event: 'session-transaction-state', + sequence: 2, + payload: {session_id: 'tab-a', in_transaction: true}, + }); + expect(transaction).toHaveBeenCalledWith({session_id: 'tab-a', in_transaction: true}); + results.forEach((result) => { + if (result.status === 'fulfilled') result.value(); + }); + }); + + it('rejects a subscription when the server sends a protocol error', async () => { + const socket = new FakeWebSocket(); + socket.acknowledgeSubscriptions = false; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => jsonResponse(SESSION)), + createWebSocket: () => socket, + }); + await transport.initialize(); + const subscription = transport.subscribe('query-status', vi.fn()); + const rejected = expect(subscription).rejects.toMatchObject({ + code: 'EVENT_SUBSCRIPTION_FAILED', + message: 'Subscription denied', + }); + await Promise.resolve(); + socket.open(); + socket.message({ + type: 'error', + code: 'EVENT_SUBSCRIPTION_FAILED', + message: 'Subscription denied', + }); + await rejected; + expect(socket.readyState).toBe(3); + }); + + it('keeps established subscriptions usable after a later subscription is rejected', async () => { + const socket = new FakeWebSocket(); + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => jsonResponse(SESSION)), + createWebSocket: () => socket, + }); + await transport.initialize(); + const health = vi.fn(); + const first = transport.subscribe('connection-health-failed', health); + await Promise.resolve(); + socket.open(); + const unsubscribe = await first; + + socket.acknowledgeSubscriptions = false; + const second = transport.subscribe('query-status', vi.fn()); + const rejected = expect(second).rejects.toMatchObject({code: 'EVENT_SUBSCRIPTION_FAILED'}); + await Promise.resolve(); + await Promise.resolve(); + socket.message({type: 'error', code: 'EVENT_SUBSCRIPTION_FAILED', message: 'Denied'}); + await rejected; + socket.message({ + type: 'event', + event: 'connection-health-failed', + sequence: 1, + payload: {connectionId: 'a', error: 'offline'}, + }); + expect(health).toHaveBeenCalledWith({connectionId: 'a', error: 'offline'}); + expect(socket.readyState).toBe(1); + + socket.acknowledgeSubscriptions = true; + const retry = await transport.subscribe('query-status', vi.fn()); + retry(); + unsubscribe(); + }); + + it('rejects pending subscriptions if the socket closes before acknowledgment', async () => { + const socket = new FakeWebSocket(); + socket.acknowledgeSubscriptions = false; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => jsonResponse(SESSION)), + createWebSocket: () => socket, + }); + await transport.initialize(); + const subscription = transport.subscribe('query-status', vi.fn()); + const rejected = expect(subscription).rejects.toMatchObject({ + code: 'EVENT_CONNECTION_FAILED', + }); + await Promise.resolve(); + socket.open(); + socket.disconnect(); + await rejected; + }); + + it('ignores the close of a socket that a new subscription already replaced', async () => { + const sockets: FakeWebSocket[] = []; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => jsonResponse(SESSION)), + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + }); + await transport.initialize(); + + const first = transport.subscribe('connection-health-failed', vi.fn()); + await Promise.resolve(); + sockets[0].open(); + (await first)(); + + // The page remounts before the old socket reports its close. + const handler = vi.fn(); + const second = transport.subscribe('connection-health-failed', handler); + await Promise.resolve(); + expect(sockets).toHaveLength(2); + sockets[0].disconnect(); + sockets[1].open(); + await expect(second).resolves.toBeTypeOf('function'); + + sockets[1].message({ + type: 'event', + event: 'connection-health-failed', + payload: {connectionId: 'connection-1', error: 'offline'}, + sequence: 1, + }); + expect(handler).toHaveBeenCalledOnce(); + }); + + it('does not reuse the connection attempt of a socket that was closed before opening', async () => { + const sockets: FakeWebSocket[] = []; + const transport = new HttpTransport({ + fetch: vi.fn().mockImplementation(async () => jsonResponse(SESSION)), + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + }); + await transport.initialize(); + + const first = transport.subscribe('connection-health-failed', vi.fn()); + await Promise.resolve(); + sockets[0].open(); + (await first)(); + const second = transport.subscribe('connection-health-failed', vi.fn()); + await Promise.resolve(); + // The replaced socket fails before it ever opened. + sockets[0].readyState = 0; + sockets[0].onerror?.(new Event('error')); + sockets[0].disconnect(); + sockets[1].open(); + await expect(second).resolves.toBeTypeOf('function'); + }); + + it('subscribes, dispatches typed events, and replays after reconnect', async () => { + vi.useFakeTimers(); + const fetchRequest = vi + .fn() + .mockImplementation(async () => jsonResponse(SESSION)); + const sockets: FakeWebSocket[] = []; + const transport = new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: fetchRequest, + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + reconnectDelayMs: 100, + maxReconnectDelayMs: 100, + }); + const handler = vi.fn(); + + await transport.initialize(); + const subscription = transport.subscribe('connection-health-failed', handler); + await Promise.resolve(); + expect(sockets).toHaveLength(1); + sockets[0].open(); + const unsubscribe = await subscription; + expect(JSON.parse(sockets[0].sent[0])).toEqual({ + type: 'subscribe', + events: ['connection-health-failed'], + }); + + sockets[0].message({ + type: 'event', + event: 'connection-health-failed', + payload: {connectionId: 'connection-1', error: 'offline'}, + sequence: 7, + }); + expect(handler).toHaveBeenCalledWith({ + connectionId: 'connection-1', + error: 'offline', + }); + + sockets[0].disconnect(); + await vi.advanceTimersByTimeAsync(100); + expect(sockets).toHaveLength(2); + sockets[1].open(); + expect(JSON.parse(sockets[1].sent[0])).toEqual({ + type: 'subscribe', + events: ['connection-health-failed'], + since: 7, + }); + + unsubscribe(); + expect(JSON.parse(sockets[1].sent[1])).toEqual({ + type: 'unsubscribe', + events: ['connection-health-failed'], + }); + expect(sockets[1].readyState).toBe(3); + }); + + it('restores active-operation event subscriptions after a browser refresh', async () => { + const sockets: FakeWebSocket[] = []; + const createTransport = () => + new HttpTransport({ + baseUrl: 'http://127.0.0.1:8080', + fetch: vi.fn().mockResolvedValueOnce(jsonResponse(SESSION)), + createWebSocket: () => { + const socket = new FakeWebSocket(); + sockets.push(socket); + return socket; + }, + }); + + const beforeRefresh = createTransport(); + await beforeRefresh.initialize(); + const firstSubscription = beforeRefresh.subscribe('query-status', vi.fn()); + await Promise.resolve(); + sockets[0].open(); + const unsubscribeBeforeRefresh = await firstSubscription; + unsubscribeBeforeRefresh(); + + const afterRefresh = createTransport(); + const refreshedHandler = vi.fn(); + await afterRefresh.initialize(); + const refreshedSubscription = afterRefresh.subscribe('query-status', refreshedHandler); + await Promise.resolve(); + sockets[1].open(); + const unsubscribeAfterRefresh = await refreshedSubscription; + expect(JSON.parse(sockets[1].sent[0])).toEqual({ + type: 'subscribe', + events: ['query-status'], + }); + + sockets[1].message({ + type: 'event', + event: 'query-status', + payload: { + requestId: 'request-active', + connectionId: 'connection-1', + status: 'completed', + }, + sequence: 9, + }); + expect(refreshedHandler).toHaveBeenCalledWith({ + requestId: 'request-active', + connectionId: 'connection-1', + status: 'completed', + }); + + unsubscribeAfterRefresh(); + }); + + it('rejects browser-side event emission explicitly', async () => { + const transport = new HttpTransport({ + fetch: vi.fn().mockResolvedValueOnce(jsonResponse(SESSION)), + }); + + const error = await transport + .emit('connections:active-changed', ['connection-1']) + .catch((caught: unknown) => caught); + + expect(error).toMatchObject({ + code: 'EVENT_EMIT_UNSUPPORTED', + message: 'Browser clients cannot publish application events', + }); + }); +}); diff --git a/packages/web-ui/tests/api/transports/tauriTransport.test.ts b/packages/web-ui/tests/api/transports/tauriTransport.test.ts new file mode 100644 index 000000000..ac23aba97 --- /dev/null +++ b/packages/web-ui/tests/api/transports/tauriTransport.test.ts @@ -0,0 +1,112 @@ +import {invoke} from '@tauri-apps/api/core'; +import {emit, listen, type EventCallback} from '@tauri-apps/api/event'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TauriTransport} from '@/api/transports/tauriTransport'; + +vi.mock('@tauri-apps/api/event', () => ({ + emit: vi.fn(), + listen: vi.fn(), +})); + +describe('TauriTransport', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('delegates typed and unmigrated commands to Tauri invoke', async () => { + const transport = new TauriTransport(); + + vi.mocked(invoke).mockResolvedValueOnce(true).mockResolvedValueOnce({value: 1}); + + await expect(transport.call('is_debug_mode', undefined)).resolves.toBe(true); + await expect( + transport.callUnmigrated( + 'legacy_command', + {enabled: true}, + { + task: 'WEB-050', + callSite: 'src/example.ts:1', + reason: 'Awaiting its command-group migration', + }, + ), + ).resolves.toEqual({value: 1}); + + expect(invoke).toHaveBeenNthCalledWith(1, 'is_debug_mode', undefined); + expect(invoke).toHaveBeenNthCalledWith(2, 'legacy_command', { + enabled: true, + }); + }); + + it('loads plugin assets through the desktop command adapter', async () => { + const transport = new TauriTransport(); + vi.mocked(invoke).mockResolvedValueOnce('window.pluginLoaded = true;'); + + await expect(transport.readPluginAsset('plugin-id', 'ui/dist/index.js')).resolves.toBe( + 'window.pluginLoaded = true;', + ); + + expect(invoke).toHaveBeenCalledWith('read_plugin_file', { + pluginId: 'plugin-id', + filePath: 'ui/dist/index.js', + }); + }); + + it('normalizes Tauri failures to the shared frontend error model', async () => { + const transport = new TauriTransport(); + vi.mocked(invoke).mockRejectedValueOnce(new Error('query failed')); + + const error = await transport + .call('is_debug_mode', undefined, {requestId: 'request-tauri'}) + .catch((caught: unknown) => caught); + + expect(error).toMatchObject({ + name: 'TabularisClientError', + code: 'TAURI_COMMAND_FAILED', + message: 'query failed', + details: null, + requestId: 'request-tauri', + }); + }); + + it('unwraps Tauri event payloads and returns the unlisten callback', async () => { + const transport = new TauriTransport(); + const handler = vi.fn(); + const unlisten = vi.fn(); + let callback: EventCallback<{connectionId: string; error: string}> | undefined; + + vi.mocked(listen).mockImplementationOnce((_event, eventHandler) => { + callback = eventHandler as EventCallback<{ + connectionId: string; + error: string; + }>; + return Promise.resolve(unlisten); + }); + + await expect(transport.subscribe('connection-health-failed', handler)).resolves.toBe( + unlisten, + ); + + callback?.({ + event: 'connection-health-failed', + id: 1, + payload: {connectionId: 'connection-1', error: 'offline'}, + }); + + expect(listen).toHaveBeenCalledWith('connection-health-failed', expect.any(Function)); + expect(handler).toHaveBeenCalledWith({ + connectionId: 'connection-1', + error: 'offline', + }); + }); + + it('delegates typed event payloads to Tauri emit', async () => { + const transport = new TauriTransport(); + const payload = ['connection-1']; + + vi.mocked(emit).mockResolvedValueOnce(undefined); + + await transport.emit('connections:active-changed', payload); + + expect(emit).toHaveBeenCalledWith('connections:active-changed', payload); + }); +}); diff --git a/tests/components/ConnectionErrorBanner.test.tsx b/packages/web-ui/tests/components/ConnectionErrorBanner.test.tsx similarity index 100% rename from tests/components/ConnectionErrorBanner.test.tsx rename to packages/web-ui/tests/components/ConnectionErrorBanner.test.tsx diff --git a/packages/web-ui/tests/components/ConnectionHealthMonitor.test.tsx b/packages/web-ui/tests/components/ConnectionHealthMonitor.test.tsx new file mode 100644 index 000000000..31340fd35 --- /dev/null +++ b/packages/web-ui/tests/components/ConnectionHealthMonitor.test.tsx @@ -0,0 +1,36 @@ +import {act, render} from '@testing-library/react'; +import {describe, expect, it, vi} from 'vitest'; +import {ConnectionHealthMonitor} from '@/components/ConnectionHealthMonitor'; + +const mocks = vi.hoisted(() => ({ + client: {subscribe: vi.fn()}, + showAlert: vi.fn(), + navigate: vi.fn(), + t: (key: string) => key, +})); +vi.mock('@/hooks/useTabularisClient', () => ({useTabularisClient: () => mocks.client})); +vi.mock('@/hooks/useAlert', () => ({useAlert: () => ({showAlert: mocks.showAlert})})); +vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); +vi.mock('react-router-dom', () => ({useNavigate: () => mocks.navigate})); + +describe('ConnectionHealthMonitor transport events', () => { + it('shows health failures from the active client and unsubscribes on unmount', async () => { + const unsubscribe = vi.fn(); + mocks.client.subscribe.mockResolvedValue(unsubscribe); + const view = render(); + expect(mocks.client.subscribe).toHaveBeenCalledWith( + 'connection-health-failed', + expect.any(Function), + ); + const handler = mocks.client.subscribe.mock.calls[0][1]; + act(() => handler({connectionId: 'c1', error: 'connection closed'})); + expect(mocks.showAlert).toHaveBeenCalledWith( + 'healthCheck.connectionLost: connection closed', + expect.objectContaining({kind: 'error'}), + ); + await act(async () => { + view.unmount(); + }); + expect(unsubscribe).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/components/ConnectionIconImage.test.tsx b/packages/web-ui/tests/components/ConnectionIconImage.test.tsx similarity index 92% rename from tests/components/ConnectionIconImage.test.tsx rename to packages/web-ui/tests/components/ConnectionIconImage.test.tsx index 0312256fc..5c1e87ae1 100644 --- a/tests/components/ConnectionIconImage.test.tsx +++ b/packages/web-ui/tests/components/ConnectionIconImage.test.tsx @@ -2,6 +2,12 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; import {render, screen, waitFor, act} from '@testing-library/react'; import {ConnectionIconImage} from '@/components/ConnectionIconImage'; +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + resolveAppAsset: async (path: string) => `tauri:///app/data/${path}`, + }), +})); + vi.mock('@tauri-apps/api/core', () => ({ convertFileSrc: (s: string) => `tauri://${s}`, invoke: vi.fn().mockResolvedValue('/app/data'), diff --git a/tests/components/SlotAnchor.test.tsx b/packages/web-ui/tests/components/SlotAnchor.test.tsx similarity index 96% rename from tests/components/SlotAnchor.test.tsx rename to packages/web-ui/tests/components/SlotAnchor.test.tsx index ac4ed9172..c3fbf6520 100644 --- a/tests/components/SlotAnchor.test.tsx +++ b/packages/web-ui/tests/components/SlotAnchor.test.tsx @@ -1,4 +1,4 @@ -import {describe, it, expect} from 'vitest'; +import {describe, it, expect, vi} from 'vitest'; import {render, screen} from '@testing-library/react'; import {PluginSlotProvider} from '@/contexts/PluginSlotProvider'; import {PluginSlotContext} from '@/contexts/PluginSlotContext'; @@ -6,6 +6,10 @@ import {SettingsContext, DEFAULT_SETTINGS} from '@/contexts/SettingsContext'; import {SlotAnchor} from '@/components/ui/SlotAnchor'; import type {SlotComponentProps} from '@/types/pluginSlots'; +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call: vi.fn()}), +})); + const settingsValue = { settings: DEFAULT_SETTINGS, updateSetting: () => {}, diff --git a/tests/components/SocialLinks.test.tsx b/packages/web-ui/tests/components/SocialLinks.test.tsx similarity index 94% rename from tests/components/SocialLinks.test.tsx rename to packages/web-ui/tests/components/SocialLinks.test.tsx index 38c2367b9..0cea03c89 100644 --- a/tests/components/SocialLinks.test.tsx +++ b/packages/web-ui/tests/components/SocialLinks.test.tsx @@ -5,8 +5,10 @@ import {SOCIAL_LINKS} from '@/config/socialLinks'; import {LINKS} from '@/config/links'; const openUrl = vi.fn(); -vi.mock('@tauri-apps/plugin-opener', () => ({ - openUrl: (url: string) => openUrl(url), +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + openExternalUrl: (url: string) => openUrl(url), + }), })); describe('SOCIAL_LINKS', () => { diff --git a/tests/components/banners/PostgresPluginMigrationBanner.test.tsx b/packages/web-ui/tests/components/banners/PostgresPluginMigrationBanner.test.tsx similarity index 100% rename from tests/components/banners/PostgresPluginMigrationBanner.test.tsx rename to packages/web-ui/tests/components/banners/PostgresPluginMigrationBanner.test.tsx diff --git a/tests/components/connection/ConnectionCatalogue.test.tsx b/packages/web-ui/tests/components/connection/ConnectionCatalogue.test.tsx similarity index 100% rename from tests/components/connection/ConnectionCatalogue.test.tsx rename to packages/web-ui/tests/components/connection/ConnectionCatalogue.test.tsx diff --git a/tests/components/connection/EngineCard.test.tsx b/packages/web-ui/tests/components/connection/EngineCard.test.tsx similarity index 100% rename from tests/components/connection/EngineCard.test.tsx rename to packages/web-ui/tests/components/connection/EngineCard.test.tsx diff --git a/tests/components/connection/InstallGate.test.tsx b/packages/web-ui/tests/components/connection/InstallGate.test.tsx similarity index 92% rename from tests/components/connection/InstallGate.test.tsx rename to packages/web-ui/tests/components/connection/InstallGate.test.tsx index fcb89be2a..7df6867a4 100644 --- a/tests/components/connection/InstallGate.test.tsx +++ b/packages/web-ui/tests/components/connection/InstallGate.test.tsx @@ -4,6 +4,16 @@ import {invoke} from '@tauri-apps/api/core'; import {InstallGate} from '@/components/modals/connection/InstallGate'; import type {CatalogueDriver} from '@/utils/connectionCatalogue'; +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openExternalUrl: vi.fn()}), +})); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, payload: unknown) => invoke(command, payload), + }), +})); + const driver = (over: Partial = {}): CatalogueDriver => ({ slug: 'firestore', name: 'Firestore', diff --git a/tests/components/connections/ConnectionCard.test.tsx b/packages/web-ui/tests/components/connections/ConnectionCard.test.tsx similarity index 100% rename from tests/components/connections/ConnectionCard.test.tsx rename to packages/web-ui/tests/components/connections/ConnectionCard.test.tsx diff --git a/tests/components/connections/ConnectionListItem.test.tsx b/packages/web-ui/tests/components/connections/ConnectionListItem.test.tsx similarity index 100% rename from tests/components/connections/ConnectionListItem.test.tsx rename to packages/web-ui/tests/components/connections/ConnectionListItem.test.tsx diff --git a/tests/components/explain/ExplainTableView.test.tsx b/packages/web-ui/tests/components/explain/ExplainTableView.test.tsx similarity index 100% rename from tests/components/explain/ExplainTableView.test.tsx rename to packages/web-ui/tests/components/explain/ExplainTableView.test.tsx diff --git a/tests/components/explain/VisualExplainView.test.tsx b/packages/web-ui/tests/components/explain/VisualExplainView.test.tsx similarity index 89% rename from tests/components/explain/VisualExplainView.test.tsx rename to packages/web-ui/tests/components/explain/VisualExplainView.test.tsx index 446fffe7c..940ab7789 100644 --- a/tests/components/explain/VisualExplainView.test.tsx +++ b/packages/web-ui/tests/components/explain/VisualExplainView.test.tsx @@ -2,13 +2,15 @@ import {act, fireEvent, render, screen} from '@testing-library/react'; import {beforeEach, describe, expect, it, vi} from 'vitest'; import {parseExplain, type ExplainPlan} from '@tabularis/explain'; import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; +import {writeFile} from '@tauri-apps/plugin-fs'; import {VisualExplainView} from '@/components/explain/VisualExplainView'; import {AlertContext} from '@/contexts/AlertContext'; import type {AlertContextType} from '@/contexts/AlertContext'; vi.mock('@tauri-apps/plugin-dialog', () => ({save: vi.fn()})); -vi.mock('@tauri-apps/plugin-fs', () => ({writeTextFile: vi.fn()})); +vi.mock('@tauri-apps/plugin-fs', () => ({writeFile: vi.fn(), readFile: vi.fn()})); +// Saves go through the platform download, which writes the encoded bytes. +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('lucide-react', () => vi.importActual('lucide-react')); vi.mock('@/themes/themeUtils', () => ({ @@ -32,7 +34,8 @@ vi.mock('@/components/ui/LazyMonaco', () => ({ })); const mockSave = vi.mocked(save); -const mockWriteTextFile = vi.mocked(writeTextFile); +const mockWriteFile = vi.mocked(writeFile); +const encode = (text: string) => new TextEncoder().encode(text); const showAlert = vi.fn(); function createTestPlan(rawOutput?: string): ExplainPlan { @@ -46,7 +49,7 @@ function createTestPlan(rawOutput?: string): ExplainPlan { describe('VisualExplainView raw plan save', () => { beforeEach(() => { mockSave.mockReset(); - mockWriteTextFile.mockReset(); + mockWriteFile.mockReset(); showAlert.mockReset(); vi.spyOn(console, 'error').mockImplementation(() => {}); }); @@ -80,7 +83,7 @@ describe('VisualExplainView raw plan save', () => { const rawContent = '{"query_block":{"cost":42}}'; const plan = createTestPlan(rawContent); mockSave.mockResolvedValue('/path/to/plan.json'); - mockWriteTextFile.mockResolvedValue(undefined); + mockWriteFile.mockResolvedValue(undefined); render( @@ -113,7 +116,7 @@ describe('VisualExplainView raw plan save', () => { {name: 'All files', extensions: ['*']}, ], }); - expect(mockWriteTextFile).toHaveBeenCalledWith('/path/to/plan.json', rawContent); + expect(mockWriteFile).toHaveBeenCalledWith('/path/to/plan.json', encode(rawContent)); expect(showAlert).toHaveBeenCalledWith('editor.visualExplain.rawExported', { kind: 'info', }); @@ -129,7 +132,7 @@ describe('VisualExplainView raw plan save', () => { resolveSave = resolve; }), ); - mockWriteTextFile.mockResolvedValue(undefined); + mockWriteFile.mockResolvedValue(undefined); const {rerender} = render( @@ -178,7 +181,7 @@ describe('VisualExplainView raw plan save', () => { }); // Must have saved the initial captured raw content, NOT the new plan's content - expect(mockWriteTextFile).toHaveBeenCalledWith('/path/to/exported.json', initialRaw); + expect(mockWriteFile).toHaveBeenCalledWith('/path/to/exported.json', encode(initialRaw)); expect(showAlert).toHaveBeenCalledWith('editor.visualExplain.rawExported', { kind: 'info', }); @@ -213,7 +216,7 @@ describe('VisualExplainView raw plan save', () => { }); expect(mockSave).toHaveBeenCalled(); - expect(mockWriteTextFile).not.toHaveBeenCalled(); + expect(mockWriteFile).not.toHaveBeenCalled(); expect(showAlert).not.toHaveBeenCalled(); }); @@ -221,7 +224,7 @@ describe('VisualExplainView raw plan save', () => { const rawContent = '{"cost": 100}'; const plan = createTestPlan(rawContent); mockSave.mockResolvedValue('/path/to/file.json'); - mockWriteTextFile.mockRejectedValue(new Error('disk full')); + mockWriteFile.mockRejectedValue(new Error('disk full')); render( @@ -247,7 +250,7 @@ describe('VisualExplainView raw plan save', () => { }); expect(mockSave).toHaveBeenCalled(); - expect(mockWriteTextFile).toHaveBeenCalledWith('/path/to/file.json', rawContent); + expect(mockWriteFile).toHaveBeenCalledWith('/path/to/file.json', encode(rawContent)); expect(showAlert).toHaveBeenCalledWith('editor.visualExplain.saveRawError', { kind: 'error', }); diff --git a/tests/components/layout/ExplorerSidebar.test.tsx b/packages/web-ui/tests/components/layout/ExplorerSidebar.test.tsx similarity index 99% rename from tests/components/layout/ExplorerSidebar.test.tsx rename to packages/web-ui/tests/components/layout/ExplorerSidebar.test.tsx index ad3fe240a..cd64f4932 100644 --- a/tests/components/layout/ExplorerSidebar.test.tsx +++ b/packages/web-ui/tests/components/layout/ExplorerSidebar.test.tsx @@ -37,6 +37,17 @@ vi.mock('@/hooks/useSettings', () => ({useSettings: vi.fn()})); vi.mock('@/hooks/useDatabaseObjectNavigation', () => ({ useDatabaseObjectNavigation: vi.fn(), })); +vi.mock('@/hooks/useSecondaryWindows', () => ({ + useSecondaryWindows: () => ({openSchemaDiagram: vi.fn()}), +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({chooseInputFile: vi.fn()}), +})); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invoke(command, request), + }), +})); vi.mock('react-router-dom', () => ({useNavigate: () => vi.fn()})); vi.mock('@/utils/notebookStore', async (importOriginal) => { const actual = await importOriginal(); diff --git a/tests/components/layout/MainLayout.test.tsx b/packages/web-ui/tests/components/layout/MainLayout.test.tsx similarity index 91% rename from tests/components/layout/MainLayout.test.tsx rename to packages/web-ui/tests/components/layout/MainLayout.test.tsx index b7b7b0e7c..581e11da1 100644 --- a/tests/components/layout/MainLayout.test.tsx +++ b/packages/web-ui/tests/components/layout/MainLayout.test.tsx @@ -79,10 +79,13 @@ describe('MainLayout', () => { it('should show the production banner only on the connection editor route', () => { const {unmount} = render( - + }> - Editor} /> + Editor} + /> Settings} /> @@ -97,7 +100,10 @@ describe('MainLayout', () => { }> - Editor} /> + Editor} + /> Settings} /> diff --git a/tests/components/layout/sidebar/Accordion.test.tsx b/packages/web-ui/tests/components/layout/sidebar/Accordion.test.tsx similarity index 100% rename from tests/components/layout/sidebar/Accordion.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/Accordion.test.tsx diff --git a/tests/components/layout/sidebar/ConnectionGroupFolder.test.tsx b/packages/web-ui/tests/components/layout/sidebar/ConnectionGroupFolder.test.tsx similarity index 100% rename from tests/components/layout/sidebar/ConnectionGroupFolder.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/ConnectionGroupFolder.test.tsx diff --git a/packages/web-ui/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx b/packages/web-ui/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx new file mode 100644 index 000000000..112626a16 --- /dev/null +++ b/packages/web-ui/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx @@ -0,0 +1,120 @@ +import {render, screen, fireEvent} from '@testing-library/react'; +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import { + DiscordCommunityCallout, + DISCORD_CALLOUT_STORAGE_KEY, +} from '@/components/layout/sidebar/DiscordCommunityCallout'; +import {UiStateStore} from '@/utils/uiStateStore'; +const openUrl = vi.hoisted(() => vi.fn()); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openExternalUrl: openUrl}), +})); + +/** A store attached to a fake backend holding `remote`. */ +const createStore = (remote: Record | Error = {}) => { + const call = vi.fn(async (command: string) => { + if (command !== 'get_ui_state') return undefined; + if (remote instanceof Error) throw remote; + return remote; + }); + const store = new UiStateStore(); + store.attach({call, subscribe: vi.fn(async () => () => {})} as unknown as TabularisClient); + return {store, call}; +}; + +describe('DiscordCommunityCallout', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + }); + + it('renders on first run when the shared flag is missing', async () => { + const {store} = createStore(); + render(); + + expect(await screen.findByTestId('discord-callout')).toBeInTheDocument(); + expect(screen.getByTestId('discord-callout-pulse')).toBeInTheDocument(); + expect(screen.getByText('discordCallout.title')).toBeInTheDocument(); + expect(screen.getByText('discordCallout.body')).toBeInTheDocument(); + }); + + it('does not flash before the shared state has loaded', () => { + const store = new UiStateStore(); + render(); + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + }); + + it('stays hidden when another host already dismissed it', async () => { + const {store, call} = createStore({[DISCORD_CALLOUT_STORAGE_KEY]: true}); + render(); + await vi.waitFor(() => expect(call).toHaveBeenCalled()); + await Promise.resolve(); + + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + expect(screen.queryByTestId('discord-callout-pulse')).not.toBeInTheDocument(); + }); + + it('persists dismissal and hides itself when the close button is clicked', async () => { + const {store, call} = createStore(); + render(); + + fireEvent.click(await screen.findByLabelText('discordCallout.dismiss')); + + expect(call).toHaveBeenCalledWith('set_ui_state', { + key: DISCORD_CALLOUT_STORAGE_KEY, + value: true, + }); + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + }); + + it('opens Discord and dismisses when the CTA is clicked', async () => { + const {store, call} = createStore(); + render(); + + fireEvent.click(await screen.findByText('discordCallout.cta')); + + expect(openUrl).toHaveBeenCalledWith('https://discord.com/invite/K2hmhfHRSt'); + expect(call).toHaveBeenCalledWith('set_ui_state', { + key: DISCORD_CALLOUT_STORAGE_KEY, + value: true, + }); + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + }); + + it('still hides for the session if the backend write fails', async () => { + const {store, call} = createStore(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + render(); + const dismiss = await screen.findByLabelText('discordCallout.dismiss'); + call.mockRejectedValueOnce(new Error('quota exceeded')); + + fireEvent.click(dismiss); + + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + }); + + it('falls back to visible when the backend cannot be read', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const {store} = createStore(new Error('offline')); + render(); + + expect(await screen.findByTestId('discord-callout')).toBeInTheDocument(); + }); + + it('migrates a dismissal an older version kept in localStorage', async () => { + localStorage.setItem(DISCORD_CALLOUT_STORAGE_KEY, 'true'); + const {store, call} = createStore(); + render(); + await vi.waitFor(() => + expect(call).toHaveBeenCalledWith('set_ui_state', { + key: DISCORD_CALLOUT_STORAGE_KEY, + value: true, + }), + ); + + expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); + expect(localStorage.getItem(DISCORD_CALLOUT_STORAGE_KEY)).toBeNull(); + }); +}); diff --git a/tests/components/layout/sidebar/MetadataErrorIndicator.test.tsx b/packages/web-ui/tests/components/layout/sidebar/MetadataErrorIndicator.test.tsx similarity index 100% rename from tests/components/layout/sidebar/MetadataErrorIndicator.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/MetadataErrorIndicator.test.tsx diff --git a/tests/components/layout/sidebar/NavItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/NavItem.test.tsx similarity index 100% rename from tests/components/layout/sidebar/NavItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/NavItem.test.tsx diff --git a/tests/components/layout/sidebar/QueryHistorySection.test.tsx b/packages/web-ui/tests/components/layout/sidebar/QueryHistorySection.test.tsx similarity index 100% rename from tests/components/layout/sidebar/QueryHistorySection.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/QueryHistorySection.test.tsx diff --git a/tests/components/layout/sidebar/RailIndicator.test.tsx b/packages/web-ui/tests/components/layout/sidebar/RailIndicator.test.tsx similarity index 100% rename from tests/components/layout/sidebar/RailIndicator.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/RailIndicator.test.tsx diff --git a/tests/components/layout/sidebar/SidebarDatabaseItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/SidebarDatabaseItem.test.tsx similarity index 100% rename from tests/components/layout/sidebar/SidebarDatabaseItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/SidebarDatabaseItem.test.tsx diff --git a/tests/components/layout/sidebar/SidebarNestedDatabaseItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/SidebarNestedDatabaseItem.test.tsx similarity index 100% rename from tests/components/layout/sidebar/SidebarNestedDatabaseItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/SidebarNestedDatabaseItem.test.tsx diff --git a/tests/components/layout/sidebar/SidebarSchemaItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/SidebarSchemaItem.test.tsx similarity index 94% rename from tests/components/layout/sidebar/SidebarSchemaItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/SidebarSchemaItem.test.tsx index 45cc81fc6..3dff5730e 100644 --- a/tests/components/layout/sidebar/SidebarSchemaItem.test.tsx +++ b/packages/web-ui/tests/components/layout/sidebar/SidebarSchemaItem.test.tsx @@ -4,10 +4,16 @@ import React from 'react'; import {SidebarSchemaItem} from '@/components/layout/sidebar/SidebarSchemaItem'; import {invoke} from '@tauri-apps/api/core'; +const clientMock = vi.hoisted(() => ({call: vi.fn()})); + vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(() => Promise.resolve([])), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => clientMock, +})); + vi.mock('react-i18next', () => ({ useTranslation: () => ({t: (key: string) => key}), })); @@ -92,6 +98,10 @@ describe('SidebarSchemaItem — materialized view double-click', () => { beforeEach(() => { vi.mocked(invoke).mockClear(); + clientMock.call.mockReset(); + clientMock.call.mockImplementation((command: string, request: unknown) => + invoke(command, request), + ); }); it('flags a materialized view (materialized=true) on double-click', () => { diff --git a/tests/components/layout/sidebar/SidebarTableItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/SidebarTableItem.test.tsx similarity index 95% rename from tests/components/layout/sidebar/SidebarTableItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/SidebarTableItem.test.tsx index e476da418..23dd8d2a7 100644 --- a/tests/components/layout/sidebar/SidebarTableItem.test.tsx +++ b/packages/web-ui/tests/components/layout/sidebar/SidebarTableItem.test.tsx @@ -117,3 +117,8 @@ describe('SidebarTableItem', () => { }); }); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: (...args: unknown[]) => invoke(...args)}; + return {useTabularisClient: () => client}; +}); diff --git a/tests/components/layout/sidebar/SidebarViewItem.test.tsx b/packages/web-ui/tests/components/layout/sidebar/SidebarViewItem.test.tsx similarity index 96% rename from tests/components/layout/sidebar/SidebarViewItem.test.tsx rename to packages/web-ui/tests/components/layout/sidebar/SidebarViewItem.test.tsx index 3dd1de55d..2840af091 100644 --- a/tests/components/layout/sidebar/SidebarViewItem.test.tsx +++ b/packages/web-ui/tests/components/layout/sidebar/SidebarViewItem.test.tsx @@ -9,6 +9,19 @@ vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), })); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + confirm: vi.fn().mockResolvedValue(true), + writeClipboard: vi.fn(), + }), +})); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invoke(command, request), + }), +})); + // Mock i18n vi.mock('react-i18next', () => ({ useTranslation: () => ({ diff --git a/tests/components/modals/AiApprovalGate.test.tsx b/packages/web-ui/tests/components/modals/AiApprovalGate.test.tsx similarity index 89% rename from tests/components/modals/AiApprovalGate.test.tsx rename to packages/web-ui/tests/components/modals/AiApprovalGate.test.tsx index 1afbeb98b..f5b7e199c 100644 --- a/tests/components/modals/AiApprovalGate.test.tsx +++ b/packages/web-ui/tests/components/modals/AiApprovalGate.test.tsx @@ -9,6 +9,12 @@ import { restoreWindowAlwaysOnTop, } from '@/utils/mcpApprovalAttention'; +const platform = vi.hoisted(() => ({notify: vi.fn()})); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, +})); + vi.mock('@/hooks/useSettings', () => ({ useSettings: vi.fn(), })); @@ -68,10 +74,13 @@ describe('AiApprovalGate', () => { }); expect(focusWindowForApproval).toHaveBeenCalledWith('approval-1'); - expect(notifyApprovalRequest).toHaveBeenCalledWith({ - title: 'aiApproval.notificationTitle', - body: 'aiApproval.notificationBody', - }); + expect(notifyApprovalRequest).toHaveBeenCalledWith( + { + title: 'aiApproval.notificationTitle', + body: 'aiApproval.notificationBody', + }, + platform, + ); expect(restoreWindowAlwaysOnTop).not.toHaveBeenCalled(); }); @@ -138,10 +147,13 @@ describe('AiApprovalGate', () => { }); expect(focusWindowForApproval).not.toHaveBeenCalled(); - expect(notifyApprovalRequest).toHaveBeenCalledWith({ - title: 'aiApproval.notificationTitle', - body: 'aiApproval.notificationBody', - }); + expect(notifyApprovalRequest).toHaveBeenCalledWith( + { + title: 'aiApproval.notificationTitle', + body: 'aiApproval.notificationBody', + }, + platform, + ); }); it('does not send notifications when notification attention is disabled', async () => { diff --git a/tests/components/modals/AiExplainModal.test.tsx b/packages/web-ui/tests/components/modals/AiExplainModal.test.tsx similarity index 94% rename from tests/components/modals/AiExplainModal.test.tsx rename to packages/web-ui/tests/components/modals/AiExplainModal.test.tsx index 6f6e657fb..0d9ede708 100644 --- a/tests/components/modals/AiExplainModal.test.tsx +++ b/packages/web-ui/tests/components/modals/AiExplainModal.test.tsx @@ -102,3 +102,8 @@ describe('AiExplainModal', () => { }); }); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: (...args: unknown[]) => invokeMock(...args)}; + return {useTabularisClient: () => client}; +}); diff --git a/tests/components/modals/AiQueryModal.test.tsx b/packages/web-ui/tests/components/modals/AiQueryModal.test.tsx similarity index 98% rename from tests/components/modals/AiQueryModal.test.tsx rename to packages/web-ui/tests/components/modals/AiQueryModal.test.tsx index 42d2f9340..650ccce21 100644 --- a/tests/components/modals/AiQueryModal.test.tsx +++ b/packages/web-ui/tests/components/modals/AiQueryModal.test.tsx @@ -7,8 +7,8 @@ const {invokeMock} = vi.hoisted(() => ({ invokeMock: vi.fn(), })); -vi.mock('@tauri-apps/api/core', () => ({ - invoke: invokeMock, +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call: invokeMock}), })); vi.mock('@/hooks/useDatabase', () => ({ diff --git a/packages/web-ui/tests/components/modals/BrowserPlatformDialogs.test.tsx b/packages/web-ui/tests/components/modals/BrowserPlatformDialogs.test.tsx new file mode 100644 index 000000000..9c6ea393a --- /dev/null +++ b/packages/web-ui/tests/components/modals/BrowserPlatformDialogs.test.tsx @@ -0,0 +1,111 @@ +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {BrowserPlatformDialogs} from '@/components/modals/BrowserPlatformDialogs'; +import { + requestBrowserMessage, + requestBrowserSaveTarget, + requestBrowserServerPath, +} from '@/platform/browserDialogs'; + +const call = vi.fn(); +const showAlert = vi.fn(); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call}), +})); + +vi.mock('@/hooks/useAlert', () => ({ + useAlert: () => ({showAlert}), +})); + +describe('BrowserPlatformDialogs', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('browses server entries and resolves a selected file', async () => { + call.mockResolvedValue({ + path: '/srv/databases', + parent: null, + entries: [ + { + name: 'main.sqlite', + path: '/srv/databases/main.sqlite', + kind: 'file', + }, + ], + }); + render(); + + let selection!: Promise<{reference: string} | null>; + act(() => { + selection = requestBrowserServerPath({ + kind: 'file', + title: 'Choose database', + filters: [{name: 'SQLite', extensions: ['sqlite']}], + }); + }); + + expect(await screen.findByText('Choose database')).toBeInTheDocument(); + fireEvent.click(await screen.findByText('main.sqlite')); + fireEvent.click(screen.getByRole('button', {name: 'serverFilePicker.select'})); + + await expect(selection).resolves.toEqual({ + reference: '/srv/databases/main.sqlite', + }); + expect(call).toHaveBeenCalledWith('list_server_directory', {}); + }); + + it('creates a save target inside the selected server folder', async () => { + call.mockImplementation((command: string) => { + if (command === 'list_server_directory') { + return Promise.resolve({ + path: '/srv/databases', + parent: null, + entries: [], + }); + } + return Promise.resolve({path: '/srv/databases/database.db'}); + }); + render(); + + let selection!: Promise<{reference: string} | null>; + act(() => { + selection = requestBrowserSaveTarget({suggestedName: 'database.db'}); + }); + + const input = await screen.findByDisplayValue('database.db'); + fireEvent.change(input, {target: {value: 'customers.db'}}); + fireEvent.click(screen.getByRole('button', {name: 'serverFilePicker.select'})); + + await expect(selection).resolves.toEqual({ + reference: '/srv/databases/database.db', + }); + expect(call).toHaveBeenLastCalledWith('resolve_server_save_target', { + directory: '/srv/databases', + fileName: 'customers.db', + }); + }); + + it('routes platform messages through the shared Tailwind alert', async () => { + showAlert.mockImplementation((_message: string, options: {onClose?: () => void}) => + options.onClose?.(), + ); + render(); + + await act(() => + requestBrowserMessage({ + title: 'Unavailable', + message: 'Server browsing is disabled', + kind: 'info', + }), + ); + + await waitFor(() => + expect(showAlert).toHaveBeenCalledWith( + 'Server browsing is disabled', + expect.objectContaining({title: 'Unavailable', kind: 'info'}), + ), + ); + }); +}); diff --git a/tests/components/modals/ClipboardImportModal.test.tsx b/packages/web-ui/tests/components/modals/ClipboardImportModal.test.tsx similarity index 91% rename from tests/components/modals/ClipboardImportModal.test.tsx rename to packages/web-ui/tests/components/modals/ClipboardImportModal.test.tsx index f11ac8467..bf9d29807 100644 --- a/tests/components/modals/ClipboardImportModal.test.tsx +++ b/packages/web-ui/tests/components/modals/ClipboardImportModal.test.tsx @@ -1,6 +1,6 @@ import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {open} from '@tauri-apps/plugin-dialog'; -import {stat, readTextFile} from '@tauri-apps/plugin-fs'; +import {readTextFile} from '@tauri-apps/plugin-fs'; import {readText} from '@tauri-apps/plugin-clipboard-manager'; import {act} from '@testing-library/react'; import {DATA_IMPORT_FILE_LIMIT} from '@/utils/dataImportFile'; @@ -10,6 +10,10 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {ClipboardImportModal} from '@/components/modals/ClipboardImportModal'; const invokeMock = vi.mocked(invoke); +const client = {call: invoke}; +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); const translateMock = vi.hoisted(() => (key: string) => key); vi.mock('react-i18next', () => ({ @@ -19,10 +23,19 @@ vi.mock('react-i18next', () => ({ // Use the real icons; the global setup mock only stubs a fixed subset. vi.mock('lucide-react', async (importOriginal) => await importOriginal()); -vi.mock('@tauri-apps/plugin-clipboard-manager', () => ({ - readText: vi.fn(async () => 'sku\tname\nKB-101\tMechanical Keyboard'), +const platform = { + readClipboard: () => readText(), + chooseInputFile: async () => { + const path = await open(); + return typeof path === 'string' ? {name: path.split('/').pop()!, reference: path} : null; + }, + readInputFile: async (path: string) => new TextEncoder().encode(await readTextFile(path)), +}; +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, })); +vi.mock('@tauri-apps/plugin-clipboard-manager', () => ({readText: vi.fn()})); vi.mock('@tauri-apps/plugin-dialog', () => ({open: vi.fn()})); vi.mock('@tauri-apps/plugin-fs', () => ({stat: vi.fn(), readTextFile: vi.fn()})); @@ -49,9 +62,6 @@ describe('ClipboardImportModal target schema', () => { beforeEach(() => { invokeMock.mockReset(); vi.mocked(open).mockReset().mockResolvedValue('/tmp/items.csv'); - vi.mocked(stat) - .mockReset() - .mockResolvedValue({size: 40, isFile: true} as Awaited>); vi.mocked(readTextFile).mockReset().mockResolvedValue('sku,name\nKB-202,File Keyboard'); vi.mocked(readText).mockReset().mockResolvedValue('sku\tname\nKB-101\tMechanical Keyboard'); invokeMock.mockImplementation(async (command) => @@ -104,9 +114,7 @@ describe('ClipboardImportModal target schema', () => { await screen.findByPlaceholderText('clipboardImport.tableNamePlaceholder'); fireEvent.click(screen.getByRole('button', {name: 'clipboardImport.fileSource'})); await screen.findByText(`items.${extension}`); - expect(open).toHaveBeenCalledWith( - expect.objectContaining({multiple: false, directory: false}), - ); + expect(open).toHaveBeenCalled(); fireEvent.change(screen.getByPlaceholderText('clipboardImport.tableNamePlaceholder'), { target: {value: 'imported_items'}, }); @@ -151,16 +159,13 @@ describe('ClipboardImportModal target schema', () => { expect(readTextFile).not.toHaveBeenCalled(); }); - it('rejects large files before reading and retains the prior preview', async () => { - vi.mocked(stat).mockResolvedValue({ - size: DATA_IMPORT_FILE_LIMIT + 1, - isFile: true, - } as Awaited>); + it('rejects large files before parsing and retains the prior preview', async () => { + vi.mocked(readTextFile).mockResolvedValue('x'.repeat(DATA_IMPORT_FILE_LIMIT + 1)); renderModal(); await screen.findAllByText('Mechanical Keyboard'); fireEvent.click(screen.getByRole('button', {name: 'clipboardImport.fileSource'})); await screen.findByText('clipboardImport.fileTooLarge'); - expect(readTextFile).not.toHaveBeenCalled(); + expect(readTextFile).toHaveBeenCalled(); expect(screen.getAllByText('Mechanical Keyboard').length).toBeGreaterThan(0); expect(invokeMock).not.toHaveBeenCalledWith('execute_clipboard_import', expect.anything()); }); @@ -184,10 +189,7 @@ describe('ClipboardImportModal target schema', () => { it('retries the file picker after a failed first file pick', async () => { vi.mocked(readText).mockResolvedValue(''); - vi.mocked(stat).mockResolvedValueOnce({ - size: DATA_IMPORT_FILE_LIMIT + 1, - isFile: true, - } as Awaited>); + vi.mocked(readTextFile).mockResolvedValueOnce('x'.repeat(DATA_IMPORT_FILE_LIMIT + 1)); renderModal(); await screen.findByText('clipboardImport.noData'); fireEvent.click(screen.getByRole('button', {name: 'clipboardImport.fileSource'})); diff --git a/tests/components/modals/CommandPaletteGenerateSql.test.tsx b/packages/web-ui/tests/components/modals/CommandPaletteGenerateSql.test.tsx similarity index 94% rename from tests/components/modals/CommandPaletteGenerateSql.test.tsx rename to packages/web-ui/tests/components/modals/CommandPaletteGenerateSql.test.tsx index 70afa30e1..e29efaf10 100644 --- a/tests/components/modals/CommandPaletteGenerateSql.test.tsx +++ b/packages/web-ui/tests/components/modals/CommandPaletteGenerateSql.test.tsx @@ -23,6 +23,7 @@ vi.mock('@/hooks/useKeybindings', () => ({ })); const invokeMock = vi.fn(); +const clientMock = vi.hoisted(() => ({call: vi.fn()})); vi.mock('@tauri-apps/api/core', () => ({ invoke: (...args: unknown[]) => invokeMock(...args), @@ -66,6 +67,10 @@ vi.mock('@/hooks/useAlert', () => ({ useAlert: () => ({showAlert: vi.fn()}), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => clientMock, +})); + vi.mock('@/hooks/useCommandPaletteScope', () => ({ useActiveCommandPaletteScope: () => ({ connectionId: 'connection-panel', @@ -121,6 +126,10 @@ const Harness = () => { describe('command palette generate SQL', () => { beforeEach(() => { + clientMock.call.mockReset(); + clientMock.call.mockImplementation((command: string, request: unknown) => + invokeMock(command, request), + ); openEditorMock.mockReset(); navigateMock.mockReset(); invokeMock.mockReset(); diff --git a/tests/components/modals/CommandPaletteModal.test.tsx b/packages/web-ui/tests/components/modals/CommandPaletteModal.test.tsx similarity index 99% rename from tests/components/modals/CommandPaletteModal.test.tsx rename to packages/web-ui/tests/components/modals/CommandPaletteModal.test.tsx index 47d10a9f5..a06f8164e 100644 --- a/tests/components/modals/CommandPaletteModal.test.tsx +++ b/packages/web-ui/tests/components/modals/CommandPaletteModal.test.tsx @@ -60,6 +60,12 @@ vi.mock('@/hooks/useAlert', () => ({ useAlert: () => ({showAlert: showAlertMock}), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invokeMock(command, request), + }), +})); + const commandScopeState: CommandScope = { connectionId: 'connection-1', driver: 'postgres', diff --git a/tests/components/modals/ConfirmModal.test.tsx b/packages/web-ui/tests/components/modals/ConfirmModal.test.tsx similarity index 100% rename from tests/components/modals/ConfirmModal.test.tsx rename to packages/web-ui/tests/components/modals/ConfirmModal.test.tsx diff --git a/tests/components/modals/DumpDatabaseModal.test.tsx b/packages/web-ui/tests/components/modals/DumpDatabaseModal.test.tsx similarity index 89% rename from tests/components/modals/DumpDatabaseModal.test.tsx rename to packages/web-ui/tests/components/modals/DumpDatabaseModal.test.tsx index 08eb06593..58413644d 100644 --- a/tests/components/modals/DumpDatabaseModal.test.tsx +++ b/packages/web-ui/tests/components/modals/DumpDatabaseModal.test.tsx @@ -93,3 +93,13 @@ describe('DumpDatabaseModal', () => { expect(refreshNestedSchemaData).not.toHaveBeenCalled(); }); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: vi.fn(), subscribe: async () => () => {}}; + return {useTabularisClient: () => client}; +}); + +vi.mock('@/hooks/usePlatformCapabilities', () => { + const platform = {negotiation: {environment: 'tauri'}}; + return {usePlatformCapabilities: () => platform}; +}); diff --git a/tests/components/modals/ExportConnectionsModal.test.tsx b/packages/web-ui/tests/components/modals/ExportConnectionsModal.test.tsx similarity index 100% rename from tests/components/modals/ExportConnectionsModal.test.tsx rename to packages/web-ui/tests/components/modals/ExportConnectionsModal.test.tsx diff --git a/tests/components/modals/ExportProgressModal.test.tsx b/packages/web-ui/tests/components/modals/ExportProgressModal.test.tsx similarity index 100% rename from tests/components/modals/ExportProgressModal.test.tsx rename to packages/web-ui/tests/components/modals/ExportProgressModal.test.tsx diff --git a/tests/components/modals/GenerateSQLTemplates.test.tsx b/packages/web-ui/tests/components/modals/GenerateSQLTemplates.test.tsx similarity index 98% rename from tests/components/modals/GenerateSQLTemplates.test.tsx rename to packages/web-ui/tests/components/modals/GenerateSQLTemplates.test.tsx index 1d855b7f7..19e52f47c 100644 --- a/tests/components/modals/GenerateSQLTemplates.test.tsx +++ b/packages/web-ui/tests/components/modals/GenerateSQLTemplates.test.tsx @@ -51,6 +51,10 @@ vi.mock('@/components/ui/SqlPreview', () => ({ })); const invokeMock = vi.mocked(invoke); +const client = {call: invoke}; +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); const columns = [ { name: 'order id', diff --git a/packages/web-ui/tests/components/modals/ImportDatabaseModal.test.tsx b/packages/web-ui/tests/components/modals/ImportDatabaseModal.test.tsx new file mode 100644 index 000000000..f15ed9766 --- /dev/null +++ b/packages/web-ui/tests/components/modals/ImportDatabaseModal.test.tsx @@ -0,0 +1,259 @@ +import {StrictMode} from 'react'; +import {act, fireEvent, render, screen} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {ImportDatabaseModal} from '@/components/modals/ImportDatabaseModal'; + +const mocks = vi.hoisted(() => ({ + call: vi.fn(), + uploadFile: vi.fn(), + showAlert: vi.fn(), + subscribe: vi.fn().mockResolvedValue(() => {}), + platform: { + negotiation: {environment: 'browser'}, + readInputBlob: vi.fn().mockResolvedValue(new Blob(['SELECT 1;'])), + }, +})); +vi.mock('@/hooks/useTabularisClient', () => ({useTabularisClient: () => mocks})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({usePlatformCapabilities: () => mocks.platform})); +vi.mock('@/hooks/useDatabase', () => ({useDatabase: () => ({activeSchema: 'public'})})); +vi.mock('@/hooks/useAlert', () => ({useAlert: () => ({showAlert: mocks.showAlert})})); +const t = (key: string) => key; +vi.mock('react-i18next', () => ({useTranslation: () => ({t})})); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return {promise, resolve, reject}; +} +const props = () => ({ + isOpen: true, + onClose: vi.fn(), + onSuccess: vi.fn(), + connectionId: 'connection-1', + databaseName: 'app', + targetDatabase: 'app', + inputFile: {reference: 'file-1', name: 'dump.sql'}, +}); + +describe('ImportDatabaseModal cancellation', () => { + beforeEach(() => { + mocks.call.mockReset().mockResolvedValue(undefined); + mocks.uploadFile.mockReset(); + mocks.showAlert.mockClear(); + mocks.subscribe.mockClear(); + mocks.platform.negotiation.environment = 'browser'; + }); + + it('keeps native imports on the file path without uploading', async () => { + mocks.platform.negotiation.environment = 'tauri'; + const callbacks = props(); + render(); + await act(async () => {}); + expect(mocks.uploadFile).not.toHaveBeenCalled(); + expect(mocks.call).toHaveBeenCalledExactlyOnceWith( + 'import_database', + { + connectionId: 'connection-1', + database: 'app', + schema: 'public', + filePath: 'file-1', + }, + expect.objectContaining({cancellationId: expect.any(String)}), + ); + expect(callbacks.onSuccess).toHaveBeenCalledOnce(); + }); + + it.each(['button', 'escape'])( + 'cancels an upload locally using %s before any SQL can start', + async (action) => { + const upload = deferred<{token: string}>(); + mocks.uploadFile.mockReturnValue(upload.promise); + const callbacks = props(); + render(); + await act(async () => {}); + if (action === 'button') + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + else fireEvent.keyDown(document, {key: 'Escape'}); + await act(async () => {}); + expect(callbacks.onClose).toHaveBeenCalledOnce(); + expect(mocks.call).not.toHaveBeenCalled(); + await act(async () => { + upload.resolve({token: 'cancelled-upload'}); + }); + expect(mocks.call).not.toHaveBeenCalled(); + expect(callbacks.onSuccess).not.toHaveBeenCalled(); + }, + ); + + it.each(['resolve', 'reject'])( + 'ignores an old upload that will %s after closing and reopening', + async (outcome) => { + const oldUpload = deferred<{token: string}>(); + const newUpload = deferred<{token: string}>(); + mocks.uploadFile + .mockReturnValueOnce(oldUpload.promise) + .mockReturnValueOnce(newUpload.promise); + const callbacks = props(); + const view = render(); + await act(async () => {}); + view.rerender(); + view.rerender(); + await act(async () => { + if (outcome === 'resolve') oldUpload.resolve({token: 'old'}); + else oldUpload.reject(new Error('stale upload failed')); + }); + expect(mocks.call).not.toHaveBeenCalled(); + expect(screen.queryByText(/stale upload failed/)).not.toBeInTheDocument(); + expect(screen.getByRole('button', {name: 'common.cancel'})).toBeInTheDocument(); + await act(async () => { + newUpload.resolve({token: 'new'}); + }); + expect(mocks.call).toHaveBeenCalledExactlyOnceWith( + 'import_database', + { + connectionId: 'connection-1', + database: 'app', + schema: 'public', + uploadToken: 'new', + }, + expect.objectContaining({cancellationId: expect.any(String)}), + ); + expect(callbacks.onSuccess).toHaveBeenCalledOnce(); + }, + ); + + it('does not close a completed new opening when an old backend cancellation returns', async () => { + mocks.uploadFile.mockResolvedValue({token: 'ready'}); + const importing = deferred(); + const cancelling = deferred(); + mocks.call + .mockReturnValueOnce(importing.promise) + .mockReturnValueOnce(cancelling.promise) + .mockResolvedValue(undefined); + const callbacks = props(); + const view = render(); + await act(async () => {}); + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + view.rerender(); + view.rerender(); + await act(async () => {}); + expect(screen.getByText('dump.importSuccess')).toBeInTheDocument(); + await act(async () => { + cancelling.resolve(); + importing.resolve(); + }); + expect(callbacks.onClose).not.toHaveBeenCalled(); + expect(callbacks.onSuccess).toHaveBeenCalledOnce(); + }); + + it.each(['complete', 'retry'])( + 'keeps the live import after failed cancellation so it can %s', + async (outcome) => { + mocks.uploadFile.mockResolvedValue({token: 'ready'}); + const importing = deferred(); + mocks.call + .mockReturnValueOnce(importing.promise) + .mockRejectedValueOnce(new Error('temporarily offline')) + .mockResolvedValue(undefined); + const callbacks = props(); + render(); + await act(async () => {}); + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + await act(async () => {}); + expect(callbacks.onClose).not.toHaveBeenCalled(); + expect(screen.getByRole('button', {name: 'common.cancel'})).toBeInTheDocument(); + act(() => + mocks.subscribe.mock.calls[0][1]({ + connection_id: 'connection-1', + total_statements: 10, + statements_executed: 5, + percentage: 50, + current_operation: 'Still importing', + }), + ); + expect(screen.getByText('Still importing')).toBeInTheDocument(); + if (outcome === 'complete') { + await act(async () => { + importing.resolve(); + }); + expect(callbacks.onSuccess).toHaveBeenCalledOnce(); + expect(screen.getByText('dump.importSuccess')).toBeInTheDocument(); + } else { + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + await act(async () => {}); + expect( + mocks.call.mock.calls.filter(([command]) => command === 'cancel_import'), + ).toHaveLength(2); + expect(callbacks.onClose).toHaveBeenCalledOnce(); + await act(async () => { + importing.resolve(); + }); + expect(callbacks.onSuccess).not.toHaveBeenCalled(); + } + }, + ); + + it('keeps an import completion that arrives while cancellation is pending', async () => { + mocks.uploadFile.mockResolvedValue({token: 'ready'}); + const importing = deferred(); + const cancelling = deferred(); + mocks.call.mockReturnValueOnce(importing.promise).mockReturnValueOnce(cancelling.promise); + const callbacks = props(); + render(); + await act(async () => {}); + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + await act(async () => { + importing.resolve(); + }); + expect(callbacks.onSuccess).toHaveBeenCalledOnce(); + expect(screen.getByText('dump.importSuccess')).toBeInTheDocument(); + await act(async () => { + cancelling.reject(new Error('job already finished')); + }); + expect(callbacks.onClose).not.toHaveBeenCalled(); + expect(screen.getByText('dump.importSuccess')).toBeInTheDocument(); + }); + + it('does not start SQL after unmounting during upload', async () => { + const upload = deferred<{token: string}>(); + mocks.uploadFile.mockReturnValue(upload.promise); + const view = render(); + await act(async () => {}); + view.unmount(); + await act(async () => { + upload.resolve({token: 'old'}); + }); + expect(mocks.call).not.toHaveBeenCalled(); + }); + + it('starts once under StrictMode and cancels an already dispatched import on the backend', async () => { + mocks.uploadFile.mockResolvedValue({token: 'ready'}); + const importing = deferred(); + mocks.call.mockImplementation((command: string) => + command === 'import_database' ? importing.promise : Promise.resolve(), + ); + const callbacks = props(); + render( + + + , + ); + await act(async () => {}); + expect(mocks.uploadFile).toHaveBeenCalledOnce(); + expect(mocks.call).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', {name: 'common.cancel'})); + await act(async () => {}); + expect(mocks.call).toHaveBeenLastCalledWith('cancel_import', { + connectionId: 'connection-1', + }); + expect(callbacks.onClose).toHaveBeenCalledOnce(); + await act(async () => { + importing.resolve(); + }); + expect(callbacks.onSuccess).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/components/modals/ImportFromAppModal.test.tsx b/packages/web-ui/tests/components/modals/ImportFromAppModal.test.tsx similarity index 53% rename from tests/components/modals/ImportFromAppModal.test.tsx rename to packages/web-ui/tests/components/modals/ImportFromAppModal.test.tsx index e3b3aa7a4..95a94bef7 100644 --- a/tests/components/modals/ImportFromAppModal.test.tsx +++ b/packages/web-ui/tests/components/modals/ImportFromAppModal.test.tsx @@ -1,32 +1,35 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; import {render, screen, fireEvent, waitFor} from '@testing-library/react'; -import {invoke} from '@tauri-apps/api/core'; -import {open} from '@tauri-apps/plugin-dialog'; -import {readTextFile} from '@tauri-apps/plugin-fs'; import {ImportFromAppModal} from '@/components/modals/ImportFromAppModal'; -// The global plugin-fs mock only exposes writeTextFile; the modal also needs -// readTextFile for the Tabularis JSON path. -vi.mock('@tauri-apps/plugin-fs', () => ({ - writeTextFile: vi.fn(), - readTextFile: vi.fn(), - BaseDirectory: {Document: 1}, +const mocks = vi.hoisted(() => ({ + call: vi.fn(), + chooseInputFile: vi.fn(), + readInputFile: vi.fn(), + openExternalUrl: vi.fn(), })); vi.mock('@/hooks/useDatabase', () => ({ useDatabase: () => ({connectionGroups: []}), })); -// The real Select is portal/ref-heavy; these tests drive the modal via the -// default resolutions, so a no-op stand-in is enough. +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mocks, +})); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + negotiation: {environment: 'tauri'}, + chooseInputFile: mocks.chooseInputFile, + readInputFile: mocks.readInputFile, + openExternalUrl: mocks.openExternalUrl, + }), +})); + vi.mock('@/components/ui/Select', () => ({ Select: () => null, })); -const mockInvoke = vi.mocked(invoke); -const mockOpen = vi.mocked(open); -const mockReadTextFile = vi.mocked(readTextFile); - const TAB_PAYLOAD = { version: 1, groups: [], @@ -71,34 +74,38 @@ function passwordInput(): HTMLInputElement { describe('ImportFromAppModal — Tabularis JSON import', () => { beforeEach(() => { vi.clearAllMocks(); - mockInvoke.mockImplementation((cmd: string) => { - if (cmd === 'list_connection_import_sources') return Promise.resolve([]); - if (cmd === 'preview_tabularis_import') return Promise.resolve(PREVIEW); + mocks.chooseInputFile.mockResolvedValue({ + name: 'export.json', + reference: '/tmp/export.json', + }); + mocks.readInputFile.mockResolvedValue( + new TextEncoder().encode(JSON.stringify(TAB_PAYLOAD)), + ); + mocks.call.mockImplementation((command: string) => { + if (command === 'list_connection_import_sources') return Promise.resolve([]); + if (command === 'preview_tabularis_import_file') { + return Promise.resolve({kind: 'preview', preview: PREVIEW}); + } return Promise.resolve(undefined); }); - mockOpen.mockResolvedValue('/tmp/export.json'); }); - it('previews a plaintext export (no silent import), then applies on confirm', async () => { - mockReadTextFile.mockResolvedValue(JSON.stringify(TAB_PAYLOAD)); + it('previews a plaintext export through an opaque file reference, then applies', async () => { const {onImported, onClose} = renderModal(); await clickContinue(); - // Preview is fetched; nothing is imported yet and the modal stays open. await waitFor(() => { - expect(mockInvoke).toHaveBeenCalledWith('preview_tabularis_import', { - payload: TAB_PAYLOAD, + expect(mocks.call).toHaveBeenCalledWith('preview_tabularis_import_file', { + file: {kind: 'serverPath', path: '/tmp/export.json'}, }); }); - expect(mockInvoke).not.toHaveBeenCalledWith('apply_tabularis_import', expect.anything()); expect(onClose).not.toHaveBeenCalled(); fireEvent.click(await screen.findByText('connections.importFromApp.importCount')); await waitFor(() => { - expect(mockInvoke).toHaveBeenCalledWith('apply_tabularis_import', { - payload: TAB_PAYLOAD, + expect(mocks.call).toHaveBeenCalledWith('apply_prepared_tabularis_import', { resolutions: [{index: 0, action: 'import', groupId: ''}], }); }); @@ -106,59 +113,55 @@ describe('ImportFromAppModal — Tabularis JSON import', () => { expect(onClose).toHaveBeenCalledTimes(1); }); - it('prompts for a password on an encrypted export, decrypts, then previews', async () => { - const envelope = {encrypted: true, ciphertext: '…'}; - mockReadTextFile.mockResolvedValue(JSON.stringify(envelope)); - mockInvoke.mockImplementation((cmd: string) => { - if (cmd === 'list_connection_import_sources') return Promise.resolve([]); - if (cmd === 'decrypt_export_payload') return Promise.resolve(TAB_PAYLOAD); - if (cmd === 'preview_tabularis_import') return Promise.resolve(PREVIEW); + it('prompts for a password before the backend decrypts and previews', async () => { + mocks.call.mockImplementation((command: string, request?: {password?: string}) => { + if (command === 'list_connection_import_sources') return Promise.resolve([]); + if (command === 'preview_tabularis_import_file') { + return Promise.resolve( + request?.password + ? {kind: 'preview', preview: PREVIEW} + : {kind: 'passwordRequired'}, + ); + } return Promise.resolve(undefined); }); renderModal(); await clickContinue(); - await waitFor(() => expect(passwordInput()).toBeInTheDocument()); - expect(mockInvoke).not.toHaveBeenCalledWith('preview_tabularis_import', expect.anything()); fireEvent.change(passwordInput(), {target: {value: 'hunter2'}}); fireEvent.click(screen.getByText('connections.importPasswordModal.unlock')); await waitFor(() => { - expect(mockInvoke).toHaveBeenCalledWith('decrypt_export_payload', { - envelope, + expect(mocks.call).toHaveBeenCalledWith('preview_tabularis_import_file', { + file: {kind: 'serverPath', path: '/tmp/export.json'}, password: 'hunter2', }); }); - // After decrypt it previews (rather than importing and closing silently). - expect(mockInvoke).toHaveBeenCalledWith('preview_tabularis_import', { - payload: TAB_PAYLOAD, - }); await screen.findByText('connections.importFromApp.importCount'); }); it('surfaces a wrong-password error and keeps the modal open', async () => { - const envelope = {encrypted: true, ciphertext: '…'}; - mockReadTextFile.mockResolvedValue(JSON.stringify(envelope)); - mockInvoke.mockImplementation((cmd: string) => { - if (cmd === 'list_connection_import_sources') return Promise.resolve([]); - if (cmd === 'decrypt_export_payload') - return Promise.reject('wrong password or corrupted file'); + mocks.call.mockImplementation((command: string, request?: {password?: string}) => { + if (command === 'list_connection_import_sources') return Promise.resolve([]); + if (command === 'preview_tabularis_import_file') { + return request?.password + ? Promise.reject('wrong password or corrupted file') + : Promise.resolve({kind: 'passwordRequired'}); + } return Promise.resolve(undefined); }); const {onImported, onClose} = renderModal(); await clickContinue(); await waitFor(() => expect(passwordInput()).toBeInTheDocument()); - fireEvent.change(passwordInput(), {target: {value: 'bad'}}); fireEvent.click(screen.getByText('connections.importPasswordModal.unlock')); await waitFor(() => { expect(screen.getByText(/wrong password or corrupted file/)).toBeInTheDocument(); }); - expect(mockInvoke).not.toHaveBeenCalledWith('preview_tabularis_import', expect.anything()); expect(onImported).not.toHaveBeenCalled(); expect(onClose).not.toHaveBeenCalled(); }); diff --git a/tests/components/modals/K8sConnectionsModal.test.tsx b/packages/web-ui/tests/components/modals/K8sConnectionsModal.test.tsx similarity index 95% rename from tests/components/modals/K8sConnectionsModal.test.tsx rename to packages/web-ui/tests/components/modals/K8sConnectionsModal.test.tsx index c186e9ed3..bd24f12fb 100644 --- a/tests/components/modals/K8sConnectionsModal.test.tsx +++ b/packages/web-ui/tests/components/modals/K8sConnectionsModal.test.tsx @@ -75,17 +75,30 @@ vi.mock('@/components/ui/Select', () => ({ ), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call: vi.fn(), subscribe: vi.fn()}), +})); + vi.mock('@/utils/k8s', () => ({ - loadK8sConnections: k8sMocks.loadK8sConnections, - saveK8sConnection: k8sMocks.saveK8sConnection, - updateK8sConnection: k8sMocks.updateK8sConnection, - deleteK8sConnection: k8sMocks.deleteK8sConnection, - testK8sConnection: k8sMocks.testK8sConnection, - getK8sContexts: k8sMocks.getK8sContexts, - getK8sNamespaces: k8sMocks.getK8sNamespaces, - getK8sResources: k8sMocks.getK8sResources, - getK8sResourcePorts: k8sMocks.getK8sResourcePorts, - validateK8sPath: k8sMocks.validateK8sPath, + loadK8sConnections: () => k8sMocks.loadK8sConnections(), + saveK8sConnection: (input: unknown) => k8sMocks.saveK8sConnection(input), + updateK8sConnection: (id: string, input: unknown) => k8sMocks.updateK8sConnection(id, input), + deleteK8sConnection: (id: string) => k8sMocks.deleteK8sConnection(id), + testK8sConnection: (context: string, namespace: string, options: unknown) => + k8sMocks.testK8sConnection(context, namespace, options), + getK8sContexts: (options: unknown) => k8sMocks.getK8sContexts(options), + getK8sNamespaces: (context: string, options: unknown) => + k8sMocks.getK8sNamespaces(context, options), + getK8sResources: (context: string, namespace: string, resourceType: string, options: unknown) => + k8sMocks.getK8sResources(context, namespace, resourceType, options), + getK8sResourcePorts: ( + context: string, + namespace: string, + resourceType: string, + resourceName: string, + options: unknown, + ) => k8sMocks.getK8sResourcePorts(context, namespace, resourceType, resourceName, options), + validateK8sPath: (path: string, kind: string) => k8sMocks.validateK8sPath(path, kind), validateK8sConnection: k8sMocks.validateK8sConnection, })); diff --git a/packages/web-ui/tests/components/modals/LocalThemePackageModal.browser.test.tsx b/packages/web-ui/tests/components/modals/LocalThemePackageModal.browser.test.tsx new file mode 100644 index 000000000..07c1eb738 --- /dev/null +++ b/packages/web-ui/tests/components/modals/LocalThemePackageModal.browser.test.tsx @@ -0,0 +1,117 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {fireEvent, render, screen} from '@testing-library/react'; +import {LocalThemePackageModal} from '@/components/modals/LocalThemePackageModal'; +import {THEME_PACKAGE_UPLOAD_PURPOSE} from '@/api/contract'; + +const mocks = vi.hoisted(() => ({ + call: vi.fn(), + uploadFile: vi.fn(), + chooseInputFile: vi.fn(), + readInputBlob: vi.fn(), + previewTheme: vi.fn(), + cancelPreview: vi.fn(), + refreshCatalog: vi.fn(), +})); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call: mocks.call, uploadFile: mocks.uploadFile}), +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + negotiation: {environment: 'browser'}, + chooseInputFile: mocks.chooseInputFile, + readInputBlob: mocks.readInputBlob, + }), +})); +vi.mock('@/hooks/useTheme', () => ({useTheme: () => mocks})); +vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string) => key})})); +vi.mock('@/components/ui/ThemeSqlSample', () => ({ThemeSqlSample: () =>
SQL sample
})); + +const preview = { + digest: 'verified-digest', + manifest: {name: 'local-theme', version: '1.0.0'}, + variants: [ + { + id: 'native-id', + name: 'Local dark', + mode: 'dark', + origin: { + kind: 'installed', + identity: { + registryKey: 'a'.repeat(64), + packageName: 'local-theme', + variantId: 'dark', + }, + }, + }, + ], +}; +const archive = new Blob(['zip bytes'], {type: 'application/zip'}); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.chooseInputFile.mockResolvedValue({name: 'theme.zip', reference: 'browser-file-1'}); + mocks.readInputBlob.mockResolvedValue(archive); + mocks.uploadFile.mockResolvedValue({ + token: 'upload-token', + fileName: 'theme.zip', + mimeType: 'application/zip', + size: 9, + expiresAt: '', + }); + mocks.refreshCatalog.mockResolvedValue(undefined); + mocks.call.mockImplementation(async (command: string) => { + if (command === 'preview_local_theme_package') return preview; + if (command === 'install_local_theme_package') return {warnings: []}; + throw new Error(`Unexpected ${command}`); + }); +}); + +describe('local theme package UI in the browser', () => { + it('uploads the archive once and binds preview and install to the upload token', async () => { + render(); + fireEvent.click(screen.getByRole('button', {name: 'themePackages.chooseArchive'})); + await screen.findByText('local-theme · 1.0.0'); + // Browsers never see a server path, so the chosen file's name is shown. + expect(screen.getByText('theme.zip')).toBeInTheDocument(); + expect(mocks.readInputBlob).toHaveBeenCalledWith('browser-file-1'); + expect(mocks.uploadFile).toHaveBeenCalledExactlyOnceWith({ + contents: archive, + fileName: 'theme.zip', + purpose: THEME_PACKAGE_UPLOAD_PURPOSE, + }); + expect(mocks.call).toHaveBeenCalledWith('preview_local_theme_package', { + uploadToken: 'upload-token', + }); + + fireEvent.click(screen.getByRole('button', {name: 'themePackages.install'})); + await screen.findByText('themePackages.installedHint'); + expect(mocks.call).toHaveBeenCalledWith('install_local_theme_package', { + uploadToken: 'upload-token', + packageName: 'local-theme', + expectedDigest: 'verified-digest', + }); + expect(mocks.uploadFile).toHaveBeenCalledOnce(); + expect(mocks.call.mock.calls.flat()).not.toContainEqual( + expect.objectContaining({path: expect.anything()}), + ); + }); + + it('does not upload or preview when the file chooser is cancelled', async () => { + mocks.chooseInputFile.mockResolvedValueOnce(null); + render(); + fireEvent.click(screen.getByRole('button', {name: 'themePackages.chooseArchive'})); + await screen.findByRole('button', {name: 'themePackages.chooseArchive'}); + await vi.waitFor(() => expect(mocks.chooseInputFile).toHaveBeenCalled()); + expect(mocks.uploadFile).not.toHaveBeenCalled(); + expect(mocks.call).not.toHaveBeenCalled(); + }); + + it('surfaces an upload failure without exposing an install action', async () => { + mocks.uploadFile.mockRejectedValueOnce(new Error('Upload rejected')); + render(); + fireEvent.click(screen.getByRole('button', {name: 'themePackages.chooseArchive'})); + expect(await screen.findByRole('alert')).toHaveTextContent('Upload rejected'); + expect(screen.getByRole('button', {name: 'themePackages.install'})).toBeDisabled(); + expect(mocks.call).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/components/modals/LocalThemePackageModal.test.tsx b/packages/web-ui/tests/components/modals/LocalThemePackageModal.test.tsx similarity index 95% rename from tests/components/modals/LocalThemePackageModal.test.tsx rename to packages/web-ui/tests/components/modals/LocalThemePackageModal.test.tsx index 2db57db05..97604dc2e 100644 --- a/tests/components/modals/LocalThemePackageModal.test.tsx +++ b/packages/web-ui/tests/components/modals/LocalThemePackageModal.test.tsx @@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({ cancelPreview: vi.fn(), refreshCatalog: vi.fn(), })); +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); vi.mock('@tauri-apps/plugin-dialog', () => ({open: mocks.open})); vi.mock('@/hooks/useTheme', () => ({useTheme: () => mocks})); diff --git a/tests/components/modals/MigrationChecklistModal.test.tsx b/packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx similarity index 99% rename from tests/components/modals/MigrationChecklistModal.test.tsx rename to packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx index dd2dc24b4..6143bccec 100644 --- a/tests/components/modals/MigrationChecklistModal.test.tsx +++ b/packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx @@ -6,6 +6,7 @@ import type {PluginManifest} from '@/types/plugins'; import type {MigrationOutcome} from '@/hooks/useBuiltinDriverMigration'; import {openUrl} from '@tauri-apps/plugin-opener'; +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const settingsMock = { settings: {} as {knownCapabilityGaps?: Record}, updateSetting: vi.fn<(key: string, value: unknown) => Promise>(), diff --git a/tests/components/modals/NewConnectionModal.test.tsx b/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx similarity index 95% rename from tests/components/modals/NewConnectionModal.test.tsx rename to packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx index af98eb5ce..b2890c28a 100644 --- a/tests/components/modals/NewConnectionModal.test.tsx +++ b/packages/web-ui/tests/components/modals/NewConnectionModal.test.tsx @@ -2,7 +2,18 @@ import {useState, type ComponentProps, type ReactNode} from 'react'; import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest'; import {act, render, screen, fireEvent, waitFor} from '@testing-library/react'; import {invoke} from '@tauri-apps/api/core'; -import {save} from '@tauri-apps/plugin-dialog'; +const save = vi.hoisted(() => vi.fn()); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + supports: (capability: string) => capability !== 'restartApplication', + chooseSaveTarget: async (options: unknown) => { + const reference = await save(options); + return reference ? {reference} : null; + }, + chooseServerPath: vi.fn(), + }), +})); import {NewConnectionModal} from '@/components/modals/NewConnectionModal'; import {PluginSlotContext} from '@/contexts/PluginSlotContext'; import type {PluginSlotRegistryType} from '@/contexts/PluginSlotContext'; @@ -20,6 +31,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 | undefined, @@ -57,6 +69,14 @@ vi.mock('@tauri-apps/api/event', () => ({ listen: eventMocks.listen, })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invoke(command, request), + subscribe: (event: string, handler: (payload: unknown) => void) => + eventMocks.listen(event, ({payload}: {payload: unknown}) => handler(payload)), + }), +})); + vi.mock('@/hooks/useAlert', () => ({ useAlert: () => ({showAlert: alertMocks.showAlert}), })); @@ -111,6 +131,7 @@ vi.mock('@/hooks/useDrivers', () => ({ file_based: false, folder_based: false, connection_string: true, + connection_uri: driverState.uriPassthrough, connection_string_examples: [ { label: 'Local MySQL', @@ -169,6 +190,7 @@ vi.mock('@/hooks/usePluginSlotRegistry', () => ({ afterEach(() => { driverState.connectionFields = undefined; + driverState.uriPassthrough = false; }); vi.mock('@/hooks/useSettings', () => ({ @@ -222,17 +244,38 @@ vi.mock('@/hooks/useConnectionCatalogue', () => ({ })); vi.mock('@/utils/ssh', () => ({ - loadSshConnections: sshMocks.loadSshConnections, - testSshConnection: sshMocks.testSshConnection, + loadSshConnections: () => sshMocks.loadSshConnections(), + testSshConnection: (ssh: unknown, options: unknown) => sshMocks.testSshConnection(ssh, options), })); vi.mock('@/utils/k8s', () => ({ - loadK8sConnections: k8sMocks.loadK8sConnections, - getK8sContexts: k8sMocks.getK8sContexts, - getK8sNamespaces: k8sMocks.getK8sNamespaces, - getK8sResources: k8sMocks.getK8sResources, - getK8sResourcePorts: k8sMocks.getK8sResourcePorts, - validateK8sPath: k8sMocks.validateK8sPath, + loadK8sConnections: () => k8sMocks.loadK8sConnections(), + getK8sContexts: (options?: unknown) => + options === undefined ? k8sMocks.getK8sContexts() : k8sMocks.getK8sContexts(options), + getK8sNamespaces: (context: string, options?: unknown) => + options === undefined + ? k8sMocks.getK8sNamespaces(context) + : k8sMocks.getK8sNamespaces(context, options), + getK8sResources: ( + context: string, + namespace: string, + resourceType: string, + options?: unknown, + ) => + options === undefined + ? k8sMocks.getK8sResources(context, namespace, resourceType) + : k8sMocks.getK8sResources(context, namespace, resourceType, options), + getK8sResourcePorts: ( + context: string, + namespace: string, + resourceType: string, + resourceName: string, + options?: unknown, + ) => + options === undefined + ? k8sMocks.getK8sResourcePorts(context, namespace, resourceType, resourceName) + : k8sMocks.getK8sResourcePorts(context, namespace, resourceType, resourceName, options), + validateK8sPath: (path: string, kind: string) => k8sMocks.validateK8sPath(path, kind), })); vi.mock('@/components/modals/NewConnectionModal/AppearanceSection', () => ({ @@ -487,6 +530,33 @@ 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', @@ -1375,7 +1445,7 @@ describe('NewConnectionModal SQLite file creation', () => { await waitFor(() => expect(pathInput).toHaveValue('/tmp/customers.db')); expect(save).toHaveBeenCalledWith({ title: 'connections.newSqliteDatabase.dialogTitle', - defaultPath: 'database.db', + suggestedName: 'database.db', filters: [ { name: 'connections.newSqliteDatabase.fileType', diff --git a/tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx b/packages/web-ui/tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx similarity index 94% rename from tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx rename to packages/web-ui/tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx index 684d7c5f3..b196e505d 100644 --- a/tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx +++ b/packages/web-ui/tests/components/modals/NewConnectionModal/AppearanceSection.test.tsx @@ -2,6 +2,15 @@ import {describe, it, expect, vi} from 'vitest'; import {render, screen, fireEvent, waitFor} from '@testing-library/react'; import {AppearanceSection} from '@/components/modals/NewConnectionModal/AppearanceSection'; +const platformMocks = vi.hoisted(() => ({ + chooseConnectionIcon: vi.fn().mockResolvedValue('connection-icons/1-abcd.png'), + resolveAppAsset: vi.fn(async (path: string) => `tauri://${path}`), +})); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platformMocks, +})); + // Mock react-i18next so the section renders predictably regardless of locale files vi.mock('react-i18next', () => ({ useTranslation: () => ({t: (k: string) => k, i18n: {language: 'en'}}), @@ -158,16 +167,12 @@ describe('AppearanceSection — icon tabs', () => { it('uploads an image and stores the returned path', async () => { const onChange = vi.fn(); - const {invoke} = await import('@tauri-apps/api/core'); render(); fireEvent.click(screen.getByRole('tab', {name: /image/i})); fireEvent.click(screen.getByRole('button', {name: /choose image/i})); // Wait for the async upload to resolve await waitFor(() => { - expect(invoke).toHaveBeenCalledWith('save_connection_icon', { - connectionId: 'conn1', - sourcePath: '/tmp/picked.png', - }); + expect(platformMocks.chooseConnectionIcon).toHaveBeenCalledWith('conn1'); }); await waitFor(() => { expect(onChange).toHaveBeenCalledWith({ @@ -179,8 +184,7 @@ describe('AppearanceSection — icon tabs', () => { it('does not eagerly delete previous image on pick', async () => { const onChange = vi.fn(); const onImageUploaded = vi.fn(); - const {invoke} = await import('@tauri-apps/api/core'); - vi.mocked(invoke).mockClear(); + platformMocks.chooseConnectionIcon.mockClear(); render( { fireEvent.click(screen.getByRole('tab', {name: /image/i})); fireEvent.click(screen.getByRole('button', {name: /choose image/i})); await waitFor(() => { - expect(invoke).toHaveBeenCalledWith('save_connection_icon', expect.any(Object)); + expect(platformMocks.chooseConnectionIcon).toHaveBeenCalledWith('conn1'); }); // The previous image must NOT be deleted as part of the pick - const deleteCalls = vi - .mocked(invoke) - .mock.calls.filter((c) => c[0] === 'delete_connection_icon'); - expect(deleteCalls).toHaveLength(0); + expect(platformMocks.chooseConnectionIcon).toHaveBeenCalledTimes(1); // onImageUploaded callback should have been called with the new path expect(onImageUploaded).toHaveBeenCalledWith('connection-icons/1-abcd.png'); }); diff --git a/tests/components/modals/PluginInstallConfirmModal.test.tsx b/packages/web-ui/tests/components/modals/PluginInstallConfirmModal.test.tsx similarity index 82% rename from tests/components/modals/PluginInstallConfirmModal.test.tsx rename to packages/web-ui/tests/components/modals/PluginInstallConfirmModal.test.tsx index 2d6fbfb60..19aad3d46 100644 --- a/tests/components/modals/PluginInstallConfirmModal.test.tsx +++ b/packages/web-ui/tests/components/modals/PluginInstallConfirmModal.test.tsx @@ -1,10 +1,22 @@ +import type {ReactElement} from 'react'; import {describe, it, expect, vi, beforeEach} from 'vitest'; import {render, screen, waitFor} from '@testing-library/react'; import {invoke} from '@tauri-apps/api/core'; import {PluginInstallConfirmModal} from '@/components/modals/PluginInstallConfirmModal'; import type {DeepLinkInstallRequest} from '@/hooks/useDeepLinkInstall'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openExternalUrl: vi.fn()}), +})); const request: DeepLinkInstallRequest = {slug: 'firestore', version: null, registry: null}; +const client = new TabularisClient(new TauriTransport()); + +const renderWithClient = (ui: ReactElement) => + render({ui}); const preview = (over: Record = {}) => ({ id: 'firestore', @@ -26,7 +38,7 @@ describe('PluginInstallConfirmModal', () => { it('shows the install button when not installed', async () => { vi.mocked(invoke).mockResolvedValue(preview({install_action: 'install'})); - render( + renderWithClient( { vi.mocked(invoke).mockResolvedValue( preview({install_action: 'update', installed_version: '1.0.0'}), ); - render( + renderWithClient( { vi.mocked(invoke).mockResolvedValue( preview({install_action: 'up_to_date', installed_version: '1.2.3'}), ); - render( + renderWithClient( vi.fn()); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openExternalUrl: openUrl}), +})); import {PluginReadmeModal} from '@/components/modals/PluginReadmeModal'; import type {PluginReadme} from '@/types/plugins'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; const readme = (over: Partial = {}): PluginReadme => ({ html: '

Db2 Driver

Connect to Db2.

', @@ -13,12 +20,18 @@ const readme = (over: Partial = {}): PluginReadme => ({ ...over, }); +const client = new TabularisClient(new TauriTransport()); + const renderModal = () => - render(); + render( + + + , + ); beforeEach(() => { vi.mocked(invoke).mockReset(); - vi.mocked(openUrl).mockReset(); + openUrl.mockReset(); }); describe('PluginReadmeModal', () => { diff --git a/tests/components/modals/QueryModal.test.tsx b/packages/web-ui/tests/components/modals/QueryModal.test.tsx similarity index 100% rename from tests/components/modals/QueryModal.test.tsx rename to packages/web-ui/tests/components/modals/QueryModal.test.tsx diff --git a/tests/components/modals/QuerySelectionModal.test.tsx b/packages/web-ui/tests/components/modals/QuerySelectionModal.test.tsx similarity index 100% rename from tests/components/modals/QuerySelectionModal.test.tsx rename to packages/web-ui/tests/components/modals/QuerySelectionModal.test.tsx diff --git a/tests/components/modals/ShortcutsEditModal.test.tsx b/packages/web-ui/tests/components/modals/ShortcutsEditModal.test.tsx similarity index 100% rename from tests/components/modals/ShortcutsEditModal.test.tsx rename to packages/web-ui/tests/components/modals/ShortcutsEditModal.test.tsx diff --git a/tests/components/modals/TableTargetModals.test.tsx b/packages/web-ui/tests/components/modals/TableTargetModals.test.tsx similarity index 96% rename from tests/components/modals/TableTargetModals.test.tsx rename to packages/web-ui/tests/components/modals/TableTargetModals.test.tsx index 24c14cef6..1e79037b8 100644 --- a/tests/components/modals/TableTargetModals.test.tsx +++ b/packages/web-ui/tests/components/modals/TableTargetModals.test.tsx @@ -7,6 +7,7 @@ import {GenerateSQLModal} from '@/components/modals/GenerateSQLModal'; import {SchemaModal} from '@/components/modals/SchemaModal'; const invokeMock = vi.mocked(invoke); +const clientMock = vi.hoisted(() => ({call: vi.fn()})); const showAlertMock = vi.fn(); const translateMock = vi.hoisted(() => (key: string) => key); @@ -49,6 +50,10 @@ vi.mock('@/hooks/useAlert', () => ({ useAlert: () => ({showAlert: showAlertMock}), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => clientMock, +})); + vi.mock('@/components/ui/SqlPreview', () => ({ SqlPreview: ({sql}: {sql: string}) =>
{sql}
, })); @@ -62,6 +67,10 @@ const LocationState = () => { describe('table target modals', () => { beforeEach(() => { invokeMock.mockReset(); + clientMock.call.mockReset(); + clientMock.call.mockImplementation((command: string, request: unknown) => + invokeMock(command, request), + ); showAlertMock.mockReset(); }); diff --git a/tests/components/modals/ThemeDeepLinkInstall.test.tsx b/packages/web-ui/tests/components/modals/ThemeDeepLinkInstall.test.tsx similarity index 96% rename from tests/components/modals/ThemeDeepLinkInstall.test.tsx rename to packages/web-ui/tests/components/modals/ThemeDeepLinkInstall.test.tsx index a3144f8d5..a5523c8de 100644 --- a/tests/components/modals/ThemeDeepLinkInstall.test.tsx +++ b/packages/web-ui/tests/components/modals/ThemeDeepLinkInstall.test.tsx @@ -2,6 +2,8 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {PluginInstallConfirmModal} from '@/components/modals/PluginInstallConfirmModal'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const mocks = vi.hoisted(() => ({invoke: vi.fn(), refreshCatalog: vi.fn()})); vi.mock('lucide-react', async () => await vi.importActual('lucide-react')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); diff --git a/tests/components/modals/ThemeDocumentModal.test.tsx b/packages/web-ui/tests/components/modals/ThemeDocumentModal.test.tsx similarity index 98% rename from tests/components/modals/ThemeDocumentModal.test.tsx rename to packages/web-ui/tests/components/modals/ThemeDocumentModal.test.tsx index 004016550..08f86779a 100644 --- a/tests/components/modals/ThemeDocumentModal.test.tsx +++ b/packages/web-ui/tests/components/modals/ThemeDocumentModal.test.tsx @@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({ updatePersonalSource: vi.fn(), updateCustomTheme: vi.fn(), })); +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); vi.mock('@/components/ui/ThemeSqlSample', () => ({ ThemeSqlSample: () =>
SQL sample
, diff --git a/tests/components/modals/ThemeReadmeModal.test.tsx b/packages/web-ui/tests/components/modals/ThemeReadmeModal.test.tsx similarity index 95% rename from tests/components/modals/ThemeReadmeModal.test.tsx rename to packages/web-ui/tests/components/modals/ThemeReadmeModal.test.tsx index e2701634c..6bba3ffa9 100644 --- a/tests/components/modals/ThemeReadmeModal.test.tsx +++ b/packages/web-ui/tests/components/modals/ThemeReadmeModal.test.tsx @@ -3,6 +3,8 @@ import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {ThemeReadmeModal} from '@/components/modals/ThemeReadmeModal'; import {ThemeRegistryInstall} from '@/components/modals/ThemeRegistryInstall'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const mocks = vi.hoisted(() => ({invoke: vi.fn(), open: vi.fn()})); vi.mock('lucide-react', async () => await vi.importActual('lucide-react')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); diff --git a/tests/components/modals/ThemeRecoveryModal.test.tsx b/packages/web-ui/tests/components/modals/ThemeRecoveryModal.test.tsx similarity index 91% rename from tests/components/modals/ThemeRecoveryModal.test.tsx rename to packages/web-ui/tests/components/modals/ThemeRecoveryModal.test.tsx index 4c7e0c6c4..f5b53ae5f 100644 --- a/tests/components/modals/ThemeRecoveryModal.test.tsx +++ b/packages/web-ui/tests/components/modals/ThemeRecoveryModal.test.tsx @@ -3,6 +3,8 @@ import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {ThemeRecoveryModal} from '@/components/modals/ThemeRecoveryModal'; const mocks = vi.hoisted(() => ({invoke: vi.fn(), refresh: vi.fn()})); +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string) => key})})); vi.mock('@/hooks/useTheme', () => ({useTheme: () => ({refreshCatalog: mocks.refresh})})); diff --git a/tests/components/modals/ThemeRegistryInstall.test.tsx b/packages/web-ui/tests/components/modals/ThemeRegistryInstall.test.tsx similarity index 97% rename from tests/components/modals/ThemeRegistryInstall.test.tsx rename to packages/web-ui/tests/components/modals/ThemeRegistryInstall.test.tsx index ca3eda3db..4f3d411f2 100644 --- a/tests/components/modals/ThemeRegistryInstall.test.tsx +++ b/packages/web-ui/tests/components/modals/ThemeRegistryInstall.test.tsx @@ -2,6 +2,8 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {ThemeRegistryInstall} from '@/components/modals/ThemeRegistryInstall'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const mocks = vi.hoisted(() => ({invoke: vi.fn(), refreshCatalog: vi.fn()})); vi.mock('lucide-react', async () => await vi.importActual('lucide-react')); vi.mock('@tauri-apps/api/core', () => ({invoke: mocks.invoke})); diff --git a/tests/components/modals/TriggerEditorModal.test.tsx b/packages/web-ui/tests/components/modals/TriggerEditorModal.test.tsx similarity index 96% rename from tests/components/modals/TriggerEditorModal.test.tsx rename to packages/web-ui/tests/components/modals/TriggerEditorModal.test.tsx index 9eb0deea4..10c9c6bca 100644 --- a/tests/components/modals/TriggerEditorModal.test.tsx +++ b/packages/web-ui/tests/components/modals/TriggerEditorModal.test.tsx @@ -297,3 +297,16 @@ describe('TriggerEditorModal save ordering', () => { }, ); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: (...args: unknown[]) => invokeMock(...args)}; + return {useTabularisClient: () => client}; +}); + +vi.mock('@/hooks/usePlatformCapabilities', () => { + const platform = { + negotiation: {environment: 'tauri'}, + confirm: (...args: unknown[]) => askMock(...args), + }; + return {usePlatformCapabilities: () => platform}; +}); diff --git a/tests/components/modals/UpdateNotificationModal.test.tsx b/packages/web-ui/tests/components/modals/UpdateNotificationModal.test.tsx similarity index 89% rename from tests/components/modals/UpdateNotificationModal.test.tsx rename to packages/web-ui/tests/components/modals/UpdateNotificationModal.test.tsx index 6d284b3a8..e8d431c8b 100644 --- a/tests/components/modals/UpdateNotificationModal.test.tsx +++ b/packages/web-ui/tests/components/modals/UpdateNotificationModal.test.tsx @@ -3,6 +3,8 @@ import {openUrl} from '@tauri-apps/plugin-opener'; import {describe, expect, it, vi} from 'vitest'; import {UpdateNotificationModal} from '@/components/modals/UpdateNotificationModal'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const updateInfo = { currentVersion: '1.0.0', latestVersion: '1.1.0', diff --git a/tests/components/modals/VisualExplainModal.test.tsx b/packages/web-ui/tests/components/modals/VisualExplainModal.test.tsx similarity index 96% rename from tests/components/modals/VisualExplainModal.test.tsx rename to packages/web-ui/tests/components/modals/VisualExplainModal.test.tsx index 1a06057dc..9a6ca8740 100644 --- a/tests/components/modals/VisualExplainModal.test.tsx +++ b/packages/web-ui/tests/components/modals/VisualExplainModal.test.tsx @@ -6,6 +6,8 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {VisualExplainModal} from '@/components/modals/VisualExplainModal'; import type {VisualExplainViewProps} from '@/components/explain/VisualExplainView'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const database = vi.hoisted(() => ({getConnectionData: vi.fn()})); vi.mock('react-i18next', () => { const t = (key: string) => key; @@ -88,8 +90,8 @@ describe('VisualExplainModal legacy execution', () => { connectionId: 'connection-1', query: defaults.query, analyze: true, - schema: null, - database: null, + schema: undefined, + database: undefined, }); expect(screen.getByRole('checkbox')).toBeChecked(); expect(screen.getByTestId('plan')).toHaveTextContent('resolved'); @@ -109,7 +111,7 @@ describe('VisualExplainModal legacy execution', () => { query, analyze: false, schema: 'reporting', - database: null, + database: undefined, }); expect(screen.getByRole('checkbox')).not.toBeChecked(); expect(screen.getByText('editor.visualExplain.analyzeWarning')).toBeInTheDocument(); @@ -134,7 +136,7 @@ describe('VisualExplainModal legacy execution', () => { query: defaults.query, analyze: true, schema: 'reporting', - database: null, + database: undefined, }); }); @@ -174,8 +176,8 @@ describe('VisualExplainModal legacy execution', () => { connectionId: 'connection-1', query: defaults.query, analyze: true, - schema: null, - database: null, + schema: undefined, + database: undefined, ...change, }); expect(screen.getByTestId('mode')).toHaveTextContent('graph'); @@ -204,8 +206,8 @@ describe('VisualExplainModal legacy execution', () => { connectionId: 'connection-1', query, analyze: false, - schema: null, - database: null, + schema: undefined, + database: undefined, }); await act(async () => { fireEvent.click(screen.getByRole('button', {name: 'editor.visualExplain.rerun'})); @@ -214,8 +216,8 @@ describe('VisualExplainModal legacy execution', () => { connectionId: 'connection-1', query, analyze: false, - schema: null, - database: null, + schema: undefined, + database: undefined, }); }); @@ -237,7 +239,7 @@ describe('VisualExplainModal legacy execution', () => { query: defaults.query, analyze: false, schema: 'reporting', - database: null, + database: undefined, }); }); @@ -263,8 +265,8 @@ describe('VisualExplainModal legacy execution', () => { connectionId: 'connection-1', query: defaults.query, analyze: false, - schema: null, - database: null, + schema: undefined, + database: undefined, }); }); diff --git a/tests/components/modals/WhatsNewModal.test.tsx b/packages/web-ui/tests/components/modals/WhatsNewModal.test.tsx similarity index 75% rename from tests/components/modals/WhatsNewModal.test.tsx rename to packages/web-ui/tests/components/modals/WhatsNewModal.test.tsx index 20dbd3ab0..12d4db988 100644 --- a/tests/components/modals/WhatsNewModal.test.tsx +++ b/packages/web-ui/tests/components/modals/WhatsNewModal.test.tsx @@ -1,9 +1,13 @@ -import {fireEvent, render, screen} from '@testing-library/react'; +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; import {openUrl} from '@tauri-apps/plugin-opener'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {WhatsNewModal} from '@/components/modals/WhatsNewModal'; +import type {TabularisClient} from '@/api/client'; import {SUPPORT_PROMPT_DISMISSED_KEY} from '@/utils/supportPrompt'; +import {uiStateStore} from '@/utils/uiStateStore'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const entry = { version: '0.23.0', date: '2026-09-10', @@ -21,12 +25,27 @@ const renderModal = (props = {}) => { return {onClose, ...view}; }; +const uiStateCall = vi.fn(); +let detachUiState: () => void = () => {}; + describe('WhatsNewModal', () => { beforeEach(() => { vi.clearAllMocks(); localStorage.clear(); + uiStateStore.reset(); + uiStateCall.mockReset(); + uiStateCall.mockImplementation(async (command: string) => + command === 'get_ui_state' ? {} : undefined, + ); + detachUiState = uiStateStore.attach({ + call: uiStateCall, + subscribe: vi.fn(async () => () => {}), + } as unknown as TabularisClient); + }); + afterEach(() => { + detachUiState(); + vi.restoreAllMocks(); }); - afterEach(() => vi.restoreAllMocks()); it('shows the sponsorship invitation alongside every changelog section', () => { renderModal(); @@ -84,11 +103,14 @@ describe('WhatsNewModal', () => { }, ); - it('remembers never-show-again after remounting without hiding the changelog', () => { + it('remembers never-show-again after remounting without hiding the changelog', async () => { const {onClose, unmount} = renderModal(); fireEvent.click(screen.getByRole('button', {name: 'whatsNew.supportNeverShow'})); - expect(localStorage.getItem(SUPPORT_PROMPT_DISMISSED_KEY)).toBe('true'); - expect(screen.queryByRole('region')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.queryByRole('region')).not.toBeInTheDocument()); + expect(uiStateCall).toHaveBeenCalledWith('set_ui_state', { + key: SUPPORT_PROMPT_DISMISSED_KEY, + value: true, + }); expect(screen.getByText('SQL files')).toBeInTheDocument(); expect(onClose).not.toHaveBeenCalled(); unmount(); @@ -98,24 +120,25 @@ describe('WhatsNewModal', () => { expect(screen.getByRole('button', {name: 'whatsNew.dismiss'})).toBeInTheDocument(); }); - it('keeps multiple modal instances in sync', () => { + it('keeps multiple modal instances in sync', async () => { renderModal(); renderModal(); expect(screen.getAllByRole('region')).toHaveLength(2); fireEvent.click(screen.getAllByRole('button', {name: 'whatsNew.supportNeverShow'})[0]); - expect(screen.queryByRole('region')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.queryByRole('region')).not.toBeInTheDocument()); }); - it('reports persistence failures instead of claiming the choice was saved', () => { - vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + it('reports persistence failures instead of claiming the choice was saved', async () => { + uiStateCall.mockImplementation(async (command: string) => { + if (command === 'get_ui_state') return {}; throw new Error('Storage unavailable'); }); vi.spyOn(console, 'error').mockImplementation(() => undefined); renderModal(); fireEvent.click(screen.getByRole('button', {name: 'whatsNew.supportNeverShow'})); - expect(screen.getByRole('alert')).toHaveTextContent('whatsNew.supportHideError'); + expect(await screen.findByRole('alert')).toHaveTextContent('whatsNew.supportHideError'); expect(screen.getByRole('region')).toBeInTheDocument(); - expect(localStorage.getItem(SUPPORT_PROMPT_DISMISSED_KEY)).toBeNull(); + expect(uiStateStore.get(SUPPORT_PROMPT_DISMISSED_KEY, false)).toBe(false); }); it('does not render when closed', () => { diff --git a/tests/components/modals/commandPalette/PaletteResults.test.tsx b/packages/web-ui/tests/components/modals/commandPalette/PaletteResults.test.tsx similarity index 100% rename from tests/components/modals/commandPalette/PaletteResults.test.tsx rename to packages/web-ui/tests/components/modals/commandPalette/PaletteResults.test.tsx diff --git a/tests/components/modals/mcp/McpSafetySection.test.tsx b/packages/web-ui/tests/components/modals/mcp/McpSafetySection.test.tsx similarity index 88% rename from tests/components/modals/mcp/McpSafetySection.test.tsx rename to packages/web-ui/tests/components/modals/mcp/McpSafetySection.test.tsx index 3881f350b..599802928 100644 --- a/tests/components/modals/mcp/McpSafetySection.test.tsx +++ b/packages/web-ui/tests/components/modals/mcp/McpSafetySection.test.tsx @@ -3,6 +3,8 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {McpSafetySection} from '@/components/modals/mcp/McpSafetySection'; import {useSettings} from '@/hooks/useSettings'; +vi.mock('@/hooks/useTabularisClient', () => import('../../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../../support/tauriBackedHooks')); vi.mock('@/hooks/useSettings', () => ({ useSettings: vi.fn(), })); diff --git a/tests/components/notebook/NotebookCellWrapper.test.tsx b/packages/web-ui/tests/components/notebook/NotebookCellWrapper.test.tsx similarity index 97% rename from tests/components/notebook/NotebookCellWrapper.test.tsx rename to packages/web-ui/tests/components/notebook/NotebookCellWrapper.test.tsx index 6d9ad0749..a3bc4cda9 100644 --- a/tests/components/notebook/NotebookCellWrapper.test.tsx +++ b/packages/web-ui/tests/components/notebook/NotebookCellWrapper.test.tsx @@ -7,6 +7,8 @@ import {NotebookCellWrapper} from '@/components/notebook/NotebookCellWrapper'; import type {SqlCellEditor} from '@/components/notebook/SqlCellEditor'; import type {VisualExplainViewProps} from '@/components/explain/VisualExplainView'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const database = vi.hoisted(() => ({ getConnectionData: vi.fn(), capabilities: {explain: false}, @@ -209,9 +211,9 @@ describe('NotebookCellWrapper query plans', () => { expect(mockInvoke).toHaveBeenCalledExactlyOnceWith('explain_query_plan', { connectionId: 'cell-connection', query: sql, - schema: activeSchema ?? null, + schema: activeSchema ?? undefined, analyze: false, - database: null, + database: undefined, }); expect(screen.getByTestId('plan')).toHaveTextContent('Result'); }, @@ -243,7 +245,7 @@ describe('NotebookCellWrapper query plans', () => { query: props.cell.content, schema: 'reporting', analyze: false, - database: null, + database: undefined, }); }); @@ -285,7 +287,7 @@ describe('NotebookCellWrapper query plans', () => { query: props.cell.content, schema: 'reporting', analyze: false, - database: null, + database: undefined, }); }); @@ -321,7 +323,7 @@ describe('NotebookCellWrapper query plans', () => { query: 'SELECT 42', schema: 'analytics', analyze: false, - database: null, + database: undefined, }); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }); diff --git a/tests/components/notebook/NotebookView.test.tsx b/packages/web-ui/tests/components/notebook/NotebookView.test.tsx similarity index 98% rename from tests/components/notebook/NotebookView.test.tsx rename to packages/web-ui/tests/components/notebook/NotebookView.test.tsx index bec0d9ba5..d9a77a442 100644 --- a/tests/components/notebook/NotebookView.test.tsx +++ b/packages/web-ui/tests/components/notebook/NotebookView.test.tsx @@ -11,6 +11,8 @@ import {resolveParams} from '@/utils/notebookParams'; import {resolveQueryVariables, type ResolvedQuery} from '@/utils/notebookVariables'; import {loadNotebook, setNotebookState} from '@/utils/notebookStore'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const fixtures = vi.hoisted(() => ({ notebooks: new Map(), database: { @@ -67,11 +69,13 @@ vi.mock('@/utils/notebookVariables', async (importOriginal) => { const actual = await importOriginal(); return {...actual, resolveQueryVariables: vi.fn(actual.resolveQueryVariables)}; }); -vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn()})); +vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn(), isTauri: () => true})); vi.mock('@tauri-apps/plugin-dialog', () => ({save: vi.fn(), open: vi.fn()})); vi.mock('@tauri-apps/plugin-fs', () => ({ writeTextFile: vi.fn(), readTextFile: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), })); vi.mock('@/components/modals/ConfirmModal', () => ({ConfirmModal: () => null})); vi.mock('@/components/notebook/NotebookHistoryPanel', () => ({ diff --git a/tests/components/notebook/ResultToolbar.test.tsx b/packages/web-ui/tests/components/notebook/ResultToolbar.test.tsx similarity index 78% rename from tests/components/notebook/ResultToolbar.test.tsx rename to packages/web-ui/tests/components/notebook/ResultToolbar.test.tsx index dfbe56cc4..66b833f5e 100644 --- a/tests/components/notebook/ResultToolbar.test.tsx +++ b/packages/web-ui/tests/components/notebook/ResultToolbar.test.tsx @@ -1,20 +1,27 @@ import {act, fireEvent, render, screen} from '@testing-library/react'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; +import {writeFile} from '@tauri-apps/plugin-fs'; import {ResultToolbar} from '@/components/notebook/ResultToolbar'; import {AlertContext} from '@/contexts/AlertContext'; import type {AlertContextType} from '@/contexts/AlertContext'; import type {QueryResult} from '@/types/editor'; import {useSettings} from '@/hooks/useSettings'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); // Keep exports in memory; never call the native dialog or filesystem. vi.mock('@tauri-apps/plugin-dialog', () => ({save: vi.fn()})); -vi.mock('@tauri-apps/plugin-fs', () => ({writeTextFile: vi.fn()})); +vi.mock('@tauri-apps/plugin-fs', () => ({ + writeTextFile: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), +})); vi.mock('@/hooks/useSettings', () => ({useSettings: vi.fn()})); const mockSave = vi.mocked(save); -const mockWriteTextFile = vi.mocked(writeTextFile); +// Exports go through the platform download, which writes the encoded bytes. +const mockWriteFile = vi.mocked(writeFile); const mockUseSettings = vi.mocked(useSettings); function useCsvDelimiter(csvDelimiter?: string) { @@ -66,7 +73,7 @@ describe('ResultToolbar', () => { beforeEach(() => { useCsvDelimiter(','); mockSave.mockReset().mockResolvedValue(filePath); - mockWriteTextFile.mockReset().mockResolvedValue(undefined); + mockWriteFile.mockReset().mockResolvedValue(undefined); showAlert.mockReset(); vi.spyOn(console, 'error').mockImplementation(() => {}); render( @@ -93,7 +100,10 @@ describe('ResultToolbar', () => { defaultPath: `result.${format}`, filters: [{name: label, extensions: [format]}], }); - expect(mockWriteTextFile).toHaveBeenCalledExactlyOnceWith(filePath, output); + expect(mockWriteFile).toHaveBeenCalledExactlyOnceWith( + filePath, + new TextEncoder().encode(output), + ); expect(showAlert).toHaveBeenCalledExactlyOnceWith( 'editor.notebook.resultExportSuccess', {kind: 'info'}, @@ -107,7 +117,7 @@ describe('ResultToolbar', () => { await clickExport(); expect(mockSave).toHaveBeenCalledTimes(1); - expect(mockWriteTextFile).not.toHaveBeenCalled(); + expect(mockWriteFile).not.toHaveBeenCalled(); expect(showAlert).not.toHaveBeenCalled(); expect(console.error).not.toHaveBeenCalled(); }); @@ -119,16 +129,19 @@ describe('ResultToolbar', () => { if (stage === 'dialog') { mockSave.mockRejectedValueOnce(error); } else { - mockWriteTextFile.mockRejectedValueOnce(error); + mockWriteFile.mockRejectedValueOnce(error); } await clickExport(); expect(mockSave).toHaveBeenCalledTimes(1); if (stage === 'dialog') { - expect(mockWriteTextFile).not.toHaveBeenCalled(); + expect(mockWriteFile).not.toHaveBeenCalled(); } else { - expect(mockWriteTextFile).toHaveBeenCalledExactlyOnceWith(filePath, output); + expect(mockWriteFile).toHaveBeenCalledExactlyOnceWith( + filePath, + new TextEncoder().encode(output), + ); } expect(showAlert).toHaveBeenCalledExactlyOnceWith('editor.notebook.exportError', { kind: 'error', @@ -148,11 +161,14 @@ describe('ResultToolbar', () => { const pendingWrite = new Promise((resolve) => { resolveWrite = resolve; }); - mockWriteTextFile.mockReturnValueOnce(pendingWrite); + mockWriteFile.mockReturnValueOnce(pendingWrite); await clickExport(); - expect(mockWriteTextFile).toHaveBeenCalledExactlyOnceWith(filePath, output); + expect(mockWriteFile).toHaveBeenCalledExactlyOnceWith( + filePath, + new TextEncoder().encode(output), + ); expect(showAlert).not.toHaveBeenCalled(); await act(async () => { @@ -172,7 +188,7 @@ describe('ResultToolbar CSV delimiter', () => { it('writes the CSV with the configured delimiter, like the editor export', async () => { useCsvDelimiter(';'); mockSave.mockReset().mockResolvedValue('/exports/result.csv'); - mockWriteTextFile.mockReset().mockResolvedValue(undefined); + mockWriteFile.mockReset().mockResolvedValue(undefined); render( @@ -183,9 +199,11 @@ describe('ResultToolbar CSV delimiter', () => { fireEvent.click(screen.getByRole('button', {name: 'CSV'})); }); - expect(mockWriteTextFile).toHaveBeenCalledExactlyOnceWith( + expect(mockWriteFile).toHaveBeenCalledExactlyOnceWith( '/exports/result.csv', - 'id;name;active;note\n1;"Ada, ""Lovelace""";true;NULL\n2;"Grace\nHopper";false;\n', + new TextEncoder().encode( + 'id;name;active;note\n1;"Ada, ""Lovelace""";true;NULL\n2;"Grace\nHopper";false;\n', + ), ); }); }); diff --git a/tests/components/notebook/SqlCell.test.tsx b/packages/web-ui/tests/components/notebook/SqlCell.test.tsx similarity index 100% rename from tests/components/notebook/SqlCell.test.tsx rename to packages/web-ui/tests/components/notebook/SqlCell.test.tsx diff --git a/tests/components/notebook/SqlCellExplain.test.tsx b/packages/web-ui/tests/components/notebook/SqlCellExplain.test.tsx similarity index 98% rename from tests/components/notebook/SqlCellExplain.test.tsx rename to packages/web-ui/tests/components/notebook/SqlCellExplain.test.tsx index 9491f6ca8..bcc865350 100644 --- a/tests/components/notebook/SqlCellExplain.test.tsx +++ b/packages/web-ui/tests/components/notebook/SqlCellExplain.test.tsx @@ -7,6 +7,8 @@ import {SqlCellExplain} from '@/components/notebook/SqlCellExplain'; import type {VisualExplainViewProps} from '@/components/explain/VisualExplainView'; import {isDataModifyingQuery} from '@/utils/sql'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); const database = vi.hoisted(() => ({ getConnectionData: vi.fn(), capabilities: {explain: false}, @@ -113,7 +115,7 @@ describe('SqlCellExplain', () => { query: defaults.query, schema: 'analytics', analyze: false, - database: null, + database: undefined, }); expect(screen.getByTestId('plan')).toHaveTextContent('initial'); }); @@ -139,7 +141,7 @@ describe('SqlCellExplain', () => { query: defaults.query, schema: 'analytics', analyze: false, - database: null, + database: undefined, }); expect(screen.getByTestId('selection')).toHaveTextContent('initial'); }); @@ -170,7 +172,7 @@ describe('SqlCellExplain', () => { query, schema: 'analytics', analyze: false, - database: null, + database: undefined, }); expect(screen.getByRole('checkbox')).not.toBeChecked(); }); @@ -218,7 +220,7 @@ describe('SqlCellExplain', () => { schema: 'analytics', ...change, analyze: false, - database: null, + database: undefined, }); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }, @@ -268,7 +270,7 @@ describe('SqlCellExplain', () => { query, schema: 'analytics', analyze: true, - database: null, + database: undefined, }); }, ); diff --git a/tests/components/plugins/PluginCard.test.tsx b/packages/web-ui/tests/components/plugins/PluginCard.test.tsx similarity index 96% rename from tests/components/plugins/PluginCard.test.tsx rename to packages/web-ui/tests/components/plugins/PluginCard.test.tsx index d38e547a4..4af3e308c 100644 --- a/tests/components/plugins/PluginCard.test.tsx +++ b/packages/web-ui/tests/components/plugins/PluginCard.test.tsx @@ -4,6 +4,8 @@ import {openUrl} from '@tauri-apps/plugin-opener'; import {PluginCard} from '@/components/plugins/PluginCard'; import type {PluginManifest} from '@/types/plugins'; +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('lucide-react', async () => await vi.importActual('lucide-react')); const manifest: PluginManifest = { id: 'postgresql', diff --git a/tests/components/plugins/PluginRuntimeWarningToasts.test.tsx b/packages/web-ui/tests/components/plugins/PluginRuntimeWarningToasts.test.tsx similarity index 93% rename from tests/components/plugins/PluginRuntimeWarningToasts.test.tsx rename to packages/web-ui/tests/components/plugins/PluginRuntimeWarningToasts.test.tsx index 2eec756f2..a81e1ba0f 100644 --- a/tests/components/plugins/PluginRuntimeWarningToasts.test.tsx +++ b/packages/web-ui/tests/components/plugins/PluginRuntimeWarningToasts.test.tsx @@ -5,6 +5,12 @@ import {ToastContext} from '@/contexts/ToastContext'; const invokeMock = vi.hoisted(() => vi.fn()); vi.mock('@tauri-apps/api/core', () => ({invoke: invokeMock})); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => + request === undefined ? invokeMock(command) : invokeMock(command, request), + }), +})); const settingsMock = vi.hoisted(() => ({activeExternalDrivers: [] as string[]})); vi.mock('@/hooks/useSettings', () => ({ diff --git a/tests/components/plugins/PluginUpdateToast.test.tsx b/packages/web-ui/tests/components/plugins/PluginUpdateToast.test.tsx similarity index 100% rename from tests/components/plugins/PluginUpdateToast.test.tsx rename to packages/web-ui/tests/components/plugins/PluginUpdateToast.test.tsx diff --git a/tests/components/settings/AiTab.test.tsx b/packages/web-ui/tests/components/settings/AiTab.test.tsx similarity index 88% rename from tests/components/settings/AiTab.test.tsx rename to packages/web-ui/tests/components/settings/AiTab.test.tsx index d5fb4ae47..89bc7aac0 100644 --- a/tests/components/settings/AiTab.test.tsx +++ b/packages/web-ui/tests/components/settings/AiTab.test.tsx @@ -56,3 +56,12 @@ describe('AiTab proxy configuration', () => { expect(updateSetting).toHaveBeenLastCalledWith('aiProviderProxies', {}); }); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: (...args: unknown[]) => invoke(...args)}; + return {useTabularisClient: () => client}; +}); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({negotiation: {environment: 'tauri'}}), +})); diff --git a/tests/components/settings/AppearanceTab.test.tsx b/packages/web-ui/tests/components/settings/AppearanceTab.test.tsx similarity index 96% rename from tests/components/settings/AppearanceTab.test.tsx rename to packages/web-ui/tests/components/settings/AppearanceTab.test.tsx index e48eecf34..b23502d13 100644 --- a/tests/components/settings/AppearanceTab.test.tsx +++ b/packages/web-ui/tests/components/settings/AppearanceTab.test.tsx @@ -37,6 +37,8 @@ let themeSettings = { }; // The unified theme toolbar uses the same icons as its management menus. +vi.mock('@/hooks/useTabularisClient', () => import('../../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); vi.mock('lucide-react', async () => await vi.importActual('lucide-react')); vi.mock('react-i18next', () => ({ diff --git a/packages/web-ui/tests/components/settings/BackupTab.test.tsx b/packages/web-ui/tests/components/settings/BackupTab.test.tsx new file mode 100644 index 000000000..3488744f8 --- /dev/null +++ b/packages/web-ui/tests/components/settings/BackupTab.test.tsx @@ -0,0 +1,144 @@ +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +vi.unmock('lucide-react'); +import {BackupTab} from '@/components/settings/BackupTab'; + +const mocks = vi.hoisted(() => ({ + call: vi.fn(), + consumeDownload: vi.fn(), + downloadFile: vi.fn(), + showAlert: vi.fn(), + updateSetting: vi.fn(), +})); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mocks, +})); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + negotiation: {environment: 'browser'}, + downloadFile: mocks.downloadFile, + }), +})); + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: () => ({ + settings: { + backupMode: 'manual', + backupTarget: 'local', + backupDirectory: '/srv/tabularis/backups', + backupIntervalMinutes: 1440, + backupRetention: 10, + }, + updateSetting: mocks.updateSetting, + }), +})); + +vi.mock('@/hooks/useAlert', () => ({ + useAlert: () => ({showAlert: mocks.showAlert}), +})); + +vi.mock('@/components/settings/SettingControls', () => ({ + SettingSection: ({children}: {children: React.ReactNode}) =>
{children}
, + SettingRow: ({ + label, + description, + children, + }: { + label: string; + description: string; + children: React.ReactNode; + }) => ( +
+ {label} + {description} + {children} +
+ ), + SettingToggle: () => null, + SettingButtonGroup: () => null, + SettingNumberInput: () => null, +})); + +vi.mock('@/components/ui/PasswordInput', () => ({ + PasswordInput: () => , +})); + +describe('BackupTab browser adaptation', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.call.mockImplementation((command: string) => { + if (command === 'get_connections' || command === 'get_registered_drivers') + return Promise.resolve([]); + if (command === 'get_database_backup_status') + return Promise.resolve({isRunning: false}); + if (command === 'get_connections_backup_status') { + return Promise.resolve({ + passwordSet: true, + targetPasswordSet: true, + lastBackupAt: null, + targetKind: 'serverDirectory', + targetDisplay: '/srv/tabularis/backups', + }); + } + if (command === 'run_connections_backup') { + return Promise.resolve({ + serverLocation: '/srv/tabularis/backups/tabularis-backup.json', + targetKind: 'serverDirectory', + download: { + kind: 'download', + fileName: 'tabularis-backup.json', + mimeType: 'application/json', + token: 'backup-download', + size: 9, + }, + }); + } + return Promise.resolve(null); + }); + mocks.consumeDownload.mockResolvedValue( + new Blob(['encrypted'], {type: 'application/json'}), + ); + mocks.downloadFile.mockResolvedValue(true); + }); + + it('lets browser users set a database backup server directory without a picker', async () => { + render(); + const directory = await screen.findByRole('textbox', { + name: 'settings.backup.dbBackupDirectory', + }); + fireEvent.change(directory, {target: {value: '/srv/database-backups'}}); + fireEvent.blur(directory); + await waitFor(() => + expect(mocks.updateSetting).toHaveBeenCalledWith( + 'databaseBackupPlan', + expect.objectContaining({destinationDirectory: '/srv/database-backups'}), + ), + ); + }); + + it('labels local targets as server paths and downloads manual backup copies', async () => { + render(); + + expect(screen.getAllByText('settings.backup.serverDirectoryDesc')[0]).toBeInTheDocument(); + expect(screen.getByDisplayValue('/srv/tabularis/backups')).toBeInTheDocument(); + + const buttons = screen.getAllByRole('button', { + name: 'settings.backup.backupNow', + }); + const backupButton = buttons.at(-1)!; + await waitFor(() => expect(backupButton).toBeEnabled()); + fireEvent.click(backupButton); + + await waitFor(() => { + expect(mocks.consumeDownload).toHaveBeenCalledWith('backup-download'); + expect(mocks.downloadFile).toHaveBeenCalledWith({ + fileName: 'tabularis-backup.json', + mimeType: 'application/json', + contents: expect.any(Uint8Array), + }); + }); + expect(mocks.showAlert).toHaveBeenCalledWith('settings.backup.backupDone'); + }); +}); diff --git a/tests/components/settings/ChatGptSettings.test.tsx b/packages/web-ui/tests/components/settings/ChatGptSettings.test.tsx similarity index 96% rename from tests/components/settings/ChatGptSettings.test.tsx rename to packages/web-ui/tests/components/settings/ChatGptSettings.test.tsx index be1733eb2..749feaa14 100644 --- a/tests/components/settings/ChatGptSettings.test.tsx +++ b/packages/web-ui/tests/components/settings/ChatGptSettings.test.tsx @@ -78,7 +78,7 @@ describe('ChatGptSettings', () => { await screen.findByText('settings.ai.chatgpt.usingPlan'); expect(invoke).toHaveBeenCalledWith('sign_in_chatgpt', {profileId: null}); expect(updateSetting).toHaveBeenCalledWith('aiModel', ''); - expect(invoke).toHaveBeenCalledWith('get_chatgpt_models'); + expect(invoke).toHaveBeenCalledWith('get_chatgpt_models', undefined); fireEvent.click(screen.getByRole('button', {name: 'settings.ai.defaultModel'})); fireEvent.click(await screen.findByText('Account Model')); expect(updateSetting).toHaveBeenCalledWith('aiModel', 'account-model'); @@ -91,7 +91,7 @@ describe('ChatGptSettings', () => { }; render(); await screen.findByText('settings.ai.chatgpt.permissionRequired'); - expect(invoke).not.toHaveBeenCalledWith('get_chatgpt_models'); + expect(invoke).not.toHaveBeenCalledWith('get_chatgpt_models', undefined); expect( screen.queryByRole('button', {name: 'settings.ai.defaultModel'}), ).not.toBeInTheDocument(); @@ -143,7 +143,7 @@ describe('ChatGptSettings', () => { render(); expect(await screen.findByRole('alert')).toHaveTextContent('usage limit reached'); fireEvent.click(screen.getByRole('button', {name: 'settings.ai.chatgpt.manageUsage'})); - expect(invoke).toHaveBeenCalledWith('open_chatgpt_usage'); + expect(invoke).toHaveBeenCalledWith('open_chatgpt_usage', undefined); }); it('cancels a pending browser sign-in when the settings panel unmounts', async () => { @@ -164,7 +164,12 @@ describe('ChatGptSettings', () => { fireEvent.click(button); await screen.findByText('settings.ai.chatgpt.browserPending'); unmount(); - expect(invoke).toHaveBeenCalledWith('cancel_chatgpt_sign_in'); + expect(invoke).toHaveBeenCalledWith('cancel_chatgpt_sign_in', undefined); await act(async () => rejectSignIn?.(new Error('Cancelled'))); }); }); + +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: (...args: unknown[]) => invoke(...args)}; + return {useTabularisClient: () => client}; +}); diff --git a/tests/components/settings/BackupTab.test.tsx b/packages/web-ui/tests/components/settings/DatabaseBackupTab.test.tsx similarity index 83% rename from tests/components/settings/BackupTab.test.tsx rename to packages/web-ui/tests/components/settings/DatabaseBackupTab.test.tsx index c589d89e6..e1ec1d893 100644 --- a/tests/components/settings/BackupTab.test.tsx +++ b/packages/web-ui/tests/components/settings/DatabaseBackupTab.test.tsx @@ -10,8 +10,13 @@ const {invoke, updateSetting, showAlert, settings} = vi.hoisted(() => ({ settings: {current: {} as Record}, })); vi.unmock('lucide-react'); -vi.mock('@tauri-apps/api/core', () => ({invoke})); -vi.mock('@tauri-apps/plugin-dialog', () => ({open: vi.fn()})); +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: invoke}; + return {useTabularisClient: () => client}; +}); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({negotiation: {environment: 'desktop'}}), +})); vi.mock('@/hooks/useSettings', () => ({ useSettings: () => ({settings: settings.current, updateSetting}), })); @@ -92,6 +97,19 @@ describe('BackupTab database backups', () => { ); }); + it('gives manual database backups the long-running transfer deadline', async () => { + mockBackend(() => idleStatus); + render(); + fireEvent.click( + await screen.findByRole('button', {name: 'settings.backup.dbBackupRunNow'}), + ); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith('run_database_backup_now', undefined, { + deadlineMs: 21_600_000, + }), + ); + }); + it('cancels the backend run in progress without naming a connection', async () => { mockBackend(() => ({...idleStatus, isRunning: true})); render(); @@ -100,7 +118,9 @@ describe('BackupTab database backups', () => { await screen.findByRole('button', {name: 'settings.backup.dbBackupCancel'}), ); - await waitFor(() => expect(invoke).toHaveBeenCalledWith('cancel_database_backup')); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith('cancel_database_backup', undefined), + ); }); it('polls the status, so a scheduled run that starts while open shows a Cancel button', async () => { diff --git a/tests/components/settings/InfoTab.test.tsx b/packages/web-ui/tests/components/settings/InfoTab.test.tsx similarity index 70% rename from tests/components/settings/InfoTab.test.tsx rename to packages/web-ui/tests/components/settings/InfoTab.test.tsx index 7cf208d03..ebeee9729 100644 --- a/tests/components/settings/InfoTab.test.tsx +++ b/packages/web-ui/tests/components/settings/InfoTab.test.tsx @@ -13,6 +13,12 @@ const translations: Record = { 'Nightly builds are unstable pre-releases. Only assets built for the nightly channel are installed.', 'update.managedByPackageManager': 'Updates managed by {{source}}', 'update.managedByPackageManagerDesc': 'Use your package manager to update Tabularis.', + 'update.serverManagedTitle': 'Server-managed updates', + 'update.serverManagedDesc': + 'A browser cannot replace the Tabularis server binary. Ask the server administrator to follow the upgrade guide.', + 'update.serverVersion': 'Server version', + 'update.serverBuild': 'Server build', + 'update.openServerUpgradeGuide': 'Open server upgrade guide', }; vi.mock('lucide-react', () => ({ @@ -41,6 +47,11 @@ vi.mock('react-i18next', () => ({ }), })); +const openExternalUrl = vi.hoisted(() => vi.fn()); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openExternalUrl}), +})); + vi.mock('@/hooks/useTheme', () => ({ useTheme: vi.fn(() => ({ currentTheme: {id: 'tabularis-dark', colors: {}}, @@ -55,6 +66,10 @@ vi.mock('@/hooks/useChangelog', () => ({ })), })); +vi.mock('@/hooks/useSecondaryWindows', () => ({ + useSecondaryWindows: () => ({openTaskManager: vi.fn()}), +})); + // Not under test here; avoid pulling in their own icon/markdown dependencies. vi.mock('@/components/modals/WhatsNewModal', () => ({ WhatsNewModal: () => null, @@ -77,12 +92,14 @@ interface RenderInfoTabOptions { installationSource?: string | null; releaseChannel?: Settings['releaseChannel']; updateSetting?: (...args: unknown[]) => void; + updaterMode?: 'native' | 'server-managed'; } function renderInfoTab({ installationSource = null, releaseChannel, updateSetting = vi.fn(), + updaterMode = 'native', }: RenderInfoTabOptions) { mockUseSettings.mockReturnValue({ settings: {releaseChannel} as Settings, @@ -95,6 +112,18 @@ function renderInfoTab({ error: null, isUpToDate: false, installationSource, + updaterMode, + serverInfo: + updaterMode === 'server-managed' + ? { + version: '1.4.2', + build: { + target: 'linux-x86_64', + profile: 'release', + commit: 'abc1234', + }, + } + : null, }); return render(); } @@ -135,4 +164,18 @@ describe('InfoTab', () => { ), ).toBeInTheDocument(); }); + + it('shows server build details and upgrade guidance in web mode', () => { + renderInfoTab({updaterMode: 'server-managed'}); + + expect(screen.getByText('Server-managed updates')).toBeInTheDocument(); + expect(screen.getByText('v1.4.2')).toBeInTheDocument(); + expect(screen.getByText('linux-x86_64 · release · abc1234')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', {name: 'Open server upgrade guide'})); + expect(openExternalUrl).toHaveBeenCalledWith( + 'https://github.com/TabularisDB/tabularis/blob/main/web-ui-project/docs/WEB_MODE_UPGRADES.md', + ); + expect(screen.queryByText('Release channel')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', {name: 'settings.checkNow'})).not.toBeInTheDocument(); + }); }); diff --git a/packages/web-ui/tests/components/settings/LogsTab.test.tsx b/packages/web-ui/tests/components/settings/LogsTab.test.tsx new file mode 100644 index 000000000..1660c51ee --- /dev/null +++ b/packages/web-ui/tests/components/settings/LogsTab.test.tsx @@ -0,0 +1,131 @@ +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {LogsTab} from '@/components/settings/LogsTab'; + +const mocks = vi.hoisted(() => { + const call = vi.fn(); + return { + call, + client: {call}, + downloadGeneratedFile: vi.fn(), + showAlert: vi.fn(), + updateSetting: vi.fn(), + }; +}); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mocks.client, +})); + +vi.mock('lucide-react', () => ({ + Trash2: () => null, + FileDown: () => null, + RotateCcw: () => null, + ChevronDown: () => null, + ChevronRight: () => null, +})); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + negotiation: {environment: 'browser'}, + supports: () => false, + }), +})); + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: () => ({ + settings: {loggingEnabled: true, maxLogEntries: 1000}, + updateSetting: mocks.updateSetting, + }), +})); + +vi.mock('@/hooks/useAlert', () => ({ + useAlert: () => ({showAlert: mocks.showAlert}), +})); + +vi.mock('@/utils/fileDownloads', () => ({ + downloadGeneratedFile: mocks.downloadGeneratedFile, +})); + +vi.mock('@/components/settings/SettingControls', () => ({ + SettingSection: ({children}: {children: React.ReactNode}) =>
{children}
, + SettingRow: ({children}: {children: React.ReactNode}) =>
{children}
, + SettingToggle: ({ + checked, + onChange, + }: { + checked: boolean; + onChange: (enabled: boolean) => void; + }) => + ); +} + +function renderWith(store: UiStateStore, client: TabularisClient) { + return render( + + + + + , + ); +} + +describe('UiStateProvider', () => { + beforeEach(() => localStorage.clear()); + afterEach(() => vi.useRealTimers()); + + it('loads shared values, follows live changes and writes with debounce', async () => { + const store = new UiStateStore(); + const mock = mockClient({[SIDEBAR.key]: 300}); + renderWith(store, mock.client); + + expect(await screen.findByText('ready:300')).toBeInTheDocument(); + + act(() => mock.emit(SIDEBAR.key, 280)); + expect(screen.getByText('ready:280')).toBeInTheDocument(); + + vi.useFakeTimers(); + act(() => screen.getByRole('button').click()); + act(() => screen.getByRole('button').click()); + expect(screen.getByText('ready:300')).toBeInTheDocument(); + expect(mock.call).not.toHaveBeenCalledWith('set_ui_state', expect.anything()); + act(() => { + vi.advanceTimersByTime(100); + }); + expect(mock.call).toHaveBeenCalledTimes(2); + expect(mock.call).toHaveBeenLastCalledWith('set_ui_state', {key: SIDEBAR.key, value: 300}); + }); + + it('flushes pending writes when the page is hidden and detaches on unmount', async () => { + const store = new UiStateStore(); + const mock = mockClient({}); + const {unmount} = renderWith(store, mock.client); + await screen.findByText('ready:256'); + + act(() => screen.getByRole('button').click()); + act(() => { + window.dispatchEvent(new Event('pagehide')); + }); + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: SIDEBAR.key, value: 266}); + + unmount(); + expect(mock.unsubscribe).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/contexts/UpdateContext.test.ts b/packages/web-ui/tests/contexts/UpdateContext.test.ts similarity index 100% rename from tests/contexts/UpdateContext.test.ts rename to packages/web-ui/tests/contexts/UpdateContext.test.ts diff --git a/tests/contexts/UpdateProvider.test.tsx b/packages/web-ui/tests/contexts/UpdateProvider.test.tsx similarity index 89% rename from tests/contexts/UpdateProvider.test.tsx rename to packages/web-ui/tests/contexts/UpdateProvider.test.tsx index a64a2c9ce..565c7843a 100644 --- a/tests/contexts/UpdateProvider.test.tsx +++ b/packages/web-ui/tests/contexts/UpdateProvider.test.tsx @@ -6,10 +6,48 @@ import {invoke} from '@tauri-apps/api/core'; import {listen} from '@tauri-apps/api/event'; import React from 'react'; import type {UpdateCheckResult} from '@/contexts/UpdateContext'; +import type {SessionNegotiation} from '@/api/session'; vi.mock('@tauri-apps/api/core'); vi.mock('@tauri-apps/api/event'); +const mockClient = vi.hoisted(() => ({call: vi.fn()})); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mockClient, +})); + +const WEB_SESSION: SessionNegotiation = { + apiVersion: 'v1', + serverVersion: '1.4.2', + serverBuild: { + target: 'linux-x86_64', + profile: 'release', + commit: 'abc1234', + }, + authenticated: true, + csrfToken: 'csrf-token', + access: { + remote: false, + authorizationLevel: 'local-admin', + highRiskCapabilities: true, + }, + capabilities: { + rpc: true, + events: true, + uploads: true, + downloads: true, + pluginAssets: true, + mcpHostConfiguration: true, + serverFileBrowser: false, + nativeUpdater: false, + }, + queryResponsePolicy: { + maxRowsPerPage: 10_000, + maxResponseBytes: 16_777_216, + streaming: false, + }, +}; + describe('UpdateProvider', () => { let unlistenProgressMock: () => void; let unlistenInstallingMock: () => void; @@ -32,6 +70,8 @@ describe('UpdateProvider', () => { return Promise.resolve(vi.fn()); }); + mockClient.call.mockImplementation((command, request) => invoke(command, request)); + // Default mock for invoke vi.mocked(invoke).mockImplementation((cmd: string) => { if (cmd === 'get_installation_source') { @@ -64,6 +104,33 @@ describe('UpdateProvider', () => { expect(result.current.isUpToDate).toBe(false); }); + it('exposes server information without starting native updater work in web mode', async () => { + vi.useFakeTimers(); + const wrapper = ({children}: {children: React.ReactNode}) => + React.createElement(UpdateProvider, {session: WEB_SESSION}, children); + + const {result} = renderHook(() => useUpdate(), {wrapper}); + + await act(async () => { + await vi.runAllTimersAsync(); + }); + + expect(result.current.updaterMode).toBe('server-managed'); + expect(result.current.serverInfo).toEqual({ + version: '1.4.2', + build: WEB_SESSION.serverBuild, + }); + expect(listen).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(mockClient.call).not.toHaveBeenCalled(); + + await act(async () => { + await result.current.checkForUpdates(true); + await result.current.downloadAndInstall(); + }); + expect(invoke).not.toHaveBeenCalled(); + }); + it('should check for updates when available', async () => { const mockUpdateResult: UpdateCheckResult = { hasUpdate: true, @@ -387,7 +454,7 @@ describe('UpdateProvider', () => { await vi.runAllTimersAsync(); }); - expect(invoke).toHaveBeenCalledWith('get_config'); + expect(invoke).toHaveBeenCalledWith('get_config', undefined); expect(invoke).not.toHaveBeenCalledWith('check_for_updates', expect.anything()); }); diff --git a/tests/contexts/connectionMetadata.test.tsx b/packages/web-ui/tests/contexts/connectionMetadata.test.tsx similarity index 96% rename from tests/contexts/connectionMetadata.test.tsx rename to packages/web-ui/tests/contexts/connectionMetadata.test.tsx index 767e0f416..ffdad6243 100644 --- a/tests/contexts/connectionMetadata.test.tsx +++ b/packages/web-ui/tests/contexts/connectionMetadata.test.tsx @@ -6,10 +6,12 @@ import {DatabaseProvider} from '@/contexts/DatabaseProvider'; import {useDatabase} from '@/hooks/useDatabase'; import type {ConnectionMetadata, DriverCapabilities} from '@/types/plugins'; +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); const {events} = vi.hoisted(() => ({ events: new Map void>(), })); -vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn()})); +vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn(), isTauri: () => true})); vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn((name: string, callback: (event: {payload: unknown}) => void) => { events.set(name, callback); diff --git a/tests/fixtures/pluginSlotProbe.tsx b/packages/web-ui/tests/fixtures/pluginSlotProbe.tsx similarity index 67% rename from tests/fixtures/pluginSlotProbe.tsx rename to packages/web-ui/tests/fixtures/pluginSlotProbe.tsx index a9bcc7c83..e6eeebc45 100644 --- a/tests/fixtures/pluginSlotProbe.tsx +++ b/packages/web-ui/tests/fixtures/pluginSlotProbe.tsx @@ -3,9 +3,13 @@ import { render } from '@testing-library/react'; import { vi } from 'vitest'; import i18n from 'i18next'; import { invoke } from '@tauri-apps/api/core'; -import { PluginSlotProvider } from '../../src/contexts/PluginSlotProvider'; -import { SettingsContext, DEFAULT_SETTINGS } from '../../src/contexts/SettingsContext'; -import type { SlotName } from '../../src/types/pluginSlots'; +import { PluginSlotProvider } from '@/contexts/PluginSlotProvider'; +import { SettingsContext, DEFAULT_SETTINGS } from '@/contexts/SettingsContext'; +import { TabularisClient } from '@/api/client'; +import { TauriTransport } from '@/api/transports/tauriTransport'; +import { TabularisClientProvider } from '@/contexts/TabularisClientProvider'; +import { API_VERSION } from '@/pluginApiVersion'; +import type { SlotName } from '@/types/pluginSlots'; /** Load probe bundles through the real manifest loader and driver filter. */ export async function renderWithSlotProbe(children: ReactNode, slots: SlotName[]) { @@ -19,7 +23,7 @@ export async function renderWithSlotProbe(children: ReactNode, slots: SlotName[] name: 'Context probe', version: '1.0.0', ui_extensions: ['postgres', 'mysql', undefined].flatMap(driver => slots.map(slot => ({ - slot, driver, module: `${driver ?? 'unfiltered'}.js`, + slot, driver, api_version: API_VERSION, module: `${driver ?? 'unfiltered'}.js`, }))), }; } @@ -35,13 +39,16 @@ export async function renderWithSlotProbe(children: ReactNode, slots: SlotName[] } throw new Error(`Unexpected probe command: ${command}`); }); + const client = new TabularisClient(new TauriTransport()); const wrapper = ({ children }: { children: ReactNode }) => ( - {children} - + + {children} + + , ); return render(children, { wrapper }); } diff --git a/packages/web-ui/tests/fixtures/transportSerialization.json b/packages/web-ui/tests/fixtures/transportSerialization.json new file mode 100644 index 000000000..f98b63973 --- /dev/null +++ b/packages/web-ui/tests/fixtures/transportSerialization.json @@ -0,0 +1,45 @@ +{ + "columns": [ + "id", + "blob_value", + "decimal_value", + "date_value", + "nullable_value", + "json_value" + ], + "rows": [ + [ + 1, + "BLOB:4:application/octet-stream:AAECAw==", + "12345678901234567890.123456789", + "2026-08-21T19:20:21.123Z", + null, + { + "nested": [true, null, { "value": "text" }] + } + ], + [ + 2, + "BLOB:0:application/octet-stream:", + "-0.000000000000000001", + "0001-01-01", + null, + ["array", 42] + ] + ], + "affected_rows": 0, + "truncated": false, + "pagination": { + "page": 1, + "page_size": 2, + "total_rows": null, + "has_more": false + }, + "additional_results": [ + { + "columns": ["nullable_decimal", "timestamp_with_offset"], + "rows": [[null, "2026-08-21T21:20:21+02:00"]], + "affected_rows": 0 + } + ] +} diff --git a/packages/web-ui/tests/hooks/useAiActivity.test.tsx b/packages/web-ui/tests/hooks/useAiActivity.test.tsx new file mode 100644 index 000000000..ea0ea13fa --- /dev/null +++ b/packages/web-ui/tests/hooks/useAiActivity.test.tsx @@ -0,0 +1,105 @@ +import {createElement, type ReactNode} from 'react'; +import {act, renderHook as renderHookBase, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {invoke} from '@tauri-apps/api/core'; +import {listen, type EventCallback} from '@tauri-apps/api/event'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; +import {clearAiActivity, useAiActivityEvents, usePendingApprovals} from '@/hooks/useAiActivity'; +import type {PendingApproval} from '@/types/ai'; + +vi.mock('@tauri-apps/api/event', () => ({ + listen: vi.fn(), + emit: vi.fn(), +})); + +const invokeMock = vi.mocked(invoke); +const listenMock = vi.mocked(listen); +const client = new TabularisClient(new TauriTransport()); +const wrapper = ({children}: {children: ReactNode}) => + createElement(TabularisClientProvider, {client}, children); +const renderHook = (callback: () => Result) => renderHookBase(callback, {wrapper}); + +const pending: PendingApproval = { + id: 'approval-1', + createdAt: '2026-08-22T00:00:00Z', + sessionId: 'mcp-session', + connectionId: 'connection-1', + connectionName: 'Fixture', + query: 'DELETE FROM values', + queryKind: 'write', + clientHint: null, + explainPlan: null, + explainError: null, +}; + +describe('useAiActivity', () => { + let eventHandler: EventCallback | undefined; + + beforeEach(() => { + invokeMock.mockReset(); + listenMock.mockReset(); + eventHandler = undefined; + listenMock.mockImplementation((event, handler) => { + if (event === 'ai://pending_approval') { + eventHandler = handler as EventCallback; + } + return Promise.resolve(() => {}); + }); + }); + + it('loads filtered activity through the typed client', async () => { + invokeMock.mockResolvedValue([]); + const {result} = renderHook(() => useAiActivityEvents({status: 'success'})); + + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(invokeMock).toHaveBeenCalledWith('get_ai_activity', { + filter: {status: 'success'}, + }); + }); + + it('refreshes and decides approvals through the shared event and RPC contract', async () => { + invokeMock.mockImplementation((command) => { + if (command === 'list_pending_approvals') return Promise.resolve([pending]); + return Promise.resolve(undefined); + }); + const {result} = renderHook(() => usePendingApprovals()); + + await waitFor(() => expect(result.current.pending).toEqual([pending])); + expect(listenMock).toHaveBeenCalledWith('ai://pending_approval', expect.any(Function)); + + await act(async () => { + eventHandler?.({ + event: 'ai://pending_approval', + id: 1, + payload: pending, + }); + }); + await waitFor(() => { + expect( + invokeMock.mock.calls.filter(([command]) => command === 'list_pending_approvals'), + ).toHaveLength(2); + }); + + await act(async () => { + await result.current.decide({ + approvalId: pending.id, + decision: 'deny', + reason: 'fixture', + }); + }); + expect(invokeMock).toHaveBeenCalledWith('decide_pending_approval', { + approvalId: pending.id, + decision: 'deny', + reason: 'fixture', + editedQuery: undefined, + }); + }); + + it('clears activity through the typed client', async () => { + invokeMock.mockResolvedValue(undefined); + await clearAiActivity(client); + expect(invokeMock).toHaveBeenCalledWith('clear_ai_activity', undefined); + }); +}); diff --git a/tests/hooks/useAutoConnectFromUrl.test.ts b/packages/web-ui/tests/hooks/useAutoConnectFromUrl.test.ts similarity index 100% rename from tests/hooks/useAutoConnectFromUrl.test.ts rename to packages/web-ui/tests/hooks/useAutoConnectFromUrl.test.ts diff --git a/tests/hooks/useAutoRefresh.test.tsx b/packages/web-ui/tests/hooks/useAutoRefresh.test.tsx similarity index 100% rename from tests/hooks/useAutoRefresh.test.tsx rename to packages/web-ui/tests/hooks/useAutoRefresh.test.tsx diff --git a/tests/hooks/useBuiltinDriverMigration.test.ts b/packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts similarity index 98% rename from tests/hooks/useBuiltinDriverMigration.test.ts rename to packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts index ec96955d7..b95b28fd5 100644 --- a/tests/hooks/useBuiltinDriverMigration.test.ts +++ b/packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; import {renderHook, act, waitFor} from '@testing-library/react'; -// Mock the four context hooks the migration hook composes, plus `invoke`. +// Mock the four context hooks the migration hook composes, plus the client. // Each test reconfigures the mock returns to drive the connectivity gate. const databaseMock = { @@ -35,6 +35,16 @@ const settingsMock = { }; vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn()})); +// The hook talks to the backend through the Tabularis client; forward its +// calls to the `invoke` mock so per-command assertions stay transport-agnostic. +vi.mock('@/hooks/useTabularisClient', async () => { + const {invoke} = await import('@tauri-apps/api/core'); + const client = { + call: (command: string, request: unknown) => + invoke(command, request as Record | undefined), + }; + return {useTabularisClient: () => client}; +}); vi.mock('@/hooks/useDatabase', () => ({ useDatabase: () => databaseMock, diff --git a/tests/hooks/useChangelog.test.ts b/packages/web-ui/tests/hooks/useChangelog.test.ts similarity index 100% rename from tests/hooks/useChangelog.test.ts rename to packages/web-ui/tests/hooks/useChangelog.test.ts diff --git a/tests/hooks/useClickOutside.test.ts b/packages/web-ui/tests/hooks/useClickOutside.test.ts similarity index 100% rename from tests/hooks/useClickOutside.test.ts rename to packages/web-ui/tests/hooks/useClickOutside.test.ts diff --git a/tests/hooks/useCommandPaletteObjectItems.test.tsx b/packages/web-ui/tests/hooks/useCommandPaletteObjectItems.test.tsx similarity index 100% rename from tests/hooks/useCommandPaletteObjectItems.test.tsx rename to packages/web-ui/tests/hooks/useCommandPaletteObjectItems.test.tsx diff --git a/tests/hooks/useCommandPaletteScope.test.tsx b/packages/web-ui/tests/hooks/useCommandPaletteScope.test.tsx similarity index 100% rename from tests/hooks/useCommandPaletteScope.test.tsx rename to packages/web-ui/tests/hooks/useCommandPaletteScope.test.tsx diff --git a/tests/hooks/useConnectionCatalogue.test.ts b/packages/web-ui/tests/hooks/useConnectionCatalogue.test.ts similarity index 93% rename from tests/hooks/useConnectionCatalogue.test.ts rename to packages/web-ui/tests/hooks/useConnectionCatalogue.test.ts index 09310a929..5128100dd 100644 --- a/tests/hooks/useConnectionCatalogue.test.ts +++ b/packages/web-ui/tests/hooks/useConnectionCatalogue.test.ts @@ -3,6 +3,8 @@ import {describe, expect, it, vi} from 'vitest'; import {invoke} from '@tauri-apps/api/core'; import {useConnectionCatalogue} from '@/hooks/useConnectionCatalogue'; +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); vi.mock('@/hooks/useDrivers', () => ({useDrivers: () => ({allDrivers: []})})); vi.mock('@/hooks/useSettings', () => ({useSettings: () => ({settings: {}})})); diff --git a/tests/hooks/useConnectionLayout.test.ts b/packages/web-ui/tests/hooks/useConnectionLayout.test.ts similarity index 100% rename from tests/hooks/useConnectionLayout.test.ts rename to packages/web-ui/tests/hooks/useConnectionLayout.test.ts diff --git a/tests/hooks/useConnectionWindowLifecycle.test.ts b/packages/web-ui/tests/hooks/useConnectionWindowLifecycle.test.ts similarity index 76% rename from tests/hooks/useConnectionWindowLifecycle.test.ts rename to packages/web-ui/tests/hooks/useConnectionWindowLifecycle.test.ts index 33323dfeb..ccff8d5c6 100644 --- a/tests/hooks/useConnectionWindowLifecycle.test.ts +++ b/packages/web-ui/tests/hooks/useConnectionWindowLifecycle.test.ts @@ -1,14 +1,12 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; import {renderHook} from '@testing-library/react'; -import {getCurrentWindow} from '@tauri-apps/api/window'; import {useConnectionWindowLifecycle} from '@/hooks/useConnectionWindowLifecycle'; const closeMock = vi.fn(); -let windowLabel = 'main'; let globallyOpen: string[] = []; -vi.mock('@tauri-apps/api/window', () => ({ - getCurrentWindow: vi.fn(() => ({label: windowLabel, close: closeMock})), +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({closeRoute: closeMock}), })); vi.mock('@/hooks/useDatabase', () => ({ @@ -22,14 +20,11 @@ const setUrl = (search: string) => { describe('useConnectionWindowLifecycle', () => { beforeEach(() => { closeMock.mockReset(); - vi.mocked(getCurrentWindow).mockClear(); - windowLabel = 'main'; globallyOpen = []; setUrl('/'); }); it('never closes the main window', () => { - windowLabel = 'main'; setUrl('/?connect=conn-1'); globallyOpen = []; renderHook(() => useConnectionWindowLifecycle()); @@ -37,16 +32,14 @@ describe('useConnectionWindowLifecycle', () => { }); it('does not close a dedicated window before its connection has opened', () => { - windowLabel = 'connection-window-conn-1'; - setUrl('/?connect=conn-1'); + setUrl('/connections?connect=conn-1&standalone=connection'); globallyOpen = []; // not open yet renderHook(() => useConnectionWindowLifecycle()); expect(closeMock).not.toHaveBeenCalled(); }); it('closes a dedicated window once its connection was open and then closes', () => { - windowLabel = 'connection-window-conn-1'; - setUrl('/?connect=conn-1'); + setUrl('/connections?connect=conn-1&standalone=connection'); globallyOpen = ['conn-1']; const {rerender} = renderHook(() => useConnectionWindowLifecycle()); expect(closeMock).not.toHaveBeenCalled(); @@ -58,8 +51,7 @@ describe('useConnectionWindowLifecycle', () => { }); it('ignores changes to other connections', () => { - windowLabel = 'connection-window-conn-1'; - setUrl('/?connect=conn-1'); + setUrl('/connections?connect=conn-1&standalone=connection'); globallyOpen = ['conn-1', 'conn-2']; const {rerender} = renderHook(() => useConnectionWindowLifecycle()); diff --git a/tests/hooks/useCopyFeedback.test.ts b/packages/web-ui/tests/hooks/useCopyFeedback.test.ts similarity index 100% rename from tests/hooks/useCopyFeedback.test.ts rename to packages/web-ui/tests/hooks/useCopyFeedback.test.ts diff --git a/tests/hooks/useCreateSqliteDatabase.test.ts b/packages/web-ui/tests/hooks/useCreateSqliteDatabase.test.ts similarity index 77% rename from tests/hooks/useCreateSqliteDatabase.test.ts rename to packages/web-ui/tests/hooks/useCreateSqliteDatabase.test.ts index cc4f37059..909643ecc 100644 --- a/tests/hooks/useCreateSqliteDatabase.test.ts +++ b/packages/web-ui/tests/hooks/useCreateSqliteDatabase.test.ts @@ -1,11 +1,23 @@ import {act, renderHook} from '@testing-library/react'; import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {invoke} from '@tauri-apps/api/core'; -import {save} from '@tauri-apps/plugin-dialog'; + +const chooseSaveTarget = vi.hoisted(() => vi.fn()); + +const call = vi.hoisted(() => vi.fn()); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + supports: () => true, + chooseSaveTarget, + }), +})); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call}), +})); import {useCreateSqliteDatabase} from '@/hooks/useCreateSqliteDatabase'; -const mockInvoke = vi.mocked(invoke); -const mockSave = vi.mocked(save); +const mockSave = chooseSaveTarget; const connection = { id: 'sqlite-1', @@ -19,8 +31,8 @@ const connection = { describe('useCreateSqliteDatabase', () => { beforeEach(() => { vi.clearAllMocks(); - mockSave.mockResolvedValue('/tmp/customers.db'); - mockInvoke.mockResolvedValue(connection); + mockSave.mockResolvedValue({reference: '/tmp/customers.db'}); + call.mockResolvedValue(connection); }); it('creates a SQLite database from the selected save path', async () => { @@ -33,7 +45,7 @@ describe('useCreateSqliteDatabase', () => { expect(mockSave).toHaveBeenCalledWith({ title: 'connections.newSqliteDatabase.dialogTitle', - defaultPath: 'database.db', + suggestedName: 'database.db', filters: [ { name: 'connections.newSqliteDatabase.fileType', @@ -41,7 +53,7 @@ describe('useCreateSqliteDatabase', () => { }, ], }); - expect(mockInvoke).toHaveBeenCalledWith('create_sqlite_database', { + expect(call).toHaveBeenCalledWith('create_sqlite_database', { path: '/tmp/customers.db', }); expect(created).toEqual(connection); @@ -58,11 +70,11 @@ describe('useCreateSqliteDatabase', () => { }); expect(created).toBeNull(); - expect(mockInvoke).not.toHaveBeenCalled(); + expect(call).not.toHaveBeenCalled(); }); it('prevents concurrent creation attempts', async () => { - let resolvePath: ((path: string | null) => void) | undefined; + let resolvePath: ((path: {reference: string} | null) => void) | undefined; mockSave.mockImplementation( () => new Promise((resolve) => { @@ -80,13 +92,13 @@ describe('useCreateSqliteDatabase', () => { expect(mockSave).toHaveBeenCalledTimes(1); await act(async () => { - resolvePath?.('/tmp/customers.db'); + resolvePath?.({reference: '/tmp/customers.db'}); await firstAttempt; }); }); it('clears the loading state when creation fails', async () => { - mockInvoke.mockRejectedValue(new Error('permission denied')); + call.mockRejectedValue(new Error('permission denied')); const {result} = renderHook(() => useCreateSqliteDatabase()); await act(async () => { diff --git a/tests/hooks/useDangerousQueryGuard.test.ts b/packages/web-ui/tests/hooks/useDangerousQueryGuard.test.ts similarity index 100% rename from tests/hooks/useDangerousQueryGuard.test.ts rename to packages/web-ui/tests/hooks/useDangerousQueryGuard.test.ts diff --git a/tests/hooks/useDataTypes.test.tsx b/packages/web-ui/tests/hooks/useDataTypes.test.tsx similarity index 97% rename from tests/hooks/useDataTypes.test.tsx rename to packages/web-ui/tests/hooks/useDataTypes.test.tsx index a8a395ee8..7e24fff1b 100644 --- a/tests/hooks/useDataTypes.test.tsx +++ b/packages/web-ui/tests/hooks/useDataTypes.test.tsx @@ -8,6 +8,11 @@ import type {DataTypeInfo, DataTypeRegistry} from '@/types/dataTypes'; vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn()})); +const client = {call: invoke}; +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); + const type = (name: string): DataTypeInfo => ({ name, category: 'json', diff --git a/tests/hooks/useDatabase.test.ts b/packages/web-ui/tests/hooks/useDatabase.test.ts similarity index 100% rename from tests/hooks/useDatabase.test.ts rename to packages/web-ui/tests/hooks/useDatabase.test.ts diff --git a/tests/hooks/useDatabaseObjectNavigation.test.ts b/packages/web-ui/tests/hooks/useDatabaseObjectNavigation.test.ts similarity index 97% rename from tests/hooks/useDatabaseObjectNavigation.test.ts rename to packages/web-ui/tests/hooks/useDatabaseObjectNavigation.test.ts index 74d94edd3..11e2cb2cc 100644 --- a/tests/hooks/useDatabaseObjectNavigation.test.ts +++ b/packages/web-ui/tests/hooks/useDatabaseObjectNavigation.test.ts @@ -20,6 +20,12 @@ vi.mock('@/hooks/useAlert', () => ({ useAlert: vi.fn(() => ({showAlert: showAlertMock})), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invoke(command, request), + }), +})); + describe('useDatabaseObjectNavigation', () => { beforeEach(() => { navigateMock.mockReset(); diff --git a/packages/web-ui/tests/hooks/useDeepLinkInstall.test.tsx b/packages/web-ui/tests/hooks/useDeepLinkInstall.test.tsx new file mode 100644 index 000000000..9a4211602 --- /dev/null +++ b/packages/web-ui/tests/hooks/useDeepLinkInstall.test.tsx @@ -0,0 +1,25 @@ +import {act, renderHook} from '@testing-library/react'; +import {invoke} from '@tauri-apps/api/core'; +import {listen} from '@tauri-apps/api/event'; +import {describe, expect, it, vi} from 'vitest'; +import {useDeepLinkInstall} from '@/hooks/useDeepLinkInstall'; + +vi.mock('@tauri-apps/api/event', () => ({listen: vi.fn(), emit: vi.fn()})); + +const mocks = vi.hoisted(() => ({client: {call: vi.fn()}})); +vi.mock('@/hooks/useTabularisClient', () => ({useTabularisClient: () => mocks.client})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({negotiation: {environment: 'browser'}}), +})); + +describe('useDeepLinkInstall browser startup', () => { + it('does not register OS handoffs or consume desktop startup requests', async () => { + vi.mocked(invoke).mockClear(); + vi.mocked(listen).mockClear(); + const {result} = renderHook(useDeepLinkInstall); + await act(async () => {}); + expect(invoke).not.toHaveBeenCalled(); + expect(listen).not.toHaveBeenCalled(); + expect(result.current.pending).toBeNull(); + }); +}); diff --git a/tests/hooks/useDrivers.test.ts b/packages/web-ui/tests/hooks/useDrivers.test.ts similarity index 96% rename from tests/hooks/useDrivers.test.ts rename to packages/web-ui/tests/hooks/useDrivers.test.ts index 1ad62828a..7d2feb7fa 100644 --- a/tests/hooks/useDrivers.test.ts +++ b/packages/web-ui/tests/hooks/useDrivers.test.ts @@ -14,6 +14,8 @@ vi.mock('@/hooks/useSettings', () => ({ import {useDrivers} from '@/hooks/useDrivers'; +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); const listenMock = vi.mocked(listen); const invokeMock = vi.mocked(invoke); diff --git a/tests/hooks/useEditor.test.ts b/packages/web-ui/tests/hooks/useEditor.test.ts similarity index 100% rename from tests/hooks/useEditor.test.ts rename to packages/web-ui/tests/hooks/useEditor.test.ts diff --git a/tests/hooks/useEditorTheme.test.ts b/packages/web-ui/tests/hooks/useEditorTheme.test.ts similarity index 100% rename from tests/hooks/useEditorTheme.test.ts rename to packages/web-ui/tests/hooks/useEditorTheme.test.ts diff --git a/tests/hooks/useExplainAnalyze.test.ts b/packages/web-ui/tests/hooks/useExplainAnalyze.test.ts similarity index 100% rename from tests/hooks/useExplainAnalyze.test.ts rename to packages/web-ui/tests/hooks/useExplainAnalyze.test.ts diff --git a/tests/hooks/useExplainPlan.test.ts b/packages/web-ui/tests/hooks/useExplainPlan.test.ts similarity index 97% rename from tests/hooks/useExplainPlan.test.ts rename to packages/web-ui/tests/hooks/useExplainPlan.test.ts index a163d7ea3..5b591c8a7 100644 --- a/tests/hooks/useExplainPlan.test.ts +++ b/packages/web-ui/tests/hooks/useExplainPlan.test.ts @@ -5,6 +5,8 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {useExplainPlan} from '@/hooks/useExplainPlan'; import * as sql from '@/utils/sql'; +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); vi.mock('react-i18next', () => { const t = (key: string) => key; return {useTranslation: () => ({t})}; @@ -75,18 +77,18 @@ describe('useExplainPlan', () => { }); it.each([ - {options: {}, expected: {analyze: false, schema: null, database: null}}, + {options: {}, expected: {analyze: false, schema: undefined, database: undefined}}, { options: {analyze: true, schema: 'analytics'}, - expected: {analyze: true, schema: 'analytics', database: null}, + expected: {analyze: true, schema: 'analytics', database: undefined}, }, { options: {analyze: false, schema: ''}, - expected: {analyze: false, schema: null, database: null}, + expected: {analyze: false, schema: undefined, database: undefined}, }, { options: {analyze: false, database: 'app_db'}, - expected: {analyze: false, schema: null, database: 'app_db'}, + expected: {analyze: false, schema: undefined, database: 'app_db'}, }, ])('preserves invoke defaults and explicit options: $expected', async ({options, expected}) => { const plan = makePlan('resolved'); diff --git a/tests/hooks/useGlobalShortcuts.test.ts b/packages/web-ui/tests/hooks/useGlobalShortcuts.test.ts similarity index 100% rename from tests/hooks/useGlobalShortcuts.test.ts rename to packages/web-ui/tests/hooks/useGlobalShortcuts.test.ts diff --git a/packages/web-ui/tests/hooks/useJsonEditorActivity.test.ts b/packages/web-ui/tests/hooks/useJsonEditorActivity.test.ts new file mode 100644 index 000000000..506d6cc47 --- /dev/null +++ b/packages/web-ui/tests/hooks/useJsonEditorActivity.test.ts @@ -0,0 +1,35 @@ +import {act, renderHook} from '@testing-library/react'; +import {describe, expect, it} from 'vitest'; +import {useJsonEditorActivity} from '@/hooks/useJsonEditorActivity'; + +describe('editable JSON window activity', () => { + it('blocks while opening and releases each editor independently', () => { + const {result} = renderHook(useJsonEditorActivity); + let first!: () => void; + let second!: () => void; + act(() => { + first = result.current.begin(); + second = result.current.begin(); + }); + expect(result.current.count).toBe(2); + expect(result.current.isEditing()).toBe(true); + act(() => first()); + expect(result.current.count).toBe(1); + // Save, close, or a failed open can all release the same activity safely. + act(() => first()); + expect(result.current.count).toBe(1); + act(() => second()); + expect(result.current.isEditing()).toBe(false); + }); + + it('clears activity on unmount and accepts a late window close', () => { + const {result, unmount} = renderHook(useJsonEditorActivity); + let end!: () => void; + act(() => { + end = result.current.begin(); + }); + unmount(); + expect(result.current.isEditing()).toBe(false); + expect(() => end()).not.toThrow(); + }); +}); diff --git a/tests/hooks/useK8sPathOverrides.test.ts b/packages/web-ui/tests/hooks/useK8sPathOverrides.test.ts similarity index 99% rename from tests/hooks/useK8sPathOverrides.test.ts rename to packages/web-ui/tests/hooks/useK8sPathOverrides.test.ts index 51bec291c..631a86eff 100644 --- a/tests/hooks/useK8sPathOverrides.test.ts +++ b/packages/web-ui/tests/hooks/useK8sPathOverrides.test.ts @@ -7,7 +7,7 @@ const k8sMocks = vi.hoisted(() => ({ })); vi.mock('@/utils/k8s', () => ({ - validateK8sPath: k8sMocks.validateK8sPath, + validateK8sPath: (path: string, kind: string) => k8sMocks.validateK8sPath(path, kind), })); interface Deferred { diff --git a/tests/hooks/useLatestAsync.test.ts b/packages/web-ui/tests/hooks/useLatestAsync.test.ts similarity index 100% rename from tests/hooks/useLatestAsync.test.ts rename to packages/web-ui/tests/hooks/useLatestAsync.test.ts diff --git a/tests/hooks/useOpenConnectionInNewWindow.test.ts b/packages/web-ui/tests/hooks/useOpenConnectionInNewWindow.test.ts similarity index 80% rename from tests/hooks/useOpenConnectionInNewWindow.test.ts rename to packages/web-ui/tests/hooks/useOpenConnectionInNewWindow.test.ts index f5d965657..f89f3a313 100644 --- a/tests/hooks/useOpenConnectionInNewWindow.test.ts +++ b/packages/web-ui/tests/hooks/useOpenConnectionInNewWindow.test.ts @@ -6,6 +6,7 @@ import {useOpenConnectionInNewWindow} from '@/hooks/useOpenConnectionInNewWindow const detachConnectionMock = vi.fn(); const isConnectionOpenMock = vi.fn<(id: string) => boolean>(); const isConnectionOpenAnywhereMock = vi.fn<(id: string) => boolean>(); +const openConnectionRouteMock = vi.fn(); vi.mock('@/hooks/useDatabase', () => ({ useDatabase: () => ({ @@ -15,6 +16,18 @@ vi.mock('@/hooks/useDatabase', () => ({ }), })); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({ + openConnectionRoute: openConnectionRouteMock, + }), +})); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({ + call: (command: string, request: unknown) => invoke(command, request), + }), +})); + const invokeMock = vi.mocked(invoke); const conn = {id: 'conn-1', name: 'My DB', params: {driver: 'mysql'}}; @@ -25,6 +38,8 @@ describe('useOpenConnectionInNewWindow', () => { detachConnectionMock.mockReset(); isConnectionOpenMock.mockReset(); isConnectionOpenAnywhereMock.mockReset(); + openConnectionRouteMock.mockReset(); + openConnectionRouteMock.mockResolvedValue(undefined); invokeMock.mockImplementation((cmd: string) => { if (cmd === 'get_connections') return Promise.resolve([conn]); return Promise.resolve(undefined); @@ -41,14 +56,12 @@ describe('useOpenConnectionInNewWindow', () => { expect(invokeMock).toHaveBeenCalledWith('test_connection', { request: {params: conn.params, connection_id: 'conn-1'}, }); - expect(invokeMock).toHaveBeenCalledWith('open_connection_window', { + expect(openConnectionRouteMock).toHaveBeenCalledWith({ connectionId: 'conn-1', title: 'My DB', }); - // test_connection must be called before open_connection_window - const order = invokeMock.mock.calls.map((c) => c[0]); - expect(order.indexOf('test_connection')).toBeLessThan( - order.indexOf('open_connection_window'), + expect(invokeMock.mock.invocationCallOrder.at(-1)).toBeLessThan( + openConnectionRouteMock.mock.invocationCallOrder[0], ); }); @@ -63,7 +76,7 @@ describe('useOpenConnectionInNewWindow', () => { const {result} = renderHook(() => useOpenConnectionInNewWindow()); await expect(result.current('conn-1', 'My DB')).rejects.toThrow('bad creds'); - expect(invokeMock).not.toHaveBeenCalledWith('open_connection_window', expect.anything()); + expect(openConnectionRouteMock).not.toHaveBeenCalled(); }); it('skips validation when the connection is already open somewhere', async () => { @@ -74,7 +87,7 @@ describe('useOpenConnectionInNewWindow', () => { await result.current('conn-1', 'My DB'); expect(invokeMock).not.toHaveBeenCalledWith('test_connection', expect.anything()); - expect(invokeMock).toHaveBeenCalledWith('open_connection_window', { + expect(openConnectionRouteMock).toHaveBeenCalledWith({ connectionId: 'conn-1', title: 'My DB', }); @@ -97,7 +110,7 @@ describe('useOpenConnectionInNewWindow', () => { await result.current('conn-1'); - expect(invokeMock).toHaveBeenCalledWith('open_connection_window', { + expect(openConnectionRouteMock).toHaveBeenCalledWith({ connectionId: 'conn-1', title: null, }); diff --git a/packages/web-ui/tests/hooks/usePluginInstallConfirmation.test.tsx b/packages/web-ui/tests/hooks/usePluginInstallConfirmation.test.tsx new file mode 100644 index 000000000..4857e6855 --- /dev/null +++ b/packages/web-ui/tests/hooks/usePluginInstallConfirmation.test.tsx @@ -0,0 +1,60 @@ +import type {ReactNode} from 'react'; +import {act, renderHook} from '@testing-library/react'; +import {invoke} from '@tauri-apps/api/core'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; +import {usePluginInstallConfirmation} from '@/hooks/usePluginInstallConfirmation'; + +const client = new TabularisClient(new TauriTransport()); +const wrapper = ({children}: {children: ReactNode}) => ( + {children} +); + +describe('usePluginInstallConfirmation', () => { + beforeEach(() => vi.mocked(invoke).mockReset()); + + it('installs only after confirmation and preserves the selected registry', async () => { + vi.mocked(invoke).mockResolvedValue(undefined); + const {result} = renderHook(() => usePluginInstallConfirmation(), {wrapper}); + + expect(invoke).not.toHaveBeenCalled(); + + await act(async () => { + await expect( + result.current.confirm({ + slug: 'postgres-driver', + version: '1.2.3', + registry: 'https://registry.example/api', + }), + ).resolves.toBe(true); + }); + + expect(invoke).toHaveBeenCalledWith('install_plugin', { + pluginId: 'postgres-driver', + version: '1.2.3', + registryUrl: 'https://registry.example/api', + }); + }); + + it('keeps the confirmation active when installation fails', async () => { + const failingInvoke = (): Promise => Promise.reject(new Error('install failed')); + const failingClient = new TabularisClient(new TauriTransport(failingInvoke)); + const failingWrapper = ({children}: {children: ReactNode}) => ( + {children} + ); + const {result} = renderHook(() => usePluginInstallConfirmation(), { + wrapper: failingWrapper, + }); + + let confirmed = true; + await act(async () => { + confirmed = await result.current.confirm({slug: 'postgres-driver'}); + }); + + expect(confirmed).toBe(false); + expect(result.current.error).toContain('install failed'); + expect(result.current.busy).toBe(false); + }); +}); diff --git a/tests/hooks/useQueryGuards.test.ts b/packages/web-ui/tests/hooks/useQueryGuards.test.ts similarity index 100% rename from tests/hooks/useQueryGuards.test.ts rename to packages/web-ui/tests/hooks/useQueryGuards.test.ts diff --git a/packages/web-ui/tests/hooks/useReferencedRecord.test.ts b/packages/web-ui/tests/hooks/useReferencedRecord.test.ts new file mode 100644 index 000000000..d13e41401 --- /dev/null +++ b/packages/web-ui/tests/hooks/useReferencedRecord.test.ts @@ -0,0 +1,143 @@ +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {invoke} from '@tauri-apps/api/core'; +import type {ForeignKey} from '@/types/schema'; +import {fetchReferencedRecord} from '@/hooks/useReferencedRecord'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; + +vi.mock('@tauri-apps/api/core', () => ({ + invoke: vi.fn(), +})); + +const client = new TabularisClient(new TauriTransport()); + +const fk = ( + name: string, + column_name: string, + ref_table: string, + ref_column: string, +): ForeignKey => ({name, column_name, ref_table, ref_column}); + +describe('useReferencedRecord hook integration', () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + describe('fetchReferencedRecord', () => { + it('calls execute_query with correct SQL filter for mysql driver', async () => { + const mockInvoke = vi.mocked(invoke); + mockInvoke.mockResolvedValueOnce({ + columns: ['id', 'name'], + rows: [[42, 'Acme Corp']], + affected_rows: 1, + }); + + const res = await fetchReferencedRecord( + { + connectionId: 'conn-123', + fk: fk('fk_org', 'org_id', 'organizations', 'id'), + value: 42, + driver: 'mysql', + }, + client, + ); + + expect(mockInvoke).toHaveBeenCalledWith('execute_query', { + connectionId: 'conn-123', + query: 'SELECT * FROM `organizations` WHERE `id` = 42', + limit: 100, + page: 1, + }); + expect(res.rows).toEqual([[42, 'Acme Corp']]); + }); + + it('calls execute_query with correct SQL filter for postgres driver with schema prefixing', async () => { + const mockInvoke = vi.mocked(invoke); + mockInvoke.mockResolvedValueOnce({ + columns: ['id', 'name'], + rows: [[42, 'Acme Corp']], + affected_rows: 1, + }); + + await fetchReferencedRecord( + { + connectionId: 'conn-123', + fk: fk('fk_org', 'org_id', 'organizations', 'id'), + value: 42, + driver: 'postgres', + schema: 'public', + }, + client, + ); + + expect(mockInvoke).toHaveBeenCalledWith('execute_query', { + connectionId: 'conn-123', + query: 'SELECT * FROM "public"."organizations" WHERE "id" = 42', + limit: 100, + page: 1, + schema: 'public', + }); + }); + + it('handles missing value by returning empty QueryResult without executing query', async () => { + const mockInvoke = vi.mocked(invoke); + const res = await fetchReferencedRecord( + { + connectionId: 'conn-123', + fk: fk('fk_org', 'org_id', 'organizations', 'id'), + value: null, + }, + client, + ); + + expect(mockInvoke).not.toHaveBeenCalled(); + expect(res).toEqual({columns: [], rows: [], affected_rows: 0}); + }); + }); +}); + +const baseParams = { + connectionId: 'conn-1', + fk: fk('fk_users', 'user_id', 'users', 'id'), + value: 42, + driver: 'postgres', + schema: 'public', + sourceColumnType: 'integer', +}; + +describe('fetchReferencedRecord database threading', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(invoke).mockResolvedValue({columns: [], rows: [], affected_rows: 0}); + }); + + it('passes the database override to execute_query when set', async () => { + await fetchReferencedRecord({...baseParams, database: 'analytics'}, client); + + expect(vi.mocked(invoke)).toHaveBeenCalledWith( + 'execute_query', + expect.objectContaining({database: 'analytics'}), + ); + }); + + it('omits database from execute_query when not set (backward-compatible)', async () => { + await fetchReferencedRecord({...baseParams}, client); + + const callArgs = vi.mocked(invoke).mock.calls[0][1] as Record; + expect(callArgs).not.toHaveProperty('database'); + }); + + it('omits database when set to null', async () => { + await fetchReferencedRecord({...baseParams, database: null}, client); + + const callArgs = vi.mocked(invoke).mock.calls[0][1] as Record; + expect(callArgs).not.toHaveProperty('database'); + }); + + it('omits database when set to empty string', async () => { + await fetchReferencedRecord({...baseParams, database: ''}, client); + + const callArgs = vi.mocked(invoke).mock.calls[0][1] as Record; + expect(callArgs).not.toHaveProperty('database'); + }); +}); diff --git a/packages/web-ui/tests/hooks/useRightSidebarResize.test.ts b/packages/web-ui/tests/hooks/useRightSidebarResize.test.ts new file mode 100644 index 000000000..37e02c36f --- /dev/null +++ b/packages/web-ui/tests/hooks/useRightSidebarResize.test.ts @@ -0,0 +1,37 @@ +import {renderHook, act} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {useRightSidebarResize} from '@/hooks/useRightSidebarResize'; +import {uiStateStore} from '@/utils/uiStateStore'; + +const KEY = 'tabularis_row_editor_sidebar_width'; + +describe('useRightSidebarResize', () => { + beforeEach(() => { + localStorage.clear(); + uiStateStore.reset(); + Object.defineProperty(window, 'innerWidth', { + configurable: true, + writable: true, + value: 1600, + }); + }); + + it('uses the shared width, clamped to half the viewport', () => { + uiStateStore.set(KEY, 1200); + const {result} = renderHook(() => useRightSidebarResize()); + expect(result.current.width).toBe(800); + }); + + it('stores the dragged width in the shared UI state', () => { + const {result} = renderHook(() => useRightSidebarResize()); + act(() => { + result.current.startResize({preventDefault: vi.fn()} as unknown as React.MouseEvent); + }); + act(() => { + document.dispatchEvent(new MouseEvent('mousemove', {clientX: 1100})); + document.dispatchEvent(new MouseEvent('mouseup')); + }); + expect(result.current.width).toBe(500); + expect(uiStateStore.get(KEY, 0)).toBe(500); + }); +}); diff --git a/tests/hooks/useRowEditor.test.ts b/packages/web-ui/tests/hooks/useRowEditor.test.ts similarity index 100% rename from tests/hooks/useRowEditor.test.ts rename to packages/web-ui/tests/hooks/useRowEditor.test.ts diff --git a/tests/hooks/useRowEditorResize.test.ts b/packages/web-ui/tests/hooks/useRowEditorResize.test.ts similarity index 90% rename from tests/hooks/useRowEditorResize.test.ts rename to packages/web-ui/tests/hooks/useRowEditorResize.test.ts index 8c2d3fa00..131a3eb16 100644 --- a/tests/hooks/useRowEditorResize.test.ts +++ b/packages/web-ui/tests/hooks/useRowEditorResize.test.ts @@ -2,6 +2,7 @@ import {renderHook, act} from '@testing-library/react'; import {describe, it, expect, beforeEach, vi} from 'vitest'; import {useRowEditorResize} from '@/hooks/useRowEditorResize'; +import {uiStateStore} from '@/utils/uiStateStore'; const STORAGE_KEY = 'tabularis_row_editor_sidebar_width'; @@ -30,6 +31,7 @@ describe('useRowEditorResize', () => { writable: true, value: createLocalStorageStub(), }); + uiStateStore.reset(); vi.restoreAllMocks(); // Pin innerWidth so clamps are deterministic. Object.defineProperty(window, 'innerWidth', { @@ -39,19 +41,21 @@ describe('useRowEditorResize', () => { }); }); - it('initializes with the default width when localStorage is empty', () => { + it('initializes with the default width when nothing was saved', () => { const {result} = renderHook(() => useRowEditorResize()); expect(result.current.width).toBe(384); }); - it('reads a persisted width from localStorage', () => { + it('reads the width an older version saved in localStorage', () => { window.localStorage.setItem(STORAGE_KEY, '720'); + uiStateStore.reset(); const {result} = renderHook(() => useRowEditorResize()); expect(result.current.width).toBe(720); }); - it('never starts below the minimum even if localStorage was corrupted', () => { + it('never starts below the minimum even if the saved width is too small', () => { window.localStorage.setItem(STORAGE_KEY, '50'); + uiStateStore.reset(); const {result} = renderHook(() => useRowEditorResize()); expect(result.current.width).toBe(320); }); @@ -124,6 +128,6 @@ describe('useRowEditorResize', () => { expect(document.body.style.cursor).toBe(''); expect(document.body.style.userSelect).toBe(''); - expect(window.localStorage.getItem(STORAGE_KEY)).toBe('500'); + expect(uiStateStore.get(STORAGE_KEY, 0)).toBe(500); }); }); diff --git a/tests/hooks/useSavedQueries.test.ts b/packages/web-ui/tests/hooks/useSavedQueries.test.ts similarity index 100% rename from tests/hooks/useSavedQueries.test.ts rename to packages/web-ui/tests/hooks/useSavedQueries.test.ts diff --git a/packages/web-ui/tests/hooks/useSecondaryWindows.test.ts b/packages/web-ui/tests/hooks/useSecondaryWindows.test.ts new file mode 100644 index 000000000..38a9b1be4 --- /dev/null +++ b/packages/web-ui/tests/hooks/useSecondaryWindows.test.ts @@ -0,0 +1,72 @@ +import {renderHook} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {RESULTS_CLOSE_REQUEST_EVENT} from '@/platform/secondaryWindowSessions'; +import {useSecondaryWindows} from '@/hooks/useSecondaryWindows'; + +const openRoute = vi.fn(); +const publishRouteEvent = vi.fn(); + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => ({openRoute, publishRouteEvent}), +})); + +describe('useSecondaryWindows', () => { + beforeEach(() => { + openRoute.mockReset(); + openRoute.mockResolvedValue(undefined); + publishRouteEvent.mockReset(); + publishRouteEvent.mockResolvedValue(undefined); + }); + + it('opens results, schema, task manager, and visual explain routes', async () => { + const {result} = renderHook(() => useSecondaryWindows()); + + await result.current.openResultsWindow('result/session', 'Query Results'); + await result.current.openSchemaDiagram({ + connectionId: 'connection-1', + connectionName: 'Primary', + databaseName: 'main', + schema: 'public', + focusTable: 'users', + }); + await result.current.openTaskManager(); + await result.current.openVisualExplain('connection-1', 'SELECT 1'); + + expect(openRoute).toHaveBeenNthCalledWith(1, { + route: '/results-window?session=result%2Fsession', + target: 'new', + label: 'results-window-result_session', + title: 'Query Results', + window: {width: 900, height: 600, minWidth: 500, minHeight: 300}, + }); + expect(openRoute).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + route: '/schema-diagram?connectionId=connection-1&connectionName=Primary&databaseName=main&schema=public&focusTable=users', + target: 'new', + label: 'er-diagram-connection-1_main_public', + }), + ); + expect(openRoute).toHaveBeenNthCalledWith( + 3, + expect.objectContaining({route: '/task-manager', label: 'task-manager'}), + ); + expect(openRoute).toHaveBeenNthCalledWith( + 4, + expect.objectContaining({ + route: expect.stringMatching(/^\/visual-explain\?connection=connection-1&query=/), + label: 'visual-explain', + }), + ); + }); + + it('asks an opened result route to close by opaque session id', async () => { + const {result} = renderHook(() => useSecondaryWindows()); + + await result.current.closeResultsWindow('result-session'); + + expect(publishRouteEvent).toHaveBeenCalledWith(RESULTS_CLOSE_REQUEST_EVENT, { + sessionId: 'result-session', + }); + }); +}); diff --git a/tests/hooks/useSettings.test.ts b/packages/web-ui/tests/hooks/useSettings.test.ts similarity index 100% rename from tests/hooks/useSettings.test.ts rename to packages/web-ui/tests/hooks/useSettings.test.ts diff --git a/tests/hooks/useSidebarResize.test.ts b/packages/web-ui/tests/hooks/useSidebarResize.test.ts similarity index 83% rename from tests/hooks/useSidebarResize.test.ts rename to packages/web-ui/tests/hooks/useSidebarResize.test.ts index 29d60076c..7b5a1012f 100644 --- a/tests/hooks/useSidebarResize.test.ts +++ b/packages/web-ui/tests/hooks/useSidebarResize.test.ts @@ -1,10 +1,12 @@ import {renderHook, act} from '@testing-library/react'; import {describe, it, expect, beforeEach, vi} from 'vitest'; import {useSidebarResize} from '@/hooks/useSidebarResize'; +import {UI_STATE_CACHE_KEY, uiStateStore} from '@/utils/uiStateStore'; describe('useSidebarResize', () => { beforeEach(() => { localStorage.clear(); + uiStateStore.reset(); vi.restoreAllMocks(); }); @@ -13,8 +15,9 @@ describe('useSidebarResize', () => { expect(result.current.sidebarWidth).toBe(256); }); - it('should initialize with saved width from localStorage', () => { + it('should initialize with the width an older version saved in localStorage', () => { localStorage.setItem('tabularis_sidebar_width', '300'); + uiStateStore.reset(); const {result} = renderHook(() => useSidebarResize()); expect(result.current.sidebarWidth).toBe(300); }); @@ -61,7 +64,7 @@ describe('useSidebarResize', () => { expect(result.current.sidebarWidth).toBe(256); // No update }); - it('should stop resizing on mouseup and save to localStorage', () => { + it('should stop resizing on mouseup and save to the shared UI state', () => { const {result} = renderHook(() => useSidebarResize()); const {startResize} = result.current; @@ -81,6 +84,10 @@ describe('useSidebarResize', () => { }); expect(document.body.style.cursor).toBe('default'); - expect(localStorage.getItem('tabularis_sidebar_width')).toBe('300'); + expect(uiStateStore.get('tabularis_sidebar_width', 0)).toBe(300); + // Mirrored for the next first paint, so the sidebar does not jump. + expect(JSON.parse(localStorage.getItem(UI_STATE_CACHE_KEY) ?? '{}')).toEqual({ + tabularis_sidebar_width: 300, + }); }); }); diff --git a/tests/hooks/useSqlAutocompleteRegistration.test.ts b/packages/web-ui/tests/hooks/useSqlAutocompleteRegistration.test.ts similarity index 96% rename from tests/hooks/useSqlAutocompleteRegistration.test.ts rename to packages/web-ui/tests/hooks/useSqlAutocompleteRegistration.test.ts index 3c7867aaf..73942021f 100644 --- a/tests/hooks/useSqlAutocompleteRegistration.test.ts +++ b/packages/web-ui/tests/hooks/useSqlAutocompleteRegistration.test.ts @@ -7,7 +7,12 @@ import {useSqlAutocompleteRegistration} from '@/hooks/useSqlAutocompleteRegistra import {registerSqlAutocomplete} from '@/utils/autocomplete'; import {useDatabase} from '@/hooks/useDatabase'; +const clientMock = vi.hoisted(() => ({call: vi.fn()})); + vi.mock('@/hooks/useDatabase'); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => clientMock, +})); vi.mock('@/utils/autocomplete', () => ({ registerSqlAutocomplete: vi.fn(), disposeSqlAutocomplete: vi.fn(), @@ -75,6 +80,7 @@ describe('useSqlAutocompleteRegistration', () => { [{name: 'Addresses', schema: 'Ops'}], 'Ops', capabilities, + expect.any(Object), 'upper', ); }); @@ -107,6 +113,7 @@ describe('useSqlAutocompleteRegistration', () => { ], 'Ops', capabilities, + expect.any(Object), 'upper', ); }); @@ -125,7 +132,7 @@ describe('useSqlAutocompleteRegistration', () => { } as ReturnType); }); - const lastKeywordCase = () => mockRegisterSqlAutocomplete.mock.calls.at(-1)?.[5]; + const lastKeywordCase = () => mockRegisterSqlAutocomplete.mock.calls.at(-1)?.[6]; it('passes the default setting (match) to the provider', () => { renderHook(() => useSqlAutocompleteRegistration('conn1', {monaco}), { diff --git a/tests/hooks/useSshAskpass.test.ts b/packages/web-ui/tests/hooks/useSshAskpass.test.ts similarity index 85% rename from tests/hooks/useSshAskpass.test.ts rename to packages/web-ui/tests/hooks/useSshAskpass.test.ts index 224b9f4d5..9f736e927 100644 --- a/tests/hooks/useSshAskpass.test.ts +++ b/packages/web-ui/tests/hooks/useSshAskpass.test.ts @@ -1,12 +1,17 @@ +import {createElement, type ReactNode} from 'react'; import {describe, it, expect, vi, beforeEach} from 'vitest'; -import {renderHook, act} from '@testing-library/react'; +import {renderHook as renderHookBase, act} from '@testing-library/react'; import {listen, type EventCallback} from '@tauri-apps/api/event'; import {invoke} from '@tauri-apps/api/core'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; import {useSshAskpass} from '@/hooks/useSshAskpass'; import type {SshAskpassRequest} from '@/types/askpass'; vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(), + emit: vi.fn(), })); const listenMock = vi.mocked(listen); @@ -14,6 +19,10 @@ const invokeMock = vi.mocked(invoke); describe('useSshAskpass', () => { let handlers: Record>; + const client = new TabularisClient(new TauriTransport()); + const wrapper = ({children}: {children: ReactNode}) => + createElement(TabularisClientProvider, {client}, children); + const renderHook = (callback: () => Result) => renderHookBase(callback, {wrapper}); beforeEach(() => { handlers = {}; diff --git a/tests/hooks/useTabSwitcher.test.tsx b/packages/web-ui/tests/hooks/useTabSwitcher.test.tsx similarity index 96% rename from tests/hooks/useTabSwitcher.test.tsx rename to packages/web-ui/tests/hooks/useTabSwitcher.test.tsx index 2945e123a..eacb91ffc 100644 --- a/tests/hooks/useTabSwitcher.test.tsx +++ b/packages/web-ui/tests/hooks/useTabSwitcher.test.tsx @@ -173,3 +173,7 @@ describe('useTabSwitcher with EditorProvider', () => { expect(event.defaultPrevented).toBe(false); }); }); + +vi.mock('@/hooks/useTabularisClient', () => ({useTabularisClient: () => client})); +import {invoke} from '@tauri-apps/api/core'; +const client = {call: (command: string, args: Record) => invoke(command, args)}; diff --git a/packages/web-ui/tests/hooks/useTaskManager.test.ts b/packages/web-ui/tests/hooks/useTaskManager.test.ts new file mode 100644 index 000000000..6c54c043e --- /dev/null +++ b/packages/web-ui/tests/hooks/useTaskManager.test.ts @@ -0,0 +1,75 @@ +import {act, renderHook, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {useTaskManager} from '@/hooks/useTaskManager'; + +const mocks = vi.hoisted(() => { + const call = vi.fn(); + return {call, client: {call}}; +}); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mocks.client, +})); + +const processFixture = { + plugin_id: 'postgres-driver', + plugin_name: 'PostgreSQL Driver', + pid: 4100, + cpu_percent: -1, + memory_bytes: 2048, + disk_read_bytes: 128, + disk_write_bytes: 64, + status: 'running' as const, + children: [], +}; + +const statsFixture = { + cpu_percent: 12.5, + memory_used: 4096, + memory_total: 8192, + disk_read_bytes: 256, + disk_write_bytes: 128, + process_count: 4, + tabularis: null, +}; + +describe('useTaskManager', () => { + beforeEach(() => { + mocks.call.mockReset(); + mocks.call.mockImplementation((command: string) => { + if (command === 'get_process_list') return Promise.resolve([processFixture]); + if (command === 'get_system_stats') return Promise.resolve(statsFixture); + return Promise.resolve(null); + }); + }); + + it('polls process and system snapshots through TabularisClient', async () => { + const {result, unmount} = renderHook(() => useTaskManager()); + + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(mocks.call).toHaveBeenCalledWith('get_process_list', undefined); + expect(mocks.call).toHaveBeenCalledWith('get_system_stats', undefined); + expect(result.current.processes[0].cpu_percent).toBe(0); + expect(result.current.systemStats).toEqual(statsFixture); + + unmount(); + }); + + it('runs destructive plugin actions through their local-admin client commands', async () => { + const {result, unmount} = renderHook(() => useTaskManager()); + await waitFor(() => expect(result.current.loading).toBe(false)); + + await act(async () => { + await result.current.killProcess('postgres-driver'); + await result.current.restartProcess('postgres-driver'); + }); + + expect(mocks.call).toHaveBeenCalledWith('kill_plugin_process', { + pluginId: 'postgres-driver', + }); + expect(mocks.call).toHaveBeenCalledWith('restart_plugin_process', { + pluginId: 'postgres-driver', + }); + unmount(); + }); +}); diff --git a/tests/hooks/useTheme.test.ts b/packages/web-ui/tests/hooks/useTheme.test.ts similarity index 100% rename from tests/hooks/useTheme.test.ts rename to packages/web-ui/tests/hooks/useTheme.test.ts diff --git a/tests/hooks/useUpdate.test.ts b/packages/web-ui/tests/hooks/useUpdate.test.ts similarity index 100% rename from tests/hooks/useUpdate.test.ts rename to packages/web-ui/tests/hooks/useUpdate.test.ts diff --git a/tests/i18n/autoRefresh.test.ts b/packages/web-ui/tests/i18n/autoRefresh.test.ts similarity index 100% rename from tests/i18n/autoRefresh.test.ts rename to packages/web-ui/tests/i18n/autoRefresh.test.ts diff --git a/tests/i18n/columnStats.test.ts b/packages/web-ui/tests/i18n/columnStats.test.ts similarity index 100% rename from tests/i18n/columnStats.test.ts rename to packages/web-ui/tests/i18n/columnStats.test.ts diff --git a/tests/i18n/commandPaletteResults.test.ts b/packages/web-ui/tests/i18n/commandPaletteResults.test.ts similarity index 100% rename from tests/i18n/commandPaletteResults.test.ts rename to packages/web-ui/tests/i18n/commandPaletteResults.test.ts diff --git a/tests/i18n/databaseBackup.test.ts b/packages/web-ui/tests/i18n/databaseBackup.test.ts similarity index 100% rename from tests/i18n/databaseBackup.test.ts rename to packages/web-ui/tests/i18n/databaseBackup.test.ts diff --git a/tests/i18n/exportLogsMessage.test.ts b/packages/web-ui/tests/i18n/exportLogsMessage.test.ts similarity index 100% rename from tests/i18n/exportLogsMessage.test.ts rename to packages/web-ui/tests/i18n/exportLogsMessage.test.ts diff --git a/tests/i18n/language.test.ts b/packages/web-ui/tests/i18n/language.test.ts similarity index 100% rename from tests/i18n/language.test.ts rename to packages/web-ui/tests/i18n/language.test.ts diff --git a/tests/i18n/localeBackend.test.ts b/packages/web-ui/tests/i18n/localeBackend.test.ts similarity index 100% rename from tests/i18n/localeBackend.test.ts rename to packages/web-ui/tests/i18n/localeBackend.test.ts diff --git a/tests/i18n/notebookQueryPlan.test.ts b/packages/web-ui/tests/i18n/notebookQueryPlan.test.ts similarity index 100% rename from tests/i18n/notebookQueryPlan.test.ts rename to packages/web-ui/tests/i18n/notebookQueryPlan.test.ts diff --git a/tests/i18n/registryLocale.test.ts b/packages/web-ui/tests/i18n/registryLocale.test.ts similarity index 100% rename from tests/i18n/registryLocale.test.ts rename to packages/web-ui/tests/i18n/registryLocale.test.ts diff --git a/tests/i18n/sqliteDatabase.test.ts b/packages/web-ui/tests/i18n/sqliteDatabase.test.ts similarity index 100% rename from tests/i18n/sqliteDatabase.test.ts rename to packages/web-ui/tests/i18n/sqliteDatabase.test.ts diff --git a/tests/i18n/whatsNew.test.ts b/packages/web-ui/tests/i18n/whatsNew.test.ts similarity index 100% rename from tests/i18n/whatsNew.test.ts rename to packages/web-ui/tests/i18n/whatsNew.test.ts diff --git a/tests/index.test.ts b/packages/web-ui/tests/index.test.ts similarity index 93% rename from tests/index.test.ts rename to packages/web-ui/tests/index.test.ts index 07682e3e5..4703a2ea0 100644 --- a/tests/index.test.ts +++ b/packages/web-ui/tests/index.test.ts @@ -1,7 +1,7 @@ import {readFileSync} from 'node:fs'; import {parse} from 'postcss'; -const stylesheet = parse(readFileSync('src/index.css', 'utf8')); +const stylesheet = parse(readFileSync('packages/web-ui/src/index.css', 'utf8')); function getDeclaration(selector: string, property: string): string | undefined { let value: string | undefined; diff --git a/packages/web-ui/tests/pages/ConnectionEditorRoute.test.tsx b/packages/web-ui/tests/pages/ConnectionEditorRoute.test.tsx new file mode 100644 index 000000000..21ec3f75f --- /dev/null +++ b/packages/web-ui/tests/pages/ConnectionEditorRoute.test.tsx @@ -0,0 +1,105 @@ +import {render, waitFor} from '@testing-library/react'; +import type {ReactNode} from 'react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ConnectionEditorRoute} from '@/pages/ConnectionEditorRoute'; + +const mocks = vi.hoisted(() => ({ + activeConnectionId: null as string | null, + connect: vi.fn<(connectionId: string) => Promise>(), + connectionId: undefined as string | undefined, + isConnectionOpen: vi.fn<(connectionId: string) => boolean>(), + navigate: vi.fn(), + switchConnection: vi.fn(), +})); + +vi.mock('react-router-dom', () => ({ + useNavigate: () => mocks.navigate, + useParams: () => ({connectionId: mocks.connectionId}), +})); + +vi.mock('@/hooks/useDatabase', () => ({ + useDatabase: () => ({ + activeConnectionId: mocks.activeConnectionId, + connect: mocks.connect, + isConnectionOpen: mocks.isConnectionOpen, + switchConnection: mocks.switchConnection, + }), +})); + +vi.mock('@/pages/Editor', () => ({ + Editor: () =>
editor
, +})); + +vi.mock('@/components/ui/EditorErrorBoundary', () => ({ + EditorErrorBoundary: ({children}: {children: ReactNode}) => children, +})); + +describe('ConnectionEditorRoute', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.activeConnectionId = null; + mocks.connectionId = undefined; + mocks.connect.mockResolvedValue(undefined); + mocks.isConnectionOpen.mockReturnValue(false); + }); + + it('redirects the legacy editor route to the active connection', async () => { + mocks.activeConnectionId = 'connection-1'; + + render(); + + await waitFor(() => + expect(mocks.navigate).toHaveBeenCalledWith('/connections/connection-1/editor', { + replace: true, + }), + ); + }); + + it('opens the connection from a direct editor URL', async () => { + mocks.connectionId = 'connection-2'; + + render(); + + await waitFor(() => expect(mocks.connect).toHaveBeenCalledWith('connection-2')); + }); + + it('switches to a connection that is already open', async () => { + mocks.connectionId = 'connection-3'; + mocks.isConnectionOpen.mockReturnValue(true); + + render(); + + await waitFor(() => expect(mocks.switchConnection).toHaveBeenCalledWith('connection-3')); + expect(mocks.connect).not.toHaveBeenCalled(); + }); + + it('keeps the URL synchronized when the active connection changes', async () => { + mocks.connectionId = 'connection-1'; + mocks.activeConnectionId = 'connection-1'; + mocks.isConnectionOpen.mockReturnValue(true); + const {rerender} = render(); + + mocks.activeConnectionId = 'connection-4'; + rerender(); + + await waitFor(() => + expect(mocks.navigate).toHaveBeenCalledWith('/connections/connection-4/editor', { + replace: true, + }), + ); + }); + + it('returns to connections when a direct connection fails', async () => { + mocks.connectionId = 'missing'; + mocks.connect.mockRejectedValue(new Error('missing')); + + render(); + + await waitFor(() => + expect(mocks.navigate).toHaveBeenCalledWith('/connections', { + replace: true, + }), + ); + }); +}); diff --git a/tests/pages/Connections.test.tsx b/packages/web-ui/tests/pages/Connections.test.tsx similarity index 96% rename from tests/pages/Connections.test.tsx rename to packages/web-ui/tests/pages/Connections.test.tsx index 69cc61065..40c8d91d4 100644 --- a/tests/pages/Connections.test.tsx +++ b/packages/web-ui/tests/pages/Connections.test.tsx @@ -71,6 +71,19 @@ vi.mock('@/hooks/useDatabase', () => ({ }), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => ({call: invoke}), +})); + +const platformMock = vi.hoisted(() => ({ + negotiation: {environment: 'tauri'}, + downloadFile: vi.fn(), + currentWindowLabel: vi.fn(() => 'main'), +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platformMock, +})); + vi.mock('@/hooks/useDrivers', () => ({ useDrivers: () => ({drivers: mocks.drivers, allDrivers: mocks.drivers, installedPlugins: []}), })); @@ -187,7 +200,7 @@ describe('Connections SQLite database action', () => { expect(mocks.createSqliteDatabase).toHaveBeenCalledTimes(1); expect(mocks.loadConnections).toHaveBeenCalledTimes(2); expect(mocks.connect).toHaveBeenCalledWith('sqlite-1'); - expect(mocks.navigate).toHaveBeenCalledWith('/editor'); + expect(mocks.navigate).toHaveBeenCalledWith('/connections/sqlite-1/editor'); }); }); diff --git a/tests/pages/EditorAutoRefresh.test.tsx b/packages/web-ui/tests/pages/EditorAutoRefresh.test.tsx similarity index 83% rename from tests/pages/EditorAutoRefresh.test.tsx rename to packages/web-ui/tests/pages/EditorAutoRefresh.test.tsx index 66f67d9bb..5215fae40 100644 --- a/tests/pages/EditorAutoRefresh.test.tsx +++ b/packages/web-ui/tests/pages/EditorAutoRefresh.test.tsx @@ -18,8 +18,25 @@ const mocks = vi.hoisted(() => ({ t: (key: string, options?: Record) => key === 'toolbar.autoRefresh.failed' ? String(options?.error) : key, notify: vi.fn().mockResolvedValue(undefined), + writeClipboard: vi.fn().mockResolvedValue(undefined), sqlOnChange: new Map void>(), })); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, +})); +const client = { + call: (command: string, args: Record) => invoke(command, args), + subscribe: vi.fn().mockResolvedValue(() => {}), +}; +const platform = { + negotiation: {environment: 'browser'}, + subscribeRouteEvent: vi.fn().mockResolvedValue(() => {}), + publishRouteEvent: vi.fn().mockResolvedValue(undefined), +}; +vi.mock('@/platform/activeCapabilities', () => ({writeActiveClipboard: mocks.writeClipboard})); vi.mock('@/utils/queryNotification', () => ({notifyQueryFinished: mocks.notify})); vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); vi.mock('lucide-react', async (importOriginal) => await importOriginal()); @@ -114,10 +131,12 @@ vi.mock('@/components/ui/DataGrid', () => ({ ref, data, onEditingChange, + onCopyAllRows, }: { ref: Ref; data: unknown[][]; onEditingChange?: (editing: boolean) => void; + onCopyAllRows?: () => void; }) { const [editing, setEditing] = useState(false); useImperativeHandle( @@ -132,6 +151,7 @@ vi.mock('@/components/ui/DataGrid', () => ({ return (
{JSON.stringify(data)} +
); @@ -238,6 +258,8 @@ describe('table auto-refresh integration', () => { vi.setSystemTime(0); mocks.connectionId = 'connection-1'; mocks.notify.mockClear(); + mocks.writeClipboard.mockClear(); + mocks.noop.mockClear(); vi.mocked(invoke).mockReset(); vi.mocked(invoke).mockImplementation((command) => command === 'execute_query' @@ -551,6 +573,97 @@ describe('table auto-refresh integration', () => { expect(context.activeTab?.result?.rows).toEqual(rows); }, ); + + it.each([15000, null])( + 'copies all 15,000 rows over two bounded pages with total %s', + async (totalRows) => { + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command !== 'execute_query') return []; + const page = args?.page as number; + const limit = Math.min(args?.limit as number, 10000); + const start = (page - 1) * limit; + return { + columns: ['id'], + affected_rows: 0, + rows: Array.from({length: Math.min(limit, 15000 - start)}, (_, index) => [ + start + index + 1, + ]), + pagination: { + page, + page_size: limit, + total_rows: totalRows, + has_more: start + limit < 15000, + }, + }; + }); + const tab = initialTab(); + tab.result = { + ...initialResult, + pagination: {...initialResult.pagination!, total_rows: totalRows}, + }; + render(); + fireEvent.click(screen.getByRole('button', {name: 'Copy all rows'})); + await advance(0); + expect(queries()).toHaveLength(2); + for (const [, args] of queries()) { + expect(args).toMatchObject({ + connectionId: 'connection-1', + sessionId: 'table-1', + schema: 'private', + limit: 10000, + }); + expect(String(args?.query)).toContain('id > 0'); + expect(String(args?.query)).toContain('DESC'); + expect(String(args?.query)).not.toContain('LIMIT 200'); + } + const text = mocks.writeClipboard.mock.calls[0]?.[0] as string; + expect(text.split('\n')).toHaveLength(15001); + expect(text.startsWith('id\n1\n2\n')).toBe(true); + expect(text.endsWith('\n14999\n15000')).toBe(true); + }, + ); + + it('uses the returned page size when a server clamps limits further, stopping on an empty last page', async () => { + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command !== 'execute_query') return []; + const page = args?.page as number; + return { + columns: ['id'], + affected_rows: 0, + rows: page <= 2 ? [[(page - 1) * 2 + 1], [(page - 1) * 2 + 2]] : [], + pagination: {page, page_size: 2, total_rows: null, has_more: true}, + }; + }); + render(); + fireEvent.click(screen.getByRole('button', {name: 'Copy all rows'})); + await advance(0); + expect(queries().map(([, args]) => ({page: args?.page, limit: args?.limit}))).toEqual([ + {page: 1, limit: 10000}, + {page: 2, limit: 2}, + {page: 3, limit: 2}, + ]); + expect(mocks.writeClipboard).toHaveBeenCalledExactlyOnceWith('id\n1\n2\n3\n4'); + }); + + it('does not copy a partial result when a subsequent page fails', async () => { + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command !== 'execute_query') return []; + if (args?.page === 2) throw new Error('page unavailable'); + return { + ...initialResult, + pagination: {page: 1, page_size: 1, total_rows: null, has_more: true}, + }; + }); + render(); + fireEvent.click(screen.getByRole('button', {name: 'Copy all rows'})); + await advance(0); + expect(queries()).toHaveLength(2); + expect(mocks.writeClipboard).not.toHaveBeenCalled(); + expect(mocks.noop).toHaveBeenCalledWith(expect.stringContaining('page unavailable'), { + title: 'common.error', + kind: 'error', + }); + }); it('waits for a values query before running an overdue table refresh without resetting its deadline', async () => { const pickerRequest = deferred(); vi.mocked(invoke).mockImplementation((command, args) => diff --git a/tests/pages/EditorCopyWithoutComments.test.tsx b/packages/web-ui/tests/pages/EditorCopyWithoutComments.test.tsx similarity index 98% rename from tests/pages/EditorCopyWithoutComments.test.tsx rename to packages/web-ui/tests/pages/EditorCopyWithoutComments.test.tsx index e2de3e7e9..e80a67c03 100644 --- a/tests/pages/EditorCopyWithoutComments.test.tsx +++ b/packages/web-ui/tests/pages/EditorCopyWithoutComments.test.tsx @@ -33,6 +33,8 @@ const mocks = vi.hoisted(() => ({ >, t: (key: string) => key, })); +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); vi.mock('lucide-react', async (importOriginal) => await importOriginal()); vi.mock('react-router-dom', () => ({ diff --git a/tests/pages/EditorHistoryReplay.test.tsx b/packages/web-ui/tests/pages/EditorHistoryReplay.test.tsx similarity index 89% rename from tests/pages/EditorHistoryReplay.test.tsx rename to packages/web-ui/tests/pages/EditorHistoryReplay.test.tsx index 65c3f9fa6..303ce0c22 100644 --- a/tests/pages/EditorHistoryReplay.test.tsx +++ b/packages/web-ui/tests/pages/EditorHistoryReplay.test.tsx @@ -2,6 +2,7 @@ import {useCallback, useLayoutEffect, useRef, useState, useImperativeHandle, typ import {act, fireEvent, render, screen} from '@testing-library/react'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {invoke} from '@tauri-apps/api/core'; +import {normalizeTabularisError} from '@/api/errors'; import {Editor} from '@/pages/Editor'; import {EditorContext, type EditorContextType} from '@/contexts/EditorContext'; import {createAutoRefreshSchedule, type AutoRefreshSchedule} from '@/utils/autoRefresh'; @@ -221,6 +222,29 @@ describe('history recording on a plain (non-opted-in) PostgreSQL connection', () }); afterEach(() => vi.restoreAllMocks()); + it('preserves a normalized transport error in the editor and query history', async () => { + const message = 'relation "missing_table" does not exist'; + vi.mocked(invoke).mockImplementation((command) => + command === 'execute_query' + ? Promise.reject(normalizeTabularisError(message, 'COMMAND_FAILED', 'query-1')) + : Promise.resolve([]), + ); + render(); + await act(async () => { + fireEvent.click(screen.getByRole('button', {name: /^editor\.run/})); + }); + + expect(context.activeTab?.error).toBe(message); + expect(mocks.addEntry).toHaveBeenCalledWith( + consoleTab().query, + null, + 'error', + null, + message, + undefined, + ); + }); + it("records the history entry's database as undefined/null, never the schema", async () => { render(); @@ -272,3 +296,19 @@ describe('history recording on a plain (non-opted-in) PostgreSQL connection', () expect(historyDbArg).toBeUndefined(); }); }); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, +})); +const client = { + call: (command: string, args: Record) => invoke(command, args), + subscribe: vi.fn().mockResolvedValue(() => {}), +}; +const platform = { + negotiation: {environment: 'browser'}, + subscribeRouteEvent: vi.fn().mockResolvedValue(() => {}), + publishRouteEvent: vi.fn().mockResolvedValue(undefined), +}; diff --git a/tests/pages/EditorTabMove.test.tsx b/packages/web-ui/tests/pages/EditorTabMove.test.tsx similarity index 97% rename from tests/pages/EditorTabMove.test.tsx rename to packages/web-ui/tests/pages/EditorTabMove.test.tsx index a5e5f53ec..8c3813a4a 100644 --- a/tests/pages/EditorTabMove.test.tsx +++ b/packages/web-ui/tests/pages/EditorTabMove.test.tsx @@ -21,6 +21,8 @@ const mocks = vi.hoisted(() => ({ selectedDatabases: [] as string[], t: (key: string) => key, })); +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); vi.mock('lucide-react', async (importOriginal) => await importOriginal()); vi.mock('react-router-dom', () => ({ diff --git a/tests/pages/EditorTabTitle.test.tsx b/packages/web-ui/tests/pages/EditorTabTitle.test.tsx similarity index 98% rename from tests/pages/EditorTabTitle.test.tsx rename to packages/web-ui/tests/pages/EditorTabTitle.test.tsx index 77f44a230..f3382992a 100644 --- a/tests/pages/EditorTabTitle.test.tsx +++ b/packages/web-ui/tests/pages/EditorTabTitle.test.tsx @@ -24,6 +24,8 @@ const mocks = vi.hoisted(() => ({ selectedDatabases: [] as string[], t: (key: string) => key, })); +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +vi.mock('@/hooks/usePlatformCapabilities', () => import('../support/tauriBackedHooks')); vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); vi.mock('lucide-react', async (importOriginal) => await importOriginal()); vi.mock('react-router-dom', () => ({ diff --git a/tests/pages/EditorToolbarQuery.test.tsx b/packages/web-ui/tests/pages/EditorToolbarQuery.test.tsx similarity index 98% rename from tests/pages/EditorToolbarQuery.test.tsx rename to packages/web-ui/tests/pages/EditorToolbarQuery.test.tsx index cf83cc197..503bb5dc5 100644 --- a/tests/pages/EditorToolbarQuery.test.tsx +++ b/packages/web-ui/tests/pages/EditorToolbarQuery.test.tsx @@ -326,6 +326,21 @@ describe('runToolbarQuery database field', () => { }); }); +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => client, +})); +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, +})); +const client = { + call: (command: string, args: Record) => invoke(command, args), + subscribe: vi.fn().mockResolvedValue(() => {}), +}; +const platform = { + negotiation: {environment: 'browser'}, + subscribeRouteEvent: vi.fn().mockResolvedValue(() => {}), + publishRouteEvent: vi.fn().mockResolvedValue(undefined), +}; describe('column statistics loader (#1001)', () => { const ALL = {distinct: true, minMax: true, topValues: true}; diff --git a/packages/web-ui/tests/pages/McpPage.test.tsx b/packages/web-ui/tests/pages/McpPage.test.tsx new file mode 100644 index 000000000..14beaf067 --- /dev/null +++ b/packages/web-ui/tests/pages/McpPage.test.tsx @@ -0,0 +1,73 @@ +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {McpPage} from '@/pages/McpPage'; + +const mocks = vi.hoisted(() => { + const call = vi.fn(); + return { + call, + client: {call}, + showAlert: vi.fn(), + }; +}); + +vi.mock('@/hooks/useTabularisClient', () => ({ + useTabularisClient: () => mocks.client, +})); + +vi.mock('@/hooks/useAlert', () => ({ + useAlert: () => ({showAlert: mocks.showAlert}), +})); + +vi.mock('@/hooks/useEditorTheme', () => ({ + useEditorTheme: () => ({id: 'tabularis-dark'}), +})); + +vi.mock('@/components/settings/AiActivityPanel', () => ({ + AiActivityPanel: () => null, +})); + +vi.mock('@/components/modals/mcp/McpSafetySection', () => ({ + McpSafetySection: () => null, +})); + +describe('McpPage transport parity', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.call.mockImplementation((command: string) => { + if (command === 'get_mcp_status') { + return Promise.resolve([ + { + client_id: 'claude', + client_name: 'Claude Desktop', + installed: false, + config_path: '/home/test/.config/Claude/claude_desktop_config.json', + executable_path: '/usr/bin/tabularis', + client_type: 'file', + manual_command: null, + }, + ]); + } + if (command === 'install_mcp_config') { + return Promise.resolve('Claude Desktop'); + } + return Promise.reject(new Error(`Unexpected command: ${command}`)); + }); + }); + + it('loads host status and installs configuration through the shared client', async () => { + render(); + + await screen.findByText('Claude Desktop'); + expect(mocks.call).toHaveBeenCalledWith('get_mcp_status', undefined); + + fireEvent.click(screen.getByRole('button', {name: 'mcp.install'})); + + await waitFor(() => { + expect(mocks.call).toHaveBeenCalledWith('install_mcp_config', { + clientId: 'claude', + }); + expect(mocks.showAlert).toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/web-ui/tests/pages/PluginInstallRoutePage.test.tsx b/packages/web-ui/tests/pages/PluginInstallRoutePage.test.tsx new file mode 100644 index 000000000..f2de2faaf --- /dev/null +++ b/packages/web-ui/tests/pages/PluginInstallRoutePage.test.tsx @@ -0,0 +1,108 @@ +import type {ReactNode} from 'react'; +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {invoke} from '@tauri-apps/api/core'; +import {MemoryRouter, Route, Routes, useLocation} from 'react-router-dom'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TabularisClient} from '@/api/client'; +import {TauriTransport} from '@/api/transports/tauriTransport'; +import {TabularisClientProvider} from '@/contexts/TabularisClientProvider'; +import {PluginInstallRoutePage} from '@/pages/PluginInstallRoutePage'; + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: () => ({ + settings: {tabulariumRegistryUrl: 'https://configured.example'}, + }), +})); + +vi.mock('@/components/modals/PluginInstallConfirmModal', () => ({ + PluginInstallConfirmModal: ({ + request, + onConfirm, + onCancel, + configuredRegistry, + }: { + request: { + slug: string; + version?: string | null; + registry?: string | null; + } | null; + onConfirm: () => void; + onCancel: () => void; + configuredRegistry?: string | null; + }) => + request ? ( +
+ {request.slug} + {request.registry} + {configuredRegistry} + + +
+ ) : null, +})); + +const client = new TabularisClient(new TauriTransport()); + +function LocationProbe() { + const location = useLocation(); + return {location.pathname}; +} + +function Providers({children}: {children: ReactNode}) { + return {children}; +} + +function renderRoute(initialEntry: string) { + return render( + + + + } /> + } /> + + + , + ); +} + +describe('PluginInstallRoutePage', () => { + beforeEach(() => vi.mocked(invoke).mockReset()); + + it('requires confirmation, installs from the selected registry, and clears the route', async () => { + vi.mocked(invoke).mockResolvedValue(undefined); + renderRoute( + '/install/postgres-driver?version=1.2.3®istry=https%3A%2F%2Fregistry.example%2Fapi', + ); + + expect(screen.getByText('postgres-driver')).toBeInTheDocument(); + expect(screen.getByText('https://registry.example/api')).toBeInTheDocument(); + expect(screen.getByText('https://configured.example')).toBeInTheDocument(); + expect(invoke).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', {name: 'Confirm install'})); + + await waitFor(() => + expect(invoke).toHaveBeenCalledWith('install_plugin', { + pluginId: 'postgres-driver', + version: '1.2.3', + registryUrl: 'https://registry.example/api', + }), + ); + await waitFor(() => expect(screen.getByText('/connections')).toBeInTheDocument()); + }); + + it('cancels without installing and rejects invalid install routes', () => { + renderRoute('/install/postgres-driver'); + fireEvent.click(screen.getByRole('button', {name: 'Cancel install'})); + expect(screen.getByText('/connections')).toBeInTheDocument(); + expect(invoke).not.toHaveBeenCalled(); + + renderRoute('/install/INVALID'); + expect(screen.getAllByText('/connections')).toHaveLength(2); + expect(invoke).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/web-ui/tests/pages/ResultsWindowPage.test.tsx b/packages/web-ui/tests/pages/ResultsWindowPage.test.tsx new file mode 100644 index 000000000..44b261259 --- /dev/null +++ b/packages/web-ui/tests/pages/ResultsWindowPage.test.tsx @@ -0,0 +1,114 @@ +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {ResultsWindowPage} from '@/pages/ResultsWindowPage'; +import { + RESULTS_ACTION_EVENT, + RESULTS_COPY_EVENT, + RESULTS_SYNC_EVENT, + singleResultToEntry, + type ResultsSyncPayload, +} from '@/utils/resultsWindowSync'; + +const mocks = vi.hoisted(() => ({ + listeners: new Map void>(), + publish: vi.fn().mockResolvedValue(undefined), + copy: vi.fn().mockResolvedValue(undefined), + alert: vi.fn(), + toast: vi.fn(), + t: (key: string) => key, +})); +const platform = { + publishRouteEvent: mocks.publish, + subscribeRouteEvent: async (event: string, handler: (payload: unknown) => void) => { + mocks.listeners.set(event, handler); + return () => { + mocks.listeners.delete(event); + }; + }, +}; +vi.mock('@/hooks/usePlatformCapabilities', () => ({usePlatformCapabilities: () => platform})); +vi.mock('@/hooks/useAlert', () => ({useAlert: () => ({showAlert: mocks.alert})})); +vi.mock('@/hooks/useToast', () => ({useToast: () => ({showToast: mocks.toast})})); +vi.mock('@/utils/clipboard', () => ({copyTextToClipboard: mocks.copy})); +vi.mock('react-i18next', () => ({useTranslation: () => ({t: mocks.t})})); +vi.mock('react-router-dom', () => ({ + useSearchParams: () => [new URLSearchParams('session=session-1')], +})); +vi.mock('@/components/ui/ResultEntryContent', () => ({ + ResultEntryContent: ({onCopyAllRows}: {onCopyAllRows: () => void}) => ( + + ), +})); +vi.mock('@/components/ui/MultiResultPanel', () => ({ + MultiResultPanel: ({onCopyAllRows}: {onCopyAllRows: (entryId: string) => void}) => ( + + ), +})); +const payload: ResultsSyncPayload = { + tabId: 'tab-1', + tabTitle: 'Query', + query: 'SELECT 1', + result: {columns: ['id'], rows: [[1]], affected_rows: 0}, + error: '', + executionTime: 1, + isLoading: false, + activeTable: null, + connectionId: 'conn-1', + copyFormat: 'csv', + csvDelimiter: ',', + csvIncludeHeaders: true, +}; + +describe('detached result copy-all', () => { + beforeEach(() => { + mocks.listeners.clear(); + vi.clearAllMocks(); + }); + it.each([false, true])( + 'forwards copy actions and writes results in the clicked window (multiple=%s)', + async (multiple) => { + const {unmount} = render(); + await waitFor(() => expect(mocks.listeners.has(RESULTS_SYNC_EVENT)).toBe(true)); + await act(async () => + mocks.listeners.get(RESULTS_SYNC_EVENT)?.({ + sessionId: 'session-1', + payload: { + ...payload, + ...(multiple + ? {results: [{...singleResultToEntry(payload), id: 'entry-1'}]} + : {}), + }, + }), + ); + fireEvent.click( + screen.getByRole('button', {name: multiple ? 'Copy entry' : 'Copy rows'}), + ); + expect(mocks.publish).toHaveBeenCalledWith(RESULTS_ACTION_EVENT, { + sessionId: 'session-1', + action: multiple + ? {type: 'copy-entry-all-rows', entryId: 'entry-1'} + : {type: 'copy-all-rows'}, + }); + await act(async () => + mocks.listeners.get(RESULTS_COPY_EVENT)?.({ + tabId: 'other-tab', + text: 'wrong', + count: 1, + }), + ); + expect(mocks.copy).not.toHaveBeenCalled(); + await act(async () => + mocks.listeners.get(RESULTS_COPY_EVENT)?.({ + tabId: 'tab-1', + text: 'id\n1\n2', + count: 2, + }), + ); + expect(mocks.copy).toHaveBeenCalledWith('id\n1\n2'); + expect(mocks.toast).toHaveBeenCalledWith('dataGrid.copiedRows', {kind: 'success'}); + unmount(); + await act(async () => {}); + expect(mocks.listeners.has(RESULTS_COPY_EVENT)).toBe(false); + }, + ); +}); diff --git a/tests/pages/SchemaDiagramPage.test.tsx b/packages/web-ui/tests/pages/SchemaDiagramPage.test.tsx similarity index 97% rename from tests/pages/SchemaDiagramPage.test.tsx rename to packages/web-ui/tests/pages/SchemaDiagramPage.test.tsx index 0ec2fbcf0..7b76624b5 100644 --- a/tests/pages/SchemaDiagramPage.test.tsx +++ b/packages/web-ui/tests/pages/SchemaDiagramPage.test.tsx @@ -14,6 +14,11 @@ vi.mock('react-router-dom', () => ({ }, })); +vi.mock('@/hooks/useTabularisClient', () => { + const client = {call: mocks.invokeMock}; + return {useTabularisClient: () => client}; +}); + vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invokeMock, })); diff --git a/packages/web-ui/tests/pages/SecondaryWindowPages.test.tsx b/packages/web-ui/tests/pages/SecondaryWindowPages.test.tsx new file mode 100644 index 000000000..9a3b0d22f --- /dev/null +++ b/packages/web-ui/tests/pages/SecondaryWindowPages.test.tsx @@ -0,0 +1,155 @@ +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {MemoryRouter} from 'react-router-dom'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import type {RouteEventHandler} from '@/platform/capabilities'; +import { + JSON_VIEWER_SESSION_DATA_EVENT, + JSON_VIEWER_SESSION_REQUEST_EVENT, + JSON_VIEWER_SESSION_SAVED_EVENT, + type JsonViewerSessionData, +} from '@/platform/secondaryWindowSessions'; +import { + RESULTS_READY_EVENT, + RESULTS_SYNC_EVENT, + type ResultsSyncPayload, +} from '@/utils/resultsWindowSync'; + +const listeners = new Map>>(); +const publishRouteEvent = vi.fn(async (event: string, payload: unknown): Promise => { + for (const listener of listeners.get(event) ?? []) listener(payload); +}); +const closeRoute = vi.fn(async () => {}); +const platform = { + publishRouteEvent, + closeRoute, + subscribeRouteEvent: async (event: string, handler: RouteEventHandler) => { + const eventListeners = listeners.get(event) ?? new Set(); + const listener = handler as RouteEventHandler; + eventListeners.add(listener); + listeners.set(event, eventListeners); + return () => eventListeners.delete(listener); + }, +}; + +vi.mock('@/hooks/usePlatformCapabilities', () => ({ + usePlatformCapabilities: () => platform, +})); + +vi.mock('@/components/ui/MultiResultPanel', () => ({ + MultiResultPanel: () =>
multi result
, +})); + +vi.mock('@/components/ui/ResultEntryContent', () => ({ + ResultEntryContent: () =>
single result
, +})); + +vi.mock('@/components/ui/JsonInput', () => ({ + JsonInput: () =>
json editor
, +})); + +// eslint-disable-next-line import/first +import {JsonViewerPage} from '@/pages/JsonViewerPage'; +// eslint-disable-next-line import/first +import {ResultsWindowPage} from '@/pages/ResultsWindowPage'; + +const resultPayload: ResultsSyncPayload = { + tabId: 'result-session', + tabTitle: 'Query', + query: 'SELECT 1', + result: {columns: ['value'], rows: [[1]], affected_rows: 0}, + error: '', + executionTime: 1, + isLoading: false, + activeTable: null, + connectionId: 'connection-1', + copyFormat: 'csv', + csvDelimiter: ',', + csvIncludeHeaders: true, +}; + +beforeEach(() => { + listeners.clear(); + publishRouteEvent.mockClear(); + closeRoute.mockClear(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('ResultsWindowPage', () => { + it('requests and renders a shared result session in a new route', async () => { + render( + + + , + ); + + await waitFor(() => + expect(publishRouteEvent).toHaveBeenCalledWith(RESULTS_READY_EVENT, { + sessionId: 'result-session', + }), + ); + await act(async () => { + await platform.publishRouteEvent(RESULTS_SYNC_EVENT, { + sessionId: 'result-session', + payload: resultPayload, + }); + }); + + expect(screen.getByText('single result')).toBeInTheDocument(); + }); + + it('clearly expires a refreshed route when its owner is gone', async () => { + vi.useFakeTimers(); + render( + + + , + ); + + await act(async () => { + await vi.runAllTimersAsync(); + }); + + expect(screen.getByText(/secondaryWindows.sessionExpired/i)).toBeInTheDocument(); + }); +}); + +describe('JsonViewerPage', () => { + it('loads and completes a shared JSON session', async () => { + render( + + + , + ); + + await waitFor(() => + expect(publishRouteEvent).toHaveBeenCalledWith(JSON_VIEWER_SESSION_REQUEST_EVENT, { + sessionId: 'json-session', + }), + ); + const data: JsonViewerSessionData = { + sessionId: 'json-session', + session: { + value: {saved: true}, + originalValue: {saved: false}, + columnName: 'metadata', + readOnly: false, + }, + }; + await act(async () => { + await platform.publishRouteEvent(JSON_VIEWER_SESSION_DATA_EVENT, data); + }); + + expect(screen.getByText('json editor')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', {name: 'jsonViewer.save'})); + await waitFor(() => + expect(publishRouteEvent).toHaveBeenCalledWith(JSON_VIEWER_SESSION_SAVED_EVENT, { + sessionId: 'json-session', + value: {saved: true}, + }), + ); + expect(closeRoute).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/pages/Settings.test.tsx b/packages/web-ui/tests/pages/Settings.test.tsx similarity index 100% rename from tests/pages/Settings.test.tsx rename to packages/web-ui/tests/pages/Settings.test.tsx diff --git a/tests/pages/VisualExplainPage.test.tsx b/packages/web-ui/tests/pages/VisualExplainPage.test.tsx similarity index 89% rename from tests/pages/VisualExplainPage.test.tsx rename to packages/web-ui/tests/pages/VisualExplainPage.test.tsx index f75704dd3..a611dde24 100644 --- a/tests/pages/VisualExplainPage.test.tsx +++ b/packages/web-ui/tests/pages/VisualExplainPage.test.tsx @@ -2,12 +2,22 @@ import {StrictMode} from 'react'; import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; import {invoke} from '@tauri-apps/api/core'; import {open as openDialog} from '@tauri-apps/plugin-dialog'; +import {readFile} from '@tauri-apps/plugin-fs'; import {parseExplain, type ExplainQueryOutput} from '@tabularis/explain'; import {beforeEach, describe, expect, it, vi} from 'vitest'; import {VisualExplainPage, type VisualExplainPageProps} from '@/pages/VisualExplainPage'; import type {VisualExplainViewProps} from '@/components/explain/VisualExplainView'; -const mocks = vi.hoisted(() => ({search: ''})); +vi.mock('@/hooks/useTabularisClient', () => import('../support/tauriBackedHooks')); +const mocks = vi.hoisted(() => ({search: '', browser: false})); +vi.mock('@/hooks/usePlatformCapabilities', async () => { + const desktop = await import('../support/tauriBackedHooks'); + const browser = {negotiation: {environment: 'browser'}}; + return { + usePlatformCapabilities: () => + mocks.browser ? browser : desktop.usePlatformCapabilities(), + }; +}); vi.mock('react-router-dom', () => ({useLocation: () => ({search: mocks.search})})); vi.mock('react-i18next', () => { @@ -67,9 +77,18 @@ function pickFile() { describe('VisualExplainPage', () => { beforeEach(() => { mocks.search = ''; + mocks.browser = false; vi.mocked(invoke).mockReset(); vi.mocked(openDialog).mockReset(); vi.mocked(invoke).mockResolvedValue(null); + // Picked files are read through the platform adapter (plugin-fs) rather + // than `load_explain_from_file`. Route those reads through the same invoke + // stub so each scenario keeps describing one backend read per picked file. + vi.mocked(readFile).mockReset(); + vi.mocked(readFile).mockImplementation(async (path) => { + const file = await invoke<{content: string}>('load_explain_from_file', {path}); + return new TextEncoder().encode(file.content); + }); }); it.each([false, true])( @@ -121,8 +140,8 @@ describe('VisualExplainPage', () => { connectionId: 'connection-1', query: 'SELECT * FROM users', analyze: false, - schema: null, - database: null, + schema: undefined, + database: undefined, }); }); @@ -169,11 +188,13 @@ describe('VisualExplainPage', () => { await waitFor(() => expect(screen.getByTestId('plan')).toHaveTextContent('picked')); expect(openDialog).toHaveBeenCalledExactlyOnceWith({ multiple: false, + directory: false, filters: [ {name: 'Explain', extensions: ['json', 'txt']}, {name: 'All files', extensions: ['*']}, ], }); + expect(readFile).toHaveBeenLastCalledWith('/tmp/picked.json'); expect(invoke).toHaveBeenLastCalledWith('load_explain_from_file', { path: '/tmp/picked.json', }); @@ -181,7 +202,9 @@ describe('VisualExplainPage', () => { fireEvent.click(screen.getByRole('button', {name: 'visualExplainPage.reload'})); await waitFor(() => expect(screen.getByTestId('plan')).toHaveTextContent('reloaded')); expect(invoke).toHaveBeenCalledTimes(3); - expect(screen.getByTitle('/tmp/picked.json')).toHaveTextContent('picked.json'); + expect(readFile).toHaveBeenCalledTimes(2); + // The platform exposes a picked file by name; its path stays an opaque reference. + expect(screen.getByTitle('picked.json')).toHaveTextContent('picked.json'); }); it.each([{selection: null}, {selection: ' '}, {selection: ['/tmp/ignored.json']}])( @@ -286,7 +309,7 @@ describe('VisualExplainPage', () => { else pending.reject(new Error('obsolete CLI failure')); }); expect(invoke).toHaveBeenCalledTimes(2); - expect(screen.getByTitle('/tmp/chosen.json')).toBeInTheDocument(); + expect(screen.getByTitle('chosen.json')).toBeInTheDocument(); expect(screen.getByTestId('plan')).toHaveTextContent('chosen'); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }, @@ -392,3 +415,18 @@ describe('VisualExplainPage', () => { }, ); }); + +describe('VisualExplainPage browser handoffs', () => { + it.each(['', '?file=%2Ftmp%2Fplan.json'])( + 'does not invoke desktop file commands for %s', + async (search) => { + mocks.browser = true; + mocks.search = search; + vi.mocked(invoke).mockClear(); + renderPage(); + await act(async () => {}); + expect(invoke).not.toHaveBeenCalled(); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }, + ); +}); diff --git a/packages/web-ui/tests/platform/browserCapabilities.test.ts b/packages/web-ui/tests/platform/browserCapabilities.test.ts new file mode 100644 index 000000000..b45fca74c --- /dev/null +++ b/packages/web-ui/tests/platform/browserCapabilities.test.ts @@ -0,0 +1,317 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import {BrowserPlatformCapabilities} from '@/platform/browserCapabilities'; +import {BROWSER_CAPABILITY_FALLBACK_EVENT} from '@/platform/browserFallbacks'; +import { + subscribeBrowserMessageRequests, + subscribeBrowserServerPathRequests, +} from '@/platform/browserDialogs'; + +function clientFixture(overrides: Partial): TabularisClient { + return overrides as TabularisClient; +} + +const request = { + connectionId: 'connection-1', + table: 'files', + colName: 'payload', + pkMap: {id: 1}, +}; + +describe('BrowserPlatformCapabilities secondary routes', () => { + it('opens a standalone connection route in a browser tab', async () => { + const open = vi.spyOn(window, 'open').mockReturnValue(null); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + await capabilities.openConnectionRoute({ + connectionId: 'connection/id', + title: 'Primary', + }); + + expect(open).toHaveBeenCalledWith( + '/connections?connect=connection%2Fid&standalone=connection', + '_blank', + 'noopener,noreferrer', + ); + open.mockRestore(); + }); + + it('shares typed route events between browser contexts', async () => { + const publisher = new BrowserPlatformCapabilities(clientFixture({})); + const subscriber = new BrowserPlatformCapabilities(clientFixture({})); + const event = `secondary-route-test:${crypto.randomUUID()}`; + let resolveReceived: (payload: {sessionId: string}) => void = () => {}; + const received = new Promise<{sessionId: string}>((resolve) => { + resolveReceived = resolve; + }); + const unsubscribe = await subscriber.subscribeRouteEvent(event, resolveReceived); + + await publisher.publishRouteEvent(event, {sessionId: 'session-1'}); + + await expect(received).resolves.toEqual({sessionId: 'session-1'}); + unsubscribe(); + }); +}); + +describe('BrowserPlatformCapabilities browser adaptations', () => { + it('advertises browser dialogs while keeping server paths explicit', () => { + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + expect(capabilities.supports('confirm')).toBe(true); + expect(capabilities.supports('showMessage')).toBe(true); + expect(capabilities.negotiation.capabilities.chooseServerPath).toEqual({ + supported: false, + adaptation: 'unsupported', + reason: 'Server file browsing is disabled. Start Tabularis with --server-file-browser-root to enable it.', + }); + }); + + it('normalizes clipboard permission denial as a typed error', async () => { + const clipboard = { + readText: vi + .fn() + .mockRejectedValue(new DOMException('Permission denied', 'NotAllowedError')), + writeText: vi.fn(), + }; + vi.stubGlobal('navigator', {...navigator, clipboard}); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + await expect(capabilities.readClipboard()).rejects.toMatchObject({ + code: 'PLATFORM_CAPABILITY_PERMISSION_DENIED', + capability: 'readClipboard', + environment: 'browser', + }); + + vi.unstubAllGlobals(); + }); + + it('uses browser-native confirmation and the in-app message bridge', async () => { + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(true); + const messageHandler = vi.fn(({resolve}: {resolve: () => void}) => resolve()); + const unsubscribe = subscribeBrowserMessageRequests(messageHandler); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + await expect( + capabilities.confirm({message: 'Drop table?', title: 'Warning'}), + ).resolves.toBe(true); + await capabilities.showMessage({message: 'Export complete'}); + + expect(confirm).toHaveBeenCalledWith('Warning\n\nDrop table?'); + expect(messageHandler).toHaveBeenCalledOnce(); + expect(messageHandler.mock.calls[0][0].request).toEqual({ + message: 'Export complete', + }); + unsubscribe(); + }); + + it('opens the server picker bridge only when advertised by the server', async () => { + const capabilities = new BrowserPlatformCapabilities(clientFixture({}), undefined, true); + const handler = vi.fn(({resolve}: {resolve: (value: {reference: string}) => void}) => + resolve({reference: '/srv/databases/main.sqlite'}), + ); + const unsubscribe = subscribeBrowserServerPathRequests(handler); + + await expect(capabilities.chooseServerPath({kind: 'file'})).resolves.toEqual({ + reference: '/srv/databases/main.sqlite', + }); + await expect( + capabilities.chooseSaveTarget({suggestedName: 'database.db'}), + ).resolves.toEqual({reference: '/srv/databases/main.sqlite'}); + expect(capabilities.supports('chooseServerPath')).toBe(true); + expect(capabilities.supports('chooseSaveTarget')).toBe(true); + expect(handler).toHaveBeenCalledTimes(2); + expect(handler.mock.calls[1][0].options).toMatchObject({ + mode: 'save', + suggestedName: 'database.db', + }); + unsubscribe(); + }); + + it('falls back in-app when browser notification permission is denied', async () => { + class DeniedNotification { + static permission: NotificationPermission = 'default'; + static requestPermission = vi.fn().mockImplementation(async () => { + DeniedNotification.permission = 'denied'; + return 'denied' as NotificationPermission; + }); + } + vi.stubGlobal('Notification', DeniedNotification); + const listener = vi.fn(); + window.addEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + await expect(capabilities.notify({title: 'Ready', body: 'Export complete'})).resolves.toBe( + 'permission-denied', + ); + expect(listener).toHaveBeenCalledOnce(); + expect((listener.mock.calls[0][0] as CustomEvent).detail).toEqual({ + kind: 'notification', + title: 'Ready', + body: 'Export complete', + }); + + window.removeEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); + vi.unstubAllGlobals(); + }); + + it('publishes an accessible fallback when an external popup is blocked', async () => { + const open = vi.spyOn(window, 'open').mockReturnValue(null); + const listener = vi.fn(); + window.addEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + await capabilities.openExternalUrl('https://tabularis.dev'); + + expect(listener).toHaveBeenCalledOnce(); + expect((listener.mock.calls[0][0] as CustomEvent).detail).toEqual({ + kind: 'external-url', + url: 'https://tabularis.dev/', + }); + window.removeEventListener(BROWSER_CAPABILITY_FALLBACK_EVENT, listener); + open.mockRestore(); + }); +}); + +describe('BrowserPlatformCapabilities file transfers', () => { + it('adapts browser-selected files to single-use opaque references', async () => { + const file = { + name: 'analysis.tabularis-notebook', + arrayBuffer: vi + .fn() + .mockResolvedValue(new TextEncoder().encode('notebook contents').buffer), + } as unknown as File; + const filePicker = vi.fn().mockResolvedValue(file); + const capabilities = new BrowserPlatformCapabilities(clientFixture({}), filePicker); + + const selected = await capabilities.chooseInputFile({ + filters: [{name: 'Tabularis Notebook', extensions: ['tabularis-notebook']}], + }); + + expect(selected?.name).toBe('analysis.tabularis-notebook'); + expect(selected?.reference).toMatch(/^browser-file:/); + expect(selected?.reference).not.toContain('analysis.tabularis-notebook'); + expect(filePicker).toHaveBeenCalledWith('.tabularis-notebook'); + await expect( + capabilities + .readInputFile(selected?.reference ?? '') + .then((contents) => Array.from(contents)), + ).resolves.toEqual(Array.from(new TextEncoder().encode('notebook contents'))); + await expect(capabilities.readInputFile(selected?.reference ?? '')).rejects.toThrow( + 'Invalid or expired browser file reference', + ); + }); +}); + +describe('BrowserPlatformCapabilities BLOB transfers', () => { + it('resolves session-scoped upload previews without exposing a path', async () => { + const uploadedBlobUrl = vi.fn((token: string) => `/api/v1/uploads/blobs/${token}`); + const capabilities = new BrowserPlatformCapabilities(clientFixture({uploadedBlobUrl})); + + await expect( + capabilities.previewBlobReference( + 'BLOB_UPLOAD_REF:8:image/png:00000000-0000-4000-8000-000000000000', + ), + ).resolves.toBe('/api/v1/uploads/blobs/00000000-0000-4000-8000-000000000000'); + expect(uploadedBlobUrl).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000000'); + await expect( + capabilities.previewBlobReference('BLOB_UPLOAD_REF:4:text/plain:token'), + ).resolves.toBeNull(); + }); + + it('reads pending upload references through the authenticated transport', async () => { + const readUploadedBlob = vi + .fn() + .mockResolvedValue(new Blob([new Uint8Array([0, 1, 2, 3])], {type: 'image/png'})); + const capabilities = new BrowserPlatformCapabilities(clientFixture({readUploadedBlob})); + + await expect( + capabilities.fetchBlobReference( + 'BLOB_UPLOAD_REF:4:image/png:00000000-0000-4000-8000-000000000000', + ), + ).resolves.toEqual({ + contents: new Uint8Array([0, 1, 2, 3]), + mimeType: 'image/png', + }); + expect(readUploadedBlob).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000000'); + }); + + it('consumes tokenized database downloads', async () => { + const call = vi.fn().mockResolvedValue({ + kind: 'download', + token: 'download-token', + size: 4, + mimeType: 'application/octet-stream', + }); + const consumeBlobDownload = vi + .fn() + .mockResolvedValue(new Blob([new Uint8Array([0, 1, 2, 3])])); + const capabilities = new BrowserPlatformCapabilities( + clientFixture({call, consumeBlobDownload}), + ); + + await expect(capabilities.fetchDatabaseBlob(request)).resolves.toEqual({ + contents: new Uint8Array([0, 1, 2, 3]), + mimeType: 'application/octet-stream', + }); + expect(call).toHaveBeenCalledWith('fetch_blob', request); + expect(consumeBlobDownload).toHaveBeenCalledWith('download-token'); + }); + + it('accepts inline BLOB responses for transport contract compatibility', async () => { + const call = vi.fn().mockResolvedValue({ + kind: 'inline', + wireValue: 'BLOB:4:application/octet-stream:AAECAw==', + }); + const capabilities = new BrowserPlatformCapabilities(clientFixture({call})); + + await expect(capabilities.fetchDatabaseBlob(request)).resolves.toEqual({ + contents: new Uint8Array([0, 1, 2, 3]), + mimeType: 'application/octet-stream', + }); + }); +}); + +describe('BrowserPlatformCapabilities host-only integrations', () => { + it('keeps native window and host folder actions out of the browser', async () => { + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + + expect(capabilities.supports('openStorageLocation')).toBe(false); + await expect(capabilities.openStorageLocation()).rejects.toThrow( + 'The browser cannot open folders on the Tabularis server', + ); + await expect(capabilities.setNativeWindowTheme('dark')).resolves.toBeUndefined(); + expect(capabilities.currentWindowLabel()).toBe('main'); + }); + + it('reads and follows the browser color scheme', async () => { + let listener: ((event: MediaQueryListEvent) => void) | undefined; + const media = { + matches: true, + addEventListener: vi.fn((_: string, handler: (event: MediaQueryListEvent) => void) => { + listener = handler; + }), + removeEventListener: vi.fn(), + }; + const original = window.matchMedia; + Object.defineProperty(window, 'matchMedia', { + configurable: true, + writable: true, + value: vi.fn(() => media as unknown as MediaQueryList), + }); + const capabilities = new BrowserPlatformCapabilities(clientFixture({})); + const onChange = vi.fn(); + + await expect(capabilities.getSystemIsDark()).resolves.toBe(true); + const stop = await capabilities.listenForSystemThemeChanges(onChange); + expect(onChange).toHaveBeenLastCalledWith(true); + listener?.({matches: false} as MediaQueryListEvent); + expect(onChange).toHaveBeenLastCalledWith(false); + stop(); + expect(media.removeEventListener).toHaveBeenCalled(); + Object.defineProperty(window, 'matchMedia', { + configurable: true, + writable: true, + value: original, + }); + }); +}); diff --git a/packages/web-ui/tests/platform/capabilities.test.ts b/packages/web-ui/tests/platform/capabilities.test.ts new file mode 100644 index 000000000..31a7c0ef4 --- /dev/null +++ b/packages/web-ui/tests/platform/capabilities.test.ts @@ -0,0 +1,51 @@ +import {describe, expect, it} from 'vitest'; +import { + createPlatformCapabilityNegotiation, + requirePlatformCapability, + UnsupportedPlatformCapabilityError, +} from '@/platform/capabilities'; + +describe('platform capability negotiation', () => { + it('makes unadvertised capabilities explicitly unsupported', () => { + const negotiation = createPlatformCapabilityNegotiation('browser', { + writeClipboard: {supported: true, adaptation: 'adapted'}, + }); + + expect(negotiation.capabilities.writeClipboard).toEqual({ + supported: true, + adaptation: 'adapted', + }); + expect(negotiation.capabilities.chooseInputFile).toEqual({ + supported: false, + adaptation: 'unsupported', + reason: 'The active platform did not advertise this capability', + }); + }); + + it('throws a typed error when a capability is unsupported', () => { + const negotiation = createPlatformCapabilityNegotiation('browser', { + restartApplication: { + supported: false, + adaptation: 'unsupported', + reason: 'Only an administrator can restart the server', + }, + }); + + expect(() => requirePlatformCapability(negotiation, 'restartApplication')).toThrowError( + UnsupportedPlatformCapabilityError, + ); + + try { + requirePlatformCapability(negotiation, 'restartApplication'); + } catch (error) { + expect(error).toMatchObject({ + code: 'PLATFORM_CAPABILITY_UNSUPPORTED', + capability: 'restartApplication', + environment: 'browser', + }); + expect((error as Error).message).toContain( + 'Only an administrator can restart the server', + ); + } + }); +}); diff --git a/packages/web-ui/tests/platform/desktopPermissions.test.ts b/packages/web-ui/tests/platform/desktopPermissions.test.ts new file mode 100644 index 000000000..fac1f1ebf --- /dev/null +++ b/packages/web-ui/tests/platform/desktopPermissions.test.ts @@ -0,0 +1,45 @@ +import {readFileSync, readdirSync} from 'node:fs'; +import {resolve} from 'node:path'; +import {describe, expect, it} from 'vitest'; + +interface Capability { + windows: string[]; + permissions: Array; + remote?: unknown; +} + +const directory = resolve(import.meta.dirname, '../../../../src-tauri/capabilities'); +const capabilities = readdirSync(directory) + .filter((name) => name.endsWith('.json')) + .map((name) => JSON.parse(readFileSync(resolve(directory, name), 'utf8')) as Capability); + +function grants(permission: string) { + return capabilities.filter((capability) => + capability.permissions.some( + (entry) => (typeof entry === 'string' ? entry : entry.identifier) === permission, + ), + ); +} + +describe('desktop platform ACL', () => { + it('allows editor and result windows to create the secondary webview windows', () => { + const allowed = grants('core:webview:allow-create-webview-window'); + for (const window of ['main', 'connection-window-*', 'results-window-*']) { + expect(allowed.flatMap((capability) => capability.windows)).toContain(window); + } + expect(allowed.every((capability) => !capability.remote)).toBe(true); + expect(allowed.flatMap((capability) => capability.windows)).not.toContain('*'); + }); + + it('allows binary and UTF-8 exports from detached editors, results, and diagrams without adding filesystem scopes', () => { + const allowed = grants('fs:allow-write-file'); + for (const window of ['main', 'connection-window-*', 'results-window-*', 'er-diagram*']) { + expect(allowed.flatMap((capability) => capability.windows)).toContain(window); + } + for (const capability of allowed) { + expect(capability.permissions).toEqual(['fs:allow-write-file']); + expect(capability.remote).toBeUndefined(); + expect(capability.windows).not.toContain('*'); + } + }); +}); diff --git a/packages/web-ui/tests/platform/dialogs.test.ts b/packages/web-ui/tests/platform/dialogs.test.ts new file mode 100644 index 000000000..05ad04f2f --- /dev/null +++ b/packages/web-ui/tests/platform/dialogs.test.ts @@ -0,0 +1,68 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import { + choosePlatformSavePath, + choosePlatformServerPath, + confirmPlatformDialog, +} from '@/platform/dialogs'; + +function platformFixture(overrides: Partial): PlatformCapabilities { + return { + supports: vi.fn(() => true), + negotiation: { + environment: 'browser', + capabilities: { + chooseServerPath: { + supported: false, + adaptation: 'unsupported', + reason: 'Server path selection is unavailable', + }, + chooseSaveTarget: { + supported: false, + adaptation: 'unsupported', + reason: 'Browser downloads replace save paths', + }, + }, + }, + ...overrides, + } as unknown as PlatformCapabilities; +} + +describe('platform dialogs', () => { + it('provides an accessible message when server paths are unavailable', async () => { + const showMessage = vi.fn().mockResolvedValue(undefined); + const platform = platformFixture({ + supports: vi.fn(() => false), + showMessage, + }); + + await expect(choosePlatformServerPath(platform, {directory: true})).resolves.toBeNull(); + await expect(choosePlatformSavePath(platform)).resolves.toBeNull(); + + expect(showMessage).toHaveBeenNthCalledWith(1, { + message: 'Server path selection is unavailable', + kind: 'info', + }); + expect(showMessage).toHaveBeenNthCalledWith(2, { + message: 'Browser downloads replace save paths', + kind: 'info', + }); + }); + + it('normalizes native confirmation options', async () => { + const confirm = vi.fn().mockResolvedValue(true); + const platform = platformFixture({confirm}); + + await expect( + confirmPlatformDialog(platform, 'Drop table?', { + title: 'Warning', + kind: 'warning', + }), + ).resolves.toBe(true); + expect(confirm).toHaveBeenCalledWith({ + message: 'Drop table?', + title: 'Warning', + kind: 'warning', + }); + }); +}); diff --git a/packages/web-ui/tests/platform/environment.test.ts b/packages/web-ui/tests/platform/environment.test.ts new file mode 100644 index 000000000..0c542b3c0 --- /dev/null +++ b/packages/web-ui/tests/platform/environment.test.ts @@ -0,0 +1,22 @@ +import {isTauri} from '@tauri-apps/api/core'; +import {describe, expect, it, vi} from 'vitest'; +import {detectPlatformEnvironment} from '@/platform/environment'; + +describe('detectPlatformEnvironment', () => { + it('uses the centralized Tauri runtime probe', () => { + const tauriProbe = vi.fn().mockReturnValue(true); + const browserProbe = vi.fn().mockReturnValue(false); + + expect(detectPlatformEnvironment(tauriProbe)).toBe('tauri'); + expect(detectPlatformEnvironment(browserProbe)).toBe('browser'); + expect(tauriProbe).toHaveBeenCalledOnce(); + expect(browserProbe).toHaveBeenCalledOnce(); + }); + + it('uses the Tauri API as its default runtime probe', () => { + vi.mocked(isTauri).mockReturnValueOnce(false); + + expect(detectPlatformEnvironment()).toBe('browser'); + expect(isTauri).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/web-ui/tests/platform/secondaryWindowSessions.test.ts b/packages/web-ui/tests/platform/secondaryWindowSessions.test.ts new file mode 100644 index 000000000..d76c98651 --- /dev/null +++ b/packages/web-ui/tests/platform/secondaryWindowSessions.test.ts @@ -0,0 +1,228 @@ +import {describe, expect, it, vi} from 'vitest'; +import type { + OpenConnectionRouteRequest, + OpenRouteRequest, + PlatformCapabilities, + RouteEventHandler, + UnsubscribeRouteEvent, +} from '@/platform/capabilities'; +import { + JSON_VIEWER_SESSION_CLOSED_EVENT, + JSON_VIEWER_SESSION_DATA_EVENT, + JSON_VIEWER_SESSION_EXPIRED_EVENT, + JSON_VIEWER_SESSION_REQUEST_EVENT, + JSON_VIEWER_SESSION_SAVED_EVENT, + JsonViewerSessionHost, + type JsonViewerSessionData, + type JsonViewerSessionExpired, + type JsonViewerSessionRequest, + type JsonViewerSessionSaved, +} from '@/platform/secondaryWindowSessions'; +import { + buildConnectionRoute, + buildResultsWindowRoute, + buildSchemaDiagramRoute, + buildVisualExplainRoute, +} from '@/routing'; + +class RouteEventPlatformFixture { + readonly openRoute = vi.fn<(request: OpenRouteRequest) => Promise>(async () => {}); + readonly listeners = new Map>>(); + + async publishRouteEvent(event: string, payload: T): Promise { + for (const listener of this.listeners.get(event) ?? []) listener(payload); + } + + async subscribeRouteEvent( + event: string, + handler: RouteEventHandler, + ): Promise { + const listeners = this.listeners.get(event) ?? new Set(); + const listener = handler as RouteEventHandler; + listeners.add(listener); + this.listeners.set(event, listeners); + return () => listeners.delete(listener); + } + + asPlatform(): PlatformCapabilities { + return { + openRoute: this.openRoute, + publishRouteEvent: this.publishRouteEvent.bind(this), + subscribeRouteEvent: this.subscribeRouteEvent.bind(this), + openConnectionRoute: async (_request: OpenConnectionRouteRequest) => {}, + } as PlatformCapabilities; + } +} + +describe('secondary window routes', () => { + it('builds refresh-safe routes with opaque session identifiers', () => { + expect(buildResultsWindowRoute('result/session')).toBe( + '/results-window?session=result%2Fsession', + ); + expect(buildConnectionRoute('connection/id')).toBe( + '/connections?connect=connection%2Fid&standalone=connection', + ); + }); + + it('encodes schema diagrams and visual explain deep links', () => { + expect( + buildSchemaDiagramRoute({ + connectionId: 'connection 1', + connectionName: 'Local DB', + databaseName: 'main', + database: 'reporting db', + schema: 'public data', + focusTable: 'users', + }), + ).toBe( + '/schema-diagram?connectionId=connection+1&connectionName=Local+DB&databaseName=main&database=reporting+db&schema=public+data&focusTable=users', + ); + expect(buildVisualExplainRoute('connection 1', 'select * from users')).toMatch( + /^\/visual-explain\?connection=connection%201&query=/, + ); + }); +}); + +describe('JsonViewerSessionHost', () => { + it('lets only the owning host answer requests on the shared event bus', async () => { + const fixture = new RouteEventPlatformFixture(); + const platform = fixture.asPlatform(); + const otherHost = new JsonViewerSessionHost(platform); + const owner = new JsonViewerSessionHost(platform, {createSessionId: () => 'owned'}); + const data: JsonViewerSessionData[] = []; + const expired: JsonViewerSessionExpired[] = []; + await platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_DATA_EVENT, + (value) => data.push(value), + ); + await platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_EXPIRED_EVENT, + (value) => expired.push(value), + ); + await owner.open({ + value: {id: 1}, + originalValue: {id: 1}, + columnName: 'json', + readOnly: false, + }); + await platform.publishRouteEvent(JSON_VIEWER_SESSION_REQUEST_EVENT, {sessionId: 'owned'}); + expect(data).toHaveLength(1); + expect(data[0].session.value).toEqual({id: 1}); + expect(expired).toEqual([]); + await owner.dispose(); + await platform.publishRouteEvent(JSON_VIEWER_SESSION_REQUEST_EVENT, {sessionId: 'owned'}); + expect(data).toHaveLength(1); + expect(expired).toEqual([]); + await otherHost.dispose(); + }); + + it('shares session data and returns saved values across route contexts', async () => { + const fixture = new RouteEventPlatformFixture(); + const platform = fixture.asPlatform(); + const onSaved = vi.fn(); + const onClosed = vi.fn(); + const host = new JsonViewerSessionHost(platform, { + createSessionId: () => 'json-session-1', + }); + const received: JsonViewerSessionData[] = []; + await platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_DATA_EVENT, + (payload) => received.push(payload), + ); + + await expect( + host.open( + { + value: {edited: false}, + originalValue: {edited: false}, + columnName: 'metadata', + rowLabel: 'id=1', + readOnly: false, + cellKey: 'pk:1:metadata', + }, + onSaved, + onClosed, + ), + ).resolves.toBe('json-session-1'); + expect(fixture.openRoute).toHaveBeenCalledWith({ + route: '/json-viewer?session=json-session-1', + target: 'new', + label: 'json-viewer-json-session-1', + title: 'metadata · id=1 — JSON Viewer', + window: {width: 900, height: 700, minWidth: 600, minHeight: 400}, + }); + + await platform.publishRouteEvent( + JSON_VIEWER_SESSION_REQUEST_EVENT, + {sessionId: 'json-session-1'}, + ); + expect(received).toEqual([ + { + sessionId: 'json-session-1', + session: { + value: {edited: false}, + originalValue: {edited: false}, + columnName: 'metadata', + rowLabel: 'id=1', + readOnly: false, + cellKey: 'pk:1:metadata', + }, + }, + ]); + + await platform.publishRouteEvent(JSON_VIEWER_SESSION_SAVED_EVENT, { + sessionId: 'json-session-1', + value: {edited: true}, + }); + expect(onSaved).toHaveBeenCalledWith({edited: true}); + expect(onClosed).toHaveBeenCalledOnce(); + + const expired: JsonViewerSessionExpired[] = []; + await platform.subscribeRouteEvent( + JSON_VIEWER_SESSION_EXPIRED_EVENT, + (payload) => expired.push(payload), + ); + await platform.publishRouteEvent( + JSON_VIEWER_SESSION_REQUEST_EVENT, + {sessionId: 'json-session-1'}, + ); + expect(expired).toEqual([]); + expect(received).toHaveLength(1); + await host.dispose(); + }); + + it('removes cancelled sessions and reuses a live cell session', async () => { + const fixture = new RouteEventPlatformFixture(); + const platform = fixture.asPlatform(); + const ids = ['json-session-1', 'json-session-2']; + const host = new JsonViewerSessionHost(platform, { + createSessionId: () => ids.shift() ?? 'unexpected', + }); + const base = { + value: {version: 1}, + originalValue: {version: 1}, + columnName: 'metadata', + readOnly: false, + cellKey: 'pk:1:metadata', + }; + + const firstClosed = vi.fn(); + const reopenedClosed = vi.fn(); + await expect(host.open(base, undefined, firstClosed)).resolves.toBe('json-session-1'); + await expect( + host.open({...base, value: {version: 2}}, undefined, reopenedClosed), + ).resolves.toBe('json-session-1'); + expect(fixture.openRoute).toHaveBeenCalledTimes(2); + expect(firstClosed).toHaveBeenCalledOnce(); + expect(reopenedClosed).not.toHaveBeenCalled(); + + await platform.publishRouteEvent(JSON_VIEWER_SESSION_CLOSED_EVENT, { + sessionId: 'json-session-1', + }); + expect(reopenedClosed).toHaveBeenCalledOnce(); + const lastClosed = vi.fn(); + await expect(host.open(base, undefined, lastClosed)).resolves.toBe('json-session-2'); + await host.dispose(); + expect(lastClosed).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/web-ui/tests/platform/tauriCapabilities.test.ts b/packages/web-ui/tests/platform/tauriCapabilities.test.ts new file mode 100644 index 000000000..073f080e6 --- /dev/null +++ b/packages/web-ui/tests/platform/tauriCapabilities.test.ts @@ -0,0 +1,261 @@ +import {invoke} from '@tauri-apps/api/core'; +import {describe, expect, it, vi} from 'vitest'; +import {createPlatformCapabilityNegotiation} from '@/platform/capabilities'; +import { + TauriPlatformCapabilities, + type TauriPlatformOperations, +} from '@/platform/tauriCapabilities'; + +const createOperations = (): TauriPlatformOperations => ({ + chooseInputPath: vi.fn(), + chooseSavePath: vi.fn(), + chooseServerPath: vi.fn(), + confirmDialog: vi.fn(), + showMessageDialog: vi.fn(), + readClipboardText: vi.fn(), + writeClipboardText: vi.fn(), + writeFileContents: vi.fn(), + readFileContents: vi.fn(), + openUrl: vi.fn(), + isNotificationPermissionGranted: vi.fn(), + requestNotificationPermission: vi.fn(), + sendNotification: vi.fn(), + openRoute: vi.fn(), + openConnectionRoute: vi.fn(), + publishRouteEvent: vi.fn(), + subscribeRouteEvent: vi.fn().mockResolvedValue(vi.fn()), + closeRoute: vi.fn(), + requestAttention: vi.fn(), + restartApplication: vi.fn(), + openStorageLocation: vi.fn(), + setNativeWindowTheme: vi.fn(), + getSystemIsDark: vi.fn().mockResolvedValue(false), + listenForSystemThemeChanges: vi.fn().mockResolvedValue(vi.fn()), + currentWindowLabel: vi.fn(() => 'main'), + getAppDataDir: vi.fn().mockResolvedValue('/data'), +}); + +describe('TauriPlatformCapabilities', () => { + it('advertises every semantic capability as native', () => { + const capabilities = new TauriPlatformCapabilities(createOperations()); + + expect(capabilities.negotiation.environment).toBe('tauri'); + expect( + Object.values(capabilities.negotiation.capabilities).every( + (availability) => availability.supported && availability.adaptation === 'native', + ), + ).toBe(true); + expect(capabilities.supports('chooseInputFile')).toBe(true); + }); + + it('normalizes Tauri input and save dialog paths as opaque references', async () => { + const operations = createOperations(); + vi.mocked(operations.chooseInputPath).mockResolvedValue('/tmp/example.sql'); + vi.mocked(operations.chooseSavePath).mockResolvedValue('/tmp/export.csv'); + vi.mocked(operations.readFileContents).mockResolvedValue(new Uint8Array([1, 2, 3])); + const capabilities = new TauriPlatformCapabilities(operations); + + await expect( + capabilities.chooseInputFile({ + title: 'Import', + filters: [{name: 'SQL', extensions: ['sql']}], + }), + ).resolves.toEqual({name: 'example.sql', reference: '/tmp/example.sql'}); + await expect(capabilities.chooseSaveTarget({suggestedName: 'export.csv'})).resolves.toEqual( + {reference: '/tmp/export.csv'}, + ); + await expect(capabilities.readInputFile('/tmp/example.sql')).resolves.toEqual( + new Uint8Array([1, 2, 3]), + ); + }); + + it('adapts desktop BLOB paths and inline database values', async () => { + const operations = createOperations(); + vi.mocked(operations.chooseInputPath).mockResolvedValue('/tmp/image.png'); + vi.mocked(invoke) + .mockResolvedValueOnce('BLOB_FILE_REF:4:image/png:/tmp/image.png') + .mockResolvedValueOnce({ + kind: 'inline', + wireValue: 'BLOB:4:application/octet-stream:AAECAw==', + }); + const capabilities = new TauriPlatformCapabilities(operations); + + await expect(capabilities.chooseBlob()).resolves.toBe( + 'BLOB_FILE_REF:4:image/png:/tmp/image.png', + ); + await expect( + capabilities.fetchDatabaseBlob({ + connectionId: 'connection-1', + table: 'files', + colName: 'payload', + pkMap: {id: 1}, + }), + ).resolves.toEqual({ + contents: new Uint8Array([0, 1, 2, 3]), + mimeType: 'application/octet-stream', + }); + expect(invoke).toHaveBeenNthCalledWith(1, 'load_blob_from_file', { + filePath: '/tmp/image.png', + }); + expect(invoke).toHaveBeenNthCalledWith(2, 'fetch_blob', { + connectionId: 'connection-1', + table: 'files', + colName: 'payload', + pkMap: {id: 1}, + }); + }); + + it('delegates dialogs, clipboard, URL, route, attention, and restart operations', async () => { + const operations = createOperations(); + vi.mocked(operations.readClipboardText).mockResolvedValue('SELECT 1'); + const capabilities = new TauriPlatformCapabilities(operations); + + vi.mocked(operations.confirmDialog).mockResolvedValue(true); + vi.mocked(operations.chooseServerPath).mockResolvedValue('/tmp/plugins'); + await expect( + capabilities.chooseServerPath({kind: 'directory', title: 'Plugins'}), + ).resolves.toEqual({reference: '/tmp/plugins'}); + await expect(capabilities.confirm({message: 'Continue?', kind: 'warning'})).resolves.toBe( + true, + ); + await capabilities.showMessage({message: 'Complete', kind: 'info'}); + await expect(capabilities.readClipboard()).resolves.toBe('SELECT 1'); + await capabilities.writeClipboard('SELECT 2'); + await capabilities.openExternalUrl('https://tabularis.dev'); + await capabilities.openRoute({ + route: '/results-window?session=1', + target: 'new', + label: 'results-window-1', + window: {width: 900, height: 600}, + }); + await capabilities.openConnectionRoute({ + connectionId: 'connection-1', + title: 'Primary', + }); + await capabilities.publishRouteEvent('results-window:ready', { + sessionId: '1', + }); + const unsubscribe = await capabilities.subscribeRouteEvent('results-window:sync', vi.fn()); + unsubscribe(); + await capabilities.closeRoute(); + await capabilities.requestAttention('critical'); + await capabilities.restartApplication(); + + expect(operations.chooseServerPath).toHaveBeenCalledWith({ + kind: 'directory', + title: 'Plugins', + }); + expect(operations.confirmDialog).toHaveBeenCalledWith({ + message: 'Continue?', + kind: 'warning', + }); + expect(operations.showMessageDialog).toHaveBeenCalledWith({ + message: 'Complete', + kind: 'info', + }); + expect(operations.writeClipboardText).toHaveBeenCalledWith('SELECT 2'); + expect(operations.openUrl).toHaveBeenCalledWith('https://tabularis.dev'); + expect(operations.openRoute).toHaveBeenCalledWith({ + route: '/results-window?session=1', + target: 'new', + label: 'results-window-1', + window: {width: 900, height: 600}, + }); + expect(operations.openConnectionRoute).toHaveBeenCalledWith({ + connectionId: 'connection-1', + title: 'Primary', + }); + expect(operations.publishRouteEvent).toHaveBeenCalledWith('results-window:ready', { + sessionId: '1', + }); + expect(operations.subscribeRouteEvent).toHaveBeenCalledWith( + 'results-window:sync', + expect.any(Function), + ); + expect(operations.closeRoute).toHaveBeenCalledOnce(); + expect(operations.requestAttention).toHaveBeenCalledWith('critical'); + expect(operations.restartApplication).toHaveBeenCalledOnce(); + }); + + it('writes downloads only after the user chooses a target', async () => { + const operations = createOperations(); + vi.mocked(operations.chooseSavePath) + .mockResolvedValueOnce('/tmp/data.csv') + .mockResolvedValueOnce(null); + const capabilities = new TauriPlatformCapabilities(operations); + const contents = new Uint8Array([1, 2, 3]); + + await expect(capabilities.downloadFile({fileName: 'data.csv', contents})).resolves.toBe( + true, + ); + await expect( + capabilities.downloadFile({fileName: 'cancelled.csv', contents}), + ).resolves.toBe(false); + + expect(operations.writeFileContents).toHaveBeenCalledOnce(); + expect(operations.writeFileContents).toHaveBeenCalledWith('/tmp/data.csv', contents); + }); + + it('negotiates notification permission without hiding denial', async () => { + const operations = createOperations(); + vi.mocked(operations.isNotificationPermissionGranted) + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(false); + vi.mocked(operations.requestNotificationPermission) + .mockResolvedValueOnce('granted') + .mockResolvedValueOnce('denied'); + const capabilities = new TauriPlatformCapabilities(operations); + + await expect(capabilities.notify({title: 'Ready', body: 'Export complete'})).resolves.toBe( + 'shown', + ); + await expect(capabilities.notify({title: 'Blocked'})).resolves.toBe('permission-denied'); + + expect(operations.sendNotification).toHaveBeenCalledOnce(); + expect(operations.sendNotification).toHaveBeenCalledWith({ + title: 'Ready', + body: 'Export complete', + }); + }); + + it('rejects calls disabled by negotiated capability flags', async () => { + const operations = createOperations(); + const negotiation = createPlatformCapabilityNegotiation('tauri', { + openExternalUrl: { + supported: false, + adaptation: 'unsupported', + reason: 'Disabled for this session', + }, + }); + const capabilities = new TauriPlatformCapabilities(operations, negotiation); + + await expect(capabilities.openExternalUrl('https://tabularis.dev')).rejects.toMatchObject({ + code: 'PLATFORM_CAPABILITY_UNSUPPORTED', + capability: 'openExternalUrl', + }); + expect(operations.openUrl).not.toHaveBeenCalled(); + }); +}); + +describe('TauriPlatformCapabilities host window integration', () => { + it('forwards native window theme, system theme, label and storage folder', async () => { + const operations = createOperations(); + vi.mocked(operations.getSystemIsDark).mockResolvedValue(true); + vi.mocked(operations.currentWindowLabel).mockReturnValue('conn-1'); + const capabilities = new TauriPlatformCapabilities(operations); + const onChange = vi.fn(); + + await capabilities.setNativeWindowTheme('dark'); + await capabilities.setNativeWindowTheme(null); + await expect(capabilities.getSystemIsDark()).resolves.toBe(true); + await capabilities.listenForSystemThemeChanges(onChange); + await capabilities.openStorageLocation(); + + expect(operations.setNativeWindowTheme).toHaveBeenNthCalledWith(1, 'dark'); + expect(operations.setNativeWindowTheme).toHaveBeenNthCalledWith(2, null); + expect(operations.listenForSystemThemeChanges).toHaveBeenCalledWith(onChange); + expect(operations.openStorageLocation).toHaveBeenCalledOnce(); + expect(capabilities.currentWindowLabel()).toBe('conn-1'); + expect(capabilities.supports('openStorageLocation')).toBe(true); + }); +}); diff --git a/packages/web-ui/tests/routing.test.ts b/packages/web-ui/tests/routing.test.ts new file mode 100644 index 000000000..57ab1faae --- /dev/null +++ b/packages/web-ui/tests/routing.test.ts @@ -0,0 +1,129 @@ +import {spawn, type ChildProcess} from 'node:child_process'; +import {createRequire} from 'node:module'; +import {createServer} from 'node:net'; +import {dirname, resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; + +import { + BROWSER_ROUTE_PATHS, + BROWSER_ROUTES, + WEB_UI_BASE_PATH, + buildEditorRoute, + isEditorRoute, +} from '@/routing'; + +const webUiRoot = dirname(dirname(fileURLToPath(import.meta.url))); +const repositoryRoot = dirname(dirname(webUiRoot)); +const require = createRequire(import.meta.url); +const viteCliPath = resolve(dirname(require.resolve('vite')), '../../bin/vite.js'); +const directNavigationUrls = [ + BROWSER_ROUTES.root, + BROWSER_ROUTES.connections, + BROWSER_ROUTES.editor, + buildEditorRoute('connection-1'), + BROWSER_ROUTES.settings, + BROWSER_ROUTES.mcp, + `${BROWSER_ROUTES.schemaDiagram}?connection=connection-1&database=main`, + `${BROWSER_ROUTES.visualExplain}?connection=connection-1&query=select%201`, + `${BROWSER_ROUTES.jsonViewer}?session=json-1`, + BROWSER_ROUTES.taskManager, + `${BROWSER_ROUTES.resultsWindow}?session=result-1`, + '/install/postgres-driver?version=1.2.3®istry=https%3A%2F%2Fregistry.example', +] as const; + +let viteProcess: ChildProcess; +let origin: string; + +const findAvailablePort = async (): Promise => + new Promise((resolve, reject) => { + const portServer = createServer(); + portServer.once('error', reject); + portServer.listen(0, '127.0.0.1', () => { + const address = portServer.address(); + if (!address || typeof address === 'string') { + portServer.close(); + reject(new Error('Unable to reserve a Vite test port')); + return; + } + portServer.close((error) => { + if (error) reject(error); + else resolve(address.port); + }); + }); + }); + +beforeAll(async () => { + const port = await findAvailablePort(); + origin = `http://127.0.0.1:${port}`; + viteProcess = spawn( + process.execPath, + [viteCliPath, webUiRoot, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: repositoryRoot, + stdio: 'ignore', + }, + ); + + for (let attempt = 0; attempt < 100; attempt += 1) { + if (viteProcess.exitCode !== null) { + throw new Error(`Vite exited before startup with code ${viteProcess.exitCode}`); + } + try { + const response = await fetch(origin); + if (response.ok) return; + } catch { + // Keep polling until Vite is listening. + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + + throw new Error('Timed out waiting for the Vite routing test server'); +}, 10_000); + +afterAll(() => { + viteProcess?.kill('SIGTERM'); +}); + +describe('web UI routing', () => { + it('uses one explicit root base path', () => { + expect(WEB_UI_BASE_PATH).toBe('/'); + }); + + it('tracks every supported browser route', () => { + expect(BROWSER_ROUTE_PATHS).toEqual([ + '/', + '/connections', + '/editor', + '/connections/:connectionId/editor', + '/mcp', + '/settings', + '/schema-diagram', + '/task-manager', + '/visual-explain', + '/json-viewer', + '/results-window', + '/install/:slug', + ]); + }); + + it('builds an editor route for a specific connection', () => { + expect(buildEditorRoute('team/database 1')).toBe('/connections/team%2Fdatabase%201/editor'); + }); + + it('recognizes legacy and connection editor routes', () => { + expect(isEditorRoute('/editor')).toBe(true); + expect(isEditorRoute('/connections/connection-1/editor')).toBe(true); + expect(isEditorRoute('/connections')).toBe(false); + }); + + it.each(directNavigationUrls)('serves the SPA shell for %s', async (url) => { + const response = await fetch(`${origin}${url}`); + const body = await response.text(); + + expect(response.status).toBe(200); + expect(response.headers.get('content-type')).toContain('text/html'); + expect(body).toContain('
'); + }); +}); diff --git a/tests/scripts/set-nightly-version.test.ts b/packages/web-ui/tests/scripts/set-nightly-version.test.ts similarity index 86% rename from tests/scripts/set-nightly-version.test.ts rename to packages/web-ui/tests/scripts/set-nightly-version.test.ts index 54066def6..d3377260a 100644 --- a/tests/scripts/set-nightly-version.test.ts +++ b/packages/web-ui/tests/scripts/set-nightly-version.test.ts @@ -13,13 +13,16 @@ function fixture(cargo = originalCargo): string { const directory = mkdtempSync(join(tmpdir(), 'tabularis-nightly-')); directories.push(directory); mkdirSync(join(directory, 'src-tauri')); - mkdirSync(join(directory, 'src')); + mkdirSync(join(directory, 'packages/web-ui/src'), {recursive: true}); writeFileSync(join(directory, 'src-tauri/Cargo.toml'), cargo); writeFileSync( join(directory, 'src-tauri/tauri.conf.json'), JSON.stringify({version: '0.25.0', identifier: 'tabularis'}), ); - writeFileSync(join(directory, 'src/version.ts'), 'export const APP_VERSION = "0.25.0";\n'); + writeFileSync( + join(directory, 'packages/web-ui/src/version.ts'), + 'export const APP_VERSION = "0.25.0";\n', + ); return directory; } @@ -38,7 +41,7 @@ describe('nightly version stamping', () => { expect( JSON.parse(readFileSync(join(directory, 'src-tauri/tauri.conf.json'), 'utf8')), ).toEqual({version: '0.25.1-6', identifier: 'tabularis'}); - expect(readFileSync(join(directory, 'src/version.ts'), 'utf8')).toBe( + expect(readFileSync(join(directory, 'packages/web-ui/src/version.ts'), 'utf8')).toBe( 'export const APP_VERSION = "0.25.1-6";\n', ); }); @@ -51,7 +54,9 @@ describe('nightly version stamping', () => { expect( JSON.parse(readFileSync(join(directory, 'src-tauri/tauri.conf.json'), 'utf8')).version, ).toBe('0.25.0'); - expect(readFileSync(join(directory, 'src/version.ts'), 'utf8')).toContain('"0.25.0"'); + expect(readFileSync(join(directory, 'packages/web-ui/src/version.ts'), 'utf8')).toContain( + '"0.25.0"', + ); }); it.each(['0.25.1-nightly.6', '0.25.1', '0.25.1-06', 'not-a-version'])( diff --git a/tests/scripts/stage-winget-installer.test.ts b/packages/web-ui/tests/scripts/stage-winget-installer.test.ts similarity index 96% rename from tests/scripts/stage-winget-installer.test.ts rename to packages/web-ui/tests/scripts/stage-winget-installer.test.ts index ad492ee2a..feb067e2c 100644 --- a/tests/scripts/stage-winget-installer.test.ts +++ b/packages/web-ui/tests/scripts/stage-winget-installer.test.ts @@ -4,7 +4,7 @@ import {join, resolve} from 'node:path'; import {afterEach, describe, expect, it} from 'vitest'; // Release scripts run directly in Node and do not participate in the app build. // @ts-expect-error JavaScript release script has no declaration file. -import {stageWingetInstaller} from '../../scripts/stage-winget-installer.mjs'; +import {stageWingetInstaller} from '../../../../scripts/stage-winget-installer.mjs'; const directories: string[] = []; function fixture() { diff --git a/tests/scripts/sync-contribute-discussion.test.ts b/packages/web-ui/tests/scripts/sync-contribute-discussion.test.ts similarity index 99% rename from tests/scripts/sync-contribute-discussion.test.ts rename to packages/web-ui/tests/scripts/sync-contribute-discussion.test.ts index 6f09ff246..e5cecdf8b 100644 --- a/tests/scripts/sync-contribute-discussion.test.ts +++ b/packages/web-ui/tests/scripts/sync-contribute-discussion.test.ts @@ -6,7 +6,7 @@ import { issueStatus, localeGaps, updateBody, -} from '../../scripts/sync-contribute-discussion.mjs'; +} from '../../../../scripts/sync-contribute-discussion.mjs'; const today = new Date(Date.UTC(2026, 9, 12)); diff --git a/tests/scripts/winget-build-config.test.ts b/packages/web-ui/tests/scripts/winget-build-config.test.ts similarity index 100% rename from tests/scripts/winget-build-config.test.ts rename to packages/web-ui/tests/scripts/winget-build-config.test.ts diff --git a/tests/setup.ts b/packages/web-ui/tests/setup.ts similarity index 98% rename from tests/setup.ts rename to packages/web-ui/tests/setup.ts index ac60b8a79..3e84c9580 100644 --- a/tests/setup.ts +++ b/packages/web-ui/tests/setup.ts @@ -30,6 +30,7 @@ Object.defineProperty(document, 'execCommand', { // Mock Tauri APIs vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), + isTauri: vi.fn().mockReturnValue(true), })); vi.mock('@tauri-apps/api/window', () => ({ @@ -66,6 +67,8 @@ vi.mock('@tauri-apps/plugin-dialog', () => ({ })); vi.mock('@tauri-apps/plugin-fs', () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), writeTextFile: vi.fn(), BaseDirectory: { Document: 1, @@ -153,6 +156,8 @@ vi.mock('lucide-react', () => ({ Network: () => null, Code: () => null, FileText: () => null, + FileIcon: () => null, + ImageIcon: () => null, Command: () => null, Braces: () => null, Sparkles: () => null, diff --git a/tests/storageEnvironment.test.ts b/packages/web-ui/tests/storageEnvironment.test.ts similarity index 100% rename from tests/storageEnvironment.test.ts rename to packages/web-ui/tests/storageEnvironment.test.ts diff --git a/packages/web-ui/tests/support/tauriBackedHooks.ts b/packages/web-ui/tests/support/tauriBackedHooks.ts new file mode 100644 index 000000000..ce9fbab12 --- /dev/null +++ b/packages/web-ui/tests/support/tauriBackedHooks.ts @@ -0,0 +1,39 @@ +/** + * Hook replacements for tests written against the Tauri APIs. + * + * `vi.mock("/hooks/useTabularisClient", () => import("/support/tauriBackedHooks"))` + * (and likewise for `usePlatformCapabilities`) routes the component's client and + * platform calls through the `@tauri-apps/*` mocks from `tests/setup.ts`, so + * assertions on `invoke`, `listen` or `openUrl` keep describing the desktop + * transport without mounting the real providers. + */ +import {invoke} from '@tauri-apps/api/core'; +import {emit, listen} from '@tauri-apps/api/event'; +import {TauriPlatformCapabilities} from '@/platform/tauriCapabilities'; +import type {TabularisClient} from '@/api/client'; + +function forward(command: string, request: unknown) { + return request === undefined + ? invoke(command) + : invoke(command, request as Record); +} + +export const tauriBackedClient = { + call: forward, + callUnmigrated: forward, + subscribe: (event: string, handler: (payload: unknown) => void) => + listen(event, ({payload}) => handler(payload)), + emit: (event: string, payload: unknown) => emit(event, payload), + readPluginAsset: (pluginId: string, filePath: string) => + invoke('read_plugin_file', {pluginId, filePath}), +} as unknown as TabularisClient; + +const platform = new TauriPlatformCapabilities(); + +export function useTabularisClient() { + return tauriBackedClient; +} + +export function usePlatformCapabilities() { + return platform; +} diff --git a/tests/themes/colorUtils.test.ts b/packages/web-ui/tests/themes/colorUtils.test.ts similarity index 100% rename from tests/themes/colorUtils.test.ts rename to packages/web-ui/tests/themes/colorUtils.test.ts diff --git a/tests/themes/compatibilityBaseline.test.ts b/packages/web-ui/tests/themes/compatibilityBaseline.test.ts similarity index 92% rename from tests/themes/compatibilityBaseline.test.ts rename to packages/web-ui/tests/themes/compatibilityBaseline.test.ts index 690a537d3..c4fa80ab8 100644 --- a/tests/themes/compatibilityBaseline.test.ts +++ b/packages/web-ui/tests/themes/compatibilityBaseline.test.ts @@ -3,11 +3,11 @@ import type * as Monaco from 'monaco-editor'; import {afterEach, describe, expect, it, vi} from 'vitest'; import {themeRegistry} from '@/themes/themeRegistry'; import {exportTheme, importTheme} from '@/utils/themeManagement'; -import builtinGolden from '../fixtures/themes/builtin-rendering.json'; -import assetGolden from '../fixtures/themes/named-editor-assets.json'; -import legacyFrontend from '../fixtures/themes/legacy-frontend.json'; +import builtinGolden from '../../../../tests/fixtures/themes/builtin-rendering.json'; +import assetGolden from '../../../../tests/fixtures/themes/named-editor-assets.json'; +import legacyFrontend from '../../../../tests/fixtures/themes/legacy-frontend.json'; -const namedAssets = import.meta.glob('../../src/themes/monaco/*.json', { +const namedAssets = import.meta.glob('@/themes/monaco/*.json', { query: '?raw', import: 'default', eager: true, diff --git a/tests/themes/themePackageLocales.test.ts b/packages/web-ui/tests/themes/themePackageLocales.test.ts similarity index 100% rename from tests/themes/themePackageLocales.test.ts rename to packages/web-ui/tests/themes/themePackageLocales.test.ts diff --git a/tests/themes/themeRegistry.test.ts b/packages/web-ui/tests/themes/themeRegistry.test.ts similarity index 100% rename from tests/themes/themeRegistry.test.ts rename to packages/web-ui/tests/themes/themeRegistry.test.ts diff --git a/tests/themes/themeRuntime.test.ts b/packages/web-ui/tests/themes/themeRuntime.test.ts similarity index 99% rename from tests/themes/themeRuntime.test.ts rename to packages/web-ui/tests/themes/themeRuntime.test.ts index 988ed7386..dcf0f16e4 100644 --- a/tests/themes/themeRuntime.test.ts +++ b/packages/web-ui/tests/themes/themeRuntime.test.ts @@ -3,7 +3,7 @@ import type * as Monaco from 'monaco-editor'; import {getMonacoThemeId} from '@/themes/themeRuntime'; import {loadMonacoTheme} from '@/themes/themeUtils'; import {resolveLegacyTheme, resolveThemeDefinition} from '@/utils/themeResolver'; -import legacy from '../fixtures/themes/legacy-frontend.json'; +import legacy from '../../../../tests/fixtures/themes/legacy-frontend.json'; import type {Theme} from '@/types/theme'; import {createInstalledThemeId} from '@/utils/themePackageIdentity'; import schema from '@/schemas/theme-definition-v1.json'; diff --git a/tests/themes/themeSnapshot.test.ts b/packages/web-ui/tests/themes/themeSnapshot.test.ts similarity index 97% rename from tests/themes/themeSnapshot.test.ts rename to packages/web-ui/tests/themes/themeSnapshot.test.ts index 249cb55b3..6ee02d896 100644 --- a/tests/themes/themeSnapshot.test.ts +++ b/packages/web-ui/tests/themes/themeSnapshot.test.ts @@ -1,7 +1,7 @@ import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; import {resolveCatalogEntry} from '@/utils/themeCatalog'; import {resolveLegacyTheme} from '@/utils/themeResolver'; -import legacy from '../fixtures/themes/legacy-frontend.json'; +import legacy from '../../../../tests/fixtures/themes/legacy-frontend.json'; import type {Theme} from '@/types/theme'; beforeAll(() => diff --git a/tests/themes/themeUtils.test.ts b/packages/web-ui/tests/themes/themeUtils.test.ts similarity index 100% rename from tests/themes/themeUtils.test.ts rename to packages/web-ui/tests/themes/themeUtils.test.ts diff --git a/tests/themes/toneCoverage.test.ts b/packages/web-ui/tests/themes/toneCoverage.test.ts similarity index 100% rename from tests/themes/toneCoverage.test.ts rename to packages/web-ui/tests/themes/toneCoverage.test.ts diff --git a/packages/web-ui/tests/types/pluginSlotsParity.test.ts b/packages/web-ui/tests/types/pluginSlotsParity.test.ts new file mode 100644 index 000000000..ba57821cf --- /dev/null +++ b/packages/web-ui/tests/types/pluginSlotsParity.test.ts @@ -0,0 +1,53 @@ +import {readFileSync} from 'node:fs'; +import {resolve} from 'node:path'; +import {describe, expect, it} from 'vitest'; +import ts from 'typescript'; +import {VALID_SLOTS} from '@/types/pluginSlots'; + +const SLOT_ANCHORS: Readonly> = { + 'row-edit-modal.field.after': 'components/modals/NewRowModal.tsx', + 'row-edit-modal.footer.before': 'components/modals/NewRowModal.tsx', + 'row-editor-sidebar.field.after': 'components/ui/RowEditorPanel.tsx', + 'row-editor-sidebar.header.actions': 'components/ui/RowEditorPanel.tsx', + 'data-grid.toolbar.actions': 'components/ui/TableToolbar.tsx', + 'data-grid.context-menu.items': 'components/ui/DataGrid.tsx', + 'sidebar.footer.actions': 'components/layout/Sidebar.tsx', + 'settings.plugin.actions': 'components/settings/PluginsTab.tsx', + 'settings.plugin.before_settings': 'components/settings/PluginSettingsPage.tsx', + 'connection-modal.connection_content': 'components/modals/NewConnectionModal.tsx', + 'connection-modal.extra_fields': 'components/modals/NewConnectionModal.tsx', +}; + +describe('plugin slot parity', () => { + it('should mount every public plugin API slot in the shared desktop and web UI', () => { + expect(new Set(Object.keys(SLOT_ANCHORS))).toEqual(VALID_SLOTS); + + const publicContract = readFileSync(resolve('packages/plugin-api/src/slots.ts'), 'utf8'); + const parsed = ts.createSourceFile( + 'slots.ts', + publicContract, + ts.ScriptTarget.Latest, + true, + ); + const declaration = parsed.statements.find( + (statement) => + ts.isTypeAliasDeclaration(statement) && statement.name.text === 'SlotContextMap', + ); + if ( + !declaration || + !ts.isTypeAliasDeclaration(declaration) || + !ts.isTypeLiteralNode(declaration.type) + ) + throw new Error('Missing public slot context map'); + const publicSlots = new Set( + declaration.type.members.flatMap((member) => + member.name && ts.isStringLiteral(member.name) ? [member.name.text] : [], + ), + ); + expect(publicSlots).toEqual(VALID_SLOTS); + for (const [slot, sourcePath] of Object.entries(SLOT_ANCHORS)) { + const source = readFileSync(resolve('packages/web-ui/src', sourcePath), 'utf8'); + expect(source, slot).toContain(`name="${slot}"`); + } + }); +}); diff --git a/tests/utils/aiActivity.test.ts b/packages/web-ui/tests/utils/aiActivity.test.ts similarity index 100% rename from tests/utils/aiActivity.test.ts rename to packages/web-ui/tests/utils/aiActivity.test.ts diff --git a/tests/utils/aiDefaults.test.ts b/packages/web-ui/tests/utils/aiDefaults.test.ts similarity index 52% rename from tests/utils/aiDefaults.test.ts rename to packages/web-ui/tests/utils/aiDefaults.test.ts index b2745ee84..3fbbe2ee3 100644 --- a/tests/utils/aiDefaults.test.ts +++ b/packages/web-ui/tests/utils/aiDefaults.test.ts @@ -1,51 +1,40 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {invoke} from '@tauri-apps/api/core'; +import type {TabularisClient} from '@/api/client'; import {DEFAULT_SETTINGS} from '@/contexts/SettingsContext'; import {detectAiDefaults} from '@/utils/aiDefaults'; +const call = vi.fn(); +const client = {call} as unknown as TabularisClient; + describe('detectAiDefaults', () => { - beforeEach(() => vi.mocked(invoke).mockReset()); + beforeEach(() => call.mockReset()); it('does no work when AI is disabled or already configured', async () => { - await detectAiDefaults({...DEFAULT_SETTINGS, aiEnabled: false}); - await detectAiDefaults({ + await detectAiDefaults(client, {...DEFAULT_SETTINGS, aiEnabled: false}); + await detectAiDefaults(client, { ...DEFAULT_SETTINGS, aiEnabled: true, aiProvider: 'openai', aiModel: 'chosen', }); - expect(invoke).not.toHaveBeenCalled(); + expect(call).not.toHaveBeenCalled(); }); it('keeps the selected provider and requests cached models', async () => { - vi.mocked(invoke).mockResolvedValue({anthropic: ['model-a'], openai: ['model-b']}); - const result = await detectAiDefaults({ + call.mockResolvedValue({anthropic: ['model-a'], openai: ['model-b']}); + const result = await detectAiDefaults(client, { ...DEFAULT_SETTINGS, aiEnabled: true, aiProvider: 'anthropic', aiModel: null, }); expect(result).toEqual({aiProvider: 'anthropic', aiModel: 'model-a'}); - expect(invoke).toHaveBeenCalledExactlyOnceWith('get_ai_models', {forceRefresh: false}); - }); - - it('does not load either catalog while hydrating ChatGPT with an empty model', async () => { - for (const aiModel of [null, '']) { - expect( - await detectAiDefaults({ - ...DEFAULT_SETTINGS, - aiEnabled: true, - aiProvider: 'chatgpt', - aiModel, - }), - ).toEqual({}); - } - expect(invoke).not.toHaveBeenCalled(); + expect(call).toHaveBeenCalledExactlyOnceWith('get_ai_models', {forceRefresh: false}); }); it('preserves provider priority even if a key lookup fails', async () => { - vi.mocked(invoke).mockImplementation(async (command, args) => { - const provider = (args as {provider?: string} | undefined)?.provider; + call.mockImplementation(async (command: string, args: {provider?: string} | undefined) => { + const provider = args?.provider; if (command === 'check_ai_key') { if (provider === 'openai') throw new Error('key unavailable'); return true; @@ -53,7 +42,7 @@ describe('detectAiDefaults', () => { return {anthropic: ['model-a']}; }); expect( - await detectAiDefaults({ + await detectAiDefaults(client, { ...DEFAULT_SETTINGS, aiEnabled: true, aiProvider: null, @@ -62,3 +51,18 @@ describe('detectAiDefaults', () => { ).toEqual({aiProvider: 'anthropic', aiModel: 'model-a'}); }); }); + +it('does not load either catalog while hydrating ChatGPT with an empty model', async () => { + call.mockReset(); + for (const aiModel of [null, '']) { + expect( + await detectAiDefaults(client, { + ...DEFAULT_SETTINGS, + aiEnabled: true, + aiProvider: 'chatgpt', + aiModel, + }), + ).toEqual({}); + } + expect(call).not.toHaveBeenCalled(); +}); diff --git a/tests/utils/anchoredPopover.test.ts b/packages/web-ui/tests/utils/anchoredPopover.test.ts similarity index 100% rename from tests/utils/anchoredPopover.test.ts rename to packages/web-ui/tests/utils/anchoredPopover.test.ts diff --git a/tests/utils/approvalExplain.test.ts b/packages/web-ui/tests/utils/approvalExplain.test.ts similarity index 100% rename from tests/utils/approvalExplain.test.ts rename to packages/web-ui/tests/utils/approvalExplain.test.ts diff --git a/tests/utils/asyncResource.test.ts b/packages/web-ui/tests/utils/asyncResource.test.ts similarity index 100% rename from tests/utils/asyncResource.test.ts rename to packages/web-ui/tests/utils/asyncResource.test.ts diff --git a/tests/utils/autoRefresh.test.ts b/packages/web-ui/tests/utils/autoRefresh.test.ts similarity index 100% rename from tests/utils/autoRefresh.test.ts rename to packages/web-ui/tests/utils/autoRefresh.test.ts diff --git a/tests/utils/autocomplete.test.ts b/packages/web-ui/tests/utils/autocomplete.test.ts similarity index 98% rename from tests/utils/autocomplete.test.ts rename to packages/web-ui/tests/utils/autocomplete.test.ts index a0e4fb5fb..1e11a1128 100644 --- a/tests/utils/autocomplete.test.ts +++ b/packages/web-ui/tests/utils/autocomplete.test.ts @@ -3,12 +3,13 @@ import { applyKeywordCase, clearAutocompleteCache, needsKeywordCaseRetrigger, - registerSqlAutocomplete, + registerSqlAutocomplete as registerSqlAutocompleteImpl, resolveKeywordCase, type AutocompleteKeywordCase, } from '@/utils/autocomplete'; import type {TableInfo} from '@/contexts/DatabaseContext'; import type {PluginManifest} from '@/types/plugins'; +import type {TypedCommandCaller} from '@/api/contract'; // Mock @tauri-apps/api/core vi.mock('@tauri-apps/api/core', () => ({ @@ -23,6 +24,28 @@ vi.mock('@/utils/sqlAnalysis', () => ({ import {invoke} from '@tauri-apps/api/core'; +const autocompleteClient = { + call: (command: string, request: unknown) => invoke(command, request), +} as unknown as TypedCommandCaller; + +const registerSqlAutocomplete = ( + monaco: Parameters[0], + connectionId: Parameters[1], + tables: Parameters[2], + schema?: Parameters[3], + driver?: Parameters[4], + keywordCase?: AutocompleteKeywordCase, +) => + registerSqlAutocompleteImpl( + monaco, + connectionId, + tables, + schema, + driver, + autocompleteClient, + keywordCase, + ); + // Create a mock Monaco object const createMockMonaco = () => ({ languages: { diff --git a/tests/utils/blob.test.ts b/packages/web-ui/tests/utils/blob.test.ts similarity index 95% rename from tests/utils/blob.test.ts rename to packages/web-ui/tests/utils/blob.test.ts index 1a7b98463..79660b25e 100644 --- a/tests/utils/blob.test.ts +++ b/packages/web-ui/tests/utils/blob.test.ts @@ -10,6 +10,7 @@ import { formatBlobValue, mimeToExtension, parseBlobFileRef, + parseBlobUploadRef, extractBase64Payload, blobPayloadToBytes, blobHexToWireFormat, @@ -120,6 +121,20 @@ describe('blob utilities', () => { ).toBe(true); }); + it('should extract opaque browser upload metadata without treating the token as bytes', () => { + const metadata = extractBlobMetadata( + 'BLOB_UPLOAD_REF:8:image/png:00000000-0000-4000-8000-000000000000', + ); + + expect(metadata).toEqual({ + mimeType: 'image/png', + size: 8, + formattedSize: '8 B', + isBase64: false, + isTruncated: false, + }); + }); + it('should handle null values', () => { expect(extractBlobMetadata(null)).toBeNull(); expect(extractBlobMetadata(undefined)).toBeNull(); @@ -331,6 +346,22 @@ describe('blob utilities', () => { }); }); + describe('parseBlobUploadRef', () => { + it('should parse only opaque upload references', () => { + expect( + parseBlobUploadRef( + 'BLOB_UPLOAD_REF:8:image/png:00000000-0000-4000-8000-000000000000', + ), + ).toEqual({ + size: 8, + mimeType: 'image/png', + token: '00000000-0000-4000-8000-000000000000', + }); + expect(parseBlobUploadRef('BLOB_UPLOAD_REF:bad:image/png:token')).toBeNull(); + expect(parseBlobUploadRef('BLOB_FILE_REF:8:image/png:/tmp/file')).toBeNull(); + }); + }); + describe('isSvgText', () => { it('should return true for SVG strings starting with { expect( diff --git a/tests/utils/builtInCommands.test.ts b/packages/web-ui/tests/utils/builtInCommands.test.ts similarity index 100% rename from tests/utils/builtInCommands.test.ts rename to packages/web-ui/tests/utils/builtInCommands.test.ts diff --git a/tests/utils/bulkCellEdit.test.ts b/packages/web-ui/tests/utils/bulkCellEdit.test.ts similarity index 100% rename from tests/utils/bulkCellEdit.test.ts rename to packages/web-ui/tests/utils/bulkCellEdit.test.ts diff --git a/tests/utils/cellValueFilter.test.ts b/packages/web-ui/tests/utils/cellValueFilter.test.ts similarity index 100% rename from tests/utils/cellValueFilter.test.ts rename to packages/web-ui/tests/utils/cellValueFilter.test.ts diff --git a/tests/utils/changelog.test.ts b/packages/web-ui/tests/utils/changelog.test.ts similarity index 100% rename from tests/utils/changelog.test.ts rename to packages/web-ui/tests/utils/changelog.test.ts diff --git a/tests/utils/clipboard.test.ts b/packages/web-ui/tests/utils/clipboard.test.ts similarity index 99% rename from tests/utils/clipboard.test.ts rename to packages/web-ui/tests/utils/clipboard.test.ts index a48efd3b0..06fafed2c 100644 --- a/tests/utils/clipboard.test.ts +++ b/packages/web-ui/tests/utils/clipboard.test.ts @@ -1,5 +1,5 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; -import {GOOGLESQL_CAPS} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL_CAPS} from '../../../../tests/fixtures/sql-syntax/googlesql'; import { rowToCSV, rowsToCSV, diff --git a/tests/utils/clipboardParser.test.ts b/packages/web-ui/tests/utils/clipboardParser.test.ts similarity index 100% rename from tests/utils/clipboardParser.test.ts rename to packages/web-ui/tests/utils/clipboardParser.test.ts diff --git a/tests/utils/closedTabs.test.ts b/packages/web-ui/tests/utils/closedTabs.test.ts similarity index 100% rename from tests/utils/closedTabs.test.ts rename to packages/web-ui/tests/utils/closedTabs.test.ts diff --git a/tests/utils/columnMasking.test.ts b/packages/web-ui/tests/utils/columnMasking.test.ts similarity index 100% rename from tests/utils/columnMasking.test.ts rename to packages/web-ui/tests/utils/columnMasking.test.ts diff --git a/tests/utils/columnStats.test.ts b/packages/web-ui/tests/utils/columnStats.test.ts similarity index 100% rename from tests/utils/columnStats.test.ts rename to packages/web-ui/tests/utils/columnStats.test.ts diff --git a/tests/utils/columnStatsSchema.test.ts b/packages/web-ui/tests/utils/columnStatsSchema.test.ts similarity index 80% rename from tests/utils/columnStatsSchema.test.ts rename to packages/web-ui/tests/utils/columnStatsSchema.test.ts index 9302e4566..9ff52421e 100644 --- a/tests/utils/columnStatsSchema.test.ts +++ b/packages/web-ui/tests/utils/columnStatsSchema.test.ts @@ -1,6 +1,6 @@ import {describe, expect, it} from 'vitest'; -import manifestSchema from '../../plugins/manifest.schema.json'; -import extensionsSchema from '../../plugins/tabularium-extensions.schema.json'; +import manifestSchema from '../../../../plugins/manifest.schema.json'; +import extensionsSchema from '../../../../plugins/tabularium-extensions.schema.json'; describe('column statistics manifest contract (#1137)', () => { for (const [name, schema] of Object.entries({manifestSchema, extensionsSchema})) { diff --git a/tests/utils/columnTypes.test.ts b/packages/web-ui/tests/utils/columnTypes.test.ts similarity index 100% rename from tests/utils/columnTypes.test.ts rename to packages/web-ui/tests/utils/columnTypes.test.ts diff --git a/tests/utils/commandScopeStore.test.ts b/packages/web-ui/tests/utils/commandScopeStore.test.ts similarity index 100% rename from tests/utils/commandScopeStore.test.ts rename to packages/web-ui/tests/utils/commandScopeStore.test.ts diff --git a/tests/utils/commandTable.test.ts b/packages/web-ui/tests/utils/commandTable.test.ts similarity index 87% rename from tests/utils/commandTable.test.ts rename to packages/web-ui/tests/utils/commandTable.test.ts index e3b4ffaa1..179a1f1d9 100644 --- a/tests/utils/commandTable.test.ts +++ b/packages/web-ui/tests/utils/commandTable.test.ts @@ -26,6 +26,21 @@ describe('resolveCommandTable', () => { }); }); + it('should expose the table target on a connection editor route', () => { + expect( + resolveCommandTable({ + pathname: '/connections/connection-1/editor', + activeConnectionId: 'connection-1', + activeSchema: 'public', + activeTab: tableTab, + }), + ).toEqual({ + connectionId: 'connection-1', + tableName: 'users', + schema: 'public', + }); + }); + it('should not leak the last editor table onto settings', () => { expect( resolveCommandTable({ diff --git a/tests/utils/connectionCatalogue.test.ts b/packages/web-ui/tests/utils/connectionCatalogue.test.ts similarity index 100% rename from tests/utils/connectionCatalogue.test.ts rename to packages/web-ui/tests/utils/connectionCatalogue.test.ts diff --git a/tests/utils/connectionCommandItems.test.ts b/packages/web-ui/tests/utils/connectionCommandItems.test.ts similarity index 100% rename from tests/utils/connectionCommandItems.test.ts rename to packages/web-ui/tests/utils/connectionCommandItems.test.ts diff --git a/tests/utils/connectionErrors.test.ts b/packages/web-ui/tests/utils/connectionErrors.test.ts similarity index 100% rename from tests/utils/connectionErrors.test.ts rename to packages/web-ui/tests/utils/connectionErrors.test.ts diff --git a/tests/utils/connectionFieldsSchema.test.ts b/packages/web-ui/tests/utils/connectionFieldsSchema.test.ts similarity index 91% rename from tests/utils/connectionFieldsSchema.test.ts rename to packages/web-ui/tests/utils/connectionFieldsSchema.test.ts index 3b5a016af..52c7242f6 100644 --- a/tests/utils/connectionFieldsSchema.test.ts +++ b/packages/web-ui/tests/utils/connectionFieldsSchema.test.ts @@ -1,6 +1,6 @@ import {describe, expect, it} from 'vitest'; -import manifestSchema from '../../plugins/manifest.schema.json'; -import extensionsSchema from '../../plugins/tabularium-extensions.schema.json'; +import manifestSchema from '../../../../plugins/manifest.schema.json'; +import extensionsSchema from '../../../../plugins/tabularium-extensions.schema.json'; const FIELDS = ['host', 'port', 'username', 'password', 'database']; diff --git a/packages/web-ui/tests/utils/connectionFiles.test.ts b/packages/web-ui/tests/utils/connectionFiles.test.ts new file mode 100644 index 000000000..d6818d68a --- /dev/null +++ b/packages/web-ui/tests/utils/connectionFiles.test.ts @@ -0,0 +1,72 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import type {GeneratedFile} from '@/api/contract'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {prepareConnectionImportFile, saveGeneratedFile} from '@/utils/connectionFiles'; + +function platform(environment: 'tauri' | 'browser'): PlatformCapabilities { + return { + negotiation: { + environment, + capabilities: {} as PlatformCapabilities['negotiation']['capabilities'], + }, + readInputFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])), + downloadFile: vi.fn().mockResolvedValue(true), + } as unknown as PlatformCapabilities; +} + +describe('connectionFiles', () => { + it('keeps desktop import paths on the native side', async () => { + const capabilities = platform('tauri'); + const client = {} as TabularisClient; + + await expect( + prepareConnectionImportFile(client, capabilities, { + name: 'connections.json', + reference: '/tmp/connections.json', + }), + ).resolves.toEqual({kind: 'serverPath', path: '/tmp/connections.json'}); + expect(capabilities.readInputFile).not.toHaveBeenCalled(); + }); + + it('uploads browser files behind a purpose-bound opaque token', async () => { + const capabilities = platform('browser'); + const uploadFile = vi.fn().mockResolvedValue({token: 'upload-token'}); + const client = {uploadFile} as unknown as TabularisClient; + + await expect( + prepareConnectionImportFile(client, capabilities, { + name: 'connections.json', + reference: 'browser-file:1', + }), + ).resolves.toEqual({kind: 'upload', token: 'upload-token'}); + expect(uploadFile).toHaveBeenCalledWith({ + contents: expect.any(Blob), + fileName: 'connections.json', + purpose: 'connection-import', + }); + }); + + it('consumes server-generated downloads without exposing server paths', async () => { + const capabilities = platform('browser'); + const consumeDownload = vi + .fn() + .mockResolvedValue(new Blob(['encrypted'], {type: 'application/json'})); + const client = {consumeDownload} as unknown as TabularisClient; + const generated: GeneratedFile = { + kind: 'download', + fileName: 'tabularis-connections.json', + mimeType: 'application/json', + token: 'download-token', + size: 9, + }; + + await expect(saveGeneratedFile(client, capabilities, generated)).resolves.toBe(true); + expect(consumeDownload).toHaveBeenCalledWith('download-token'); + expect(capabilities.downloadFile).toHaveBeenCalledWith({ + fileName: 'tabularis-connections.json', + mimeType: 'application/json', + contents: expect.any(Uint8Array), + }); + }); +}); diff --git a/tests/utils/connectionIconPack.test.tsx b/packages/web-ui/tests/utils/connectionIconPack.test.tsx similarity index 100% rename from tests/utils/connectionIconPack.test.tsx rename to packages/web-ui/tests/utils/connectionIconPack.test.tsx diff --git a/tests/utils/connectionLayout.test.ts b/packages/web-ui/tests/utils/connectionLayout.test.ts similarity index 100% rename from tests/utils/connectionLayout.test.ts rename to packages/web-ui/tests/utils/connectionLayout.test.ts diff --git a/tests/utils/connectionManager.test.ts b/packages/web-ui/tests/utils/connectionManager.test.ts similarity index 100% rename from tests/utils/connectionManager.test.ts rename to packages/web-ui/tests/utils/connectionManager.test.ts diff --git a/tests/utils/connectionMetadata.test.ts b/packages/web-ui/tests/utils/connectionMetadata.test.ts similarity index 100% rename from tests/utils/connectionMetadata.test.ts rename to packages/web-ui/tests/utils/connectionMetadata.test.ts diff --git a/tests/utils/connectionStringParser.test.ts b/packages/web-ui/tests/utils/connectionStringParser.test.ts similarity index 100% rename from tests/utils/connectionStringParser.test.ts rename to packages/web-ui/tests/utils/connectionStringParser.test.ts diff --git a/tests/utils/connectionTest.test.ts b/packages/web-ui/tests/utils/connectionTest.test.ts similarity index 100% rename from tests/utils/connectionTest.test.ts rename to packages/web-ui/tests/utils/connectionTest.test.ts diff --git a/tests/utils/connections.test.ts b/packages/web-ui/tests/utils/connections.test.ts similarity index 100% rename from tests/utils/connections.test.ts rename to packages/web-ui/tests/utils/connections.test.ts diff --git a/tests/utils/contextMenu.test.ts b/packages/web-ui/tests/utils/contextMenu.test.ts similarity index 100% rename from tests/utils/contextMenu.test.ts rename to packages/web-ui/tests/utils/contextMenu.test.ts diff --git a/tests/utils/createTable.test.ts b/packages/web-ui/tests/utils/createTable.test.ts similarity index 100% rename from tests/utils/createTable.test.ts rename to packages/web-ui/tests/utils/createTable.test.ts diff --git a/packages/web-ui/tests/utils/credentials.test.ts b/packages/web-ui/tests/utils/credentials.test.ts new file mode 100644 index 000000000..50a3eb78c --- /dev/null +++ b/packages/web-ui/tests/utils/credentials.test.ts @@ -0,0 +1,36 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import type {TypedCommandCaller} from '@/api/contract'; +import {fetchConnectionWithCredentials} from '@/utils/credentials'; + +describe('credentials', () => { + const call = vi.fn(); + const client = {call} as Pick; + + beforeEach(() => { + call.mockReset(); + }); + + describe('fetchConnectionWithCredentials', () => { + it('calls get_connection_by_id with the supplied id', async () => { + const mockConnection = { + id: 'abc', + name: 'Test', + params: {driver: 'mysql', password: 'secret', database: 'mydb'}, + }; + call.mockResolvedValueOnce(mockConnection); + + const result = await fetchConnectionWithCredentials(client, 'abc'); + + expect(call).toHaveBeenCalledWith('get_connection_by_id', {id: 'abc'}); + expect(result).toEqual(mockConnection); + }); + + it('propagates backend errors', async () => { + call.mockRejectedValueOnce('Connection not found'); + + await expect(fetchConnectionWithCredentials(client, 'unknown')).rejects.toBe( + 'Connection not found', + ); + }); + }); +}); diff --git a/tests/utils/dataGrid.test.ts b/packages/web-ui/tests/utils/dataGrid.test.ts similarity index 100% rename from tests/utils/dataGrid.test.ts rename to packages/web-ui/tests/utils/dataGrid.test.ts diff --git a/tests/utils/dataGridCell.test.tsx b/packages/web-ui/tests/utils/dataGridCell.test.tsx similarity index 100% rename from tests/utils/dataGridCell.test.tsx rename to packages/web-ui/tests/utils/dataGridCell.test.tsx diff --git a/packages/web-ui/tests/utils/dataImportFile.test.ts b/packages/web-ui/tests/utils/dataImportFile.test.ts new file mode 100644 index 000000000..79ba2caa6 --- /dev/null +++ b/packages/web-ui/tests/utils/dataImportFile.test.ts @@ -0,0 +1,38 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DATA_IMPORT_FILE_LIMIT, readDataImportFile} from '@/utils/dataImportFile'; +const readInputFile = vi.fn(); +const platform = {readInputFile}; +const file = (name = 'data.csv') => ({name, reference: 'opaque-reference'}); +describe('readDataImportFile', () => { + beforeEach(() => { + readInputFile.mockReset(); + readInputFile.mockResolvedValue(new TextEncoder().encode('a,b\n1,2')); + }); + it.each(['csv', 'tsv', 'json', 'md', 'CSV'])( + 'reads supported %s files through opaque references', + async (ext) => { + expect(await readDataImportFile(file(`data.${ext}`), platform)).toBe('a,b\n1,2'); + expect(readInputFile).toHaveBeenCalledWith('opaque-reference'); + }, + ); + it('rejects oversized bytes before text decoding', async () => { + readInputFile.mockResolvedValue(new Uint8Array(DATA_IMPORT_FILE_LIMIT + 1)); + await expect(readDataImportFile(file(), platform)).rejects.toMatchObject({ + code: 'tooLarge', + }); + }); + it('accepts the exact byte limit', async () => { + readInputFile.mockResolvedValue(new Uint8Array(DATA_IMPORT_FILE_LIMIT)); + expect((await readDataImportFile(file(), platform)).length).toBe(DATA_IMPORT_FILE_LIMIT); + }); + it('rejects unsupported extensions before reading', async () => { + await expect(readDataImportFile(file('data.exe'), platform)).rejects.toMatchObject({ + code: 'unsupported', + }); + expect(readInputFile).not.toHaveBeenCalled(); + }); + it('propagates read errors', async () => { + readInputFile.mockRejectedValue(new Error('Permission denied')); + await expect(readDataImportFile(file(), platform)).rejects.toThrow('Permission denied'); + }); +}); diff --git a/tests/utils/database.test.ts b/packages/web-ui/tests/utils/database.test.ts similarity index 100% rename from tests/utils/database.test.ts rename to packages/web-ui/tests/utils/database.test.ts diff --git a/tests/utils/databaseBackup.test.ts b/packages/web-ui/tests/utils/databaseBackup.test.ts similarity index 100% rename from tests/utils/databaseBackup.test.ts rename to packages/web-ui/tests/utils/databaseBackup.test.ts diff --git a/tests/utils/databaseObjectActions.test.ts b/packages/web-ui/tests/utils/databaseObjectActions.test.ts similarity index 97% rename from tests/utils/databaseObjectActions.test.ts rename to packages/web-ui/tests/utils/databaseObjectActions.test.ts index 46cf40ac3..f446ff5cc 100644 --- a/tests/utils/databaseObjectActions.test.ts +++ b/packages/web-ui/tests/utils/databaseObjectActions.test.ts @@ -1,5 +1,6 @@ import {invoke} from '@tauri-apps/api/core'; import {describe, expect, it, vi} from 'vitest'; +import {TauriTransport} from '@/api/transports/tauriTransport'; import { createDefinitionRequest, @@ -181,8 +182,10 @@ describe('definition actions', () => { .mockResolvedValueOnce('routine sql') .mockResolvedValueOnce('trigger sql'); + const client = new TauriTransport(); + await expect( - loadRoutineDefinition({ + loadRoutineDefinition(client, { connectionId: 'connection-b', routineName: 'refresh_orders', routineType: 'FUNCTION', @@ -190,7 +193,7 @@ describe('definition actions', () => { }), ).resolves.toBe('routine sql'); await expect( - loadTriggerDefinition({ + loadTriggerDefinition(client, { connectionId: 'connection-b', triggerName: 'audit_orders', tableName: 'orders', diff --git a/packages/web-ui/tests/utils/databaseTransfers.test.ts b/packages/web-ui/tests/utils/databaseTransfers.test.ts new file mode 100644 index 000000000..c71b0d708 --- /dev/null +++ b/packages/web-ui/tests/utils/databaseTransfers.test.ts @@ -0,0 +1,106 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {prepareDatabaseImportSource, runDatabaseDump} from '@/utils/databaseTransfers'; + +function asClient(value: object): TabularisClient { + return value as unknown as TabularisClient; +} + +function asPlatform(value: object): PlatformCapabilities { + return value as unknown as PlatformCapabilities; +} + +describe('databaseTransfers', () => { + it('uploads browser imports with a purpose-bound opaque token', async () => { + const uploadFile = vi.fn().mockResolvedValue({token: 'upload-token'}); + const readInputBlob = vi.fn().mockResolvedValue(new Blob(['SELECT 1;'])); + + await expect( + prepareDatabaseImportSource( + asClient({uploadFile}), + asPlatform({ + negotiation: {environment: 'browser'}, + readInputBlob, + }), + {name: 'backup.sql', reference: 'browser-file:1'}, + ), + ).resolves.toEqual({uploadToken: 'upload-token'}); + + expect(uploadFile).toHaveBeenCalledWith( + expect.objectContaining({ + fileName: 'backup.sql', + purpose: 'database-import', + }), + ); + }); + + it('keeps desktop import paths local to the Tauri adapter', async () => { + await expect( + prepareDatabaseImportSource( + asClient({}), + asPlatform({negotiation: {environment: 'tauri'}}), + {name: 'backup.sql', reference: '/tmp/backup.sql'}, + ), + ).resolves.toEqual({filePath: '/tmp/backup.sql'}); + }); + + it('requests and saves a streamed browser dump download', async () => { + const call = vi.fn().mockResolvedValue({ + kind: 'download', + fileName: 'database.sql', + mimeType: 'application/sql', + token: 'download-token', + size: 42, + }); + const requestDownload = vi.fn().mockResolvedValue(undefined); + + await expect( + runDatabaseDump( + asClient({call, requestDownload}), + asPlatform({negotiation: {environment: 'browser'}}), + { + connectionId: 'connection-1', + options: {structure: true, data: true, tables: ['users']}, + }, + 'database.sql', + ), + ).resolves.toBe(true); + + expect(call).toHaveBeenCalledWith( + 'dump_database', + { + connectionId: 'connection-1', + options: {structure: true, data: true, tables: ['users']}, + }, + expect.any(Object), + ); + expect(requestDownload).toHaveBeenCalledWith('download-token'); + }); + + it('uses a native save target without exposing a browser download', async () => { + const chooseSaveTarget = vi.fn().mockResolvedValue({reference: '/tmp/database.sql'}); + const call = vi.fn().mockResolvedValue(null); + + await expect( + runDatabaseDump( + asClient({call}), + asPlatform({ + negotiation: {environment: 'tauri'}, + chooseSaveTarget, + }), + { + connectionId: 'connection-1', + options: {structure: true, data: false}, + }, + 'database.sql', + ), + ).resolves.toBe(true); + + expect(call).toHaveBeenCalledWith( + 'dump_database', + expect.objectContaining({filePath: '/tmp/database.sql'}), + expect.any(Object), + ); + }); +}); diff --git a/tests/utils/dateGroups.test.ts b/packages/web-ui/tests/utils/dateGroups.test.ts similarity index 100% rename from tests/utils/dateGroups.test.ts rename to packages/web-ui/tests/utils/dateGroups.test.ts diff --git a/tests/utils/dateInput.test.ts b/packages/web-ui/tests/utils/dateInput.test.ts similarity index 100% rename from tests/utils/dateInput.test.ts rename to packages/web-ui/tests/utils/dateInput.test.ts diff --git a/tests/utils/derivedTables.test.ts b/packages/web-ui/tests/utils/derivedTables.test.ts similarity index 100% rename from tests/utils/derivedTables.test.ts rename to packages/web-ui/tests/utils/derivedTables.test.ts diff --git a/tests/utils/driverCapabilities.test.ts b/packages/web-ui/tests/utils/driverCapabilities.test.ts similarity index 100% rename from tests/utils/driverCapabilities.test.ts rename to packages/web-ui/tests/utils/driverCapabilities.test.ts diff --git a/tests/utils/driverUI.test.tsx b/packages/web-ui/tests/utils/driverUI.test.tsx similarity index 100% rename from tests/utils/driverUI.test.tsx rename to packages/web-ui/tests/utils/driverUI.test.tsx diff --git a/tests/utils/dropTable.test.ts b/packages/web-ui/tests/utils/dropTable.test.ts similarity index 96% rename from tests/utils/dropTable.test.ts rename to packages/web-ui/tests/utils/dropTable.test.ts index e09d1cea4..72e1220ad 100644 --- a/tests/utils/dropTable.test.ts +++ b/packages/web-ui/tests/utils/dropTable.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect, vi} from 'vitest'; import {buildDropTableSql, resolveDropTableSql} from '@/utils/dropTable'; -import manifestSchema from '../../plugins/manifest.schema.json'; -import extensionsSchema from '../../plugins/tabularium-extensions.schema.json'; +import manifestSchema from '../../../../plugins/manifest.schema.json'; +import extensionsSchema from '../../../../plugins/tabularium-extensions.schema.json'; import type {DriverCapabilities} from '@/types/plugins'; const backtickPlugin: DriverCapabilities = { diff --git a/tests/utils/dropdownPosition.test.ts b/packages/web-ui/tests/utils/dropdownPosition.test.ts similarity index 100% rename from tests/utils/dropdownPosition.test.ts rename to packages/web-ui/tests/utils/dropdownPosition.test.ts diff --git a/tests/utils/dumpUtils.test.ts b/packages/web-ui/tests/utils/dumpUtils.test.ts similarity index 100% rename from tests/utils/dumpUtils.test.ts rename to packages/web-ui/tests/utils/dumpUtils.test.ts diff --git a/tests/utils/editor.test.ts b/packages/web-ui/tests/utils/editor.test.ts similarity index 100% rename from tests/utils/editor.test.ts rename to packages/web-ui/tests/utils/editor.test.ts diff --git a/tests/utils/editorCommands.test.ts b/packages/web-ui/tests/utils/editorCommands.test.ts similarity index 100% rename from tests/utils/editorCommands.test.ts rename to packages/web-ui/tests/utils/editorCommands.test.ts diff --git a/tests/utils/editorFontSize.test.ts b/packages/web-ui/tests/utils/editorFontSize.test.ts similarity index 100% rename from tests/utils/editorFontSize.test.ts rename to packages/web-ui/tests/utils/editorFontSize.test.ts diff --git a/tests/utils/editorNavigation.test.ts b/packages/web-ui/tests/utils/editorNavigation.test.ts similarity index 100% rename from tests/utils/editorNavigation.test.ts rename to packages/web-ui/tests/utils/editorNavigation.test.ts diff --git a/tests/utils/environment.test.ts b/packages/web-ui/tests/utils/environment.test.ts similarity index 100% rename from tests/utils/environment.test.ts rename to packages/web-ui/tests/utils/environment.test.ts diff --git a/tests/utils/errors.test.ts b/packages/web-ui/tests/utils/errors.test.ts similarity index 100% rename from tests/utils/errors.test.ts rename to packages/web-ui/tests/utils/errors.test.ts diff --git a/tests/utils/explainImport.test.ts b/packages/web-ui/tests/utils/explainImport.test.ts similarity index 100% rename from tests/utils/explainImport.test.ts rename to packages/web-ui/tests/utils/explainImport.test.ts diff --git a/tests/utils/explainRaw.test.ts b/packages/web-ui/tests/utils/explainRaw.test.ts similarity index 77% rename from tests/utils/explainRaw.test.ts rename to packages/web-ui/tests/utils/explainRaw.test.ts index f9ebd1391..15f4cbc6b 100644 --- a/tests/utils/explainRaw.test.ts +++ b/packages/web-ui/tests/utils/explainRaw.test.ts @@ -8,6 +8,7 @@ import { getRawExplainFormatLabel, saveRawExplainOutput, } from '@/utils/explainRaw'; +import type {PlatformCapabilities} from '@/platform/capabilities'; describe('explainRaw', () => { describe('detectRawExplainLanguage', () => { @@ -158,64 +159,57 @@ describe('explainRaw', () => { }); describe('saveRawExplainOutput', () => { - it('writes original content without modification to the chosen file path', async () => { - const saveDialog = vi.fn().mockResolvedValue('/tmp/saved_explain.json'); - const writeFile = vi.fn().mockResolvedValue(undefined); + function platformWith(downloadFile: ReturnType) { + return {downloadFile} as unknown as PlatformCapabilities; + } + + it('downloads the original content without modification', async () => { + const downloadFile = vi.fn().mockResolvedValue(true); const raw = '{"query_block": {"cost": 10.5}}'; - const result = await saveRawExplainOutput(raw, {saveDialog, writeFile}); + const result = await saveRawExplainOutput(platformWith(downloadFile), raw); expect(result).toBe(true); - expect(saveDialog).toHaveBeenCalledWith({ - defaultPath: 'explain.json', + // Content must match the original raw string exactly, not reformatted + expect(downloadFile).toHaveBeenCalledExactlyOnceWith({ + fileName: 'explain.json', + contents: new TextEncoder().encode(raw), + mimeType: 'application/json', + title: undefined, filters: [ {name: 'JSON', extensions: ['json']}, {name: 'All files', extensions: ['*']}, ], }); - // Content must match the original raw string exactly, not reformatted - expect(writeFile).toHaveBeenCalledWith('/tmp/saved_explain.json', raw); }); it('preserves unformatted single-line XML when saving', async () => { - const saveDialog = vi.fn().mockResolvedValue('/tmp/plan.xml'); - const writeFile = vi.fn().mockResolvedValue(undefined); + const downloadFile = vi.fn().mockResolvedValue(true); const singleLineXml = ''; - const result = await saveRawExplainOutput(singleLineXml, {saveDialog, writeFile}); - - expect(result).toBe(true); - expect(writeFile).toHaveBeenCalledWith('/tmp/plan.xml', singleLineXml); - }); - - it('returns false and does not write when user cancels dialog', async () => { - const saveDialog = vi.fn().mockResolvedValue(null); - const writeFile = vi.fn(); - - const result = await saveRawExplainOutput('{"test": true}', {saveDialog, writeFile}); + await saveRawExplainOutput(platformWith(downloadFile), singleLineXml); - expect(result).toBe(false); - expect(saveDialog).toHaveBeenCalled(); - expect(writeFile).not.toHaveBeenCalled(); + expect(downloadFile).toHaveBeenCalledWith( + expect.objectContaining({ + fileName: 'explain.xml', + contents: new TextEncoder().encode(singleLineXml), + }), + ); }); - it('propagates dialog rejection', async () => { - const saveDialog = vi.fn().mockRejectedValue(new Error('dialog cancelled by OS')); - const writeFile = vi.fn(); + it('returns false when the user cancels', async () => { + const downloadFile = vi.fn().mockResolvedValue(false); await expect( - saveRawExplainOutput('raw content', {saveDialog, writeFile}), - ).rejects.toThrow('dialog cancelled by OS'); - - expect(writeFile).not.toHaveBeenCalled(); + saveRawExplainOutput(platformWith(downloadFile), '{"test": true}'), + ).resolves.toBe(false); }); - it('propagates file write rejection', async () => { - const saveDialog = vi.fn().mockResolvedValue('/read-only/path.txt'); - const writeFile = vi.fn().mockRejectedValue(new Error('permission denied')); + it('propagates download rejection', async () => { + const downloadFile = vi.fn().mockRejectedValue(new Error('permission denied')); await expect( - saveRawExplainOutput('raw content', {saveDialog, writeFile}), + saveRawExplainOutput(platformWith(downloadFile), 'raw content'), ).rejects.toThrow('permission denied'); }); }); diff --git a/tests/utils/explainTableExport.test.ts b/packages/web-ui/tests/utils/explainTableExport.test.ts similarity index 87% rename from tests/utils/explainTableExport.test.ts rename to packages/web-ui/tests/utils/explainTableExport.test.ts index 0b42c487a..e656230b3 100644 --- a/tests/utils/explainTableExport.test.ts +++ b/packages/web-ui/tests/utils/explainTableExport.test.ts @@ -5,8 +5,7 @@ import { saveExplainTableCsv, EXPLAIN_TABLE_CSV_HEADERS, } from '@/utils/explainTableExport'; -import {save} from '@tauri-apps/plugin-dialog'; -import {writeTextFile} from '@tauri-apps/plugin-fs'; +import type {PlatformCapabilities} from '@/platform/capabilities'; function makeNode(overrides: Partial = {}): ExplainNode { return { @@ -213,37 +212,35 @@ describe('explainTableExport', () => { }); describe('saveExplainTableCsv', () => { - it('returns false without writing if user cancels the save dialog', async () => { - vi.mocked(save).mockResolvedValueOnce(null); - const plan = makePlan(); + it('returns false when the user cancels the download', async () => { + const downloadFile = vi.fn().mockResolvedValue(false); + const platform = {downloadFile} as unknown as PlatformCapabilities; - const result = await saveExplainTableCsv(plan); + const result = await saveExplainTableCsv(platform, makePlan()); expect(result).toBe(false); - expect(save).toHaveBeenCalledWith({ - defaultPath: 'explain-plan.csv', - filters: [{name: 'CSV', extensions: ['csv']}], - }); - expect(writeTextFile).not.toHaveBeenCalled(); + expect(downloadFile).toHaveBeenCalledWith( + expect.objectContaining({ + fileName: 'explain-plan.csv', + filters: [{name: 'CSV', extensions: ['csv']}], + }), + ); }); - it('writes formatted CSV to selected path and returns true on confirmation', async () => { - vi.mocked(save).mockResolvedValueOnce('/path/to/my-plan.csv'); + it('downloads the formatted CSV under the given file name', async () => { + const downloadFile = vi.fn().mockResolvedValue(true); + const platform = {downloadFile} as unknown as PlatformCapabilities; const plan = makePlan({ root: makeNode({id: 'root', node_type: 'Limit', total_cost: 10}), }); - const result = await saveExplainTableCsv(plan, undefined, 'custom.csv'); + const result = await saveExplainTableCsv(platform, plan, undefined, 'custom.csv'); expect(result).toBe(true); - expect(save).toHaveBeenCalledWith({ - defaultPath: 'custom.csv', - filters: [{name: 'CSV', extensions: ['csv']}], - }); - expect(writeTextFile).toHaveBeenCalledWith( - '/path/to/my-plan.csv', - expect.stringContaining('index,depth,node_type'), - ); + const request = downloadFile.mock.calls[0][0]; + expect(request.fileName).toBe('custom.csv'); + expect(request.mimeType).toBe('text/csv'); + expect(new TextDecoder().decode(request.contents)).toContain('index,depth,node_type'); }); }); }); diff --git a/tests/utils/exportFileName.test.ts b/packages/web-ui/tests/utils/exportFileName.test.ts similarity index 100% rename from tests/utils/exportFileName.test.ts rename to packages/web-ui/tests/utils/exportFileName.test.ts diff --git a/packages/web-ui/tests/utils/fileDownloads.test.ts b/packages/web-ui/tests/utils/fileDownloads.test.ts new file mode 100644 index 000000000..5ef1c4d0a --- /dev/null +++ b/packages/web-ui/tests/utils/fileDownloads.test.ts @@ -0,0 +1,52 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {downloadGeneratedFile, downloadTextFile} from '@/utils/fileDownloads'; + +function fixture() { + const requestDownload = vi.fn().mockResolvedValue(undefined); + const downloadFile = vi.fn().mockResolvedValue(true); + return { + client: {requestDownload} as unknown as TabularisClient, + platform: {downloadFile} as unknown as PlatformCapabilities, + requestDownload, + downloadFile, + }; +} + +describe('fileDownloads', () => { + it('starts token downloads without buffering their contents in the UI', async () => { + const {client, platform, requestDownload, downloadFile} = fixture(); + + await expect( + downloadGeneratedFile(client, platform, { + kind: 'download', + fileName: 'large.csv', + mimeType: 'text/csv', + token: 'opaque-token', + size: 50_000_000, + }), + ).resolves.toBe(true); + + expect(requestDownload).toHaveBeenCalledWith('opaque-token'); + expect(downloadFile).not.toHaveBeenCalled(); + }); + + it('encodes inline text through the semantic platform capability', async () => { + const {platform, downloadFile} = fixture(); + await downloadTextFile(platform, { + fileName: 'schema.dbml', + contents: 'Table users {}', + mimeType: 'text/plain', + filters: [{name: 'DBML', extensions: ['dbml']}], + }); + + expect(downloadFile).toHaveBeenCalledWith({ + fileName: 'schema.dbml', + contents: new TextEncoder().encode('Table users {}'), + mimeType: 'text/plain', + title: undefined, + filters: [{name: 'DBML', extensions: ['dbml']}], + }); + }); +}); diff --git a/tests/utils/filterBar.test.ts b/packages/web-ui/tests/utils/filterBar.test.ts similarity index 99% rename from tests/utils/filterBar.test.ts rename to packages/web-ui/tests/utils/filterBar.test.ts index 86ad195ae..e8dd8d544 100644 --- a/tests/utils/filterBar.test.ts +++ b/packages/web-ui/tests/utils/filterBar.test.ts @@ -1,5 +1,5 @@ import {describe, it, expect} from 'vitest'; -import {GOOGLESQL_CAPS} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL_CAPS} from '../../../../tests/fixtures/sql-syntax/googlesql'; import { filterColumnSuggestions, getCurrentWordPrefix, diff --git a/tests/utils/findUnsupportedFeatures.test.ts b/packages/web-ui/tests/utils/findUnsupportedFeatures.test.ts similarity index 100% rename from tests/utils/findUnsupportedFeatures.test.ts rename to packages/web-ui/tests/utils/findUnsupportedFeatures.test.ts diff --git a/tests/utils/foreignKeys.test.ts b/packages/web-ui/tests/utils/foreignKeys.test.ts similarity index 99% rename from tests/utils/foreignKeys.test.ts rename to packages/web-ui/tests/utils/foreignKeys.test.ts index 7218f18cc..4c6028db6 100644 --- a/tests/utils/foreignKeys.test.ts +++ b/packages/web-ui/tests/utils/foreignKeys.test.ts @@ -1,5 +1,5 @@ import {describe, it, expect} from 'vitest'; -import {GOOGLESQL_CAPS} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL_CAPS} from '../../../../tests/fixtures/sql-syntax/googlesql'; import type {ForeignKey} from '@/types/schema'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; import { diff --git a/tests/utils/formatTime.test.ts b/packages/web-ui/tests/utils/formatTime.test.ts similarity index 100% rename from tests/utils/formatTime.test.ts rename to packages/web-ui/tests/utils/formatTime.test.ts diff --git a/tests/utils/fsPath.test.ts b/packages/web-ui/tests/utils/fsPath.test.ts similarity index 100% rename from tests/utils/fsPath.test.ts rename to packages/web-ui/tests/utils/fsPath.test.ts diff --git a/tests/utils/fuzzy.test.ts b/packages/web-ui/tests/utils/fuzzy.test.ts similarity index 100% rename from tests/utils/fuzzy.test.ts rename to packages/web-ui/tests/utils/fuzzy.test.ts diff --git a/tests/utils/geometry.test.ts b/packages/web-ui/tests/utils/geometry.test.ts similarity index 100% rename from tests/utils/geometry.test.ts rename to packages/web-ui/tests/utils/geometry.test.ts diff --git a/tests/utils/geometryInput.test.ts b/packages/web-ui/tests/utils/geometryInput.test.ts similarity index 100% rename from tests/utils/geometryInput.test.ts rename to packages/web-ui/tests/utils/geometryInput.test.ts diff --git a/tests/utils/graphLayout.test.ts b/packages/web-ui/tests/utils/graphLayout.test.ts similarity index 100% rename from tests/utils/graphLayout.test.ts rename to packages/web-ui/tests/utils/graphLayout.test.ts diff --git a/tests/utils/gridUndo.test.ts b/packages/web-ui/tests/utils/gridUndo.test.ts similarity index 100% rename from tests/utils/gridUndo.test.ts rename to packages/web-ui/tests/utils/gridUndo.test.ts diff --git a/tests/utils/groupTree.test.ts b/packages/web-ui/tests/utils/groupTree.test.ts similarity index 100% rename from tests/utils/groupTree.test.ts rename to packages/web-ui/tests/utils/groupTree.test.ts diff --git a/tests/utils/identifiers.test.ts b/packages/web-ui/tests/utils/identifiers.test.ts similarity index 100% rename from tests/utils/identifiers.test.ts rename to packages/web-ui/tests/utils/identifiers.test.ts diff --git a/tests/utils/json.test.ts b/packages/web-ui/tests/utils/json.test.ts similarity index 100% rename from tests/utils/json.test.ts rename to packages/web-ui/tests/utils/json.test.ts diff --git a/tests/utils/jsonHighlight.test.ts b/packages/web-ui/tests/utils/jsonHighlight.test.ts similarity index 100% rename from tests/utils/jsonHighlight.test.ts rename to packages/web-ui/tests/utils/jsonHighlight.test.ts diff --git a/tests/utils/jsonTree.test.ts b/packages/web-ui/tests/utils/jsonTree.test.ts similarity index 100% rename from tests/utils/jsonTree.test.ts rename to packages/web-ui/tests/utils/jsonTree.test.ts diff --git a/tests/utils/jsonValueDecorators.test.ts b/packages/web-ui/tests/utils/jsonValueDecorators.test.ts similarity index 100% rename from tests/utils/jsonValueDecorators.test.ts rename to packages/web-ui/tests/utils/jsonValueDecorators.test.ts diff --git a/tests/utils/k8s.test.ts b/packages/web-ui/tests/utils/k8s.test.ts similarity index 99% rename from tests/utils/k8s.test.ts rename to packages/web-ui/tests/utils/k8s.test.ts index 89f791bcb..37b7f28b0 100644 --- a/tests/utils/k8s.test.ts +++ b/packages/web-ui/tests/utils/k8s.test.ts @@ -214,7 +214,7 @@ describe('k8s', () => { const result = await getK8sContexts(); - expect(invoke).toHaveBeenCalledWith('get_k8s_contexts_cmd'); + expect(invoke).toHaveBeenCalledWith('get_k8s_contexts_cmd', undefined); expect(result).toEqual(['minikube', 'gke_project_cluster']); }); diff --git a/tests/utils/keybindings.test.ts b/packages/web-ui/tests/utils/keybindings.test.ts similarity index 100% rename from tests/utils/keybindings.test.ts rename to packages/web-ui/tests/utils/keybindings.test.ts diff --git a/tests/utils/keyboardEvents.test.ts b/packages/web-ui/tests/utils/keyboardEvents.test.ts similarity index 100% rename from tests/utils/keyboardEvents.test.ts rename to packages/web-ui/tests/utils/keyboardEvents.test.ts diff --git a/tests/utils/localThemePlugins.test.ts b/packages/web-ui/tests/utils/localThemePlugins.test.ts similarity index 100% rename from tests/utils/localThemePlugins.test.ts rename to packages/web-ui/tests/utils/localThemePlugins.test.ts diff --git a/tests/utils/mcpApprovalAttention.test.ts b/packages/web-ui/tests/utils/mcpApprovalAttention.test.ts similarity index 89% rename from tests/utils/mcpApprovalAttention.test.ts rename to packages/web-ui/tests/utils/mcpApprovalAttention.test.ts index dcc3e5095..7417221cd 100644 --- a/tests/utils/mcpApprovalAttention.test.ts +++ b/packages/web-ui/tests/utils/mcpApprovalAttention.test.ts @@ -1,11 +1,6 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; -import { - isPermissionGranted, - requestPermission, - sendNotification, -} from '@tauri-apps/plugin-notification'; - const getCurrentWindow = vi.fn(); +const notify = vi.fn().mockResolvedValue('shown'); vi.mock('@tauri-apps/api/window', () => ({ UserAttentionType: { @@ -19,6 +14,7 @@ describe('mcpApprovalAttention', () => { beforeEach(() => { vi.resetAllMocks(); vi.resetModules(); + notify.mockResolvedValue('shown'); }); it('restores minimized and hidden state after approval attention', async () => { @@ -114,10 +110,6 @@ describe('mcpApprovalAttention', () => { }); it('sends native notifications and still plays the short alert sound', async () => { - vi.mocked(isPermissionGranted).mockResolvedValue(true); - vi.mocked(requestPermission).mockResolvedValue('granted'); - vi.mocked(sendNotification).mockResolvedValue(undefined); - const setValueAtTime = vi.fn(); const exponentialRampToValueAtTime = vi.fn(); const connect = vi.fn(); @@ -157,12 +149,15 @@ describe('mcpApprovalAttention', () => { const attention = await import('@/utils/mcpApprovalAttention'); - await attention.notifyApprovalRequest({ - title: 'Approval needed', - body: 'Review pending approval', - }); + await attention.notifyApprovalRequest( + { + title: 'Approval needed', + body: 'Review pending approval', + }, + {notify}, + ); - expect(sendNotification).toHaveBeenCalledWith({ + expect(notify).toHaveBeenCalledWith({ title: 'Approval needed', body: 'Review pending approval', }); @@ -178,10 +173,6 @@ describe('mcpApprovalAttention', () => { value: 'Linux x86_64', }); - vi.mocked(isPermissionGranted).mockResolvedValue(true); - vi.mocked(requestPermission).mockResolvedValue('granted'); - vi.mocked(sendNotification).mockResolvedValue(undefined); - const audioContext = vi.fn(); Object.defineProperty(window, 'AudioContext', { configurable: true, @@ -190,12 +181,15 @@ describe('mcpApprovalAttention', () => { const attention = await import('@/utils/mcpApprovalAttention'); - await attention.notifyApprovalRequest({ - title: 'Approval needed', - body: 'Review pending approval', - }); + await attention.notifyApprovalRequest( + { + title: 'Approval needed', + body: 'Review pending approval', + }, + {notify}, + ); - expect(sendNotification).toHaveBeenCalledWith({ + expect(notify).toHaveBeenCalledWith({ title: 'Approval needed', body: 'Review pending approval', sound: 'message-new-instant', @@ -211,8 +205,7 @@ describe('mcpApprovalAttention', () => { }); it('still plays the short alert sound when notification permission is denied', async () => { - vi.mocked(isPermissionGranted).mockResolvedValue(false); - vi.mocked(requestPermission).mockResolvedValue('denied'); + notify.mockResolvedValue('permission-denied'); const createOscillator = vi.fn(() => ({ type: '', @@ -245,12 +238,15 @@ describe('mcpApprovalAttention', () => { const attention = await import('@/utils/mcpApprovalAttention'); - await attention.notifyApprovalRequest({ - title: 'Approval needed', - body: 'Review pending approval', - }); + await attention.notifyApprovalRequest( + { + title: 'Approval needed', + body: 'Review pending approval', + }, + {notify}, + ); - expect(sendNotification).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledOnce(); expect(audioContext).toHaveBeenCalledTimes(1); expect(createOscillator).toHaveBeenCalledTimes(1); }); @@ -307,9 +303,6 @@ describe('mcpApprovalAttention', () => { }); it('resumes suspended audio contexts before playing the short alert sound', async () => { - vi.mocked(isPermissionGranted).mockResolvedValue(true); - vi.mocked(sendNotification).mockResolvedValue(undefined); - const setValueAtTime = vi.fn(); const exponentialRampToValueAtTime = vi.fn(); const connect = vi.fn(); @@ -353,10 +346,13 @@ describe('mcpApprovalAttention', () => { const attention = await import('@/utils/mcpApprovalAttention'); - await attention.notifyApprovalRequest({ - title: 'Approval needed', - body: 'Review pending approval', - }); + await attention.notifyApprovalRequest( + { + title: 'Approval needed', + body: 'Review pending approval', + }, + {notify}, + ); await Promise.resolve(); diff --git a/tests/utils/minimax.test.ts b/packages/web-ui/tests/utils/minimax.test.ts similarity index 100% rename from tests/utils/minimax.test.ts rename to packages/web-ui/tests/utils/minimax.test.ts diff --git a/tests/utils/monaco.test.ts b/packages/web-ui/tests/utils/monaco.test.ts similarity index 100% rename from tests/utils/monaco.test.ts rename to packages/web-ui/tests/utils/monaco.test.ts diff --git a/tests/utils/monacoInputArea.test.ts b/packages/web-ui/tests/utils/monacoInputArea.test.ts similarity index 100% rename from tests/utils/monacoInputArea.test.ts rename to packages/web-ui/tests/utils/monacoInputArea.test.ts diff --git a/tests/utils/multiResult.test.ts b/packages/web-ui/tests/utils/multiResult.test.ts similarity index 100% rename from tests/utils/multiResult.test.ts rename to packages/web-ui/tests/utils/multiResult.test.ts diff --git a/tests/utils/newConsole.test.ts b/packages/web-ui/tests/utils/newConsole.test.ts similarity index 100% rename from tests/utils/newConsole.test.ts rename to packages/web-ui/tests/utils/newConsole.test.ts diff --git a/tests/utils/notebook.test.ts b/packages/web-ui/tests/utils/notebook.test.ts similarity index 100% rename from tests/utils/notebook.test.ts rename to packages/web-ui/tests/utils/notebook.test.ts diff --git a/tests/utils/notebookChart.test.ts b/packages/web-ui/tests/utils/notebookChart.test.ts similarity index 100% rename from tests/utils/notebookChart.test.ts rename to packages/web-ui/tests/utils/notebookChart.test.ts diff --git a/tests/utils/notebookDnd.test.ts b/packages/web-ui/tests/utils/notebookDnd.test.ts similarity index 100% rename from tests/utils/notebookDnd.test.ts rename to packages/web-ui/tests/utils/notebookDnd.test.ts diff --git a/tests/utils/notebookFile.test.ts b/packages/web-ui/tests/utils/notebookFile.test.ts similarity index 100% rename from tests/utils/notebookFile.test.ts rename to packages/web-ui/tests/utils/notebookFile.test.ts diff --git a/tests/utils/notebookHistory.test.ts b/packages/web-ui/tests/utils/notebookHistory.test.ts similarity index 100% rename from tests/utils/notebookHistory.test.ts rename to packages/web-ui/tests/utils/notebookHistory.test.ts diff --git a/tests/utils/notebookHtmlExport.test.ts b/packages/web-ui/tests/utils/notebookHtmlExport.test.ts similarity index 100% rename from tests/utils/notebookHtmlExport.test.ts rename to packages/web-ui/tests/utils/notebookHtmlExport.test.ts diff --git a/tests/utils/notebookOutline.test.ts b/packages/web-ui/tests/utils/notebookOutline.test.ts similarity index 100% rename from tests/utils/notebookOutline.test.ts rename to packages/web-ui/tests/utils/notebookOutline.test.ts diff --git a/tests/utils/notebookParams.test.ts b/packages/web-ui/tests/utils/notebookParams.test.ts similarity index 100% rename from tests/utils/notebookParams.test.ts rename to packages/web-ui/tests/utils/notebookParams.test.ts diff --git a/tests/utils/notebookQueryPlanFixture.test.ts b/packages/web-ui/tests/utils/notebookQueryPlanFixture.test.ts similarity index 95% rename from tests/utils/notebookQueryPlanFixture.test.ts rename to packages/web-ui/tests/utils/notebookQueryPlanFixture.test.ts index 4555d60b1..24f5a5aff 100644 --- a/tests/utils/notebookQueryPlanFixture.test.ts +++ b/packages/web-ui/tests/utils/notebookQueryPlanFixture.test.ts @@ -6,7 +6,7 @@ import {resolveParams} from '@/utils/notebookParams'; import {resolveQueryVariables} from '@/utils/notebookVariables'; const fixture = readFileSync( - resolve(__dirname, '../fixtures/notebook-query-plan.tabularis-notebook'), + resolve(__dirname, '../../../../tests/fixtures/notebook-query-plan.tabularis-notebook'), 'utf8', ); diff --git a/tests/utils/notebookRunAll.test.ts b/packages/web-ui/tests/utils/notebookRunAll.test.ts similarity index 100% rename from tests/utils/notebookRunAll.test.ts rename to packages/web-ui/tests/utils/notebookRunAll.test.ts diff --git a/tests/utils/notebookStore.test.ts b/packages/web-ui/tests/utils/notebookStore.test.ts similarity index 80% rename from tests/utils/notebookStore.test.ts rename to packages/web-ui/tests/utils/notebookStore.test.ts index f4ebb6fac..dad36f30d 100644 --- a/tests/utils/notebookStore.test.ts +++ b/packages/web-ui/tests/utils/notebookStore.test.ts @@ -1,13 +1,6 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest'; +import type {TypedCommandCaller} from '@/api/contract'; import type {NotebookState} from '@/types/notebook'; - -// Mock Tauri invoke -vi.mock('@tauri-apps/api/core', () => ({ - invoke: vi.fn(), -})); - -// Import after mock setup -import {invoke} from '@tauri-apps/api/core'; import { getNotebookState, setNotebookState, @@ -24,7 +17,8 @@ import { _resetForTesting, } from '@/utils/notebookStore'; -const mockedInvoke = vi.mocked(invoke); +const call = vi.fn(); +const client = {call} as unknown as TypedCommandCaller; const CONN = 'conn_1'; @@ -40,16 +34,16 @@ function makeState(content = 'SELECT 1'): NotebookState { * the real lifecycle. Seed that association via a (mocked) load returning null. */ async function seedConnection(id: string) { - mockedInvoke.mockResolvedValueOnce(null); - await loadNotebook(id, CONN); + call.mockResolvedValueOnce(null); + await loadNotebook(id, CONN, client); } describe('notebookStore', () => { beforeEach(() => { _resetForTesting(); vi.useFakeTimers(); - mockedInvoke.mockReset(); - mockedInvoke.mockResolvedValue(undefined); + call.mockReset(); + call.mockResolvedValue(undefined); }); afterEach(() => { @@ -71,7 +65,7 @@ describe('notebookStore', () => { describe('debounced save', () => { it('does not save immediately on setNotebookState', () => { setNotebookState('debounce-1', makeState()); - expect(mockedInvoke).not.toHaveBeenCalledWith('save_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('save_notebook', expect.anything()); }); it('saves after debounce period', async () => { @@ -81,7 +75,7 @@ describe('notebookStore', () => { await vi.advanceTimersByTimeAsync(1500); - expect(mockedInvoke).toHaveBeenCalledWith('save_notebook', { + expect(call).toHaveBeenCalledWith('save_notebook', { connectionId: CONN, notebookId: 'debounce-2', content: expect.any(String), @@ -94,18 +88,18 @@ describe('notebookStore', () => { setNotebookState('debounce-3', makeState('SELECT 1')); await vi.advanceTimersByTimeAsync(1000); - expect(mockedInvoke).not.toHaveBeenCalledWith('save_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('save_notebook', expect.anything()); // Second call resets the timer setNotebookState('debounce-3', makeState('SELECT 2')); await vi.advanceTimersByTimeAsync(1000); // Still not saved (only 1000ms since last call) - expect(mockedInvoke).not.toHaveBeenCalledWith('save_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('save_notebook', expect.anything()); await vi.advanceTimersByTimeAsync(500); // Now 1500ms since last call — should save - expect(mockedInvoke).toHaveBeenCalledWith('save_notebook', { + expect(call).toHaveBeenCalledWith('save_notebook', { connectionId: CONN, notebookId: 'debounce-3', content: expect.any(String), @@ -119,7 +113,7 @@ describe('notebookStore', () => { await vi.advanceTimersByTimeAsync(1500); - expect(mockedInvoke).not.toHaveBeenCalledWith('save_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('save_notebook', expect.anything()); }); }); @@ -131,11 +125,11 @@ describe('notebookStore', () => { createdAt: '2026-01-01', cells: [{type: 'sql', content: 'SELECT 42'}], }); - mockedInvoke.mockResolvedValueOnce(fileContent); + call.mockResolvedValueOnce(fileContent); - const state = await loadNotebook('load-1', CONN); + const state = await loadNotebook('load-1', CONN, client); - expect(mockedInvoke).toHaveBeenCalledWith('load_notebook', { + expect(call).toHaveBeenCalledWith('load_notebook', { connectionId: CONN, notebookId: 'load-1', }); @@ -149,16 +143,16 @@ describe('notebookStore', () => { const state = makeState(); setNotebookState('load-2', state); - const result = await loadNotebook('load-2', CONN); + const result = await loadNotebook('load-2', CONN, client); expect(result).toBe(state); // Should NOT call invoke since it's cached - expect(mockedInvoke).not.toHaveBeenCalledWith('load_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('load_notebook', expect.anything()); }); it('creates default state when file not found', async () => { - mockedInvoke.mockResolvedValueOnce(null); + call.mockResolvedValueOnce(null); - const state = await loadNotebook('load-3', CONN); + const state = await loadNotebook('load-3', CONN, client); expect(state.cells).toHaveLength(1); expect(state.cells[0].type).toBe('sql'); expect(state.cells[0].content).toBe(''); @@ -167,13 +161,13 @@ describe('notebookStore', () => { describe('createNotebook', () => { it('generates unique ID and saves to disk', async () => { - const {notebookId, state} = await createNotebook('New Notebook', CONN); + const {notebookId, state} = await createNotebook('New Notebook', CONN, client); expect(notebookId).toMatch(/^nb_/); expect(state.cells).toHaveLength(1); expect(getNotebookState(notebookId)).toBe(state); expect(getNotebookTitle(notebookId)).toBe('New Notebook'); - expect(mockedInvoke).toHaveBeenCalledWith('create_notebook', { + expect(call).toHaveBeenCalledWith('create_notebook', { connectionId: CONN, notebookId, content: expect.any(String), @@ -184,12 +178,12 @@ describe('notebookStore', () => { describe('createNotebookFromState', () => { it('saves existing state as new file', async () => { const state = makeState('SELECT * FROM orders'); - const {notebookId} = await createNotebookFromState('Migrated', state, CONN); + const {notebookId} = await createNotebookFromState('Migrated', state, CONN, client); expect(notebookId).toMatch(/^nb_/); expect(getNotebookState(notebookId)).toBe(state); expect(getNotebookTitle(notebookId)).toBe('Migrated'); - expect(mockedInvoke).toHaveBeenCalledWith('create_notebook', { + expect(call).toHaveBeenCalledWith('create_notebook', { connectionId: CONN, notebookId, content: expect.stringContaining('SELECT * FROM orders'), @@ -202,11 +196,11 @@ describe('notebookStore', () => { setNotebookState('del-1', makeState()); setNotebookTitle('del-1', 'To Delete'); - await deleteNotebook('del-1', CONN); + await deleteNotebook('del-1', CONN, client); expect(getNotebookState('del-1')).toBeUndefined(); expect(getNotebookTitle('del-1')).toBeUndefined(); - expect(mockedInvoke).toHaveBeenCalledWith('delete_notebook', { + expect(call).toHaveBeenCalledWith('delete_notebook', { connectionId: CONN, notebookId: 'del-1', }); @@ -218,22 +212,22 @@ describe('notebookStore', () => { await seedConnection('ren-1'); setNotebookState('ren-1', makeState()); - await renameNotebook('ren-1', CONN, 'Renamed Open'); + await renameNotebook('ren-1', CONN, 'Renamed Open', client); // Open notebooks flush the full file with the new title (no rename cmd). - expect(mockedInvoke).toHaveBeenCalledWith('save_notebook', { + expect(call).toHaveBeenCalledWith('save_notebook', { connectionId: CONN, notebookId: 'ren-1', content: expect.stringContaining('Renamed Open'), }); - expect(mockedInvoke).not.toHaveBeenCalledWith('rename_notebook', expect.anything()); + expect(call).not.toHaveBeenCalledWith('rename_notebook', expect.anything()); expect(getNotebookTitle('ren-1')).toBe('Renamed Open'); }); it('patches the file via rename_notebook when not open', async () => { - await renameNotebook('ren-2', CONN, 'Renamed Closed'); + await renameNotebook('ren-2', CONN, 'Renamed Closed', client); - expect(mockedInvoke).toHaveBeenCalledWith('rename_notebook', { + expect(call).toHaveBeenCalledWith('rename_notebook', { connectionId: CONN, notebookId: 'ren-2', title: 'Renamed Closed', @@ -251,7 +245,7 @@ describe('notebookStore', () => { await evictFromCache('evict-1'); // Should have flushed the save - expect(mockedInvoke).toHaveBeenCalledWith('save_notebook', { + expect(call).toHaveBeenCalledWith('save_notebook', { connectionId: CONN, notebookId: 'evict-1', content: expect.any(String), @@ -271,7 +265,7 @@ describe('notebookStore', () => { await flushAllPendingSaves(); - const saveCalls = mockedInvoke.mock.calls.filter(([cmd]) => cmd === 'save_notebook'); + const saveCalls = call.mock.calls.filter(([cmd]) => cmd === 'save_notebook'); expect(saveCalls).toHaveLength(2); }); }); @@ -280,7 +274,7 @@ describe('notebookStore', () => { it('emits NOTEBOOKS_CHANGED_EVENT on create', async () => { const handler = vi.fn(); window.addEventListener(NOTEBOOKS_CHANGED_EVENT, handler); - await createNotebook('Notify Create', CONN); + await createNotebook('Notify Create', CONN, client); window.removeEventListener(NOTEBOOKS_CHANGED_EVENT, handler); expect(handler).toHaveBeenCalledTimes(1); }); @@ -288,7 +282,7 @@ describe('notebookStore', () => { it('emits NOTEBOOKS_CHANGED_EVENT on delete', async () => { const handler = vi.fn(); window.addEventListener(NOTEBOOKS_CHANGED_EVENT, handler); - await deleteNotebook('notify-del', CONN); + await deleteNotebook('notify-del', CONN, client); window.removeEventListener(NOTEBOOKS_CHANGED_EVENT, handler); expect(handler).toHaveBeenCalledTimes(1); }); @@ -296,7 +290,7 @@ describe('notebookStore', () => { it('emits NOTEBOOKS_CHANGED_EVENT on rename', async () => { const handler = vi.fn(); window.addEventListener(NOTEBOOKS_CHANGED_EVENT, handler); - await renameNotebook('notify-ren', CONN, 'X'); + await renameNotebook('notify-ren', CONN, 'X', client); window.removeEventListener(NOTEBOOKS_CHANGED_EVENT, handler); expect(handler).toHaveBeenCalledTimes(1); }); @@ -315,7 +309,7 @@ describe('notebookStore', () => { await vi.advanceTimersByTimeAsync(1500); - expect(mockedInvoke).toHaveBeenCalledWith('save_notebook', { + expect(call).toHaveBeenCalledWith('save_notebook', { connectionId: CONN, notebookId: 'title-2', content: expect.stringContaining('Updated Title'), diff --git a/packages/web-ui/tests/utils/notebookTransfer.test.ts b/packages/web-ui/tests/utils/notebookTransfer.test.ts new file mode 100644 index 000000000..8be99ad93 --- /dev/null +++ b/packages/web-ui/tests/utils/notebookTransfer.test.ts @@ -0,0 +1,117 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import type {NotebookState} from '@/types/notebook'; +import { + chooseNotebookImport, + downloadNotebook, + downloadNotebookHtml, +} from '@/utils/notebookTransfer'; + +const state: NotebookState = { + cells: [ + { + id: 'cell-1', + type: 'sql', + content: 'SELECT 42 AS answer', + name: 'Answer', + chartConfig: { + type: 'bar', + labelColumn: 'answer', + valueColumns: ['answer'], + }, + }, + {id: 'cell-2', type: 'markdown', content: '# Results'}, + ], + params: [{name: 'region', value: 'eu'}], + stopOnError: true, +}; + +function platformFixture(overrides: Partial): PlatformCapabilities { + return overrides as PlatformCapabilities; +} + +describe('notebookTransfer', () => { + it('imports the desktop-compatible notebook format through an opaque reference', async () => { + const contents = new TextEncoder().encode( + JSON.stringify({ + version: 2, + title: 'Imported', + createdAt: '2026-08-22T00:00:00Z', + cells: [ + { + type: 'sql', + content: 'SELECT 42 AS answer', + name: 'Answer', + chartConfig: state.cells[0].chartConfig, + }, + ], + params: state.params, + stopOnError: true, + }), + ); + const chooseInputFile = vi.fn().mockResolvedValue({ + name: 'import.tabularis-notebook', + reference: 'opaque-browser-file', + }); + const readInputFile = vi.fn().mockResolvedValue(contents); + + await expect( + chooseNotebookImport(platformFixture({chooseInputFile, readInputFile})), + ).resolves.toMatchObject({ + title: 'Imported', + state: { + stopOnError: true, + params: state.params, + cells: [ + { + type: 'sql', + content: 'SELECT 42 AS answer', + name: 'Answer', + chartConfig: state.cells[0].chartConfig, + }, + ], + }, + }); + expect(readInputFile).toHaveBeenCalledWith('opaque-browser-file'); + }); + + it('exports notebook JSON through the platform download adapter', async () => { + const downloadFile = vi.fn().mockResolvedValue(true); + + await expect( + downloadNotebook(platformFixture({downloadFile}), 'Revenue / 2026', state), + ).resolves.toBe(true); + + const request = downloadFile.mock.calls[0][0]; + expect(request.fileName).toBe('Revenue___2026.tabularis-notebook'); + expect(request.mimeType).toBe('application/json'); + expect(JSON.parse(new TextDecoder().decode(request.contents))).toMatchObject({ + version: 2, + title: 'Revenue / 2026', + stopOnError: true, + params: state.params, + cells: [ + { + type: 'sql', + content: 'SELECT 42 AS answer', + chartConfig: state.cells[0].chartConfig, + }, + {type: 'markdown', content: '# Results'}, + ], + }); + }); + + it('preserves HTML export through the same browser-safe download adapter', async () => { + const downloadFile = vi.fn().mockResolvedValue(true); + + await downloadNotebookHtml(platformFixture({downloadFile}), 'Revenue', state); + + const request = downloadFile.mock.calls[0][0]; + expect(request.fileName).toBe('Revenue.html'); + expect(request.mimeType).toBe('text/html;charset=utf-8'); + const html = new TextDecoder().decode(request.contents); + expect(html).toContain('Revenue'); + expect(html).toContain('SELECT 42 AS answer'); + expect(html).toContain('Results'); + }); +}); diff --git a/tests/utils/notebookUndo.test.ts b/packages/web-ui/tests/utils/notebookUndo.test.ts similarity index 100% rename from tests/utils/notebookUndo.test.ts rename to packages/web-ui/tests/utils/notebookUndo.test.ts diff --git a/tests/utils/notebookVariables.test.ts b/packages/web-ui/tests/utils/notebookVariables.test.ts similarity index 99% rename from tests/utils/notebookVariables.test.ts rename to packages/web-ui/tests/utils/notebookVariables.test.ts index 21eccabd4..e973a61f2 100644 --- a/tests/utils/notebookVariables.test.ts +++ b/packages/web-ui/tests/utils/notebookVariables.test.ts @@ -8,7 +8,7 @@ import { } from '@/utils/notebookVariables'; import type {NotebookCell} from '@/types/notebook'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; -import {GOOGLESQL_CAPS} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL_CAPS} from '../../../../tests/fixtures/sql-syntax/googlesql'; function makeCell(overrides: Partial = {}): NotebookCell { return { diff --git a/tests/utils/objectNameCopy.test.ts b/packages/web-ui/tests/utils/objectNameCopy.test.ts similarity index 100% rename from tests/utils/objectNameCopy.test.ts rename to packages/web-ui/tests/utils/objectNameCopy.test.ts diff --git a/tests/utils/objectPaletteItems.test.ts b/packages/web-ui/tests/utils/objectPaletteItems.test.ts similarity index 100% rename from tests/utils/objectPaletteItems.test.ts rename to packages/web-ui/tests/utils/objectPaletteItems.test.ts diff --git a/tests/utils/openSourceLibraries.test.ts b/packages/web-ui/tests/utils/openSourceLibraries.test.ts similarity index 100% rename from tests/utils/openSourceLibraries.test.ts rename to packages/web-ui/tests/utils/openSourceLibraries.test.ts diff --git a/tests/utils/paletteItems.test.ts b/packages/web-ui/tests/utils/paletteItems.test.ts similarity index 100% rename from tests/utils/paletteItems.test.ts rename to packages/web-ui/tests/utils/paletteItems.test.ts diff --git a/tests/utils/pendingInsertions.test.ts b/packages/web-ui/tests/utils/pendingInsertions.test.ts similarity index 100% rename from tests/utils/pendingInsertions.test.ts rename to packages/web-ui/tests/utils/pendingInsertions.test.ts diff --git a/packages/web-ui/tests/utils/pluginApiCompatibility.test.ts b/packages/web-ui/tests/utils/pluginApiCompatibility.test.ts new file mode 100644 index 000000000..5f19cfa15 --- /dev/null +++ b/packages/web-ui/tests/utils/pluginApiCompatibility.test.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from 'vitest'; +import {isPluginApiCompatible} from '@/utils/pluginApiCompatibility'; + +describe('pluginApiCompatibility', () => { + it('should accept legacy declarations and compatible patch versions', () => { + expect(isPluginApiCompatible('0.1.1')).toBe(true); + expect(isPluginApiCompatible('0.1.1', '0.1.0')).toBe(true); + expect(isPluginApiCompatible('0.1.1', '0.1.1')).toBe(true); + }); + + it('should reject newer, incompatible, and malformed API versions', () => { + expect(isPluginApiCompatible('0.1.1', '0.1.2')).toBe(false); + expect(isPluginApiCompatible('0.1.1', '0.2.0')).toBe(false); + expect(isPluginApiCompatible('1.2.0', '2.0.0')).toBe(false); + expect(isPluginApiCompatible('0.1.1', 'latest')).toBe(false); + }); + + it('should apply stable-major compatibility after version one', () => { + expect(isPluginApiCompatible('1.3.0', '1.2.5')).toBe(true); + expect(isPluginApiCompatible('1.2.0', '1.3.0')).toBe(false); + }); +}); diff --git a/tests/utils/pluginConfig.test.ts b/packages/web-ui/tests/utils/pluginConfig.test.ts similarity index 100% rename from tests/utils/pluginConfig.test.ts rename to packages/web-ui/tests/utils/pluginConfig.test.ts diff --git a/tests/utils/pluginExplainLoader.test.ts b/packages/web-ui/tests/utils/pluginExplainLoader.test.ts similarity index 96% rename from tests/utils/pluginExplainLoader.test.ts rename to packages/web-ui/tests/utils/pluginExplainLoader.test.ts index 09baaff18..91c6be9d6 100644 --- a/tests/utils/pluginExplainLoader.test.ts +++ b/packages/web-ui/tests/utils/pluginExplainLoader.test.ts @@ -4,11 +4,9 @@ import {getExplainParser, parseRawExplain, unregisterExplainParser} from '@tabul import {loadPluginExplainParsers} from '@/utils/pluginExplainLoader'; import type {PluginManifest} from '@/types/plugins'; -const invokeMock = vi.hoisted(() => vi.fn()); - -vi.mock('@tauri-apps/api/core', () => ({ - invoke: invokeMock, -})); +const invokeMock = vi.fn(); +const readAsset = (pluginId: string, filePath: string) => + invokeMock('read_plugin_file', {pluginId, filePath}) as Promise; const testFormats = new Set(); @@ -96,7 +94,7 @@ describe('pluginExplainLoader', () => { }; `); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); const plan = parseRawExplain({ engine: 'example-db', format: 'example-db-plan-text', @@ -127,7 +125,7 @@ describe('pluginExplainLoader', () => { ]; `); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); expect(formats).toEqual(['example-format-a', 'example-format-b']); expect(invokeMock).toHaveBeenCalledTimes(1); @@ -152,7 +150,7 @@ describe('pluginExplainLoader', () => { `var __tabularis_explain_parser__ = ${parserDescriptor('example-db', 'ordered-format-b')};`, ); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); expect(formats).toEqual(['ordered-format-a', 'ordered-format-b', 'ordered-format-c']); expect(invokeMock).toHaveBeenCalledTimes(2); @@ -165,7 +163,7 @@ describe('pluginExplainLoader', () => { ]); invokeMock.mockResolvedValue('throw new Error("bundle exploded");'); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); expect(formats).toEqual([]); expect(getExplainParser('throwing-format')).toBeNull(); @@ -182,7 +180,7 @@ describe('pluginExplainLoader', () => { ]); invokeMock.mockResolvedValue('var unrelated_bundle_export = {};'); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); expect(formats).toEqual([]); expect(getExplainParser('missing-format')).toBeNull(); @@ -204,7 +202,7 @@ describe('pluginExplainLoader', () => { }; `); - const formats = await loadPluginExplainParsers(pluginManifest); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset); expect(formats).toEqual([]); expect(getExplainParser('invalid-format')).toBeNull(); @@ -222,7 +220,7 @@ describe('pluginExplainLoader', () => { return `var __tabularis_explain_parser__ = ${parserDescriptor('example-db', 'cancelled-format')};`; }); - const formats = await loadPluginExplainParsers(pluginManifest, () => !cancelled); + const formats = await loadPluginExplainParsers(pluginManifest, readAsset, () => !cancelled); expect(formats).toEqual([]); expect(invokeMock).toHaveBeenCalledTimes(1); @@ -250,9 +248,9 @@ describe('pluginExplainLoader', () => { `var __tabularis_explain_parser__ = ${parserDescriptor('example-db', 'repeat-format')};`, ); - const firstPass = await loadPluginExplainParsers(pluginManifest); + const firstPass = await loadPluginExplainParsers(pluginManifest, readAsset); firstPass.forEach(unregisterExplainParser); - const secondPass = await loadPluginExplainParsers(pluginManifest); + const secondPass = await loadPluginExplainParsers(pluginManifest, readAsset); expect(firstPass).toEqual(['repeat-format']); expect(secondPass).toEqual(['repeat-format']); diff --git a/packages/web-ui/tests/utils/pluginInstallRoute.test.ts b/packages/web-ui/tests/utils/pluginInstallRoute.test.ts new file mode 100644 index 000000000..95884c7ab --- /dev/null +++ b/packages/web-ui/tests/utils/pluginInstallRoute.test.ts @@ -0,0 +1,58 @@ +import {describe, expect, it} from 'vitest'; +import {buildPluginInstallRoute, parsePluginInstallRoute} from '@/utils/pluginInstallRoute'; + +describe('pluginInstallRoute', () => { + it('builds the canonical browser install route with source selection', () => { + expect( + buildPluginInstallRoute({ + slug: 'postgres-driver', + version: '1.2.3', + registry: 'https://registry.example/api/', + }), + ).toBe( + '/install/postgres-driver?version=1.2.3®istry=https%3A%2F%2Fregistry.example%2Fapi', + ); + }); + + it('parses the canonical route into the shared confirmation request', () => { + expect( + parsePluginInstallRoute( + 'postgres-driver', + new URLSearchParams( + 'version=1.2.3®istry=http%3A%2F%2F127.0.0.1%3A9000%2Fregistry%2F', + ), + ), + ).toEqual({ + slug: 'postgres-driver', + version: '1.2.3', + registry: 'http://127.0.0.1:9000/registry', + }); + }); + + it('allows omitted optional selections', () => { + expect(parsePluginInstallRoute('sqlite', new URLSearchParams())).toEqual({ + slug: 'sqlite', + version: null, + registry: null, + }); + }); + + it.each([ + ['missing slug', undefined, ''], + ['unsafe slug', '../plugin', ''], + ['uppercase registry slug', 'Postgres', ''], + ['non-HTTP registry', 'postgres', 'registry=file%3A%2F%2F%2Ftmp%2Fplugins'], + [ + 'registry credentials', + 'postgres', + 'registry=https%3A%2F%2Fuser%3Asecret%40registry.example', + ], + [ + 'registry query', + 'postgres', + 'registry=https%3A%2F%2Fregistry.example%2Fapi%3Ftoken%3Dsecret', + ], + ])('rejects %s', (_label, slug, search) => { + expect(parsePluginInstallRoute(slug, new URLSearchParams(search))).toBeNull(); + }); +}); diff --git a/tests/utils/pluginIssueReport.test.ts b/packages/web-ui/tests/utils/pluginIssueReport.test.ts similarity index 100% rename from tests/utils/pluginIssueReport.test.ts rename to packages/web-ui/tests/utils/pluginIssueReport.test.ts diff --git a/tests/utils/pluginModuleLoader.test.ts b/packages/web-ui/tests/utils/pluginModuleLoader.test.ts similarity index 100% rename from tests/utils/pluginModuleLoader.test.ts rename to packages/web-ui/tests/utils/pluginModuleLoader.test.ts diff --git a/tests/utils/pluginPresentation.test.ts b/packages/web-ui/tests/utils/pluginPresentation.test.ts similarity index 100% rename from tests/utils/pluginPresentation.test.ts rename to packages/web-ui/tests/utils/pluginPresentation.test.ts diff --git a/tests/utils/pluginReadme.test.ts b/packages/web-ui/tests/utils/pluginReadme.test.ts similarity index 100% rename from tests/utils/pluginReadme.test.ts rename to packages/web-ui/tests/utils/pluginReadme.test.ts diff --git a/tests/utils/pluginUpdates.test.ts b/packages/web-ui/tests/utils/pluginUpdates.test.ts similarity index 100% rename from tests/utils/pluginUpdates.test.ts rename to packages/web-ui/tests/utils/pluginUpdates.test.ts diff --git a/tests/utils/pluginVersions.test.ts b/packages/web-ui/tests/utils/pluginVersions.test.ts similarity index 100% rename from tests/utils/pluginVersions.test.ts rename to packages/web-ui/tests/utils/pluginVersions.test.ts diff --git a/tests/utils/plugins.test.ts b/packages/web-ui/tests/utils/plugins.test.ts similarity index 100% rename from tests/utils/plugins.test.ts rename to packages/web-ui/tests/utils/plugins.test.ts diff --git a/tests/utils/pointerDrag.test.ts b/packages/web-ui/tests/utils/pointerDrag.test.ts similarity index 100% rename from tests/utils/pointerDrag.test.ts rename to packages/web-ui/tests/utils/pointerDrag.test.ts diff --git a/tests/utils/proxy.test.ts b/packages/web-ui/tests/utils/proxy.test.ts similarity index 100% rename from tests/utils/proxy.test.ts rename to packages/web-ui/tests/utils/proxy.test.ts diff --git a/tests/utils/queryBuilderLayout.test.ts b/packages/web-ui/tests/utils/queryBuilderLayout.test.ts similarity index 100% rename from tests/utils/queryBuilderLayout.test.ts rename to packages/web-ui/tests/utils/queryBuilderLayout.test.ts diff --git a/tests/utils/queryGuard.test.ts b/packages/web-ui/tests/utils/queryGuard.test.ts similarity index 100% rename from tests/utils/queryGuard.test.ts rename to packages/web-ui/tests/utils/queryGuard.test.ts diff --git a/tests/utils/queryHistoryDetails.test.ts b/packages/web-ui/tests/utils/queryHistoryDetails.test.ts similarity index 100% rename from tests/utils/queryHistoryDetails.test.ts rename to packages/web-ui/tests/utils/queryHistoryDetails.test.ts diff --git a/tests/utils/queryHistoryFilter.test.ts b/packages/web-ui/tests/utils/queryHistoryFilter.test.ts similarity index 100% rename from tests/utils/queryHistoryFilter.test.ts rename to packages/web-ui/tests/utils/queryHistoryFilter.test.ts diff --git a/packages/web-ui/tests/utils/queryNotification.test.ts b/packages/web-ui/tests/utils/queryNotification.test.ts new file mode 100644 index 000000000..93b7bc642 --- /dev/null +++ b/packages/web-ui/tests/utils/queryNotification.test.ts @@ -0,0 +1,167 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +const platform = vi.hoisted(() => ({notify: vi.fn().mockResolvedValue({status: 'sent'})})); +vi.mock('@/platform/activeCapabilities', () => ({ + getActivePlatformCapabilitiesOrNull: () => platform as unknown as PlatformCapabilities, +})); +const CONTENT = {title: 'Query finished', body: 'tab · 25.00 s'}; +async function importQueryNotification() { + return import('@/utils/queryNotification'); +} +describe('queryNotification', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + describe('shouldNotifyQueryFinished', () => { + it('does not notify when the window is focused', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec: 20, + durationMs: 30000, + windowFocused: true, + }), + ).toBe(false); + }); + + it('does not notify when the setting is disabled', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: false, + thresholdSec: 20, + durationMs: 30000, + windowFocused: false, + }), + ).toBe(false); + }); + + it('does not notify below the threshold', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec: 20, + durationMs: 19999, + windowFocused: false, + }), + ).toBe(false); + }); + + it('notifies at the threshold', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec: 20, + durationMs: 20000, + windowFocused: false, + }), + ).toBe(true); + }); + + it('notifies above the threshold', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec: 20, + durationMs: 60000, + windowFocused: false, + }), + ).toBe(true); + }); + + it('treats an undefined enabled setting as on', async () => { + const {shouldNotifyQueryFinished} = await importQueryNotification(); + expect( + shouldNotifyQueryFinished({ + enabled: undefined, + thresholdSec: 20, + durationMs: 30000, + windowFocused: false, + }), + ).toBe(true); + }); + + it.each([undefined, 0, -5, Number.NaN])( + 'falls back to the default 20s threshold when thresholdSec is %s', + async (thresholdSec) => { + const {shouldNotifyQueryFinished, DEFAULT_NOTIFY_THRESHOLD_SEC} = + await importQueryNotification(); + + expect(DEFAULT_NOTIFY_THRESHOLD_SEC).toBe(20); + // Below 20s: no notification even with a broken threshold value. + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec, + durationMs: 19999, + windowFocused: false, + }), + ).toBe(false); + // At 20s the default threshold applies. + expect( + shouldNotifyQueryFinished({ + enabled: true, + thresholdSec, + durationMs: 20000, + windowFocused: false, + }), + ).toBe(true); + }, + ); + }); + + describe('notifyQueryFinished', () => { + it('notifies through the active platform when unfocused', async () => { + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(false); + try { + const {notifyQueryFinished} = await importQueryNotification(); + await notifyQueryFinished({durationMs: 25000, content: CONTENT}); + expect(platform.notify).toHaveBeenCalledWith(CONTENT); + focus.mockReturnValue(true); + await notifyQueryFinished({durationMs: 25000, content: CONTENT}); + expect(platform.notify).toHaveBeenCalledOnce(); + } finally { + focus.mockRestore(); + } + }); + it('skips disabled or short queries', async () => { + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(false); + try { + const {notifyQueryFinished} = await importQueryNotification(); + await notifyQueryFinished({durationMs: 1000, content: CONTENT}); + await notifyQueryFinished({enabled: false, durationMs: 25000, content: CONTENT}); + expect(platform.notify).not.toHaveBeenCalled(); + } finally { + focus.mockRestore(); + } + }); + it('treats a failed focus probe as unfocused', async () => { + const focus = vi.spyOn(document, 'hasFocus').mockImplementation(() => { + throw new Error('unavailable'); + }); + try { + const {notifyQueryFinished} = await importQueryNotification(); + await notifyQueryFinished({durationMs: 25000, content: CONTENT}); + expect(platform.notify).toHaveBeenCalledWith(CONTENT); + } finally { + focus.mockRestore(); + } + }); + it('never lets notification failures break query execution', async () => { + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(false); + platform.notify.mockRejectedValueOnce(new Error('denied')); + try { + const {notifyQueryFinished} = await importQueryNotification(); + await expect( + notifyQueryFinished({durationMs: 25000, content: CONTENT}), + ).resolves.toBeUndefined(); + } finally { + focus.mockRestore(); + } + }); + }); +}); diff --git a/tests/utils/queryParameters.test.ts b/packages/web-ui/tests/utils/queryParameters.test.ts similarity index 100% rename from tests/utils/queryParameters.test.ts rename to packages/web-ui/tests/utils/queryParameters.test.ts diff --git a/tests/utils/quickNavigator.test.ts b/packages/web-ui/tests/utils/quickNavigator.test.ts similarity index 100% rename from tests/utils/quickNavigator.test.ts rename to packages/web-ui/tests/utils/quickNavigator.test.ts diff --git a/tests/utils/restoreSession.test.ts b/packages/web-ui/tests/utils/restoreSession.test.ts similarity index 100% rename from tests/utils/restoreSession.test.ts rename to packages/web-ui/tests/utils/restoreSession.test.ts diff --git a/tests/utils/resultExport.test.ts b/packages/web-ui/tests/utils/resultExport.test.ts similarity index 100% rename from tests/utils/resultExport.test.ts rename to packages/web-ui/tests/utils/resultExport.test.ts diff --git a/tests/utils/resultPresentation.test.ts b/packages/web-ui/tests/utils/resultPresentation.test.ts similarity index 100% rename from tests/utils/resultPresentation.test.ts rename to packages/web-ui/tests/utils/resultPresentation.test.ts diff --git a/tests/utils/resultsWindowSync.test.ts b/packages/web-ui/tests/utils/resultsWindowSync.test.ts similarity index 94% rename from tests/utils/resultsWindowSync.test.ts rename to packages/web-ui/tests/utils/resultsWindowSync.test.ts index c8516dd16..7d3f964ff 100644 --- a/tests/utils/resultsWindowSync.test.ts +++ b/packages/web-ui/tests/utils/resultsWindowSync.test.ts @@ -222,16 +222,24 @@ describe('applyCopyResult', () => { return {onCopied: vi.fn(), onError: vi.fn()}; } + it("ignores results for another tab's window", () => { + const h = makeHandlers(); + applyCopyResult({tabId: 'other', text: 'a', count: 1}, 'tab1', h); + applyCopyResult({tabId: 'other', error: 'boom'}, 'tab1', h); + expect(h.onCopied).not.toHaveBeenCalled(); + expect(h.onError).not.toHaveBeenCalled(); + }); + it('passes copied rows', () => { const h = makeHandlers(); - applyCopyResult({text: 'id\n1', count: 1}, h); + applyCopyResult({tabId: 'tab-1', text: 'id\n1', count: 1}, 'tab-1', h); expect(h.onCopied).toHaveBeenCalledWith({text: 'id\n1', count: 1}); expect(h.onError).not.toHaveBeenCalled(); }); it('passes the error', () => { const h = makeHandlers(); - applyCopyResult({error: 'boom'}, h); + applyCopyResult({tabId: 'tab-1', error: 'boom'}, 'tab-1', h); expect(h.onError).toHaveBeenCalledWith('boom'); expect(h.onCopied).not.toHaveBeenCalled(); }); diff --git a/tests/utils/routineCall.test.ts b/packages/web-ui/tests/utils/routineCall.test.ts similarity index 100% rename from tests/utils/routineCall.test.ts rename to packages/web-ui/tests/utils/routineCall.test.ts diff --git a/tests/utils/routines.test.ts b/packages/web-ui/tests/utils/routines.test.ts similarity index 100% rename from tests/utils/routines.test.ts rename to packages/web-ui/tests/utils/routines.test.ts diff --git a/tests/utils/rowIdentity.test.ts b/packages/web-ui/tests/utils/rowIdentity.test.ts similarity index 100% rename from tests/utils/rowIdentity.test.ts rename to packages/web-ui/tests/utils/rowIdentity.test.ts diff --git a/tests/utils/runTarget.test.ts b/packages/web-ui/tests/utils/runTarget.test.ts similarity index 100% rename from tests/utils/runTarget.test.ts rename to packages/web-ui/tests/utils/runTarget.test.ts diff --git a/tests/utils/savedQueryFolders.test.ts b/packages/web-ui/tests/utils/savedQueryFolders.test.ts similarity index 100% rename from tests/utils/savedQueryFolders.test.ts rename to packages/web-ui/tests/utils/savedQueryFolders.test.ts diff --git a/tests/utils/savedQueryNames.test.ts b/packages/web-ui/tests/utils/savedQueryNames.test.ts similarity index 100% rename from tests/utils/savedQueryNames.test.ts rename to packages/web-ui/tests/utils/savedQueryNames.test.ts diff --git a/tests/utils/savedQuerySearch.test.ts b/packages/web-ui/tests/utils/savedQuerySearch.test.ts similarity index 100% rename from tests/utils/savedQuerySearch.test.ts rename to packages/web-ui/tests/utils/savedQuerySearch.test.ts diff --git a/tests/utils/schema.test.ts b/packages/web-ui/tests/utils/schema.test.ts similarity index 100% rename from tests/utils/schema.test.ts rename to packages/web-ui/tests/utils/schema.test.ts diff --git a/tests/utils/schemaDiagram.test.ts b/packages/web-ui/tests/utils/schemaDiagram.test.ts similarity index 100% rename from tests/utils/schemaDiagram.test.ts rename to packages/web-ui/tests/utils/schemaDiagram.test.ts diff --git a/tests/utils/schemaExport.test.ts b/packages/web-ui/tests/utils/schemaExport.test.ts similarity index 100% rename from tests/utils/schemaExport.test.ts rename to packages/web-ui/tests/utils/schemaExport.test.ts diff --git a/tests/utils/settings.test.ts b/packages/web-ui/tests/utils/settings.test.ts similarity index 100% rename from tests/utils/settings.test.ts rename to packages/web-ui/tests/utils/settings.test.ts diff --git a/tests/utils/settingsUI.test.ts b/packages/web-ui/tests/utils/settingsUI.test.ts similarity index 100% rename from tests/utils/settingsUI.test.ts rename to packages/web-ui/tests/utils/settingsUI.test.ts diff --git a/tests/utils/sidebarTableItem.test.ts b/packages/web-ui/tests/utils/sidebarTableItem.test.ts similarity index 100% rename from tests/utils/sidebarTableItem.test.ts rename to packages/web-ui/tests/utils/sidebarTableItem.test.ts diff --git a/tests/utils/sql.test.ts b/packages/web-ui/tests/utils/sql.test.ts similarity index 100% rename from tests/utils/sql.test.ts rename to packages/web-ui/tests/utils/sql.test.ts diff --git a/tests/utils/sqlAnalysis.test.ts b/packages/web-ui/tests/utils/sqlAnalysis.test.ts similarity index 100% rename from tests/utils/sqlAnalysis.test.ts rename to packages/web-ui/tests/utils/sqlAnalysis.test.ts diff --git a/tests/utils/sqlContext.test.ts b/packages/web-ui/tests/utils/sqlContext.test.ts similarity index 100% rename from tests/utils/sqlContext.test.ts rename to packages/web-ui/tests/utils/sqlContext.test.ts diff --git a/tests/utils/sqlFile.test.ts b/packages/web-ui/tests/utils/sqlFile.test.ts similarity index 100% rename from tests/utils/sqlFile.test.ts rename to packages/web-ui/tests/utils/sqlFile.test.ts diff --git a/packages/web-ui/tests/utils/sqlFileTransfer.test.ts b/packages/web-ui/tests/utils/sqlFileTransfer.test.ts new file mode 100644 index 000000000..bb408db88 --- /dev/null +++ b/packages/web-ui/tests/utils/sqlFileTransfer.test.ts @@ -0,0 +1,121 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {PlatformCapabilities} from '@/platform/capabilities'; +import {openSqlFile, saveSqlFile} from '@/utils/sqlFileTransfer'; + +const filters = [{name: 'SQL', extensions: ['sql']}]; + +function platformFixture(serverFiles: boolean) { + return { + supports: vi.fn((capability: string) => + capability === 'chooseServerPath' || capability === 'chooseSaveTarget' + ? serverFiles + : true, + ), + chooseServerPath: vi.fn().mockResolvedValue({reference: '/srv/q.sql'}), + chooseSaveTarget: vi.fn().mockResolvedValue({reference: '/srv/new.sql'}), + chooseInputFile: vi + .fn() + .mockResolvedValue({name: 'local.sql', reference: 'browser-file:1'}), + readInputFile: vi.fn().mockResolvedValue(new TextEncoder().encode('select 1')), + downloadFile: vi.fn().mockResolvedValue(true), + showMessage: vi.fn(), + }; +} + +function clientFixture() { + return { + call: vi.fn(async (command: string) => + command === 'read_sql_file' ? 'select 2' : undefined, + ), + }; +} + +const asPlatform = (value: ReturnType) => + value as unknown as PlatformCapabilities; + +describe('openSqlFile', () => { + it('reads a host or server path through the backend', async () => { + const platform = platformFixture(true); + const client = clientFixture(); + await expect(openSqlFile(asPlatform(platform), client, filters)).resolves.toEqual({ + kind: 'path', + path: '/srv/q.sql', + query: 'select 2', + }); + expect(platform.chooseServerPath).toHaveBeenCalledWith({kind: 'file', filters}); + expect(client.call).toHaveBeenCalledWith('read_sql_file', {path: '/srv/q.sql'}); + }); + + it('falls back to a browser upload without server file browsing', async () => { + const platform = platformFixture(false); + const client = clientFixture(); + await expect(openSqlFile(asPlatform(platform), client, filters)).resolves.toEqual({ + kind: 'upload', + name: 'local.sql', + query: 'select 1', + }); + expect(client.call).not.toHaveBeenCalled(); + }); + + it('returns null when the picker is cancelled', async () => { + const platform = platformFixture(true); + platform.chooseServerPath.mockResolvedValue(null); + await expect( + openSqlFile(asPlatform(platform), clientFixture(), filters), + ).resolves.toBeNull(); + }); +}); + +describe('saveSqlFile', () => { + it('writes back to the known path without asking', async () => { + const platform = platformFixture(true); + const client = clientFixture(); + await expect( + saveSqlFile(asPlatform(platform), client, { + query: 'select 3', + title: 'q.sql', + sourceFilePath: '/srv/q.sql', + filters, + }), + ).resolves.toEqual({kind: 'path', path: '/srv/q.sql'}); + expect(platform.chooseSaveTarget).not.toHaveBeenCalled(); + expect(client.call).toHaveBeenCalledWith('write_sql_file', { + path: '/srv/q.sql', + content: 'select 3', + }); + }); + + it('asks for a target on save as', async () => { + const platform = platformFixture(true); + const client = clientFixture(); + await expect( + saveSqlFile(asPlatform(platform), client, { + query: 'select 3', + title: 'q.sql', + sourceFilePath: '/srv/q.sql', + saveAs: true, + filters, + }), + ).resolves.toEqual({kind: 'path', path: '/srv/new.sql'}); + expect(platform.chooseSaveTarget).toHaveBeenCalledWith({ + suggestedName: '/srv/q.sql', + filters, + }); + }); + + it('downloads the file in a browser without server file browsing', async () => { + const platform = platformFixture(false); + const client = clientFixture(); + await expect( + saveSqlFile(asPlatform(platform), client, { + query: 'select 4', + title: 'Console', + filters, + }), + ).resolves.toEqual({kind: 'download'}); + expect(platform.downloadFile).toHaveBeenCalledWith( + expect.objectContaining({fileName: 'Console.sql', mimeType: 'application/sql'}), + ); + expect(client.call).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/utils/sqlFoldPreview.test.ts b/packages/web-ui/tests/utils/sqlFoldPreview.test.ts similarity index 100% rename from tests/utils/sqlFoldPreview.test.ts rename to packages/web-ui/tests/utils/sqlFoldPreview.test.ts diff --git a/tests/utils/sqlFolding.test.ts b/packages/web-ui/tests/utils/sqlFolding.test.ts similarity index 100% rename from tests/utils/sqlFolding.test.ts rename to packages/web-ui/tests/utils/sqlFolding.test.ts diff --git a/tests/utils/sqlFormat.test.ts b/packages/web-ui/tests/utils/sqlFormat.test.ts similarity index 97% rename from tests/utils/sqlFormat.test.ts rename to packages/web-ui/tests/utils/sqlFormat.test.ts index aa592a8d1..55278c161 100644 --- a/tests/utils/sqlFormat.test.ts +++ b/packages/web-ui/tests/utils/sqlFormat.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from 'vitest'; import {formatSql, toFormatterLanguage} from '@/utils/sqlFormat'; import {resolveSqlSyntax} from '@/utils/sqlSyntax'; -import {GOOGLESQL} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../tests/fixtures/sql-syntax/googlesql'; describe('sqlFormat', () => { describe('toFormatterLanguage', () => { diff --git a/tests/utils/sqlGenerator.test.ts b/packages/web-ui/tests/utils/sqlGenerator.test.ts similarity index 100% rename from tests/utils/sqlGenerator.test.ts rename to packages/web-ui/tests/utils/sqlGenerator.test.ts diff --git a/tests/utils/sqlInvisibleCharacters.test.ts b/packages/web-ui/tests/utils/sqlInvisibleCharacters.test.ts similarity index 98% rename from tests/utils/sqlInvisibleCharacters.test.ts rename to packages/web-ui/tests/utils/sqlInvisibleCharacters.test.ts index 31afdfffb..1277ce9fa 100644 --- a/tests/utils/sqlInvisibleCharacters.test.ts +++ b/packages/web-ui/tests/utils/sqlInvisibleCharacters.test.ts @@ -4,7 +4,7 @@ import { getSqlInvisibleCharacterEdits, } from '@/utils/sqlInvisibleCharacters'; import {resolveSqlSyntax} from '@/utils/sqlSyntax'; -import {GOOGLESQL} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../tests/fixtures/sql-syntax/googlesql'; describe('cleanSqlInvisibleCharacters', () => { it('removes invisible characters from SQL code but keeps layout', () => { diff --git a/tests/utils/sqlLiteral.test.ts b/packages/web-ui/tests/utils/sqlLiteral.test.ts similarity index 97% rename from tests/utils/sqlLiteral.test.ts rename to packages/web-ui/tests/utils/sqlLiteral.test.ts index 1168a3868..10d73bd36 100644 --- a/tests/utils/sqlLiteral.test.ts +++ b/packages/web-ui/tests/utils/sqlLiteral.test.ts @@ -8,8 +8,8 @@ import { stringEscapeStyle, supportsLikeEscape, } from '@/utils/sqlLiteral'; -import {GOOGLESQL_CAPS} from '../fixtures/sql-syntax/googlesql'; -import stringLiterals from '../fixtures/sql-syntax/string-literals.json'; +import {GOOGLESQL_CAPS} from '../../../../tests/fixtures/sql-syntax/googlesql'; +import stringLiterals from '../../../../tests/fixtures/sql-syntax/string-literals.json'; import type {StringEscapeStyle} from '@/utils/sqlSyntax'; import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; diff --git a/tests/utils/sqlSplitter/classify.test.ts b/packages/web-ui/tests/utils/sqlSplitter/classify.test.ts similarity index 100% rename from tests/utils/sqlSplitter/classify.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/classify.test.ts diff --git a/tests/utils/sqlSplitter/dialects.test.ts b/packages/web-ui/tests/utils/sqlSplitter/dialects.test.ts similarity index 97% rename from tests/utils/sqlSplitter/dialects.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/dialects.test.ts index 413dacb00..e01de6501 100644 --- a/tests/utils/sqlSplitter/dialects.test.ts +++ b/packages/web-ui/tests/utils/sqlSplitter/dialects.test.ts @@ -1,6 +1,6 @@ import {describe, it, expect} from 'vitest'; import {splitQueries} from '@/utils/sqlSplitter'; -import {GOOGLESQL} from '../../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../../tests/fixtures/sql-syntax/googlesql'; describe('dialect canaries', () => { it('postgres treats $$ as a string boundary', () => { diff --git a/tests/utils/sqlSplitter/nonCodeSpans.test.ts b/packages/web-ui/tests/utils/sqlSplitter/nonCodeSpans.test.ts similarity index 100% rename from tests/utils/sqlSplitter/nonCodeSpans.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/nonCodeSpans.test.ts diff --git a/tests/utils/sqlSplitter/scriptBlocks.test.ts b/packages/web-ui/tests/utils/sqlSplitter/scriptBlocks.test.ts similarity index 99% rename from tests/utils/sqlSplitter/scriptBlocks.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/scriptBlocks.test.ts index 3aed118c7..79362381b 100644 --- a/tests/utils/sqlSplitter/scriptBlocks.test.ts +++ b/packages/web-ui/tests/utils/sqlSplitter/scriptBlocks.test.ts @@ -8,7 +8,7 @@ import { resetScriptBlockState, scanScriptWord, } from '@/utils/sqlSplitter/scriptBlocks'; -import {GOOGLESQL} from '../../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../../tests/fixtures/sql-syntax/googlesql'; // GoogleSQL as a plugin declares it: the `sql_syntax` descriptor fixture. const BQ = GOOGLESQL.options; diff --git a/tests/utils/sqlSplitter/splitter.test.ts b/packages/web-ui/tests/utils/sqlSplitter/splitter.test.ts similarity index 100% rename from tests/utils/sqlSplitter/splitter.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/splitter.test.ts diff --git a/tests/utils/sqlSplitter/statementAt.test.ts b/packages/web-ui/tests/utils/sqlSplitter/statementAt.test.ts similarity index 100% rename from tests/utils/sqlSplitter/statementAt.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/statementAt.test.ts diff --git a/tests/utils/sqlSplitter/tokenizer.test.ts b/packages/web-ui/tests/utils/sqlSplitter/tokenizer.test.ts similarity index 99% rename from tests/utils/sqlSplitter/tokenizer.test.ts rename to packages/web-ui/tests/utils/sqlSplitter/tokenizer.test.ts index b02a1cd65..df90701c6 100644 --- a/tests/utils/sqlSplitter/tokenizer.test.ts +++ b/packages/web-ui/tests/utils/sqlSplitter/tokenizer.test.ts @@ -1,7 +1,7 @@ import {describe, it, expect} from 'vitest'; import {scanToken, type TokenizerState} from '@/utils/sqlSplitter/tokenizer'; import {dialectOptions} from '@/utils/sqlSplitter'; -import {GOOGLESQL} from '../../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../../tests/fixtures/sql-syntax/googlesql'; const PG = dialectOptions('postgres'); const MY = dialectOptions('mysql'); diff --git a/tests/utils/sqlSyntax.test.ts b/packages/web-ui/tests/utils/sqlSyntax.test.ts similarity index 99% rename from tests/utils/sqlSyntax.test.ts rename to packages/web-ui/tests/utils/sqlSyntax.test.ts index 200ebaae0..c110b6ec8 100644 --- a/tests/utils/sqlSyntax.test.ts +++ b/packages/web-ui/tests/utils/sqlSyntax.test.ts @@ -15,7 +15,11 @@ import { resolveSqlSyntax, syntaxKeywords, } from '@/utils/sqlSyntax'; -import {GOOGLESQL, GOOGLESQL_CAPS, GOOGLESQL_DESCRIPTOR} from '../fixtures/sql-syntax/googlesql'; +import { + GOOGLESQL, + GOOGLESQL_CAPS, + GOOGLESQL_DESCRIPTOR, +} from '../../../../tests/fixtures/sql-syntax/googlesql'; const PRESETS: readonly Dialect[] = ['postgres', 'mysql', 'mssql', 'sqlite', 'oracle', 'generic']; diff --git a/tests/utils/sqlSyntaxSchema.test.ts b/packages/web-ui/tests/utils/sqlSyntaxSchema.test.ts similarity index 90% rename from tests/utils/sqlSyntaxSchema.test.ts rename to packages/web-ui/tests/utils/sqlSyntaxSchema.test.ts index bb30bf40e..9c083f5d3 100644 --- a/tests/utils/sqlSyntaxSchema.test.ts +++ b/packages/web-ui/tests/utils/sqlSyntaxSchema.test.ts @@ -1,8 +1,8 @@ import {describe, expect, it} from 'vitest'; import Ajv from 'ajv'; -import manifestSchema from '../../plugins/manifest.schema.json'; -import extensionsSchema from '../../plugins/tabularium-extensions.schema.json'; -import {GOOGLESQL_DESCRIPTOR} from '../fixtures/sql-syntax/googlesql'; +import manifestSchema from '../../../../plugins/manifest.schema.json'; +import extensionsSchema from '../../../../plugins/tabularium-extensions.schema.json'; +import {GOOGLESQL_DESCRIPTOR} from '../../../../tests/fixtures/sql-syntax/googlesql'; import {SQL_SYNTAX_FORMATTERS, SQL_SYNTAX_LIMITS} from '@/utils/sqlSyntax'; describe('sql_syntax manifest contract', () => { diff --git a/tests/utils/ssh.test.ts b/packages/web-ui/tests/utils/ssh.test.ts similarity index 95% rename from tests/utils/ssh.test.ts rename to packages/web-ui/tests/utils/ssh.test.ts index b93a8794c..04cd1d6d2 100644 --- a/tests/utils/ssh.test.ts +++ b/packages/web-ui/tests/utils/ssh.test.ts @@ -1,4 +1,5 @@ import {describe, it, expect, vi, beforeEach} from 'vitest'; +import type {TypedCommandCaller} from '@/api/contract'; import { validateSshConnection, formatSshConnectionString, @@ -389,6 +390,29 @@ describe('ssh', () => { vi.clearAllMocks(); }); + it('routes through the injected typed client', async () => { + const call = vi.fn().mockResolvedValue('SSH connection successful'); + const client = {call} as unknown as TypedCommandCaller; + + await testSshConnection( + { + host: 'example.com', + port: 22, + user: 'testuser', + auth_type: 'password', + password: 'secret', + }, + {}, + client, + ); + + expect(call).toHaveBeenCalledWith( + 'test_ssh_connection', + {ssh: expect.objectContaining({host: 'example.com'})}, + {deadlineMs: 180_000}, + ); + }); + it('should call invoke with correct parameters', async () => { const {invoke} = await import('@tauri-apps/api/core'); vi.mocked(invoke).mockResolvedValue('SSH connection successful'); diff --git a/tests/utils/sslMode.test.ts b/packages/web-ui/tests/utils/sslMode.test.ts similarity index 100% rename from tests/utils/sslMode.test.ts rename to packages/web-ui/tests/utils/sslMode.test.ts diff --git a/tests/utils/ssm.test.ts b/packages/web-ui/tests/utils/ssm.test.ts similarity index 100% rename from tests/utils/ssm.test.ts rename to packages/web-ui/tests/utils/ssm.test.ts diff --git a/packages/web-ui/tests/utils/startupConfig.test.ts b/packages/web-ui/tests/utils/startupConfig.test.ts new file mode 100644 index 000000000..c1b3a7026 --- /dev/null +++ b/packages/web-ui/tests/utils/startupConfig.test.ts @@ -0,0 +1,28 @@ +import {describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import {loadStartupConfig} from '@/utils/startupConfig'; + +function mockClient() { + const call = vi.fn(); + return {call, client: {call} as unknown as TabularisClient}; +} + +describe('loadStartupConfig', () => { + it('coalesces bootstrap readers without caching subsequent settings edits', async () => { + const {call, client} = mockClient(); + call.mockResolvedValueOnce({language: 'it'}).mockResolvedValueOnce({language: 'en'}); + const first = loadStartupConfig(client); + expect(loadStartupConfig(client)).toBe(first); + expect(await first).toEqual({language: 'it'}); + expect(await loadStartupConfig(client)).toEqual({language: 'en'}); + expect(call).toHaveBeenCalledTimes(2); + expect(call).toHaveBeenCalledWith('get_config', undefined); + }); + + it('allows retry after a failed read', async () => { + const {call, client} = mockClient(); + call.mockRejectedValueOnce(new Error('unavailable')).mockResolvedValueOnce({}); + await expect(loadStartupConfig(client)).rejects.toThrow('unavailable'); + await expect(loadStartupConfig(client)).resolves.toEqual({}); + }); +}); diff --git a/tests/utils/storageLocation.test.ts b/packages/web-ui/tests/utils/storageLocation.test.ts similarity index 94% rename from tests/utils/storageLocation.test.ts rename to packages/web-ui/tests/utils/storageLocation.test.ts index c11cf88c3..ad9b34d00 100644 --- a/tests/utils/storageLocation.test.ts +++ b/packages/web-ui/tests/utils/storageLocation.test.ts @@ -5,13 +5,11 @@ vi.mock('@tauri-apps/api/core', () => ({ invoke: (...args: unknown[]) => invokeMock(...args), })); +import {defaultModeFor, pendingPathOf, type StorageLocationInfo} from '@/utils/storageLocation'; import { - defaultModeFor, - pendingPathOf, - getAppDataDir, + getTauriAppDataDir as getAppDataDir, resetAppDataDirCache, - type StorageLocationInfo, -} from '@/utils/storageLocation'; +} from '@/platform/tauriCapabilities'; const baseInfo: StorageLocationInfo = { currentPath: '/home/u/.config/tabularis', diff --git a/tests/utils/stripSqlComments.test.ts b/packages/web-ui/tests/utils/stripSqlComments.test.ts similarity index 99% rename from tests/utils/stripSqlComments.test.ts rename to packages/web-ui/tests/utils/stripSqlComments.test.ts index d6c237eff..ace579e4b 100644 --- a/tests/utils/stripSqlComments.test.ts +++ b/packages/web-ui/tests/utils/stripSqlComments.test.ts @@ -1,7 +1,7 @@ import {describe, expect, it} from 'vitest'; import {canStripSqlComments, stripSqlComments} from '@/utils/stripSqlComments'; import {resolveSqlSyntax} from '@/utils/sqlSyntax'; -import {GOOGLESQL} from '../fixtures/sql-syntax/googlesql'; +import {GOOGLESQL} from '../../../../tests/fixtures/sql-syntax/googlesql'; describe('stripSqlComments', () => { it('removes a line comment and keeps the SQL', () => { diff --git a/packages/web-ui/tests/utils/supportPrompt.test.ts b/packages/web-ui/tests/utils/supportPrompt.test.ts new file mode 100644 index 000000000..c51e04c4b --- /dev/null +++ b/packages/web-ui/tests/utils/supportPrompt.test.ts @@ -0,0 +1,72 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import { + SUPPORT_PROMPT_DISMISSED_KEY, + dismissSupportPrompt, + isSupportPromptDismissed, + subscribeToSupportPrompt, +} from '@/utils/supportPrompt'; +import {uiStateStore} from '@/utils/uiStateStore'; + +function attachClient( + call = vi.fn(async (command: string) => (command === 'get_ui_state' ? {} : undefined)), +) { + const client = { + call, + subscribe: vi.fn(async () => () => {}), + } as unknown as TabularisClient; + const detach = uiStateStore.attach(client); + return {call, detach}; +} + +describe('supportPrompt', () => { + beforeEach(() => { + localStorage.clear(); + uiStateStore.reset(); + }); + afterEach(() => vi.restoreAllMocks()); + + it('defaults to visible and only treats true as dismissed', async () => { + expect(isSupportPromptDismissed()).toBe(false); + uiStateStore.set(SUPPORT_PROMPT_DISMISSED_KEY, 'true'); + expect(isSupportPromptDismissed()).toBe(false); + await dismissSupportPrompt(); + expect(isSupportPromptDismissed()).toBe(true); + }); + + it('persists dismissal in the shared store before notifying subscribers', async () => { + const {call, detach} = attachClient(); + const listener = vi.fn(() => expect(isSupportPromptDismissed()).toBe(true)); + await Promise.resolve(); + const unsubscribe = subscribeToSupportPrompt(listener); + try { + await dismissSupportPrompt(); + expect(call).toHaveBeenCalledWith('set_ui_state', { + key: SUPPORT_PROMPT_DISMISSED_KEY, + value: true, + }); + expect(listener).toHaveBeenCalled(); + } finally { + unsubscribe(); + detach(); + } + }); + + it('propagates write failures without notifying subscribers', async () => { + const {detach} = attachClient( + vi.fn(async (command: string) => { + if (command === 'get_ui_state') return {}; + throw new Error('Storage unavailable'); + }), + ); + const listener = vi.fn(); + const unsubscribe = subscribeToSupportPrompt(listener); + try { + await expect(dismissSupportPrompt()).rejects.toThrow('Storage unavailable'); + expect(isSupportPromptDismissed()).toBe(false); + } finally { + unsubscribe(); + detach(); + } + }); +}); diff --git a/tests/utils/systemTheme.test.ts b/packages/web-ui/tests/utils/systemTheme.test.ts similarity index 100% rename from tests/utils/systemTheme.test.ts rename to packages/web-ui/tests/utils/systemTheme.test.ts diff --git a/tests/utils/tabCleaner.test.ts b/packages/web-ui/tests/utils/tabCleaner.test.ts similarity index 100% rename from tests/utils/tabCleaner.test.ts rename to packages/web-ui/tests/utils/tabCleaner.test.ts diff --git a/tests/utils/tabDnd.test.ts b/packages/web-ui/tests/utils/tabDnd.test.ts similarity index 100% rename from tests/utils/tabDnd.test.ts rename to packages/web-ui/tests/utils/tabDnd.test.ts diff --git a/tests/utils/tabFilters.test.ts b/packages/web-ui/tests/utils/tabFilters.test.ts similarity index 100% rename from tests/utils/tabFilters.test.ts rename to packages/web-ui/tests/utils/tabFilters.test.ts diff --git a/tests/utils/tabScroll.test.ts b/packages/web-ui/tests/utils/tabScroll.test.ts similarity index 100% rename from tests/utils/tabScroll.test.ts rename to packages/web-ui/tests/utils/tabScroll.test.ts diff --git a/tests/utils/tableQueryTemplateSchema.test.ts b/packages/web-ui/tests/utils/tableQueryTemplateSchema.test.ts similarity index 80% rename from tests/utils/tableQueryTemplateSchema.test.ts rename to packages/web-ui/tests/utils/tableQueryTemplateSchema.test.ts index 64215c69a..27c96f6c6 100644 --- a/tests/utils/tableQueryTemplateSchema.test.ts +++ b/packages/web-ui/tests/utils/tableQueryTemplateSchema.test.ts @@ -1,6 +1,6 @@ import {describe, expect, it} from 'vitest'; -import manifestSchema from '../../plugins/manifest.schema.json'; -import extensionsSchema from '../../plugins/tabularium-extensions.schema.json'; +import manifestSchema from '../../../../plugins/manifest.schema.json'; +import extensionsSchema from '../../../../plugins/tabularium-extensions.schema.json'; describe('table query template manifest contract', () => { for (const [name, schema] of Object.entries({manifestSchema, extensionsSchema})) { diff --git a/tests/utils/tableQueryTemplates.test.ts b/packages/web-ui/tests/utils/tableQueryTemplates.test.ts similarity index 75% rename from tests/utils/tableQueryTemplates.test.ts rename to packages/web-ui/tests/utils/tableQueryTemplates.test.ts index 3a4eaaebc..51a212e59 100644 --- a/tests/utils/tableQueryTemplates.test.ts +++ b/packages/web-ui/tests/utils/tableQueryTemplates.test.ts @@ -1,8 +1,8 @@ -import {invoke} from '@tauri-apps/api/core'; import {beforeEach, describe, expect, it, vi} from 'vitest'; import {loadTableQueryTemplates} from '@/utils/tableQueryTemplates'; -const invokeMock = vi.mocked(invoke); +const invokeMock = vi.fn(); +const client = {call: invokeMock}; describe('loadTableQueryTemplates', () => { beforeEach(() => { @@ -11,7 +11,9 @@ describe('loadTableQueryTemplates', () => { it('requests all four previews without executing SQL', async () => { invokeMock.mockResolvedValue('driver SQL'); - const result = await loadTableQueryTemplates('connection', 'orders', undefined, ['id']); + const result = await loadTableQueryTemplates(client, 'connection', 'orders', undefined, [ + 'id', + ]); expect(result).toEqual({ 'select-all': 'driver SQL', 'select-fields': 'driver SQL', @@ -27,6 +29,7 @@ describe('loadTableQueryTemplates', () => { ]) { expect(invokeMock).toHaveBeenCalledWith('get_table_query_template', { connectionId: 'connection', + database: undefined, request: {table: 'orders', schema: null, kind, columns, limit}, }); } @@ -34,7 +37,7 @@ describe('loadTableQueryTemplates', () => { it('forwards an explicit database override to every RPC call', async () => { invokeMock.mockResolvedValue('driver SQL'); - await loadTableQueryTemplates('connection', 'orders', 'sales', ['id'], 'analytics'); + await loadTableQueryTemplates(client, 'connection', 'orders', 'sales', ['id'], 'analytics'); expect(invokeMock).toHaveBeenCalledWith('get_table_query_template', { connectionId: 'connection', request: {table: 'orders', schema: 'sales', kind: 'select', columns: [], limit: null}, @@ -44,9 +47,11 @@ describe('loadTableQueryTemplates', () => { it('keeps null as the explicit fallback signal and propagates failures', async () => { invokeMock.mockResolvedValue(null); - expect((await loadTableQueryTemplates('c', 't', 's', []))['select-fields']).toBeNull(); + expect( + (await loadTableQueryTemplates(client, 'c', 't', 's', []))['select-fields'], + ).toBeNull(); invokeMock.mockRejectedValue(new Error('permission denied')); - await expect(loadTableQueryTemplates('c', 't', 's', [])).rejects.toThrow( + await expect(loadTableQueryTemplates(client, 'c', 't', 's', [])).rejects.toThrow( 'permission denied', ); }); diff --git a/tests/utils/tableToolbar.test.ts b/packages/web-ui/tests/utils/tableToolbar.test.ts similarity index 100% rename from tests/utils/tableToolbar.test.ts rename to packages/web-ui/tests/utils/tableToolbar.test.ts diff --git a/tests/utils/taskManager.test.ts b/packages/web-ui/tests/utils/taskManager.test.ts similarity index 100% rename from tests/utils/taskManager.test.ts rename to packages/web-ui/tests/utils/taskManager.test.ts diff --git a/tests/utils/text.test.ts b/packages/web-ui/tests/utils/text.test.ts similarity index 100% rename from tests/utils/text.test.ts rename to packages/web-ui/tests/utils/text.test.ts diff --git a/tests/utils/themeArchive.test.ts b/packages/web-ui/tests/utils/themeArchive.test.ts similarity index 100% rename from tests/utils/themeArchive.test.ts rename to packages/web-ui/tests/utils/themeArchive.test.ts diff --git a/tests/utils/themeBoot.test.ts b/packages/web-ui/tests/utils/themeBoot.test.ts similarity index 100% rename from tests/utils/themeBoot.test.ts rename to packages/web-ui/tests/utils/themeBoot.test.ts diff --git a/tests/utils/themeCatalog.test.ts b/packages/web-ui/tests/utils/themeCatalog.test.ts similarity index 100% rename from tests/utils/themeCatalog.test.ts rename to packages/web-ui/tests/utils/themeCatalog.test.ts diff --git a/tests/utils/themeColor.test.ts b/packages/web-ui/tests/utils/themeColor.test.ts similarity index 100% rename from tests/utils/themeColor.test.ts rename to packages/web-ui/tests/utils/themeColor.test.ts diff --git a/tests/utils/themeContrast.test.ts b/packages/web-ui/tests/utils/themeContrast.test.ts similarity index 100% rename from tests/utils/themeContrast.test.ts rename to packages/web-ui/tests/utils/themeContrast.test.ts diff --git a/tests/utils/themeDefinitionEditing.test.ts b/packages/web-ui/tests/utils/themeDefinitionEditing.test.ts similarity index 100% rename from tests/utils/themeDefinitionEditing.test.ts rename to packages/web-ui/tests/utils/themeDefinitionEditing.test.ts diff --git a/tests/utils/themeDiscovery.test.ts b/packages/web-ui/tests/utils/themeDiscovery.test.ts similarity index 100% rename from tests/utils/themeDiscovery.test.ts rename to packages/web-ui/tests/utils/themeDiscovery.test.ts diff --git a/tests/utils/themeExportPermissions.test.ts b/packages/web-ui/tests/utils/themeExportPermissions.test.ts similarity index 81% rename from tests/utils/themeExportPermissions.test.ts rename to packages/web-ui/tests/utils/themeExportPermissions.test.ts index 28a7b1635..f67f02fc7 100644 --- a/tests/utils/themeExportPermissions.test.ts +++ b/packages/web-ui/tests/utils/themeExportPermissions.test.ts @@ -1,5 +1,5 @@ import {describe, expect, it} from 'vitest'; -import capability from '../../src-tauri/capabilities/theme-package-export.json'; +import capability from '../../../../src-tauri/capabilities/theme-package-export.json'; describe('theme ZIP export capability', () => { it('adds only binary file writing in the main window, without broader filesystem scopes', () => { diff --git a/tests/utils/themeManagement.test.ts b/packages/web-ui/tests/utils/themeManagement.test.ts similarity index 100% rename from tests/utils/themeManagement.test.ts rename to packages/web-ui/tests/utils/themeManagement.test.ts diff --git a/tests/utils/themePackageExport.test.ts b/packages/web-ui/tests/utils/themePackageExport.test.ts similarity index 100% rename from tests/utils/themePackageExport.test.ts rename to packages/web-ui/tests/utils/themePackageExport.test.ts diff --git a/tests/utils/themePackageIdentity.test.ts b/packages/web-ui/tests/utils/themePackageIdentity.test.ts similarity index 100% rename from tests/utils/themePackageIdentity.test.ts rename to packages/web-ui/tests/utils/themePackageIdentity.test.ts diff --git a/tests/utils/themePackageValidation.test.ts b/packages/web-ui/tests/utils/themePackageValidation.test.ts similarity index 100% rename from tests/utils/themePackageValidation.test.ts rename to packages/web-ui/tests/utils/themePackageValidation.test.ts diff --git a/tests/utils/themeReadme.test.ts b/packages/web-ui/tests/utils/themeReadme.test.ts similarity index 100% rename from tests/utils/themeReadme.test.ts rename to packages/web-ui/tests/utils/themeReadme.test.ts diff --git a/tests/utils/themeResolver.test.ts b/packages/web-ui/tests/utils/themeResolver.test.ts similarity index 100% rename from tests/utils/themeResolver.test.ts rename to packages/web-ui/tests/utils/themeResolver.test.ts diff --git a/tests/utils/themeSchemaHints.test.ts b/packages/web-ui/tests/utils/themeSchemaHints.test.ts similarity index 100% rename from tests/utils/themeSchemaHints.test.ts rename to packages/web-ui/tests/utils/themeSchemaHints.test.ts diff --git a/tests/utils/themeSchemaParity.test.ts b/packages/web-ui/tests/utils/themeSchemaParity.test.ts similarity index 100% rename from tests/utils/themeSchemaParity.test.ts rename to packages/web-ui/tests/utils/themeSchemaParity.test.ts diff --git a/tests/utils/themeSnapshotSchema.test.ts b/packages/web-ui/tests/utils/themeSnapshotSchema.test.ts similarity index 84% rename from tests/utils/themeSnapshotSchema.test.ts rename to packages/web-ui/tests/utils/themeSnapshotSchema.test.ts index c690cc324..a8ea9fd4f 100644 --- a/tests/utils/themeSnapshotSchema.test.ts +++ b/packages/web-ui/tests/utils/themeSnapshotSchema.test.ts @@ -1,8 +1,8 @@ import {describe, expect, it} from 'vitest'; import Ajv from 'ajv'; import schema from '@/schemas/theme-snapshot-v1.json'; -import vectors from '../fixtures/themes/snapshot-editor-vectors.json'; -import legacy from '../fixtures/themes/legacy-frontend.json'; +import vectors from '../../../../tests/fixtures/themes/snapshot-editor-vectors.json'; +import legacy from '../../../../tests/fixtures/themes/legacy-frontend.json'; const validate = new Ajv({strict: false}).compile(schema); describe('portable snapshot public schema', () => { diff --git a/tests/utils/themeSystemEvents.test.ts b/packages/web-ui/tests/utils/themeSystemEvents.test.ts similarity index 60% rename from tests/utils/themeSystemEvents.test.ts rename to packages/web-ui/tests/utils/themeSystemEvents.test.ts index e388c0a03..dc8a901b1 100644 --- a/tests/utils/themeSystemEvents.test.ts +++ b/packages/web-ui/tests/utils/themeSystemEvents.test.ts @@ -1,5 +1,11 @@ import {beforeEach, expect, it, vi} from 'vitest'; -import {listenForSystemThemeChanges} from '@/utils/themeSystemEvents'; +import {listenForTauriSystemThemeChanges as listenForSystemThemeChanges} from '@/platform/tauriCapabilities'; +import { + getSystemIsDark, + listenForSystemThemeChanges as listenThroughActivePlatform, +} from '@/utils/themeSystemEvents'; +import {registerActivePlatformCapabilities} from '@/platform/activeCapabilities'; +import type {PlatformCapabilities} from '@/platform/capabilities'; const native = vi.hoisted(() => ({theme: vi.fn(), onThemeChanged: vi.fn()})); vi.mock('@tauri-apps/api/window', () => ({getCurrentWindow: () => native})); @@ -38,3 +44,16 @@ it('does not allow a delayed initial read to override a newer event', async () = expect(change).toHaveBeenLastCalledWith(false); stop(); }); + +it('delegates to the registered platform', async () => { + const stop = vi.fn(); + const platform = { + getSystemIsDark: vi.fn().mockResolvedValue(true), + listenForSystemThemeChanges: vi.fn().mockResolvedValue(stop), + }; + registerActivePlatformCapabilities(platform as unknown as PlatformCapabilities); + const change = vi.fn(); + await expect(getSystemIsDark()).resolves.toBe(true); + await expect(listenThroughActivePlatform(change)).resolves.toBe(stop); + expect(platform.listenForSystemThemeChanges).toHaveBeenCalledWith(change); +}); diff --git a/tests/utils/themeValidationParity.test.ts b/packages/web-ui/tests/utils/themeValidationParity.test.ts similarity index 87% rename from tests/utils/themeValidationParity.test.ts rename to packages/web-ui/tests/utils/themeValidationParity.test.ts index edc38e0e0..9d681557d 100644 --- a/tests/utils/themeValidationParity.test.ts +++ b/packages/web-ui/tests/utils/themeValidationParity.test.ts @@ -1,5 +1,5 @@ import {describe, expect, it} from 'vitest'; -import vectors from '../fixtures/themes/validation-v1.json'; +import vectors from '../../../../tests/fixtures/themes/validation-v1.json'; import {parseThemeDefinition, parseThemePackageManifest} from '@/utils/themePackageValidation'; describe('shared native/frontend v1 validation vectors', () => { diff --git a/tests/utils/tones.test.ts b/packages/web-ui/tests/utils/tones.test.ts similarity index 100% rename from tests/utils/tones.test.ts rename to packages/web-ui/tests/utils/tones.test.ts diff --git a/tests/utils/triggerSql.test.ts b/packages/web-ui/tests/utils/triggerSql.test.ts similarity index 100% rename from tests/utils/triggerSql.test.ts rename to packages/web-ui/tests/utils/triggerSql.test.ts diff --git a/packages/web-ui/tests/utils/uiStateStore.test.ts b/packages/web-ui/tests/utils/uiStateStore.test.ts new file mode 100644 index 000000000..54326f0d0 --- /dev/null +++ b/packages/web-ui/tests/utils/uiStateStore.test.ts @@ -0,0 +1,251 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import type {TabularisClient} from '@/api/client'; +import {UI_STATE_CACHE_KEY, UI_STATE_KEYS, UiStateStore} from '@/utils/uiStateStore'; + +const SIDEBAR = UI_STATE_KEYS.sidebarWidth.key; +const LAST_SEEN = UI_STATE_KEYS.lastSeenVersion.key; +const SUPPORT = UI_STATE_KEYS.supportPromptDismissed.key; + +type ChangeHandler = (payload: {key: string; value: unknown}) => void; + +function mockClient(remote: Record | Error = {}) { + let handler: ChangeHandler | undefined; + const unsubscribe = vi.fn(); + const call = vi.fn(async (command: string) => { + if (command === 'get_ui_state') { + if (remote instanceof Error) throw remote; + return remote; + } + return undefined; + }); + const subscribe = vi.fn(async (_event: string, next: ChangeHandler) => { + handler = next; + return unsubscribe; + }); + return { + call, + subscribe, + unsubscribe, + emit: (key: string, value: unknown) => handler?.({key, value}), + client: {call, subscribe} as unknown as TabularisClient, + }; +} + +async function settle() { + for (let i = 0; i < 5; i += 1) await Promise.resolve(); +} + +describe('UiStateStore', () => { + beforeEach(() => { + localStorage.clear(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('loads every known key once and becomes ready', async () => { + const store = new UiStateStore(); + const mock = mockClient({[SIDEBAR]: 320, [LAST_SEEN]: '1.0.0'}); + const listener = vi.fn(); + store.subscribe(listener); + + expect(store.isReady()).toBe(false); + store.attach(mock.client); + await settle(); + + expect(mock.call).toHaveBeenCalledTimes(1); + expect(mock.call).toHaveBeenCalledWith('get_ui_state', { + keys: Object.values(UI_STATE_KEYS).map(({key}) => key), + }); + expect(store.isReady()).toBe(true); + expect(store.get(SIDEBAR, 256)).toBe(320); + expect(store.get(LAST_SEEN, null)).toBe('1.0.0'); + expect(store.get(SUPPORT, false)).toBe(false); + expect(listener).toHaveBeenCalled(); + }); + + it('writes values through the backend and deletes cleared ones', async () => { + const store = new UiStateStore(); + const mock = mockClient(); + store.attach(mock.client); + await settle(); + + store.set(LAST_SEEN, '2.0.0'); + store.set(LAST_SEEN, null); + await settle(); + + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: LAST_SEEN, value: '2.0.0'}); + expect(mock.call).toHaveBeenCalledWith('delete_ui_state', {key: LAST_SEEN}); + expect(store.get(LAST_SEEN, 'fallback')).toBe('fallback'); + }); + + it('debounces rapid writes and flushes them on demand', async () => { + vi.useFakeTimers(); + const store = new UiStateStore(); + const mock = mockClient(); + store.attach(mock.client); + await settle(); + mock.call.mockClear(); + + store.set(SIDEBAR, 300, {debounceMs: 200}); + store.set(SIDEBAR, 310, {debounceMs: 200}); + expect(store.get(SIDEBAR, 0)).toBe(310); + expect(mock.call).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(200); + expect(mock.call).toHaveBeenCalledTimes(1); + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: SIDEBAR, value: 310}); + + store.set(SIDEBAR, 330, {debounceMs: 200}); + store.flush(); + expect(mock.call).toHaveBeenLastCalledWith('set_ui_state', {key: SIDEBAR, value: 330}); + vi.advanceTimersByTime(500); + expect(mock.call).toHaveBeenCalledTimes(2); + }); + + it('follows changes from other windows but keeps a pending local write', async () => { + vi.useFakeTimers(); + const store = new UiStateStore(); + const mock = mockClient(); + store.attach(mock.client); + await settle(); + + mock.emit(LAST_SEEN, '3.0.0'); + expect(store.get(LAST_SEEN, null)).toBe('3.0.0'); + mock.emit(LAST_SEEN, null); + expect(store.get(LAST_SEEN, null)).toBeNull(); + + store.set(SIDEBAR, 400, {debounceMs: 200}); + mock.emit(SIDEBAR, 250); + expect(store.get(SIDEBAR, 0)).toBe(400); + }); + + it('migrates values older versions kept in localStorage', async () => { + localStorage.setItem(SIDEBAR, '300'); + localStorage.setItem(SUPPORT, 'true'); + localStorage.setItem(LAST_SEEN, '0.9.0'); + const store = new UiStateStore(); + const mock = mockClient({[LAST_SEEN]: '1.2.0'}); + store.attach(mock.client); + await settle(); + + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: SIDEBAR, value: 300}); + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: SUPPORT, value: true}); + // The backend value wins over the one this host had. + expect(mock.call).not.toHaveBeenCalledWith('set_ui_state', { + key: LAST_SEEN, + value: '0.9.0', + }); + expect(store.get(LAST_SEEN, null)).toBe('1.2.0'); + expect(store.get(SUPPORT, false)).toBe(true); + for (const key of [SIDEBAR, SUPPORT, LAST_SEEN]) { + expect(localStorage.getItem(key)).toBeNull(); + } + }); + + it('ignores legacy values it cannot parse', async () => { + localStorage.setItem(SUPPORT, 'false'); + const store = new UiStateStore(); + const mock = mockClient(); + store.attach(mock.client); + await settle(); + + expect(mock.call).not.toHaveBeenCalledWith('set_ui_state', expect.anything()); + expect(store.get(SUPPORT, false)).toBe(false); + }); + + it('keeps the legacy value when migrating it fails', async () => { + localStorage.setItem(SUPPORT, 'true'); + const store = new UiStateStore(); + const mock = mockClient(); + mock.call.mockImplementation(async (command: string) => { + if (command === 'get_ui_state') return {}; + throw new Error('disk full'); + }); + store.attach(mock.client); + await settle(); + + expect(store.get(SUPPORT, false)).toBe(true); + expect(localStorage.getItem(SUPPORT)).toBe('true'); + }); + + it('falls back to local values when the backend cannot be read', async () => { + localStorage.setItem(SIDEBAR, '300'); + const store = new UiStateStore(); + const mock = mockClient(new Error('offline')); + store.attach(mock.client); + await settle(); + + expect(store.isReady()).toBe(true); + expect(store.get(SIDEBAR, 256)).toBe(300); + expect(localStorage.getItem(SIDEBAR)).toBe('300'); + }); + + it('does not let a slow load overwrite a local change', async () => { + let resolve: (value: Record) => void = () => {}; + const store = new UiStateStore(); + const mock = mockClient(); + mock.call.mockImplementation((command: string) => + command === 'get_ui_state' + ? new Promise((next) => { + resolve = next; + }) + : Promise.resolve(undefined), + ); + store.attach(mock.client); + store.set(SIDEBAR, 450); + resolve({[SIDEBAR]: 200}); + await settle(); + + expect(store.get(SIDEBAR, 0)).toBe(450); + }); + + it('keeps layout values in a first-paint cache only', async () => { + const store = new UiStateStore(); + store.attach(mockClient().client); + await settle(); + store.set(SIDEBAR, 333); + store.set(LAST_SEEN, '1.0.0'); + + expect(JSON.parse(localStorage.getItem(UI_STATE_CACHE_KEY) ?? '{}')).toEqual({ + [SIDEBAR]: 333, + }); + const next = new UiStateStore(); + expect(next.get(SIDEBAR, 256)).toBe(333); + expect(next.get(LAST_SEEN, null)).toBeNull(); + }); + + it('commits before notifying and rejects without changing the value', async () => { + const store = new UiStateStore(); + const mock = mockClient(); + store.attach(mock.client); + await settle(); + const listener = vi.fn(); + store.subscribe(listener); + + mock.call.mockRejectedValueOnce(new Error('denied')); + await expect(store.commit(SUPPORT, true)).rejects.toThrow('denied'); + expect(store.get(SUPPORT, false)).toBe(false); + expect(listener).not.toHaveBeenCalled(); + + await store.commit(SUPPORT, true); + expect(store.get(SUPPORT, false)).toBe(true); + expect(listener).toHaveBeenCalledOnce(); + }); + + it('stops following changes and flushes writes when detached', async () => { + vi.useFakeTimers(); + const store = new UiStateStore(); + const mock = mockClient(); + const detach = store.attach(mock.client); + await settle(); + + store.set(SIDEBAR, 290, {debounceMs: 200}); + detach(); + + expect(mock.unsubscribe).toHaveBeenCalledOnce(); + expect(mock.call).toHaveBeenCalledWith('set_ui_state', {key: SIDEBAR, value: 290}); + }); +}); diff --git a/tests/utils/versionCompare.test.ts b/packages/web-ui/tests/utils/versionCompare.test.ts similarity index 100% rename from tests/utils/versionCompare.test.ts rename to packages/web-ui/tests/utils/versionCompare.test.ts diff --git a/tests/utils/visualQuery.test.ts b/packages/web-ui/tests/utils/visualQuery.test.ts similarity index 100% rename from tests/utils/visualQuery.test.ts rename to packages/web-ui/tests/utils/visualQuery.test.ts diff --git a/tests/utils/vsCodeThemeImport.test.ts b/packages/web-ui/tests/utils/vsCodeThemeImport.test.ts similarity index 100% rename from tests/utils/vsCodeThemeImport.test.ts rename to packages/web-ui/tests/utils/vsCodeThemeImport.test.ts diff --git a/tests/version.test.ts b/packages/web-ui/tests/version.test.ts similarity index 100% rename from tests/version.test.ts rename to packages/web-ui/tests/version.test.ts diff --git a/tests/workers/layoutWorker.test.ts b/packages/web-ui/tests/workers/layoutWorker.test.ts similarity index 100% rename from tests/workers/layoutWorker.test.ts rename to packages/web-ui/tests/workers/layoutWorker.test.ts diff --git a/tsconfig.app.json b/packages/web-ui/tsconfig.app.json similarity index 68% rename from tsconfig.app.json rename to packages/web-ui/tsconfig.app.json index bce8ff5da..b00b3cf13 100644 --- a/tsconfig.app.json +++ b/packages/web-ui/tsconfig.app.json @@ -10,14 +10,12 @@ /* Bundler mode */ "moduleResolution": "bundler", + "paths": {"@/*": ["./src/*"]}, "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx", - "paths": { - "@/*": ["./src/*"] - }, /* Linting */ "strict": true, @@ -28,10 +26,13 @@ "noUncheckedSideEffectImports": true }, "include": [ - "src", - "tests/setup.ts", - "tests/components/layout/sidebar/Accordion.test.tsx", - "tests/components/layout/sidebar/NavItem.test.tsx", - "tests/utils/triggerSql.test.ts" + "./src", + "./tests/setup.ts", + "./tests/api/contract.type-test.ts", + "./tests/api/contract/**/*.ts", + "./tests/api/dualTransportContract.test.ts", + "./tests/components/layout/Accordion.test.tsx", + "./tests/components/layout/NavItem.test.tsx", + "./tests/utils/triggerSql.test.ts" ] } diff --git a/tsconfig.json b/packages/web-ui/tsconfig.json similarity index 100% rename from tsconfig.json rename to packages/web-ui/tsconfig.json diff --git a/tsconfig.node.json b/packages/web-ui/tsconfig.node.json similarity index 92% rename from tsconfig.node.json rename to packages/web-ui/tsconfig.node.json index 8a67f62f4..7ad54d46b 100644 --- a/tsconfig.node.json +++ b/packages/web-ui/tsconfig.node.json @@ -22,5 +22,5 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "vitest.config.ts"] } diff --git a/vite.config.ts b/packages/web-ui/vite.config.ts similarity index 80% rename from vite.config.ts rename to packages/web-ui/vite.config.ts index afb1061d5..957e1f855 100644 --- a/vite.config.ts +++ b/packages/web-ui/vite.config.ts @@ -1,14 +1,23 @@ -import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + import {defineConfig} from 'vite'; import react from '@vitejs/plugin-react'; -// https://vite.dev/config/ +import {WEB_UI_BASE_PATH} from './src/routing'; + +const webUiRoot = fileURLToPath(new URL('.', import.meta.url)); + export default defineConfig({ + appType: 'spa', + base: WEB_UI_BASE_PATH, plugins: [react()], + css: { + postcss: webUiRoot, + }, server: {watch: {ignored: ['**/src-tauri/**']}}, resolve: { alias: { - '@': path.resolve(__dirname, './src'), + '@': fileURLToPath(new URL('./src', import.meta.url)), // Polyfills for browser environment (needed by wkx library) buffer: 'buffer', util: 'util', diff --git a/packages/web-ui/vitest.config.ts b/packages/web-ui/vitest.config.ts new file mode 100644 index 000000000..2702a8daf --- /dev/null +++ b/packages/web-ui/vitest.config.ts @@ -0,0 +1,42 @@ +/// +import {fileURLToPath} from 'node:url'; + +import react from '@vitejs/plugin-react'; +import {defineConfig} from 'vitest/config'; + +const repositoryRoot = fileURLToPath(new URL('../..', import.meta.url)); +const sourceRoot = fileURLToPath(new URL('./src', import.meta.url)); + +export default defineConfig({ + root: repositoryRoot, + plugins: [react()], + resolve: { + alias: { + '@': sourceRoot, + }, + }, + test: { + globals: true, + environment: 'jsdom', + setupFiles: ['./packages/web-ui/tests/setup.ts'], + include: [ + 'packages/web-ui/tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', + // Other workspace packages (packages/*) run their own vitest with a node + // environment via `pnpm --filter test` (see packages.yml). They are + // deliberately not included here: the jsdom environment breaks Node-only + // tests (Vite rewrites `new URL(x, import.meta.url)` against location). + // Web UI project tooling tests live with the tracked migration process. + 'web-ui-project/tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', + ], + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + include: ['packages/web-ui/src/**/*.ts', 'packages/web-ui/src/**/*.tsx'], + exclude: [ + 'packages/web-ui/src/**/*.test.ts', + 'packages/web-ui/src/**/*.d.ts', + 'packages/web-ui/src/test/**', + ], + }, + }, +}); diff --git a/plugins/PLUGIN_GUIDE.md b/plugins/PLUGIN_GUIDE.md index 22c759051..66977b9b5 100644 --- a/plugins/PLUGIN_GUIDE.md +++ b/plugins/PLUGIN_GUIDE.md @@ -498,15 +498,18 @@ Add an optional `ui_extensions` array to your manifest: { "slot": "row-editor-sidebar.field.after", "module": "ui/field-preview.js", + "api_version": "0.1.1", "order": 50 }, { "slot": "data-grid.toolbar.actions", - "module": "ui/export-button.js" + "module": "ui/export-button.js", + "api_version": "0.1.1" }, { "slot": "settings.plugin.before_settings", "module": "ui/auth-panel.js", + "api_version": "0.1.1", "driver": "my-plugin" } ] @@ -521,6 +524,7 @@ Add an optional `ui_extensions` array to your manifest: | `module` | string | yes | Relative path to the pre-built IIFE JavaScript bundle inside the plugin folder. | | `order` | number | no | Sort order within the slot. Lower values render first. Default: `100`. | | `driver` | string | no | If set, the contribution is only active when the active connection's driver matches this value. Useful for plugins that should only appear for their own driver. | +| `api_version` | string | recommended | Exact `@tabularis/plugin-api` version used to build the bundle. Incompatible bundles are skipped before execution. Omit only for legacy compatibility. | ### Available Slots @@ -592,6 +596,8 @@ back to the host `password` input when `setSecretField` is undefined). ### Building UI Extension Bundles +Installed UI extensions execute as trusted application code rather than sandboxed widgets. Review the [plugin UI extension trust model](../docs/security/plugin-ui-extensions.md) before distributing or installing third-party bundles. + Plugin UI components must be pre-built as **IIFE bundles** (Immediately Invoked Function Expression). The host provides `React`, `ReactJSXRuntime`, and the plugin API as globals — your bundle must **not** bundle its own copies of these. #### Installing the plugin API types diff --git a/plugins/tabularium-extensions.schema.json b/plugins/tabularium-extensions.schema.json index da7b62ef5..e4b44f0ca 100644 --- a/plugins/tabularium-extensions.schema.json +++ b/plugins/tabularium-extensions.schema.json @@ -418,6 +418,11 @@ "type": "integer", "minimum": 0, "description": "Ordering weight when multiple plugins target the same slot. Lower runs first." + }, + "api_version": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$", + "description": "@tabularis/plugin-api version used to build the bundle." } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 827024dde..910f19604 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -41,6 +41,9 @@ importers: '@tauri-apps/plugin-opener': specifier: ^2.5.3 version: 2.5.3 + '@tauri-apps/plugin-updater': + specifier: ~2.10.0 + version: 2.10.1 '@types/dagre': specifier: ^0.7.54 version: 0.7.54 @@ -126,6 +129,9 @@ importers: '@eslint/js': specifier: ^9.39.4 version: 9.39.4 + '@playwright/test': + specifier: ^1.62.1 + version: 1.62.1 '@tauri-apps/cli': specifier: ^2.11.4 version: 2.11.4 @@ -287,6 +293,42 @@ importers: specifier: ~5.9.3 version: 5.9.3 + packages/web-ui: + devDependencies: + '@tailwindcss/postcss': + specifier: ^4.2.2 + version: 4.2.2 + '@types/node': + specifier: ^24.12.0 + version: 24.12.0 + '@vitejs/plugin-react': + specifier: ^5.2.0 + version: 5.2.0(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)) + '@vitest/coverage-v8': + specifier: ^4.1.2 + version: 4.1.2(vitest@4.1.2(@types/node@24.12.0)(jsdom@28.1.0)(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0))) + autoprefixer: + specifier: ^10.4.27 + version: 10.4.27(postcss@8.5.8) + eslint: + specifier: ^9.39.4 + version: 9.39.4(jiti@2.6.1) + jsdom: + specifier: ^28.1.0 + version: 28.1.0 + postcss: + specifier: ^8.5.8 + version: 8.5.8 + typescript: + specifier: ~5.9.3 + version: 5.9.3 + vite: + specifier: ^7.3.1 + version: 7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.2 + version: 4.1.2(@types/node@24.12.0)(jsdom@28.1.0)(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)) + packages: '@acemir/cssom@0.9.31': @@ -914,6 +956,11 @@ packages: '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + '@playwright/test@1.62.1': + resolution: {integrity: sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==} + engines: {node: '>=20'} + hasBin: true + '@protobufjs/aspromise@1.1.2': resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} @@ -1323,6 +1370,9 @@ packages: '@tauri-apps/plugin-opener@2.5.3': resolution: {integrity: sha512-CCcUltXMOfUEArbf3db3kCE7Ggy1ExBEBl51Ko2ODJ6GDYHRp1nSNlQm5uNCFY5k7/ufaK5Ib3Du/Zir19IYQQ==} + '@tauri-apps/plugin-updater@2.10.1': + resolution: {integrity: sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==} + '@testing-library/dom@10.4.1': resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} engines: {node: '>=18'} @@ -2433,6 +2483,11 @@ packages: resolution: {integrity: sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==} engines: {node: '>=14.14'} + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -3439,6 +3494,16 @@ packages: platform@1.3.6: resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + playwright-core@1.62.1: + resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.62.1: + resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==} + engines: {node: '>=20'} + hasBin: true + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -4980,6 +5045,10 @@ snapshots: '@pinojs/redact@0.4.0': {} + '@playwright/test@1.62.1': + dependencies: + playwright: 1.62.1 + '@protobufjs/aspromise@1.1.2': {} '@protobufjs/base64@1.1.2': {} @@ -5261,6 +5330,10 @@ snapshots: dependencies: '@tauri-apps/api': 2.10.1 + '@tauri-apps/plugin-updater@2.10.1': + dependencies: + '@tauri-apps/api': 2.10.1 + '@testing-library/dom@10.4.1': dependencies: '@babel/code-frame': 7.29.0 @@ -6572,6 +6645,9 @@ snapshots: jsonfile: 6.2.1 universalify: 2.0.1 + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true @@ -7754,6 +7830,14 @@ snapshots: platform@1.3.6: {} + playwright-core@1.62.1: {} + + playwright@1.62.1: + dependencies: + playwright-core: 1.62.1 + optionalDependencies: + fsevents: 2.3.2 + possible-typed-array-names@1.1.0: {} postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.8)(tsx@4.21.0): diff --git a/scripts/check-theme-tokens.mjs b/scripts/check-theme-tokens.mjs index ce2916f94..7c537ebd2 100644 --- a/scripts/check-theme-tokens.mjs +++ b/scripts/check-theme-tokens.mjs @@ -3,7 +3,7 @@ * Theme token conformance check. * * Every color, radius and font the UI paints must come from the theme tokens - * described in docs/DESIGN.md, so that built-in and third-party themes (light, + * described in DESIGN.md, so that built-in and third-party themes (light, * dark, square-cornered, high-contrast) restyle the whole application. This * script fails when a source file reintroduces a hardcoded color: * @@ -30,88 +30,105 @@ import {join, relative, sep} from 'node:path'; import {fileURLToPath} from 'node:url'; const ROOT = join(fileURLToPath(import.meta.url), '..', '..'); -const SRC = join(ROOT, 'src'); -const SKIP_DIRS = ['src/themes', 'src/schemas', 'src/i18n']; +const SRC = join(ROOT, 'packages', 'web-ui', 'src'); +const SKIP_DIRS = [ + 'packages/web-ui/src/themes', + 'packages/web-ui/src/schemas', + 'packages/web-ui/src/i18n', +]; const EXTENSIONS = new Set(['.ts', '.tsx', '.css']); /** @type {Record, reason: string }>} */ const ALLOWLIST = { - 'src/index.css': { + 'packages/web-ui/src/index.css': { rules: ['hex', 'rgb'], reason: 'Tabularis Dark defaults for :root before a theme is applied', }, - 'src/App.css': {rules: ['hex'], reason: 'Vite scaffold leftovers, unused by the app'}, - 'src/utils/themeResolver.ts': { + 'packages/web-ui/src/App.css': { + rules: ['hex'], + reason: 'Vite scaffold leftovers, unused by the app', + }, + 'packages/web-ui/src/utils/themeResolver.ts': { rules: ['hex'], reason: 'theme engine: transparent constant used while resolving definitions', }, - 'src/utils/themePackageExport.ts': { + 'packages/web-ui/src/utils/themePackageExport.ts': { rules: ['hex'], reason: 'theme engine: transparent constant used while exporting definitions', }, - 'src/utils/themeContrast.ts': { + 'packages/web-ui/src/utils/themeContrast.ts': { rules: ['hex'], reason: 'contrast audit: black/white labels derived like --text-on-accent-*', }, - 'src/components/icons/ClientIcons.tsx': { + 'packages/web-ui/src/components/icons/ClientIcons.tsx': { rules: ['hex', 'palette'], reason: 'third-party brand marks', }, - 'src/components/icons/BrandIcons.tsx': { + 'packages/web-ui/src/components/icons/BrandIcons.tsx': { rules: ['hex', 'palette'], reason: 'third-party brand marks', }, - 'src/components/icons/DiscordIcon.tsx': { + 'packages/web-ui/src/components/icons/DiscordIcon.tsx': { rules: ['hex', 'palette'], reason: 'Discord brand mark', }, - 'src/components/layout/sidebar/DiscordCommunityCallout.tsx': { + 'packages/web-ui/src/components/layout/sidebar/DiscordCommunityCallout.tsx': { rules: ['palette', 'white'], reason: 'Discord-branded callout', }, - 'src/utils/notebookHtmlExport.ts': { + 'packages/web-ui/src/utils/notebookHtmlExport.ts': { rules: ['hex', 'rgb'], reason: 'standalone HTML document rendered outside the app', }, - 'src/hooks/useDrivers.ts': { + 'packages/web-ui/src/hooks/useDrivers.ts': { rules: ['hex'], reason: 'driver identity colors, shown next to the driver logo', }, - 'src/utils/driverUI.tsx': { + 'packages/web-ui/src/utils/driverUI.tsx': { rules: ['hex'], reason: 'neutral fallback for drivers without an identity color', }, - 'src/components/modals/NewConnectionModal.tsx': { + 'packages/web-ui/src/components/modals/NewConnectionModal.tsx': { rules: ['hex'], reason: 'database paradigm identity colors', }, - 'src/components/modals/connection/InstallGate.tsx': { + 'packages/web-ui/src/components/modals/connection/InstallGate.tsx': { rules: ['hex'], reason: 'database paradigm identity colors', }, - 'src/components/modals/connection/EngineCard.tsx': { + 'packages/web-ui/src/components/modals/connection/EngineCard.tsx': { rules: ['hex'], reason: 'database paradigm identity colors', }, - 'src/components/modals/NewConnectionModal/palette.ts': { + 'packages/web-ui/src/components/modals/NewConnectionModal/palette.ts': { rules: ['hex'], reason: 'swatches the user picks for connections and tags', }, - 'src/components/modals/NewConnectionModal/AppearanceSection.tsx': { + 'packages/web-ui/src/components/modals/NewConnectionModal/AppearanceSection.tsx': { rules: ['hex', 'rgb'], reason: 'user-picked connection color and its neutral swatch shadows', }, - 'src/components/settings/AiTab.tsx': {rules: ['hex'], reason: 'AI provider brand marks'}, - 'src/pages/McpPage.tsx': {rules: ['hex'], reason: 'AI client brand marks'}, - 'src/components/settings/InfoTab.tsx': { + 'packages/web-ui/src/components/settings/AiTab.tsx': { + rules: ['hex'], + reason: 'AI provider brand marks', + }, + 'packages/web-ui/src/pages/McpPage.tsx': {rules: ['hex'], reason: 'AI client brand marks'}, + 'packages/web-ui/src/components/modals/McpModal.tsx': { + rules: ['hex'], + reason: 'AI client brand marks', + }, + 'packages/web-ui/src/components/settings/InfoTab.tsx': { rules: ['hex'], reason: 'fallback when the theme has no surface color yet', }, - 'src/components/layout/Sidebar.tsx': { + 'packages/web-ui/src/components/layout/Sidebar.tsx': { rules: ['hex'], reason: 'fallback when the theme has no surface color yet', }, - 'src/components/ui/TableToolbar.tsx': {rules: ['rgb'], reason: 'neutral black drop shadow'}, + 'packages/web-ui/src/components/ui/TableToolbar.tsx': { + rules: ['rgb'], + reason: 'neutral black drop shadow', + }, }; const FAMILIES = @@ -168,7 +185,7 @@ function checkFile(full, rel, ext) { if (!allowed(rel, 'palette')) { for (const match of line.matchAll(PALETTE)) { report( - `Tailwind palette class "${match[0]}" bypasses the theme (use an accent/surface/semantic token, see docs/DESIGN.md)`, + `Tailwind palette class "${match[0]}" bypasses the theme (use an accent/surface/semantic token, see DESIGN.md)`, ); } } @@ -225,12 +242,12 @@ if (findings.length > 0) { `::error file=${file},line=${line},title=Theme token::${message.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A')}`, ); } - console.error('\nSee docs/DESIGN.md for the token to use in each case.'); + console.error('\nSee DESIGN.md for the token to use in each case.'); process.exit(1); } if (verbose) { console.log( - `Theme token check: scanned src/, allowlist has ${Object.keys(ALLOWLIST).length} file(s).`, + `Theme token check: scanned packages/web-ui/src/, allowlist has ${Object.keys(ALLOWLIST).length} file(s).`, ); } console.log('Theme token check: OK'); diff --git a/scripts/dev-web.mjs b/scripts/dev-web.mjs new file mode 100644 index 000000000..da8795886 --- /dev/null +++ b/scripts/dev-web.mjs @@ -0,0 +1,41 @@ +import {spawnSync} from 'node:child_process'; +import {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const rootDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const pnpmCommand = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'; +const forwardedArguments = process.argv.slice(2); + +const build = spawnSync(pnpmCommand, ['--filter', '@tabularis/web-ui', 'build'], { + cwd: rootDir, + stdio: 'inherit', +}); + +if (build.error) { + console.error(`Failed to start the Web UI build: ${build.error.message}`); + process.exit(1); +} +if (build.status !== 0) { + process.exit(build.status ?? 1); +} + +const server = spawnSync( + 'cargo', + [ + 'run', + '--manifest-path', + 'src-tauri/Cargo.toml', + '--', + 'web', + '--web-root', + join(rootDir, 'packages/web-ui/dist'), + ...forwardedArguments, + ], + {cwd: rootDir, stdio: 'inherit'}, +); + +if (server.error) { + console.error(`Failed to start the Web server: ${server.error.message}`); + process.exit(1); +} +process.exit(server.status ?? 1); diff --git a/scripts/set-nightly-version.mjs b/scripts/set-nightly-version.mjs index 8fdc982e5..9e0650729 100644 --- a/scripts/set-nightly-version.mjs +++ b/scripts/set-nightly-version.mjs @@ -7,7 +7,7 @@ if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-(0|[1-9]\d*)$/.test(version ?? ' const configPath = 'src-tauri/tauri.conf.json'; const cargoPath = 'src-tauri/Cargo.toml'; -const frontendPath = 'src/version.ts'; +const frontendPath = 'packages/web-ui/src/version.ts'; const config = JSON.parse(readFileSync(configPath, 'utf8')); const cargo = readFileSync(cargoPath, 'utf8'); const lines = cargo.split(/\r?\n/); diff --git a/scripts/sync-links.js b/scripts/sync-links.js index e9671c934..98209d3d2 100644 --- a/scripts/sync-links.js +++ b/scripts/sync-links.js @@ -4,7 +4,7 @@ import {resolve} from 'path'; // File paths const paths = { package: resolve('package.json'), - configLinks: resolve('src/config/links.ts'), + configLinks: resolve('packages/web-ui/src/config/links.ts'), readme: resolve('README.md'), contributing: resolve('CONTRIBUTING.md'), }; @@ -24,7 +24,7 @@ for (const [key, value] of entries) { console.log(` ${key}: ${value}`); } -// 2. Create/update src/config/links.ts +// 2. Create/update packages/web-ui/src/config/links.ts const constKey = (key) => key.toUpperCase().replace(/[^A-Z0-9]+/g, '_'); const linkLines = entries.map(([key, value]) => ` ${constKey(key)}: "${value}",`).join('\n'); const namedExports = entries @@ -48,7 +48,7 @@ ${namedExports} `; writeFileSync(paths.configLinks, linksConfig); -console.log('✅ Updated src/config/links.ts'); +console.log('✅ Updated packages/web-ui/src/config/links.ts'); // 3. Update README.md - Discord links let readme = readFileSync(paths.readme, 'utf-8'); @@ -63,4 +63,6 @@ writeFileSync(paths.contributing, contributing); console.log('✅ Updated CONTRIBUTING.md'); console.log('\n✨ All links synced successfully!'); -console.log('\n💡 React components automatically use the updated links from src/config/links.ts'); +console.log( + '\n💡 React components automatically use the updated links from packages/web-ui/src/config/links.ts', +); diff --git a/scripts/sync-version.js b/scripts/sync-version.js index 7178bbfa4..14ad1e1f7 100644 --- a/scripts/sync-version.js +++ b/scripts/sync-version.js @@ -6,7 +6,7 @@ const paths = { package: resolve('package.json'), tauri: resolve('src-tauri/tauri.conf.json'), cargo: resolve('src-tauri/Cargo.toml'), - appVersion: resolve('src/version.ts'), + appVersion: resolve('packages/web-ui/src/version.ts'), }; // README.md at the root plus its translations in docs/translations (README.it.md, README.zh-CN.md, ...) @@ -38,10 +38,10 @@ cargo = cargo.replace(/^version = ".*"/m, `version = "${newVersion}"`); writeFileSync(paths.cargo, cargo); console.log('✅ Updated Cargo.toml'); -// 4. Update src/version.ts +// 4. Update packages/web-ui/src/version.ts const versionContent = `export const APP_VERSION = "${newVersion}";\n`; writeFileSync(paths.appVersion, versionContent); -console.log('✅ Updated src/version.ts'); +console.log('✅ Updated packages/web-ui/src/version.ts'); // 5. Update download links in every README (all languages) for (const readmePath of readmeFiles) { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index de361bde7..f8b087674 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -431,13 +431,50 @@ dependencies = [ "fs_extra", ] +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core 0.4.5", + "base64 0.22.1", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit 0.7.3", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "axum" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "axum-core", + "axum-core 0.5.6", "bytes", "form_urlencoded", "futures-util", @@ -447,7 +484,7 @@ dependencies = [ "hyper", "hyper-util", "itoa", - "matchit", + "matchit 0.8.4", "memchr", "mime", "percent-encoding", @@ -464,6 +501,27 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "axum-core" version = "0.5.6" @@ -2746,6 +2804,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573" +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + [[package]] name = "httparse" version = "1.10.1" @@ -3502,6 +3566,12 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + [[package]] name = "matchit" version = "0.8.4" @@ -3545,6 +3615,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minisign-verify" version = "0.2.5" @@ -6646,7 +6726,9 @@ dependencies = [ "aes-gcm", "argon2", "async-trait", + "axum 0.7.9", "base64 0.22.1", + "bytes", "chrono", "chrono-tz", "clap", @@ -6658,13 +6740,16 @@ dependencies = [ "fs2", "futures", "gtk", + "http-body-util", "infer 0.16.0", + "ipnet", "jsonschema", "keyring", "libc", "log", "notify", "once_cell", + "open", "openssl", "plist", "reqwest 0.12.28", @@ -6700,7 +6785,10 @@ dependencies = [ "tokio", "tokio-postgres", "tokio-postgres-rustls", + "tokio-tungstenite", + "tokio-util", "toon-format", + "tower-http", "ulid", "url", "urlencoding", @@ -7135,7 +7223,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ff685620f11d61c691d03190feae66d2d729f46d21bea38986ff1bbd3f97650" dependencies = [ - "axum", + "axum 0.8.9", "serde", "serde_json", "tauri", @@ -7514,6 +7602,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.18" @@ -7659,14 +7759,24 @@ checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ "bitflags 2.11.0", "bytes", + "futures-core", "futures-util", "http", "http-body", + "http-body-util", + "http-range-header", + "httpdate", "iri-string", + "mime", + "mime_guess", + "percent-encoding", "pin-project-lite", + "tokio", + "tokio-util", "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -7752,6 +7862,24 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.5", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + [[package]] name = "typeid" version = "1.0.3" @@ -7873,6 +8001,12 @@ dependencies = [ "unic-common", ] +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-bidi" version = "0.3.18" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 5504977dc..ef9c46399 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"] } @@ -34,20 +51,27 @@ tempfile = "3.24.0" jsonschema = { version = "0.18", default-features = false } fs2 = "0.4" serde = { version = "1.0", features = ["derive"] } +bytes = "1" +ipnet = "2" 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"] } +axum = { version = "0.7.9", features = ["ws"] } +http-body-util = "0.1" +tower-http = { version = "0.6.8", features = ["fs", "limit"] } +open = "5.3.3" openssl = { version = "0.10", features = ["vendored"] } 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" @@ -60,7 +84,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"] } @@ -85,9 +109,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 @@ -127,7 +151,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 @@ -137,7 +161,9 @@ 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"] } filetime = "0.2" +tokio-tungstenite = "0.24.0" 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/capabilities/secondary-window-export.json b/src-tauri/capabilities/secondary-window-export.json new file mode 100644 index 000000000..1ea7f57c9 --- /dev/null +++ b/src-tauri/capabilities/secondary-window-export.json @@ -0,0 +1,7 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "secondary-window-export", + "description": "Allow detached editors, result grids, and schema diagrams to export bytes to an existing filesystem scope or a path explicitly granted by the save dialog. Adds no filesystem scope.", + "windows": ["connection-window-*", "results-window-*", "er-diagram*"], + "permissions": ["fs:allow-write-file"] +} diff --git a/src-tauri/capabilities/secondary-windows.json b/src-tauri/capabilities/secondary-windows.json new file mode 100644 index 000000000..d1b2a6af3 --- /dev/null +++ b/src-tauri/capabilities/secondary-windows.json @@ -0,0 +1,7 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "secondary-windows", + "description": "Allow local editor and result windows to open secondary application webview windows.", + "windows": ["main", "connection-window-*", "results-window-*"], + "permissions": ["core:webview:allow-create-webview-window"] +} diff --git a/src-tauri/src/ai.rs b/src-tauri/src/ai.rs index 432f13a51..029935f0c 100644 --- a/src-tauri/src/ai.rs +++ b/src-tauri/src/ai.rs @@ -1,4 +1,6 @@ use crate::config; +use crate::credential_cache::CredentialCache; +use crate::runtime::RuntimeContext; use reqwest::Client; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -6,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; // --- Data Structures --- @@ -143,12 +144,12 @@ fn load_default_models() -> HashMap> { }) } -fn get_cache_path(_app: &AppHandle) -> Option { - Some(crate::paths::get_app_config_dir().join("ai_models_cache.json")) +fn get_cache_path(runtime: &RuntimeContext) -> std::path::PathBuf { + runtime.paths.config_dir().join("ai_models_cache.json") } -fn load_cache(app: &AppHandle) -> Option { - let path = get_cache_path(app)?; +fn load_cache(runtime: &RuntimeContext) -> Option { + let path = get_cache_path(runtime); if path.exists() { let content = fs::read_to_string(path).ok()?; serde_json::from_str(&content).ok() @@ -157,21 +158,21 @@ fn load_cache(app: &AppHandle) -> Option { } } -fn save_cache(app: &AppHandle, models: &HashMap>) { - if let Some(path) = get_cache_path(app) { - let timestamp = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); +fn save_cache(runtime: &RuntimeContext, models: &HashMap>) { + let path = get_cache_path(runtime); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); - let cache = AiModelsCache { - last_updated: timestamp, - models: models.clone(), - }; + let cache = AiModelsCache { + last_updated: timestamp, + models: models.clone(), + }; - if let Ok(content) = serde_json::to_string(&cache) { - let _ = fs::write(path, content); - } + if let Ok(content) = serde_json::to_string(&cache) { + let _ = fs::create_dir_all(runtime.paths.config_dir()); + let _ = fs::write(path, content); } } @@ -382,35 +383,32 @@ async fn fetch_custom_openai_models(base_url: &str, api_key: &str) -> Vec Result<(), String> { - if let Some(path) = get_cache_path(&app) { - if path.exists() { - fs::remove_file(path).map_err(|e| e.to_string())?; - } +pub fn clear_models_cache(runtime: &RuntimeContext) -> Result<(), String> { + let path = get_cache_path(runtime); + if path.exists() { + fs::remove_file(path).map_err(|e| e.to_string())?; } Ok(()) } -#[tauri::command] -pub async fn get_ai_models( - app: AppHandle, +pub async fn get_models( + runtime: &RuntimeContext, + cache: &CredentialCache, force_refresh: bool, ) -> Result>, String> { - // Load config to get Ollama port - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); // 1. Check Cache (if not forced) if !force_refresh { - if let Some(cache) = load_cache(&app) { + if let Some(models_cache) = load_cache(runtime) { let now = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs(); // 24 hours = 86400 seconds - if now - cache.last_updated < 86400 { - let mut cached_models = cache.models; + if now - models_cache.last_updated < 86400 { + let mut cached_models = models_cache.models; // Always refresh Ollama as it is local and fast let ollama_models = fetch_ollama_models(ollama_port).await; @@ -424,7 +422,7 @@ pub async fn get_ai_models( // Always refresh custom-openai as it depends on user configuration if let (Some(base_url), Ok(api_key)) = ( app_config.ai_custom_openai_url.clone(), - config::get_ai_api_key(&app, "custom-openai"), + crate::application::ai::get_api_key(runtime, cache, "custom-openai"), ) { if !base_url.is_empty() && !api_key.is_empty() { let custom_models = fetch_custom_openai_models(&base_url, &api_key).await; @@ -437,7 +435,7 @@ pub async fn get_ai_models( } // Always refresh Anthropic if API key is present - if let Ok(key) = config::get_ai_api_key(&app, "anthropic") { + if let Ok(key) = crate::application::ai::get_api_key(runtime, cache, "anthropic") { let anthropic_models = fetch_anthropic_models(&key).await; if !anthropic_models.is_empty() { cached_models.insert("anthropic".to_string(), anthropic_models); @@ -445,7 +443,7 @@ pub async fn get_ai_models( } // Always refresh MiniMax if API key is present - if let Ok(key) = config::get_ai_api_key(&app, "minimax") { + if let Ok(key) = crate::application::ai::get_api_key(runtime, cache, "minimax") { let minimax_models = fetch_minimax_models(&key).await; if !minimax_models.is_empty() { cached_models.insert("minimax".to_string(), minimax_models); @@ -468,7 +466,7 @@ pub async fn get_ai_models( } // 2. OpenAI (Dynamic if key exists) - if let Ok(key) = config::get_ai_api_key(&app, "openai") { + if let Ok(key) = crate::application::ai::get_api_key(runtime, cache, "openai") { let remote_models = fetch_openai_models(&key).await; if !remote_models.is_empty() { if let Some(static_list) = models.get_mut("openai") { @@ -481,7 +479,7 @@ pub async fn get_ai_models( } // 3. Anthropic (Dynamic if key exists) - if let Ok(key) = config::get_ai_api_key(&app, "anthropic") { + if let Ok(key) = crate::application::ai::get_api_key(runtime, cache, "anthropic") { let remote_models = fetch_anthropic_models(&key).await; if !remote_models.is_empty() { if let Some(static_list) = models.get_mut("anthropic") { @@ -494,7 +492,7 @@ pub async fn get_ai_models( } // 4. MiniMax (Dynamic if key exists) - if let Ok(key) = config::get_ai_api_key(&app, "minimax") { + if let Ok(key) = crate::application::ai::get_api_key(runtime, cache, "minimax") { let remote_models = fetch_minimax_models(&key).await; if !remote_models.is_empty() { if let Some(static_list) = models.get_mut("minimax") { @@ -541,7 +539,7 @@ pub async fn get_ai_models( // 7. Custom OpenAI (Dynamic if configured) if let (Some(base_url), Ok(api_key)) = ( app_config.ai_custom_openai_url, - config::get_ai_api_key(&app, "custom-openai"), + crate::application::ai::get_api_key(runtime, cache, "custom-openai"), ) { if !base_url.is_empty() && !api_key.is_empty() { let custom_models = fetch_custom_openai_models(&base_url, &api_key).await; @@ -558,34 +556,11 @@ pub async fn get_ai_models( } // Save to Cache - save_cache(&app, &models); + save_cache(runtime, &models); Ok(models) } -#[tauri::command] -pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result { - generate_query(app, req).await -} - -#[tauri::command] -pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result { - explain_query(app, req).await -} - -#[tauri::command] -pub async fn analyze_ai_explain_plan( - app: AppHandle, - req: AiExplainRequest, -) -> Result { - analyze_explain_plan(app, req).await -} - -#[tauri::command] -pub async fn generate_cell_name(app: AppHandle, req: AiCellNameRequest) -> Result { - generate_cellname(app, req).await -} - // --- Shared helpers --- async fn resolve_model( @@ -631,7 +606,8 @@ async fn resolve_model( } async fn dispatch_provider( - app: &AppHandle, + runtime: &RuntimeContext, + cache: &CredentialCache, app_config: &config::AppConfig, gen_req: &AiGenerateRequest, system_prompt: &str, @@ -641,7 +617,7 @@ async fn dispatch_provider( return crate::chatgpt::generate(&gen_req.model, &gen_req.prompt, system_prompt).await; } let api_key = if gen_req.provider != "ollama" { - config::get_ai_api_key(app, &gen_req.provider)? + crate::application::ai::get_api_key(runtime, cache, &gen_req.provider)? } else { String::new() }; @@ -672,17 +648,32 @@ async fn dispatch_provider( // --- Logic Implementation --- -pub async fn generate_query(app: AppHandle, mut req: AiGenerateRequest) -> Result { +pub async fn generate_query( + runtime: &RuntimeContext, + cache: &CredentialCache, + mut req: AiGenerateRequest, +) -> Result { log::info!("Generating AI query using provider: {}", req.provider); - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); req.model = resolve_model(&req.provider, &req.model, &app_config, ollama_port).await?; - let raw_prompt = config::get_system_prompt(app.clone()); + let raw_prompt = crate::application::persistence::get_prompt( + runtime, + crate::application::persistence::PromptKind::System, + ); let system_prompt = raw_prompt.replace("{{SCHEMA}}", &req.schema); - let result = dispatch_provider(&app, &app_config, &req, &system_prompt, ollama_port).await; + let result = dispatch_provider( + runtime, + cache, + &app_config, + &req, + &system_prompt, + ollama_port, + ) + .await; match &result { Ok(_) => log::info!("AI query generated successfully using {}", req.model), @@ -692,14 +683,21 @@ pub async fn generate_query(app: AppHandle, mut req: AiGenerateRequest) -> Resul result } -pub async fn explain_query(app: AppHandle, mut req: AiExplainRequest) -> Result { +pub async fn explain_query( + runtime: &RuntimeContext, + cache: &CredentialCache, + mut req: AiExplainRequest, +) -> Result { log::info!("Explaining query using AI provider: {}", req.provider); - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); req.model = resolve_model(&req.provider, &req.model, &app_config, ollama_port).await?; - let raw_prompt = config::get_explain_prompt(app.clone()); + let raw_prompt = crate::application::persistence::get_prompt( + runtime, + crate::application::persistence::PromptKind::Explain, + ); let system_prompt = raw_prompt.replace("{{LANGUAGE}}", &req.language); let gen_req = AiGenerateRequest { @@ -709,7 +707,15 @@ pub async fn explain_query(app: AppHandle, mut req: AiExplainRequest) -> Result< schema: String::new(), }; - let result = dispatch_provider(&app, &app_config, &gen_req, &system_prompt, ollama_port).await; + let result = dispatch_provider( + runtime, + cache, + &app_config, + &gen_req, + &system_prompt, + ollama_port, + ) + .await; match &result { Ok(_) => log::info!( @@ -723,16 +729,20 @@ pub async fn explain_query(app: AppHandle, mut req: AiExplainRequest) -> Result< } pub async fn analyze_explain_plan( - app: AppHandle, + runtime: &RuntimeContext, + cache: &CredentialCache, mut req: AiExplainRequest, ) -> Result { log::info!("Analyzing explain plan using AI provider: {}", req.provider); - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); req.model = resolve_model(&req.provider, &req.model, &app_config, ollama_port).await?; - let raw_prompt = config::get_explainplan_prompt(app.clone()); + let raw_prompt = crate::application::persistence::get_prompt( + runtime, + crate::application::persistence::PromptKind::ExplainPlan, + ); let system_prompt = raw_prompt.replace("{{LANGUAGE}}", &req.language); let gen_req = AiGenerateRequest { @@ -742,7 +752,15 @@ pub async fn analyze_explain_plan( schema: String::new(), }; - let result = dispatch_provider(&app, &app_config, &gen_req, &system_prompt, ollama_port).await; + let result = dispatch_provider( + runtime, + cache, + &app_config, + &gen_req, + &system_prompt, + ollama_port, + ) + .await; match &result { Ok(_) => log::info!( @@ -756,20 +774,20 @@ pub async fn analyze_explain_plan( } async fn generate_with_simple_prompt( - app: AppHandle, + runtime: &RuntimeContext, + cache: &CredentialCache, provider: String, model: String, query: String, - get_prompt: fn(AppHandle) -> String, + prompt_kind: crate::application::persistence::PromptKind, label: &str, ) -> Result { log::info!("Generating {} using AI provider: {}", label, provider); - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); let resolved_model = resolve_model(&provider, &model, &app_config, ollama_port).await?; - - let system_prompt = get_prompt(app.clone()); + let system_prompt = crate::application::persistence::get_prompt(runtime, prompt_kind); let gen_req = AiGenerateRequest { provider: provider.clone(), @@ -778,7 +796,15 @@ async fn generate_with_simple_prompt( schema: String::new(), }; - let result = dispatch_provider(&app, &app_config, &gen_req, &system_prompt, ollama_port).await; + let result = dispatch_provider( + runtime, + cache, + &app_config, + &gen_req, + &system_prompt, + ollama_port, + ) + .await; match &result { Ok(v) => log::info!("{} generated: {}", label, v), @@ -788,26 +814,31 @@ async fn generate_with_simple_prompt( result } -pub async fn generate_cellname(app: AppHandle, req: AiCellNameRequest) -> Result { +pub async fn generate_cellname( + runtime: &RuntimeContext, + cache: &CredentialCache, + req: AiCellNameRequest, +) -> Result { generate_with_simple_prompt( - app, + runtime, + cache, req.provider, req.model, req.query, - config::get_cellname_prompt, + crate::application::persistence::PromptKind::CellName, "Cell name", ) .await } -#[tauri::command] -pub async fn suggest_table_name( - app: AppHandle, +pub async fn suggest_table_name_with_runtime( + runtime: &RuntimeContext, + cache: &CredentialCache, req: AiSuggestTableNameRequest, ) -> Result { log::info!("Suggesting table name using AI provider: {}", req.provider); - let app_config = config::load_config_internal(&app); + let app_config = crate::application::persistence::load_config(runtime); let ollama_port = app_config.ai_ollama_port.unwrap_or(11434); let resolved_model = resolve_model(&req.provider, &req.model, &app_config, ollama_port).await?; @@ -833,7 +864,15 @@ pub async fn suggest_table_name( }; let system_prompt = "You are a database naming expert. Reply with only a snake_case table name, no explanation."; - let result = dispatch_provider(&app, &app_config, &gen_req, system_prompt, ollama_port).await; + let result = dispatch_provider( + runtime, + cache, + &app_config, + &gen_req, + system_prompt, + ollama_port, + ) + .await; match &result { Ok(name) => { @@ -855,17 +894,18 @@ pub async fn suggest_table_name( } } -#[tauri::command] -pub async fn generate_tab_rename( - app: AppHandle, +pub async fn generate_tab_name( + runtime: &RuntimeContext, + cache: &CredentialCache, req: AiTabRenameRequest, ) -> Result { generate_with_simple_prompt( - app, + runtime, + cache, req.provider, req.model, req.query, - config::get_tabrename_prompt, + crate::application::persistence::PromptKind::TabRename, "Tab name", ) .await @@ -1140,8 +1180,7 @@ async fn generate_minimax( .await { Ok(res) if res.status().is_success() => { - let json: serde_json::Value = - res.json().await.map_err(|e| e.to_string())?; + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; let content = json["choices"][0]["message"]["content"] .as_str() .ok_or("Invalid response format from MiniMax")?; diff --git a/src-tauri/src/ai_approval_watcher.rs b/src-tauri/src/ai_approval_watcher.rs index 8cbac187d..4ecd75aec 100644 --- a/src-tauri/src/ai_approval_watcher.rs +++ b/src-tauri/src/ai_approval_watcher.rs @@ -4,99 +4,106 @@ //! 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::sync::mpsc; +use std::collections::{HashMap, HashSet}; +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; -/// 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; - }); -} +/// Poll the approval queue for headless Web mode and deliver each prompt to +/// exactly one browser session that currently owns the target connection. +pub fn spawn_headless( + runtime: crate::runtime::RuntimeContext, + state: Arc, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + let config_dir = runtime.paths.config_dir().to_path_buf(); + let mut delivered = HashMap::new(); + let mut poll = tokio::time::interval(Duration::from_millis(HEADLESS_POLL_INTERVAL_MS)); + let mut last_cleanup = std::time::Instant::now(); -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())?; + loop { + poll.tick().await; + let pending = match ai_approval::list_pending_in(&config_dir) { + Ok(pending) => pending, + Err(error) => { + log::warn!("Failed to poll pending AI approvals: {error}"); + continue; + } + }; + let current = pending + .iter() + .map(|approval| approval.id.clone()) + .collect::>(); + delivered.retain(|approval_id, _| current.contains(approval_id)); - 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(()) -} + for approval in pending { + let authorized_sessions = + crate::application::ai::authorized_sessions_for_pending(&state, &approval); + if delivered + .get(&approval.id) + .is_some_and(|owner| authorized_sessions.contains(owner)) + { + continue; + } + if let Some(previous_owner) = delivered.remove(&approval.id) { + crate::application::ai::release_pending_owner( + &state, + &approval.id, + previous_owner, + ); + } + let payload = match serde_json::to_value(&approval) { + Ok(payload) => payload, + Err(error) => { + log::warn!("Failed to serialize {PENDING_APPROVAL_EVENT}: {error}"); + continue; + } + }; + for session_id in authorized_sessions { + if !crate::application::ai::claim_pending_for_session( + &state, session_id, &approval, + ) { + continue; + } + match runtime.events.emit_to( + session_id, + PENDING_APPROVAL_EVENT, + payload.clone(), + ) { + Ok(()) => { + delivered.insert(approval.id.clone(), session_id); + break; + } + Err(error) => { + crate::application::ai::release_pending_owner( + &state, + &approval.id, + session_id, + ); + log::warn!("Failed to emit {PENDING_APPROVAL_EVENT}: {error}"); + } + } + } + } -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); + if last_cleanup.elapsed() >= Duration::from_secs(CLEANUP_INTERVAL_SECS) { + if let Err(error) = + ai_approval::cleanup_expired_in(&config_dir, CLEANUP_MAX_AGE_SECS) + { + log::warn!("Failed to clean pending AI approvals: {error}"); + } + last_cleanup = std::time::Instant::now(); } } - } + }) } -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 818742502..000000000 --- a/src-tauri/src/ai_commands.rs +++ /dev/null @@ -1,155 +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::{self, NotebookExport}; -use crate::config; - -/// The user's configured display timezone (IANA name), or `None` to fall back -/// to the OS local timezone. Read from `config.json` so exports match the UI. -fn display_timezone() -> Option { - config::load_config_from_disk().display_timezone -} - -#[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 { - let events = - tokio::task::spawn_blocking(|| ai_activity::read_events(&EventFilter::default())) - .await - .map_err(|e| e.to_string())??; - let tz = display_timezone(); - let mut out = String::new(); - for mut ev in events { - ev.timestamp = ai_activity::to_local_rfc3339(&ev.timestamp, tz.as_deref()); - let line = serde_json::to_string(&ev).map_err(|e| e.to_string())?; - out.push_str(&line); - out.push('\n'); - } - Ok(out) -} - -#[tauri::command] -pub async fn export_ai_activity_csv() -> Result { - let events = - tokio::task::spawn_blocking(|| ai_activity::read_events(&EventFilter::default())) - .await - .map_err(|e| e.to_string())??; - let mut wtr = csv::Writer::from_writer(vec![]); - wtr.write_record([ - "id", - "session_id", - "timestamp", - "tool", - "connection_id", - "connection_name", - "database", - "query", - "query_kind", - "duration_ms", - "status", - "rows", - "error", - "client_hint", - "approval_id", - ]) - .map_err(|e| e.to_string())?; - let tz = display_timezone(); - for ev in events { - let timestamp = ai_activity::to_local_rfc3339(&ev.timestamp, tz.as_deref()); - wtr.write_record([ - ev.id, - ev.session_id, - timestamp, - ev.tool, - ev.connection_id.unwrap_or_default(), - ev.connection_name.unwrap_or_default(), - ev.database.unwrap_or_default(), - ev.query.unwrap_or_default(), - ev.query_kind.unwrap_or_default(), - ev.duration_ms.to_string(), - ev.status, - ev.rows.map(|r| r.to_string()).unwrap_or_default(), - ev.error.unwrap_or_default(), - ev.client_hint.unwrap_or_default(), - ev.approval_id.unwrap_or_default(), - ]) - .map_err(|e| e.to_string())?; - } - let bytes = wtr.into_inner().map_err(|e| e.to_string())?; - String::from_utf8(bytes).map_err(|e| e.to_string()) -} - -#[tauri::command] -pub async fn export_ai_session_as_notebook(session_id: String) -> Result { - let tz = display_timezone(); - tokio::task::spawn_blocking(move || { - ai_notebook_export::export_session(&session_id, tz.as_deref()) - }) - .await - .map_err(|e| e.to_string())? -} - -#[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/ai_notebook_export.rs b/src-tauri/src/ai_notebook_export.rs index e8b02a411..734b5e20b 100644 --- a/src-tauri/src/ai_notebook_export.rs +++ b/src-tauri/src/ai_notebook_export.rs @@ -1,7 +1,7 @@ //! Build a `.tabularis-notebook` document from an audit log session. //! //! Produces the same JSON shape that the frontend's notebook editor reads -//! and writes (see `src/types/notebook.ts` `NotebookFile`). Results are not +//! and writes (see `packages/web-ui/src/types/notebook.ts` `NotebookFile`). Results are not //! embedded — notebook cells re-execute on load, which matches the existing //! notebook UX. diff --git a/src-tauri/src/application/ai.rs b/src-tauri/src/application/ai.rs new file mode 100644 index 000000000..7a51c3162 --- /dev/null +++ b/src-tauri/src/application/ai.rs @@ -0,0 +1,433 @@ +use crate::ai::{ + AiCellNameRequest, AiExplainRequest, AiGenerateRequest, AiSuggestTableNameRequest, + AiTabRenameRequest, +}; +use crate::ai_activity::EventFilter; +use crate::ai_approval::{ApprovalDecision, PendingApproval}; +use crate::credential_cache::{CacheEntry, CredentialCache}; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use serde::Serialize; +use serde_json::Value; +use uuid::Uuid; + +const AI_KEY_PREFIX: &str = "ai_key:"; + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AiKeyStatus { + pub configured: bool, + pub from_env: bool, +} + +#[derive(Debug)] +pub enum AiCommand { + SetKey { + provider: String, + key: String, + }, + DeleteKey { + provider: String, + }, + CheckKey { + provider: String, + }, + CheckKeyStatus { + provider: String, + }, + GetModels { + force_refresh: bool, + }, + GenerateQuery(AiGenerateRequest), + ExplainQuery(AiExplainRequest), + AnalyzeExplainPlan(AiExplainRequest), + GenerateCellName(AiCellNameRequest), + GenerateTabRename(AiTabRenameRequest), + SuggestTableName(AiSuggestTableNameRequest), + GetSchemaContext { + connection_id: String, + schema: Option, + database: Option, + }, + GetActivity { + filter: Option, + }, + GetSessions, + GetSessionEvents { + session_id: String, + }, + ClearActivity, + ListPendingApprovals, + DecidePendingApproval { + approval_id: String, + decision: String, + reason: Option, + edited_query: Option, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &ApplicationState, + web_session_id: Option, + command: AiCommand, +) -> Result { + match command { + AiCommand::SetKey { provider, key } => { + set_key(runtime, &state.credential_cache, &provider, &key)?; + Ok(Value::Null) + } + AiCommand::DeleteKey { provider } => { + delete_key(runtime, &state.credential_cache, &provider)?; + Ok(Value::Null) + } + AiCommand::CheckKey { provider } => { + json(get_api_key(runtime, &state.credential_cache, &provider).is_ok()) + } + AiCommand::CheckKeyStatus { provider } => { + json(key_status(runtime, &state.credential_cache, &provider)) + } + AiCommand::GetModels { force_refresh } => { + json(crate::ai::get_models(runtime, &state.credential_cache, force_refresh).await?) + } + AiCommand::GenerateQuery(request) => { + json(crate::ai::generate_query(runtime, &state.credential_cache, request).await?) + } + AiCommand::ExplainQuery(request) => { + json(crate::ai::explain_query(runtime, &state.credential_cache, request).await?) + } + AiCommand::AnalyzeExplainPlan(request) => { + json(crate::ai::analyze_explain_plan(runtime, &state.credential_cache, request).await?) + } + AiCommand::GenerateCellName(request) => { + json(crate::ai::generate_cellname(runtime, &state.credential_cache, request).await?) + } + AiCommand::GenerateTabRename(request) => { + json(crate::ai::generate_tab_name(runtime, &state.credential_cache, request).await?) + } + AiCommand::SuggestTableName(request) => json( + crate::ai::suggest_table_name_with_runtime(runtime, &state.credential_cache, request) + .await?, + ), + AiCommand::GetSchemaContext { + connection_id, + schema, + database, + } => json( + crate::application::metadata::get_ai_schema_context( + runtime, + web_session_id, + &connection_id, + schema, + database, + ) + .await?, + ), + AiCommand::GetActivity { filter } => { + let config_dir = runtime.paths.config_dir().to_path_buf(); + let filter = filter.unwrap_or_default(); + json( + tokio::task::spawn_blocking(move || { + crate::ai_activity::read_events_in(&config_dir, &filter) + }) + .await + .map_err(|error| error.to_string())??, + ) + } + AiCommand::GetSessions => { + let config_dir = runtime.paths.config_dir().to_path_buf(); + json( + tokio::task::spawn_blocking(move || { + crate::ai_activity::read_sessions_in(&config_dir) + }) + .await + .map_err(|error| error.to_string())??, + ) + } + AiCommand::GetSessionEvents { session_id } => { + let config_dir = runtime.paths.config_dir().to_path_buf(); + json( + tokio::task::spawn_blocking(move || { + crate::ai_activity::read_session_events_in(&config_dir, &session_id) + }) + .await + .map_err(|error| error.to_string())??, + ) + } + AiCommand::ClearActivity => { + let config_dir = runtime.paths.config_dir().to_path_buf(); + tokio::task::spawn_blocking(move || crate::ai_activity::clear_in(&config_dir)) + .await + .map_err(|error| error.to_string())??; + Ok(Value::Null) + } + AiCommand::ListPendingApprovals => { + json(list_pending_approvals(runtime, state, web_session_id).await?) + } + AiCommand::DecidePendingApproval { + approval_id, + decision, + reason, + edited_query, + } => { + decide_pending_approval( + runtime, + state, + web_session_id, + approval_id, + decision, + reason, + edited_query, + ) + .await?; + Ok(Value::Null) + } + } +} + +pub fn set_key( + runtime: &RuntimeContext, + cache: &CredentialCache, + provider: &str, + key: &str, +) -> Result<(), String> { + if key.trim().is_empty() { + return Err("The AI provider key must not be empty".to_string()); + } + runtime.secrets.set(&key_account(provider), key)?; + crate::credential_cache::set_ai_key_cached(cache, provider, key); + Ok(()) +} + +pub fn delete_key( + runtime: &RuntimeContext, + cache: &CredentialCache, + provider: &str, +) -> Result<(), String> { + runtime.secrets.delete(&key_account(provider))?; + crate::credential_cache::invalidate_ai_key(cache, provider); + Ok(()) +} + +pub fn get_api_key( + runtime: &RuntimeContext, + cache: &CredentialCache, + provider: &str, +) -> Result { + match cached_key(cache, provider) { + Some(Some(key)) => return Ok(key), + Some(None) => {} + None => match runtime.secrets.get(&key_account(provider)) { + Ok(Some(key)) if !key.is_empty() => { + crate::credential_cache::set_ai_key_cached(cache, provider, &key); + return Ok(key); + } + Ok(_) => { + cache + .ai_keys + .lock() + .unwrap_or_else(|error| error.into_inner()) + .insert(provider.to_string(), CacheEntry::Absent); + } + Err(error) => log::warn!("Failed to read the {provider} AI key: {error}"), + }, + } + + environment_key(provider).ok_or_else(|| missing_key_error(provider)) +} + +pub fn key_status( + runtime: &RuntimeContext, + cache: &CredentialCache, + provider: &str, +) -> AiKeyStatus { + let stored = match cached_key(cache, provider) { + Some(value) => value.is_some(), + None => match runtime.secrets.get(&key_account(provider)) { + Ok(Some(key)) if !key.is_empty() => { + crate::credential_cache::set_ai_key_cached(cache, provider, &key); + true + } + Ok(_) => { + cache + .ai_keys + .lock() + .unwrap_or_else(|error| error.into_inner()) + .insert(provider.to_string(), CacheEntry::Absent); + false + } + Err(error) => { + log::warn!("Failed to check the {provider} AI key: {error}"); + false + } + }, + }; + let from_env = !stored && environment_key(provider).is_some(); + AiKeyStatus { + configured: stored || from_env, + from_env, + } +} + +pub async fn list_pending_approvals( + runtime: &RuntimeContext, + state: &ApplicationState, + web_session_id: Option, +) -> Result, String> { + let config_dir = runtime.paths.config_dir().to_path_buf(); + let pending = + tokio::task::spawn_blocking(move || crate::ai_approval::list_pending_in(&config_dir)) + .await + .map_err(|error| error.to_string())??; + + let Some(session_id) = web_session_id else { + return Ok(pending); + }; + Ok(pending + .into_iter() + .filter(|approval| claim_pending_for_session(state, session_id, approval)) + .collect()) +} + +pub fn authorized_sessions_for_pending( + state: &ApplicationState, + pending: &PendingApproval, +) -> Vec { + let mut sessions = state + .web_active_connections + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .filter_map(|(session_id, connections)| { + connections + .contains(&pending.connection_id) + .then_some(*session_id) + }) + .collect::>(); + sessions.sort_unstable(); + sessions +} + +pub fn release_pending_owner(state: &ApplicationState, approval_id: &str, session_id: Uuid) { + let mut owners = state + .web_approval_owners + .lock() + .unwrap_or_else(|error| error.into_inner()); + if owners.get(approval_id) == Some(&session_id) { + owners.remove(approval_id); + } +} + +pub(crate) fn claim_pending_for_session( + state: &ApplicationState, + session_id: Uuid, + pending: &PendingApproval, +) -> bool { + let authorized_sessions = authorized_sessions_for_pending(state, pending); + if !authorized_sessions.contains(&session_id) { + return false; + } + + let mut owners = state + .web_approval_owners + .lock() + .unwrap_or_else(|error| error.into_inner()); + match owners.get(&pending.id) { + Some(owner) if *owner == session_id => true, + Some(owner) if authorized_sessions.contains(owner) => false, + Some(_) | None => { + owners.insert(pending.id.clone(), session_id); + true + } + } +} + +async fn decide_pending_approval( + runtime: &RuntimeContext, + state: &ApplicationState, + web_session_id: Option, + approval_id: String, + decision: String, + reason: Option, + edited_query: Option, +) -> Result<(), String> { + if decision != "approve" && decision != "deny" { + return Err(format!( + "Invalid decision '{decision}': expected 'approve' or 'deny'" + )); + } + + let config_dir = runtime.paths.config_dir().to_path_buf(); + let pending_id = approval_id.clone(); + let pending = tokio::task::spawn_blocking({ + let config_dir = config_dir.clone(); + move || crate::ai_approval::read_pending_in(&config_dir, &pending_id) + }) + .await + .map_err(|error| error.to_string())?? + .ok_or_else(|| "The pending AI approval no longer exists".to_string())?; + + if let Some(session_id) = web_session_id { + if !claim_pending_for_session(state, session_id, &pending) { + return Err("The AI approval belongs to another authorized session".to_string()); + } + } + + let payload = ApprovalDecision { + approval_id: approval_id.clone(), + decided_at: crate::ai_activity::now_iso8601(), + decision, + reason, + edited_query, + }; + tokio::task::spawn_blocking(move || { + crate::ai_approval::write_decision_in(&config_dir, &payload) + }) + .await + .map_err(|error| error.to_string())??; + state + .web_approval_owners + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&approval_id); + Ok(()) +} + +fn cached_key(cache: &CredentialCache, provider: &str) -> Option> { + cache + .ai_keys + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(provider) + .map(|entry| match entry { + CacheEntry::Present(key) => Some(key.clone()), + CacheEntry::Absent => None, + }) +} + +fn key_account(provider: &str) -> String { + format!("{AI_KEY_PREFIX}{provider}") +} + +fn environment_key(provider: &str) -> Option { + let variable = match provider { + "openai" => "OPENAI_API_KEY", + "anthropic" => "ANTHROPIC_API_KEY", + "openrouter" => "OPENROUTER_API_KEY", + "custom-openai" => "CUSTOM_OPENAI_API_KEY", + "minimax" => "MINIMAX_API_KEY", + "requesty" => "REQUESTY_API_KEY", + _ => return None, + }; + std::env::var(variable).ok().filter(|key| !key.is_empty()) +} + +fn missing_key_error(provider: &str) -> String { + format!("API Key for {provider} not found in Keychain or Environment") +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/application/ai/tests.rs b/src-tauri/src/application/ai/tests.rs new file mode 100644 index 000000000..1e52e06e6 --- /dev/null +++ b/src-tauri/src/application/ai/tests.rs @@ -0,0 +1,199 @@ +use super::*; +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct MemorySecrets { + values: Mutex>, +} + +impl RuntimeSecrets for MemorySecrets { + fn get(&self, account: &str) -> Result, String> { + Ok(self + .values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(account) + .cloned()) + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .insert(account.to_string(), secret.to_string()); + Ok(()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(account); + Ok(()) + } +} + +fn fixture() -> (tempfile::TempDir, RuntimeContext, ApplicationState) { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path().join("config"); + let data_dir = temp.path().join("data"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::create_dir_all(&data_dir).unwrap(); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new(config_dir, data_dir)), + Arc::new(NoopRuntimeEvents), + Arc::new(MemorySecrets::default()), + ); + (temp, runtime, ApplicationState::default()) +} + +#[tokio::test] +async fn provider_keys_are_write_only_across_the_application_contract() { + let (_temp, runtime, state) = fixture(); + + let set_result = execute( + &runtime, + &state, + None, + AiCommand::SetKey { + provider: "fixture-provider".to_string(), + key: "provider-secret".to_string(), + }, + ) + .await + .unwrap(); + assert_eq!(set_result, Value::Null); + + let status = execute( + &runtime, + &state, + None, + AiCommand::CheckKeyStatus { + provider: "fixture-provider".to_string(), + }, + ) + .await + .unwrap(); + assert_eq!( + status, + serde_json::json!({"configured": true, "fromEnv": false}) + ); + assert!(!status.to_string().contains("provider-secret")); + + let delete_result = execute( + &runtime, + &state, + None, + AiCommand::DeleteKey { + provider: "fixture-provider".to_string(), + }, + ) + .await + .unwrap(); + assert_eq!(delete_result, Value::Null); +} + +#[tokio::test] +async fn pending_approvals_are_owned_by_an_authorized_web_session() { + let (_temp, runtime, state) = fixture(); + let authorized_session = Uuid::new_v4(); + let other_session = Uuid::new_v4(); + state.web_active_connections.lock().unwrap().insert( + authorized_session, + HashSet::from(["connection-1".to_string()]), + ); + state + .web_active_connections + .lock() + .unwrap() + .insert(other_session, HashSet::new()); + + let pending = PendingApproval { + id: "approval-1".to_string(), + created_at: "2026-08-22T00:00:00Z".to_string(), + session_id: "mcp-session".to_string(), + connection_id: "connection-1".to_string(), + connection_name: "Fixture".to_string(), + query: "DELETE FROM values".to_string(), + query_kind: "write".to_string(), + database: None, + client_hint: None, + explain_plan: None, + explain_error: None, + }; + crate::ai_approval::write_pending_in(runtime.paths.config_dir(), &pending).unwrap(); + + let authorized = execute( + &runtime, + &state, + Some(authorized_session), + AiCommand::ListPendingApprovals, + ) + .await + .unwrap(); + assert_eq!(authorized.as_array().map(Vec::len), Some(1)); + + let unauthorized = execute( + &runtime, + &state, + Some(other_session), + AiCommand::ListPendingApprovals, + ) + .await + .unwrap(); + assert_eq!(unauthorized, serde_json::json!([])); + + let denied = execute( + &runtime, + &state, + Some(other_session), + AiCommand::DecidePendingApproval { + approval_id: pending.id.clone(), + decision: "deny".to_string(), + reason: None, + edited_query: None, + }, + ) + .await; + assert!(denied.is_err()); + + { + let mut sessions = state.web_active_connections.lock().unwrap(); + sessions.get_mut(&authorized_session).unwrap().clear(); + sessions + .get_mut(&other_session) + .unwrap() + .insert("connection-1".to_string()); + } + let transferred = execute( + &runtime, + &state, + Some(other_session), + AiCommand::ListPendingApprovals, + ) + .await + .unwrap(); + assert_eq!(transferred.as_array().map(Vec::len), Some(1)); + + execute( + &runtime, + &state, + Some(other_session), + AiCommand::DecidePendingApproval { + approval_id: pending.id.clone(), + decision: "approve".to_string(), + reason: Some("approved by owner".to_string()), + edited_query: None, + }, + ) + .await + .unwrap(); + let decision = crate::ai_approval::read_decision_in(runtime.paths.config_dir(), &pending.id) + .unwrap() + .unwrap(); + assert_eq!(decision.decision, "approve"); +} diff --git a/src-tauri/src/application/api.rs b/src-tauri/src/application/api.rs new file mode 100644 index 000000000..90ff20dba --- /dev/null +++ b/src-tauri/src/application/api.rs @@ -0,0 +1,474 @@ +use super::{ + ai, connection_files, connections, database_objects, database_transfers, generic_exports, + host_settings, mcp_host, metadata, notebooks, operations, persistence, plugins, productivity, + queries, records, themes, tunnels, ui_state, +}; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use async_trait::async_trait; +use serde_json::Value; +use std::sync::Arc; +use std::time::Instant; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum AuthorizationLevel { + Session, + Database, + Sensitive, + LocalAdmin, +} + +impl AuthorizationLevel { + pub fn permits(self, required: Self) -> bool { + self >= required + } +} + +#[derive(Clone, Debug)] +pub struct ApplicationRequestContext { + pub request_id: String, + pub deadline: Instant, + pub cancellation_id: Option, + pub authorization: AuthorizationLevel, + pub session_id: Option, +} + +#[derive(Debug)] +pub struct ApplicationError { + pub message: String, + pub details: Option, +} + +impl ApplicationError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + details: None, + } + } +} + +#[async_trait] +pub trait ApplicationApi: Send + Sync { + fn clear_session(&self, session_id: Uuid); + + async fn is_debug_mode( + &self, + context: ApplicationRequestContext, + ) -> Result; + + async fn get_connections( + &self, + context: ApplicationRequestContext, + ) -> Result, ApplicationError>; + + /// Redacted saved parameters used by transport authorization; never resolves secrets or tunnels. + async fn connection_params_for_authorization( + &self, + context: ApplicationRequestContext, + connection_id: &str, + ) -> Result, ApplicationError> { + Ok(self + .get_connections(context) + .await? + .into_iter() + .find(|connection| connection.id == connection_id) + .map(|connection| connection.params)) + } + + async fn cancel_query( + &self, + context: ApplicationRequestContext, + connection_id: String, + query_request_id: Option, + ) -> Result<(), ApplicationError>; + + async fn execute_query_command( + &self, + context: ApplicationRequestContext, + command: queries::QueryCommand, + ) -> Result; + + async fn execute_connection_command( + &self, + context: ApplicationRequestContext, + command: connections::ConnectionCommand, + ) -> Result; + + async fn execute_connection_files_command( + &self, + context: ApplicationRequestContext, + command: connection_files::ConnectionFilesCommand, + ) -> Result; + + async fn execute_database_transfer_command( + &self, + context: ApplicationRequestContext, + command: database_transfers::DatabaseTransferCommand, + ) -> Result; + + async fn execute_generic_export_command( + &self, + context: ApplicationRequestContext, + command: generic_exports::GenericExportCommand, + ) -> Result; + + async fn execute_ai_command( + &self, + context: ApplicationRequestContext, + command: ai::AiCommand, + ) -> Result; + + async fn execute_metadata_command( + &self, + context: ApplicationRequestContext, + command: metadata::MetadataCommand, + ) -> Result; + + async fn execute_database_object_command( + &self, + context: ApplicationRequestContext, + command: database_objects::DatabaseObjectCommand, + ) -> Result; + + async fn execute_record_command( + &self, + context: ApplicationRequestContext, + command: records::RecordCommand, + ) -> Result; + + async fn execute_tunnel_command( + &self, + context: ApplicationRequestContext, + command: tunnels::TunnelCommand, + ) -> Result; + + async fn execute_persistence_command( + &self, + context: ApplicationRequestContext, + command: persistence::PersistenceCommand, + ) -> Result; + + async fn execute_productivity_command( + &self, + context: ApplicationRequestContext, + command: productivity::ProductivityCommand, + ) -> Result; + + async fn execute_notebook_command( + &self, + context: ApplicationRequestContext, + command: notebooks::NotebookCommand, + ) -> Result; + + async fn execute_plugin_command( + &self, + context: ApplicationRequestContext, + command: plugins::PluginCommand, + ) -> Result; + + async fn execute_operational_command( + &self, + context: ApplicationRequestContext, + command: operations::OperationalCommand, + ) -> Result; + + async fn execute_mcp_host_command( + &self, + context: ApplicationRequestContext, + command: mcp_host::McpHostCommand, + ) -> Result; + + async fn execute_theme_command( + &self, + context: ApplicationRequestContext, + command: themes::ThemeCommand, + ) -> Result; + + async fn execute_host_settings_command( + &self, + context: ApplicationRequestContext, + command: host_settings::HostSettingsCommand, + ) -> Result; + + async fn execute_ui_state_command( + &self, + context: ApplicationRequestContext, + command: ui_state::UiStateCommand, + ) -> Result; +} + +pub struct RuntimeApplicationApi { + runtime: RuntimeContext, + state: Arc, +} + +impl RuntimeApplicationApi { + pub fn new(runtime: RuntimeContext, state: Arc) -> Self { + Self { runtime, state } + } +} + +#[async_trait] +impl ApplicationApi for RuntimeApplicationApi { + fn clear_session(&self, session_id: Uuid) { + self.state.import_envelope_cache.clear_session(session_id); + queries::cancel_session_queries(&self.state.query_cancellation, session_id); + super::query_sessions::clear_owner(session_id); + database_transfers::cancel_session_jobs(&self.state.dump_cancellation, session_id); + generic_exports::cancel_session_exports(&self.state.export_cancellation, session_id); + self.state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&session_id); + self.state + .web_active_connections + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&session_id); + self.state + .web_approval_owners + .lock() + .unwrap_or_else(|error| error.into_inner()) + .retain(|_, owner| *owner != session_id); + } + + async fn is_debug_mode( + &self, + _context: ApplicationRequestContext, + ) -> Result { + Ok(crate::runtime::bootstrap::is_debug_mode()) + } + + async fn get_connections( + &self, + _context: ApplicationRequestContext, + ) -> Result, ApplicationError> { + let path = self.runtime.paths.connections_file(); + tokio::task::spawn_blocking(move || connections::load_redacted_connections(&path)) + .await + .map_err(|error| ApplicationError::new(format!("Failed to load connections: {error}")))? + .map_err(ApplicationError::new) + } + + async fn cancel_query( + &self, + context: ApplicationRequestContext, + connection_id: String, + query_request_id: Option, + ) -> Result<(), ApplicationError> { + queries::cancel_query( + &self.state.query_cancellation, + context.session_id, + &connection_id, + query_request_id.as_deref(), + ) + .map_err(ApplicationError::new) + } + + async fn execute_query_command( + &self, + context: ApplicationRequestContext, + command: queries::QueryCommand, + ) -> Result { + queries::execute( + &self.runtime, + &self.state, + context.session_id, + &context.request_id, + command, + ) + .await + .map_err(ApplicationError::new) + } + + async fn execute_connection_command( + &self, + context: ApplicationRequestContext, + command: connections::ConnectionCommand, + ) -> Result { + connections::execute_for_session(&self.runtime, &self.state, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_connection_files_command( + &self, + context: ApplicationRequestContext, + command: connection_files::ConnectionFilesCommand, + ) -> Result { + connection_files::execute(&self.runtime, &self.state, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_database_transfer_command( + &self, + context: ApplicationRequestContext, + command: database_transfers::DatabaseTransferCommand, + ) -> Result { + database_transfers::execute( + &self.runtime, + &self.state.dump_cancellation, + context.session_id, + command, + ) + .await + .map_err(ApplicationError::new) + } + + async fn execute_generic_export_command( + &self, + context: ApplicationRequestContext, + command: generic_exports::GenericExportCommand, + ) -> Result { + generic_exports::execute( + &self.runtime, + &self.state.export_cancellation, + context.session_id, + command, + ) + .await + .map_err(ApplicationError::new) + } + + async fn execute_ai_command( + &self, + context: ApplicationRequestContext, + command: ai::AiCommand, + ) -> Result { + ai::execute(&self.runtime, &self.state, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_metadata_command( + &self, + context: ApplicationRequestContext, + command: metadata::MetadataCommand, + ) -> Result { + metadata::execute(&self.runtime, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_database_object_command( + &self, + context: ApplicationRequestContext, + command: database_objects::DatabaseObjectCommand, + ) -> Result { + database_objects::execute(&self.runtime, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_record_command( + &self, + context: ApplicationRequestContext, + command: records::RecordCommand, + ) -> Result { + records::execute(&self.runtime, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_tunnel_command( + &self, + context: ApplicationRequestContext, + command: tunnels::TunnelCommand, + ) -> Result { + tunnels::execute(&self.runtime, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_persistence_command( + &self, + context: ApplicationRequestContext, + command: persistence::PersistenceCommand, + ) -> Result { + persistence::execute(&self.runtime, &self.state, context.session_id, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_productivity_command( + &self, + _context: ApplicationRequestContext, + command: productivity::ProductivityCommand, + ) -> Result { + productivity::execute(self.runtime.paths.config_dir(), command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_notebook_command( + &self, + _context: ApplicationRequestContext, + command: notebooks::NotebookCommand, + ) -> Result { + notebooks::execute(self.runtime.paths.config_dir(), command).map_err(ApplicationError::new) + } + + async fn execute_plugin_command( + &self, + _context: ApplicationRequestContext, + command: plugins::PluginCommand, + ) -> Result { + plugins::execute(&self.runtime, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_operational_command( + &self, + _context: ApplicationRequestContext, + command: operations::OperationalCommand, + ) -> Result { + operations::execute(command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_mcp_host_command( + &self, + _context: ApplicationRequestContext, + command: mcp_host::McpHostCommand, + ) -> Result { + mcp_host::execute(command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_theme_command( + &self, + _context: ApplicationRequestContext, + command: themes::ThemeCommand, + ) -> Result { + themes::execute(&self.runtime, command) + .await + .map_err(ApplicationError::new) + } + + async fn execute_host_settings_command( + &self, + _context: ApplicationRequestContext, + command: host_settings::HostSettingsCommand, + ) -> Result { + tokio::task::spawn_blocking(move || host_settings::execute(command)) + .await + .map_err(|error| ApplicationError::new(error.to_string()))? + .map_err(ApplicationError::new) + } + + async fn execute_ui_state_command( + &self, + _context: ApplicationRequestContext, + command: ui_state::UiStateCommand, + ) -> Result { + ui_state::execute(&self.runtime, command) + .await + .map_err(ApplicationError::new) + } +} diff --git a/src-tauri/src/application/connection_files.rs b/src-tauri/src/application/connection_files.rs new file mode 100644 index 000000000..b0ecea2ed --- /dev/null +++ b/src-tauri/src/application/connection_files.rs @@ -0,0 +1,868 @@ +use super::file_transfers::FileTransferStore; +use crate::connection_import::{ + all_importers, analyzer, convert, expand_home, importer_by_id, tabularis, ImportEnvelope, +}; +use crate::models::{ExportPayload, K8sConnection, SavedConnection, SshConnection}; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +pub const CONNECTION_IMPORT_PURPOSE: &str = "connection-import"; +const JSON_MIME_TYPE: &str = "application/json"; +const EXPORT_FILE_NAME: &str = "tabularis-connections.json"; +const MAX_CONNECTION_IMPORT_BYTES: u64 = 64 * 1024 * 1024; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConnectionFilesCommand { + Export { + mode: ConnectionExportMode, + password: Option, + connection_ids: Option>, + }, + ListImportSources, + PreviewForeignImport { + source_id: String, + include_passwords: bool, + file: Option, + }, + ApplyForeignImport { + source_id: String, + resolutions: Vec, + }, + PreviewTabularisImport { + file: ConnectionImportFile, + password: Option, + }, + ApplyPreparedTabularisImport { + resolutions: Vec, + }, + GetBackupStatus, + GetDatabaseBackupStatus, + RunDatabaseBackup, + CancelDatabaseBackup, + SetBackupPassword { + password: String, + }, + SetBackupTargetPassword { + target_id: String, + password: String, + }, + RunBackup, +} + +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConnectionExportMode { + Encrypted, + NoSecrets, + Plaintext, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum ConnectionImportFile { + ServerPath { path: String }, + Upload { token: String }, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum GeneratedFile { + Inline { + file_name: String, + mime_type: String, + contents: String, + }, + Download { + file_name: String, + mime_type: String, + token: String, + size: u64, + }, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BackupRunResult { + pub server_location: String, + pub target_kind: crate::backup::BackupTargetKind, + pub download: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportSourceInfo { + pub id: String, + pub display_name: String, + pub available: bool, + pub connection_count: usize, + pub reads_passwords_from_keychain: bool, + pub needs_file: bool, + pub manual_path_supported: bool, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum TabularisImportPreviewResult { + PasswordRequired, + Preview { preview: analyzer::ImportPreview }, +} + +#[derive(Default)] +pub struct ImportEnvelopeCache { + foreign: Mutex, String), ImportEnvelope>>, + tabularis: Mutex, ExportPayload>>, +} + +impl ImportEnvelopeCache { + pub fn clear_session(&self, session_id: Uuid) { + self.foreign + .lock() + .unwrap_or_else(|error| error.into_inner()) + .retain(|(owner, _), _| *owner != Some(session_id)); + self.tabularis + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&Some(session_id)); + } +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &Arc, + session_id: Option, + command: ConnectionFilesCommand, +) -> Result { + match command { + ConnectionFilesCommand::Export { + mode, + password, + connection_ids, + } => json(generate_export_file(runtime, session_id, mode, password, connection_ids).await?), + ConnectionFilesCommand::ListImportSources => json(list_import_sources().await?), + ConnectionFilesCommand::PreviewForeignImport { + source_id, + include_passwords, + file, + } => json( + preview_foreign_import( + runtime, + &state.import_envelope_cache, + session_id, + source_id, + include_passwords, + file, + ) + .await?, + ), + ConnectionFilesCommand::ApplyForeignImport { + source_id, + resolutions, + } => { + apply_foreign_import( + runtime, + &state.connection_cache, + &state.credential_cache, + &state.import_envelope_cache, + session_id, + source_id, + resolutions, + ) + .await?; + Ok(Value::Null) + } + ConnectionFilesCommand::PreviewTabularisImport { file, password } => json( + preview_tabularis_import_file( + runtime, + &state.import_envelope_cache, + session_id, + file, + password, + ) + .await?, + ), + ConnectionFilesCommand::ApplyPreparedTabularisImport { resolutions } => { + apply_prepared_tabularis_import( + runtime, + &state.connection_cache, + &state.credential_cache, + &state.import_envelope_cache, + session_id, + resolutions, + ) + .await?; + Ok(Value::Null) + } + ConnectionFilesCommand::GetDatabaseBackupStatus => json(crate::database_backup::get_database_backup_status(runtime).await?), + ConnectionFilesCommand::RunDatabaseBackup => json(crate::database_backup::run_database_backup_now(runtime, &state.dump_cancellation).await?), + ConnectionFilesCommand::CancelDatabaseBackup => { + crate::database_backup::cancel_database_backup(&state.dump_cancellation).await?; + Ok(Value::Null) + } + ConnectionFilesCommand::GetBackupStatus => { + json(crate::backup::backup_status(runtime).await?) + } + ConnectionFilesCommand::SetBackupPassword { password } => { + crate::backup::set_backup_password(runtime, &password)?; + Ok(Value::Null) + } + ConnectionFilesCommand::SetBackupTargetPassword { + target_id, + password, + } => { + crate::backup::set_backup_target_password(runtime, &target_id, &password)?; + Ok(Value::Null) + } + ConnectionFilesCommand::RunBackup => { + let artifact = crate::backup::run_backup_for_runtime(runtime, "manual").await?; + let download = if let Some(session_id) = session_id { + Some( + store_download(runtime, session_id, &artifact.file_name, artifact.content) + .await?, + ) + } else { + None + }; + json(BackupRunResult { + server_location: artifact.location, + target_kind: artifact.target_kind, + download, + }) + } + } +} + +pub async fn generate_export_file( + runtime: &RuntimeContext, + session_id: Option, + mode: ConnectionExportMode, + password: Option, + connection_ids: Option>, +) -> Result { + if session_id.is_some() && matches!(mode, ConnectionExportMode::Plaintext) { + return Err("Plaintext connection exports are not available in the browser".to_string()); + } + let include_secrets = !matches!(mode, ConnectionExportMode::NoSecrets); + let payload = export_payload(runtime, include_secrets, connection_ids).await?; + let contents = match mode { + ConnectionExportMode::Encrypted => { + let password = password.filter(|value| !value.is_empty()).ok_or_else(|| { + "A password is required for encrypted connection exports".to_string() + })?; + let plaintext = serde_json::to_string(&payload).map_err(|error| error.to_string())?; + let envelope = crate::export_crypto::encrypt(&plaintext, &password)?; + serde_json::to_string_pretty(&envelope).map_err(|error| error.to_string())? + } + ConnectionExportMode::NoSecrets | ConnectionExportMode::Plaintext => { + serde_json::to_string_pretty(&payload).map_err(|error| error.to_string())? + } + }; + match session_id { + Some(session_id) => store_download(runtime, session_id, EXPORT_FILE_NAME, contents).await, + None => Ok(GeneratedFile::Inline { + file_name: EXPORT_FILE_NAME.to_string(), + mime_type: JSON_MIME_TYPE.to_string(), + contents, + }), + } +} + +pub async fn export_payload( + runtime: &RuntimeContext, + include_secrets: bool, + connection_ids: Option>, +) -> Result { + let mut file = crate::persistence::load_connections_file(&runtime.paths.connections_file())?; + let mut ssh_connections = + crate::application::tunnels::get_ssh_connections(runtime, include_secrets)?; + let mut k8s_connections = crate::application::tunnels::get_k8s_connections(runtime)?; + + if let Some(ids) = connection_ids.as_ref() { + let selected: HashSet<&str> = ids.iter().map(String::as_str).collect(); + file.connections + .retain(|connection| selected.contains(connection.id.as_str())); + ssh_connections.retain(|connection| selected.contains(connection.id.as_str())); + k8s_connections.retain(|connection| selected.contains(connection.id.as_str())); + let kept_groups = crate::models::collect_group_ancestors( + &file.groups, + file.connections + .iter() + .filter_map(|connection| connection.group_id.as_deref()), + ); + file.groups.retain(|group| kept_groups.contains(&group.id)); + let kept_tags: HashSet = file + .connections + .iter() + .flat_map(|connection| connection.tag_ids.iter().flatten()) + .cloned() + .collect(); + file.tags.retain(|tag| kept_tags.contains(&tag.id)); + } + + let mut plugin_secrets = HashMap::new(); + for connection in &mut file.connections { + if include_secrets { + // A missing keychain entry must not abort the whole export (or a + // scheduled backup): the connection is exported without that value. + let values = + crate::application::connections::load_plugin_secrets(runtime, connection); + if !values.is_empty() { + plugin_secrets.insert(connection.id.clone(), values); + } + crate::application::connections::restore_connection_secrets( + runtime, + &connection.id, + &mut connection.params, + )?; + } else { + connection.params.password = None; + connection.params.connection_uri = None; + connection.params.ssh_password = None; + connection.params.ssh_key_passphrase = None; + connection.plugin_secret_keys.clear(); + } + } + + Ok(ExportPayload { + version: 1, + groups: file.groups, + connections: file.connections, + ssh_connections, + k8s_connections, + tags: file.tags, + plugin_secrets, + }) +} + +pub async fn list_import_sources() -> Result, String> { + let mut sources = Vec::new(); + for importer in all_importers() { + let available = importer.is_available().await; + let connection_count = if available { + importer.connection_count().await + } else { + 0 + }; + sources.push(ImportSourceInfo { + id: importer.id().to_string(), + display_name: importer.display_name().to_string(), + available, + connection_count, + reads_passwords_from_keychain: importer.reads_passwords_from_keychain(), + needs_file: importer.import_file_types().is_some(), + manual_path_supported: importer.supports_manual_path(), + }); + } + Ok(sources) +} + +pub async fn preview_foreign_import( + runtime: &RuntimeContext, + cache: &ImportEnvelopeCache, + session_id: Option, + source_id: String, + include_passwords: bool, + file: Option, +) -> Result { + let importer = + importer_by_id(&source_id).ok_or_else(|| format!("Unknown import source: {source_id}"))?; + let claimed = resolve_import_file(runtime, session_id, file)?; + let path = claimed.as_ref().map(ResolvedImportFile::path); + let envelope = importer + .import(include_passwords, path) + .await + .map_err(|error| error.to_string())?; + let preview = analyze_import(runtime, &envelope).await?; + cache + .foreign + .lock() + .map_err(|_| "Import cache poisoned".to_string())? + .insert((session_id, source_id), envelope); + Ok(preview) +} + +pub async fn apply_foreign_import( + runtime: &RuntimeContext, + connection_cache: &crate::connection_cache::ConnectionCache, + credential_cache: &crate::credential_cache::CredentialCache, + cache: &ImportEnvelopeCache, + session_id: Option, + source_id: String, + resolutions: Vec, +) -> Result<(), String> { + let envelope = cache + .foreign + .lock() + .map_err(|_| "Import cache poisoned".to_string())? + .remove(&(session_id, source_id)) + .ok_or_else(|| "No import preview found; run preview first".to_string())?; + let registered_ids = registered_driver_ids().await; + let existing_groups = load_file(runtime)?.groups; + let payload = + convert::build_payload(&envelope, &resolutions, ®istered_ids, &existing_groups); + apply_export_payload(runtime, connection_cache, credential_cache, payload).await +} + +pub async fn preview_tabularis_import_file( + runtime: &RuntimeContext, + cache: &ImportEnvelopeCache, + session_id: Option, + file: ConnectionImportFile, + password: Option, +) -> Result { + let (content, upload_to_consume) = + read_tabularis_import_file(runtime, session_id, file).await?; + let value: Value = serde_json::from_str(&content) + .map_err(|error| format!("Invalid connection export: {error}"))?; + let payload = if value.get("encrypted").and_then(Value::as_bool) == Some(true) { + let Some(password) = password.filter(|value| !value.is_empty()) else { + return Ok(TabularisImportPreviewResult::PasswordRequired); + }; + let envelope = serde_json::from_value(value) + .map_err(|error| format!("Invalid encrypted export: {error}"))?; + let plaintext = crate::export_crypto::decrypt(&envelope, &password)?; + serde_json::from_str(&plaintext) + .map_err(|error| format!("Invalid export payload: {error}"))? + } else { + serde_json::from_value(value).map_err(|error| format!("Invalid export payload: {error}"))? + }; + let preview = preview_tabularis_payload(runtime, &payload).await?; + cache + .tabularis + .lock() + .map_err(|_| "Import cache poisoned".to_string())? + .insert(session_id, payload); + if let Some((owner, token)) = upload_to_consume { + FileTransferStore::new(runtime.paths.data_dir()).claim_upload( + owner, + &token, + CONNECTION_IMPORT_PURPOSE, + )?; + } + Ok(TabularisImportPreviewResult::Preview { preview }) +} + +pub async fn apply_prepared_tabularis_import( + runtime: &RuntimeContext, + connection_cache: &crate::connection_cache::ConnectionCache, + credential_cache: &crate::credential_cache::CredentialCache, + cache: &ImportEnvelopeCache, + session_id: Option, + resolutions: Vec, +) -> Result<(), String> { + let payload = cache + .tabularis + .lock() + .map_err(|_| "Import cache poisoned".to_string())? + .remove(&session_id) + .ok_or_else(|| "No Tabularis import preview found; run preview first".to_string())?; + let existing_groups = load_file(runtime)?.groups; + let payload = tabularis::apply(&payload, &resolutions, &existing_groups); + apply_export_payload(runtime, connection_cache, credential_cache, payload).await +} + +pub async fn preview_tabularis_payload( + runtime: &RuntimeContext, + payload: &ExportPayload, +) -> Result { + let existing = load_file(runtime)?.connections; + let registered_ids = registered_driver_ids().await; + Ok(tabularis::preview(payload, &existing, ®istered_ids)) +} + +pub async fn apply_export_payload( + runtime: &RuntimeContext, + connection_cache: &crate::connection_cache::ConnectionCache, + credential_cache: &crate::credential_cache::CredentialCache, + mut payload: ExportPayload, +) -> Result<(), String> { + let mut current = load_file(runtime).unwrap_or_default(); + let mut imported_plugin_secrets = std::mem::take(&mut payload.plugin_secrets); + let mut plugin_secret_writes = Vec::new(); + let mut current_ssh: Vec = load_json(&ssh_path(runtime))?; + crate::commands::merge_groups(&mut current.groups, payload.groups); + let tag_remap = crate::connection_tags::merge_imported_tags(&mut current.tags, payload.tags); + let mut incoming = payload.connections; + remap_tags(&mut current.connections, &mut incoming, &tag_remap); + + for mut connection in incoming { + connection.environment = normalize_environment(connection.environment.take()); + let declared_plugin_secret_keys = std::mem::take(&mut connection.plugin_secret_keys); + let imported_values = imported_plugin_secrets + .remove(&connection.id) + .unwrap_or_default(); + let previous_plugin_metadata = current + .connections + .iter() + .find(|existing| existing.id == connection.id) + .map(|existing| { + ( + existing.params.driver.clone(), + existing.plugin_secret_keys.clone(), + ) + }); + // Keychain writes are deferred until the connections file is saved, + // so a failed import never leaves orphaned plugin secrets behind. + plugin_secret_writes.extend(crate::plugin_secrets::plan_imported_secrets( + &mut connection, + &declared_plugin_secret_keys, + imported_values, + previous_plugin_metadata + .as_ref() + .map(|(driver, keys)| (driver.as_str(), keys.as_slice())), + )); + persist_imported_connection_secrets(runtime, credential_cache, &mut connection)?; + if let Some(existing) = current + .connections + .iter_mut() + .find(|existing| existing.id == connection.id) + { + *existing = connection; + } else { + current.connections.push(connection); + } + } + + for mut connection in payload.ssh_connections { + persist_imported_ssh_secrets(runtime, credential_cache, &mut connection)?; + if let Some(existing) = current_ssh + .iter_mut() + .find(|existing| existing.id == connection.id) + { + *existing = connection; + } else { + current_ssh.push(connection); + } + } + + crate::plugin_secrets::commit_secret_writes( + &RuntimeSecretStore(runtime), + credential_cache, + plugin_secret_writes, + || crate::persistence::save_connections_file(&runtime.paths.connections_file(), ¤t), + )?; + save_json(&ssh_path(runtime), ¤t_ssh)?; + let mut current_k8s: Vec = load_json(&k8s_path(runtime))?; + for connection in payload.k8s_connections { + if let Some(existing) = current_k8s + .iter_mut() + .find(|existing| existing.id == connection.id) + { + *existing = connection; + } else { + current_k8s.push(connection); + } + } + save_json(&k8s_path(runtime), ¤t_k8s)?; + connection_cache.invalidate(); + Ok(()) +} + +async fn store_download( + runtime: &RuntimeContext, + session_id: Uuid, + file_name: &str, + contents: String, +) -> Result { + let metadata = FileTransferStore::new(runtime.paths.data_dir()) + .store_download_bytes( + session_id, + "connection-export", + file_name, + Some(JSON_MIME_TYPE), + contents.into_bytes(), + ) + .await?; + Ok(GeneratedFile::Download { + file_name: metadata.file_name, + mime_type: metadata.mime_type, + token: metadata.token, + size: metadata.size, + }) +} + +async fn analyze_import( + runtime: &RuntimeContext, + envelope: &ImportEnvelope, +) -> Result { + let existing = load_file(runtime)?.connections; + let registered_ids = registered_driver_ids().await; + let file_exists = |path: &str| PathBuf::from(expand_home(path)).exists(); + Ok(analyzer::analyze( + envelope, + &existing, + ®istered_ids, + &file_exists, + )) +} + +async fn registered_driver_ids() -> Vec { + crate::drivers::registry::list_drivers() + .await + .into_iter() + .map(|manifest| manifest.id) + .collect() +} + +enum ResolvedImportFile { + Server(PathBuf), + Upload(super::file_transfers::ClaimedUpload), +} + +impl ResolvedImportFile { + fn path(&self) -> &Path { + match self { + Self::Server(path) => path, + Self::Upload(upload) => upload.path(), + } + } +} + +async fn read_tabularis_import_file( + runtime: &RuntimeContext, + session_id: Option, + file: ConnectionImportFile, +) -> Result<(String, Option<(Uuid, String)>), String> { + match file { + ConnectionImportFile::ServerPath { path } if session_id.is_none() => { + let content = fs::read_to_string(path).map_err(|error| error.to_string())?; + Ok((content, None)) + } + ConnectionImportFile::ServerPath { .. } => { + Err("Browser imports cannot reference server filesystem paths".to_string()) + } + ConnectionImportFile::Upload { token } => { + let owner = session_id + .ok_or_else(|| "Upload tokens are only valid for browser sessions".to_string())?; + let mut reader = FileTransferStore::new(runtime.paths.data_dir()) + .open_upload(owner, &token, CONNECTION_IMPORT_PURPOSE) + .await?; + if reader.metadata().size > MAX_CONNECTION_IMPORT_BYTES { + return Err(format!( + "Connection import exceeds the {MAX_CONNECTION_IMPORT_BYTES} byte limit" + )); + } + let mut content = String::new(); + tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut content) + .await + .map_err(|error| format!("Failed to read connection import: {error}"))?; + Ok((content, Some((owner, token)))) + } + } +} + +fn resolve_import_file( + runtime: &RuntimeContext, + session_id: Option, + file: Option, +) -> Result, String> { + match file { + None => Ok(None), + Some(ConnectionImportFile::ServerPath { path }) if session_id.is_none() => { + Ok(Some(ResolvedImportFile::Server(PathBuf::from(path)))) + } + Some(ConnectionImportFile::ServerPath { .. }) => { + Err("Browser imports cannot reference server filesystem paths".to_string()) + } + Some(ConnectionImportFile::Upload { token }) => { + let session_id = session_id + .ok_or_else(|| "Upload tokens are only valid for browser sessions".to_string())?; + let upload = FileTransferStore::new(runtime.paths.data_dir()).claim_upload( + session_id, + &token, + CONNECTION_IMPORT_PURPOSE, + )?; + if upload.metadata().size > MAX_CONNECTION_IMPORT_BYTES { + return Err(format!( + "Connection import exceeds the {MAX_CONNECTION_IMPORT_BYTES} byte limit" + )); + } + Ok(Some(ResolvedImportFile::Upload(upload))) + } + } +} + +struct RuntimeSecretStore<'a>(&'a RuntimeContext); + +impl crate::plugin_secrets::SecretStore for RuntimeSecretStore<'_> { + fn set(&self, connection_id: &str, driver: &str, key: &str, value: &str) -> Result<(), String> { + let account = super::connections::plugin_secret_account(connection_id, driver, key); + self.0.secrets.set(&account, value) + } + + fn delete(&self, connection_id: &str, driver: &str, key: &str) -> Result<(), String> { + let account = super::connections::plugin_secret_account(connection_id, driver, key); + self.0.secrets.delete(&account) + } +} + +fn persist_imported_connection_secrets( + runtime: &RuntimeContext, + credential_cache: &crate::credential_cache::CredentialCache, + connection: &mut SavedConnection, +) -> Result<(), String> { + crate::credential_cache::invalidate_all_for_connection(credential_cache, &connection.id); + let keychain = connection.params.save_in_keychain.unwrap_or(false); + let imported_uri = connection + .params + .connection_uri + .as_deref() + .filter(|value| !value.trim().is_empty()); + if let Some(uri) = imported_uri { + if !keychain { + return Err("Connection URIs must be stored in the OS keychain".to_string()); + } + runtime + .secrets + .set(&format!("{}:connection_uri", connection.id), uri)?; + crate::credential_cache::set_connection_uri_cached(credential_cache, &connection.id, uri); + connection.params.connection_uri_in_keychain = Some(true); + } else { + connection.params.connection_uri_in_keychain = None; + } + if keychain { + set_imported_secret( + runtime, + credential_cache, + &connection.id, + "db", + connection.params.password.as_deref(), + )?; + set_imported_secret( + runtime, + credential_cache, + &connection.id, + "ssh", + connection.params.ssh_password.as_deref(), + )?; + set_imported_secret( + runtime, + credential_cache, + &connection.id, + "ssh_passphrase", + connection.params.ssh_key_passphrase.as_deref(), + )?; + connection.params.password = None; + connection.params.ssh_password = None; + connection.params.ssh_key_passphrase = None; + } + connection.params.connection_uri = None; + connection.params.connection_id = None; + Ok(()) +} + +fn persist_imported_ssh_secrets( + runtime: &RuntimeContext, + credential_cache: &crate::credential_cache::CredentialCache, + connection: &mut SshConnection, +) -> Result<(), String> { + crate::credential_cache::invalidate_all_for_connection(credential_cache, &connection.id); + if connection.save_in_keychain.unwrap_or(false) { + set_imported_secret( + runtime, + credential_cache, + &connection.id, + "ssh", + connection.password.as_deref(), + )?; + set_imported_secret( + runtime, + credential_cache, + &connection.id, + "ssh_passphrase", + connection.key_passphrase.as_deref(), + )?; + connection.password = None; + connection.key_passphrase = None; + } + Ok(()) +} + +fn set_imported_secret( + runtime: &RuntimeContext, + credential_cache: &crate::credential_cache::CredentialCache, + id: &str, + suffix: &str, + value: Option<&str>, +) -> Result<(), String> { + if let Some(value) = value.filter(|value| !value.is_empty()) { + runtime.secrets.set(&format!("{id}:{suffix}"), value)?; + match suffix { + "db" => crate::credential_cache::set_db_password_cached(credential_cache, id, value), + "ssh" => crate::credential_cache::set_ssh_password_cached(credential_cache, id, value), + "ssh_passphrase" => { + crate::credential_cache::set_ssh_key_passphrase_cached(credential_cache, id, value) + } + _ => {} + } + } + Ok(()) +} + +fn remap_tags( + existing: &mut [SavedConnection], + incoming: &mut [SavedConnection], + remap: &HashMap, +) { + for connection in incoming.iter_mut().chain(existing.iter_mut()) { + if let Some(tag_ids) = connection.tag_ids.as_mut() { + let mut seen = HashSet::new(); + *tag_ids = tag_ids + .iter() + .map(|id| remap.get(id).unwrap_or(id).clone()) + .filter(|id| seen.insert(id.clone())) + .collect(); + } + } +} + +fn normalize_environment(environment: Option) -> Option { + match environment.as_deref() { + Some("development" | "staging" | "production") => environment, + _ => None, + } +} + +fn load_file(runtime: &RuntimeContext) -> Result { + crate::persistence::load_connections_file(&runtime.paths.connections_file()) +} + +fn ssh_path(runtime: &RuntimeContext) -> PathBuf { + runtime.paths.config_dir().join("ssh_connections.json") +} + +fn k8s_path(runtime: &RuntimeContext) -> PathBuf { + runtime.paths.config_dir().join("k8s_connections.json") +} + +fn load_json(path: &Path) -> Result, String> { + if !path.exists() { + return Ok(Vec::new()); + } + serde_json::from_str(&fs::read_to_string(path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string()) +} + +fn save_json(path: &Path, values: &[impl Serialize]) -> Result<(), String> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + crate::persistence::write_private_file( + path, + serde_json::to_string_pretty(values).map_err(|error| error.to_string())?, + ) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "connection_files_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/connection_files_tests.rs b/src-tauri/src/application/connection_files_tests.rs new file mode 100644 index 000000000..69d075cac --- /dev/null +++ b/src-tauri/src/application/connection_files_tests.rs @@ -0,0 +1,369 @@ +use super::*; +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use std::sync::Arc; + +#[derive(Default)] +struct TestSecrets(Mutex>); + +impl RuntimeSecrets for TestSecrets { + fn get(&self, account: &str) -> Result, String> { + Ok(self.0.lock().unwrap().get(account).cloned()) + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + self.0 + .lock() + .unwrap() + .insert(account.to_string(), secret.to_string()); + Ok(()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + self.0.lock().unwrap().remove(account); + Ok(()) + } +} + +fn fixture() -> (tempfile::TempDir, RuntimeContext, Arc) { + let temp = tempfile::tempdir().unwrap(); + let config = temp.path().join("config"); + let data = temp.path().join("data"); + fs::create_dir_all(&config).unwrap(); + fs::create_dir_all(&data).unwrap(); + let secrets = Arc::new(TestSecrets::default()); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new(config, data)), + Arc::new(NoopRuntimeEvents), + secrets.clone(), + ); + let mut params = crate::models::ConnectionParams::default(); + params.driver = "sqlite".to_string(); + params.database = crate::models::DatabaseSelection::Single("fixture.db".to_string()); + params.save_in_keychain = Some(true); + let file = crate::models::ConnectionsFile { + connections: vec![SavedConnection { + id: "connection-1".to_string(), + name: "Fixture".to_string(), + params, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + }], + ..Default::default() + }; + crate::persistence::save_connections_file(&runtime.paths.connections_file(), &file).unwrap(); + (temp, runtime, secrets) +} + +#[tokio::test] +async fn browser_exports_encrypt_before_creating_an_opaque_download() { + let (_temp, runtime, secrets) = fixture(); + secrets.set("connection-1:db", "database-secret").unwrap(); + let session = Uuid::new_v4(); + + let generated = generate_export_file( + &runtime, + Some(session), + ConnectionExportMode::Encrypted, + Some("export-password".to_string()), + None, + ) + .await + .unwrap(); + + let GeneratedFile::Download { token, .. } = generated else { + panic!("browser exports must return a download token"); + }; + let mut reader = FileTransferStore::new(runtime.paths.data_dir()) + .consume_download(session, &token) + .await + .unwrap(); + let mut content = String::new(); + tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut content) + .await + .unwrap(); + assert!(content.contains("tabularis-connections-encrypted")); + assert!(!content.contains("database-secret")); +} + +#[tokio::test] +async fn browser_rejects_plaintext_secret_exports() { + let (_temp, runtime, _secrets) = fixture(); + let error = generate_export_file( + &runtime, + Some(Uuid::new_v4()), + ConnectionExportMode::Plaintext, + None, + None, + ) + .await + .unwrap_err(); + assert!(error.contains("not available in the browser")); +} + +#[tokio::test] +async fn manual_backup_writes_the_server_target_as_an_encrypted_artifact() { + let (_temp, runtime, secrets) = fixture(); + let backup_dir = runtime.paths.data_dir().join("server-backups"); + fs::write( + runtime.paths.config_dir().join("config.json"), + serde_json::json!({ + "backupTarget": "local", + "backupDirectory": backup_dir, + "backupRetention": 2 + }) + .to_string(), + ) + .unwrap(); + secrets + .set("connections-backup", "backup-password") + .unwrap(); + + let artifact = crate::backup::run_backup_for_runtime(&runtime, "manual") + .await + .unwrap(); + + assert!(matches!( + artifact.target_kind, + crate::backup::BackupTargetKind::ServerDirectory + )); + assert!(Path::new(&artifact.location).is_file()); + assert!(artifact.content.contains("tabularis-connections-encrypted")); + assert!(!artifact.content.contains("backup-password")); +} + +#[tokio::test] +async fn uploaded_tabularis_imports_are_session_scoped_and_single_use() { + let (_temp, runtime, _secrets) = fixture(); + let session = Uuid::new_v4(); + let payload = export_payload(&runtime, false, None).await.unwrap(); + let content = serde_json::to_vec(&payload).unwrap(); + let transfer = FileTransferStore::new(runtime.paths.data_dir()) + .store_upload( + session, + CONNECTION_IMPORT_PURPOSE, + "connections.json", + Some("application/json"), + futures::stream::once(async move { + Ok::(bytes::Bytes::from(content)) + }), + ) + .await + .unwrap(); + let cache = ImportEnvelopeCache::default(); + + let preview = preview_tabularis_import_file( + &runtime, + &cache, + Some(session), + ConnectionImportFile::Upload { + token: transfer.token.clone(), + }, + None, + ) + .await + .unwrap(); + + let TabularisImportPreviewResult::Preview { preview } = preview else { + panic!("plaintext imports must return a preview"); + }; + assert_eq!(preview.items.len(), 1); + assert!( + FileTransferStore::new(runtime.paths.data_dir()) + .claim_upload(session, &transfer.token, CONNECTION_IMPORT_PURPOSE) + .is_err(), + "the uploaded file token must be consumed by preview" + ); + assert!(cache.tabularis.lock().unwrap().contains_key(&Some(session))); + cache.clear_session(session); + assert!(!cache.tabularis.lock().unwrap().contains_key(&Some(session))); +} + +#[tokio::test] +async fn foreign_import_files_use_purpose_bound_single_use_uploads() { + let (_temp, runtime, _secrets) = fixture(); + let session = Uuid::new_v4(); + let store = FileTransferStore::new(runtime.paths.data_dir()); + let upload = store + .store_upload( + session, + CONNECTION_IMPORT_PURPOSE, + "foreign.json", + Some("application/json"), + futures::stream::once(async { + Ok::(bytes::Bytes::from_static(b"fixture")) + }), + ) + .await + .unwrap(); + + let resolved = resolve_import_file( + &runtime, + Some(session), + Some(ConnectionImportFile::Upload { + token: upload.token.clone(), + }), + ) + .unwrap() + .unwrap(); + assert_eq!(fs::read_to_string(resolved.path()).unwrap(), "fixture"); + assert!(store + .claim_upload(session, &upload.token, CONNECTION_IMPORT_PURPOSE) + .is_err()); +} + +#[tokio::test] +async fn encrypted_upload_survives_a_wrong_password_for_retry() { + let (_temp, runtime, _secrets) = fixture(); + let session = Uuid::new_v4(); + let payload = export_payload(&runtime, false, None).await.unwrap(); + let plaintext = serde_json::to_string(&payload).unwrap(); + let envelope = crate::export_crypto::encrypt(&plaintext, "correct-password").unwrap(); + let content = serde_json::to_vec(&envelope).unwrap(); + let transfer = FileTransferStore::new(runtime.paths.data_dir()) + .store_upload( + session, + CONNECTION_IMPORT_PURPOSE, + "connections.json", + Some("application/json"), + futures::stream::once(async move { + Ok::(bytes::Bytes::from(content)) + }), + ) + .await + .unwrap(); + let cache = ImportEnvelopeCache::default(); + let file = || ConnectionImportFile::Upload { + token: transfer.token.clone(), + }; + + let password_required = + preview_tabularis_import_file(&runtime, &cache, Some(session), file(), None) + .await + .unwrap(); + assert!(matches!( + password_required, + TabularisImportPreviewResult::PasswordRequired + )); + + let error = preview_tabularis_import_file( + &runtime, + &cache, + Some(session), + file(), + Some("wrong-password".to_string()), + ) + .await + .unwrap_err(); + assert!(error.contains("wrong password")); + + let preview = preview_tabularis_import_file( + &runtime, + &cache, + Some(session), + file(), + Some("correct-password".to_string()), + ) + .await + .unwrap(); + let TabularisImportPreviewResult::Preview { preview } = preview else { + panic!("the correct password must return a preview"); + }; + assert_eq!(preview.items.len(), 1); +} + +#[tokio::test] +async fn imported_secrets_replace_stale_runtime_cache_entries() { + let (_temp, runtime, secrets) = fixture(); + secrets.set("connection-1:db", "old-secret").unwrap(); + let credential_cache = crate::credential_cache::CredentialCache::default(); + crate::credential_cache::set_db_password_cached( + &credential_cache, + "connection-1", + "old-secret", + ); + let mut payload = export_payload(&runtime, false, None).await.unwrap(); + payload.connections[0].params.password = Some("new-secret".to_string()); + payload.connections[0].params.save_in_keychain = Some(true); + + apply_export_payload( + &runtime, + &crate::connection_cache::ConnectionCache::default(), + &credential_cache, + payload, + ) + .await + .unwrap(); + + assert_eq!( + secrets.get("connection-1:db").unwrap().as_deref(), + Some("new-secret") + ); + assert!(matches!( + credential_cache + .db_passwords + .lock() + .unwrap() + .get("connection-1"), + Some(crate::credential_cache::CacheEntry::Present(value)) if value == "new-secret" + )); + let saved = + crate::persistence::load_connections_file(&runtime.paths.connections_file()).unwrap(); + assert!(saved.connections[0].params.password.is_none()); +} + +#[test] +fn browser_imports_never_accept_server_paths() { + let (_temp, runtime, _secrets) = fixture(); + let error = resolve_import_file( + &runtime, + Some(Uuid::new_v4()), + Some(ConnectionImportFile::ServerPath { + path: "/etc/passwd".to_string(), + }), + ) + .err() + .expect("server paths must be rejected"); + assert!(error.contains("cannot reference server filesystem paths")); +} + +#[cfg(unix)] +#[tokio::test] +async fn imported_ssh_secrets_create_and_repair_private_file_permissions() { + use std::os::unix::fs::PermissionsExt; + let (_temp, runtime, _secrets) = fixture(); + let mut payload = export_payload(&runtime, false, None).await.unwrap(); + payload.ssh_connections = vec![serde_json::from_value(serde_json::json!({ + "id": "ssh-import", "name": "Imported", "host": "localhost", "port": 22, + "user": "user", "auth_type": "password", "password": "imported-secret", + "save_in_keychain": false + })) + .unwrap()]; + let path = ssh_path(&runtime); + for existing in [false, true] { + if existing { + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + } + apply_export_payload( + &runtime, + &crate::connection_cache::ConnectionCache::default(), + &crate::credential_cache::CredentialCache::default(), + payload.clone(), + ) + .await + .unwrap(); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert!(fs::read_to_string(&path) + .unwrap() + .contains("imported-secret")); + } +} diff --git a/src-tauri/src/application/connection_secret_writes.rs b/src-tauri/src/application/connection_secret_writes.rs new file mode 100644 index 000000000..2d914d3c0 --- /dev/null +++ b/src-tauri/src/application/connection_secret_writes.rs @@ -0,0 +1,45 @@ +use crate::runtime::RuntimeContext; + +#[derive(Default)] +pub(super) struct SecretWrites(Vec<(String, Option)>); + +impl SecretWrites { + pub(super) fn set( + &mut self, + runtime: &RuntimeContext, + account: String, + value: &str, + ) -> Result<(), String> { + let previous = runtime.secrets.get(&account)?; + runtime.secrets.set(&account, value)?; + self.0.push((account, previous)); + Ok(()) + } + + pub(super) fn delete( + &mut self, + runtime: &RuntimeContext, + account: String, + ) -> Result<(), String> { + let previous = runtime.secrets.get(&account)?; + runtime.secrets.delete(&account)?; + self.0.push((account, previous)); + Ok(()) + } + + pub(super) fn append(&mut self, mut other: Self) { + self.0.append(&mut other.0); + } + + pub(super) fn rollback(&mut self, runtime: &RuntimeContext) { + for (account, previous) in self.0.drain(..).rev() { + let result = match previous { + Some(value) => runtime.secrets.set(&account, &value), + None => runtime.secrets.delete(&account), + }; + if let Err(error) = result { + log::warn!("Failed to restore connection credential {account}: {error}"); + } + } + } +} diff --git a/src-tauri/src/application/connections.rs b/src-tauri/src/application/connections.rs new file mode 100644 index 000000000..0cad710a8 --- /dev/null +++ b/src-tauri/src/application/connections.rs @@ -0,0 +1,1778 @@ +#[path = "connection_secret_writes.rs"] +mod connection_secret_writes; +use connection_secret_writes::SecretWrites; + +use crate::models::{ + ConnectionAppearance, ConnectionGroup, ConnectionParams, ConnectionsFile, SavedConnection, + TestConnectionRequest, +}; +use crate::plugin_secrets::PluginSecretChanges; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use serde::Serialize; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; +use uuid::Uuid; + +const ICON_UPLOAD_TTL: Duration = Duration::from_secs(5 * 60); +const MAX_PENDING_ICON_UPLOADS_PER_SESSION: usize = 16; +const DB_SECRET_SUFFIX: &str = "db"; +const SSH_SECRET_SUFFIX: &str = "ssh"; +const SSH_PASSPHRASE_SUFFIX: &str = "ssh_passphrase"; +const CONNECTION_URI_SUFFIX: &str = "connection_uri"; + +#[derive(Debug)] +pub enum ConnectionCommand { + SetSelectedDatabases { + connection_id: String, + databases: Vec, + }, + GetConnections, + GetConnectionById { + id: String, + }, + GetConnectionsWithGroups, + SaveConnection { + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, + }, + UpdateConnection { + id: String, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, + }, + DeleteConnection { + id: String, + }, + DuplicateConnection { + id: String, + }, + SetConnectionAppearance { + id: String, + appearance: Option, + }, + SaveConnectionIcon { + connection_id: String, + upload_token: String, + session_id: Uuid, + }, + DeleteConnectionIcon { + relative_path: String, + }, + GetConnectionGroups, + CreateConnectionGroup { + name: String, + parent_id: Option, + }, + CreateGroupPath { + path: String, + parent_id: Option, + }, + UpdateConnectionGroup { + id: String, + name: Option, + collapsed: Option, + sort_order: Option, + }, + MoveGroupToParent { + id: String, + parent_id: Option, + }, + DeleteConnectionGroup { + id: String, + }, + MoveConnectionToGroup { + connection_id: String, + group_id: Option, + sort_order: Option, + }, + ReorderGroups { + group_orders: Vec<(String, i32)>, + }, + ReorderConnectionsInGroup { + connection_orders: Vec<(String, i32)>, + }, + ListConnectionTags, + CreateConnectionTag { + name: String, + color: String, + }, + UpdateConnectionTag { + id: String, + name: String, + color: String, + }, + DeleteConnectionTag { + id: String, + }, + SetConnectionTags { + connection_id: String, + tag_ids: Vec, + }, + GetRegisteredDrivers, + GetDriverManifest { + driver_id: String, + }, + GetActiveConnections, + RegisterActiveConnection { + connection_id: String, + }, + DisconnectConnection { + connection_id: String, + }, + TestConnection { + request: TestConnectionRequest, + }, + ListDatabases { + request: TestConnectionRequest, + }, + CreateSqliteDatabase { + path: String, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &Arc, + command: ConnectionCommand, +) -> Result { + execute_for_session(runtime, state, None, command).await +} + +pub async fn execute_for_session( + runtime: &RuntimeContext, + state: &Arc, + session_id: Option, + command: ConnectionCommand, +) -> Result { + match command { + ConnectionCommand::SetSelectedDatabases { + connection_id, + databases, + } => { + set_selected_databases(runtime, &connection_id, databases).await?; + state.connection_cache.invalidate(); + Ok(Value::Null) + } + ConnectionCommand::GetConnections => { + json(redacted_connections(load_file(runtime)?.connections)) + } + ConnectionCommand::GetConnectionById { id } => { + let connection = find_connection(&load_file(runtime)?, &id)?; + json(redact_connection(connection)) + } + ConnectionCommand::GetConnectionsWithGroups => { + let mut file = load_file(runtime)?; + file.connections = redacted_connections(file.connections); + json(file) + } + ConnectionCommand::SaveConnection { + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + } => json(save_connection( + runtime, + state, + name, + params, + plugin_secret_changes.unwrap_or_default(), + detect_json_in_text_columns, + environment, + )?), + ConnectionCommand::UpdateConnection { + id, + name, + params, + plugin_secret_changes, + detect_json_in_text_columns, + environment, + } => { + let previous_driver = find_connection(&load_file(runtime)?, &id)?.params.driver; + let updated = update_connection( + runtime, + state, + id.clone(), + name, + params, + plugin_secret_changes.unwrap_or_default(), + detect_json_in_text_columns, + environment, + )?; + invalidate_connection_metadata( + runtime, + &id, + [&previous_driver, &updated.params.driver], + ) + .await; + json(updated) + } + ConnectionCommand::DeleteConnection { id } => { + delete_connection(runtime, state, &id)?; + Ok(Value::Null) + } + ConnectionCommand::DuplicateConnection { id } => { + json(duplicate_connection(runtime, state, &id)?) + } + ConnectionCommand::SetConnectionAppearance { id, appearance } => { + let mut file = load_file(runtime)?; + let connection = file + .connections + .iter_mut() + .find(|connection| connection.id == id) + .ok_or_else(|| "Connection not found".to_string())?; + connection.appearance = appearance; + save_file(runtime, state, &file)?; + Ok(Value::Null) + } + ConnectionCommand::SaveConnectionIcon { + connection_id, + upload_token, + session_id, + } => { + let upload = consume_icon_upload(runtime, session_id, &upload_token)?; + let destination = runtime.paths.data_dir().join("connection-icons"); + let result = + crate::connection_appearance::save_icon_impl(&destination, &connection_id, &upload) + .map_err(|error| error.to_string()); + let _ = fs::remove_file(upload); + json(result?) + } + ConnectionCommand::DeleteConnectionIcon { relative_path } => { + delete_icon(runtime.paths.data_dir(), &relative_path)?; + Ok(Value::Null) + } + ConnectionCommand::GetConnectionGroups => json(load_file(runtime)?.groups), + ConnectionCommand::CreateConnectionGroup { name, parent_id } => { + json(create_group(runtime, state, name, parent_id)?) + } + ConnectionCommand::CreateGroupPath { path, parent_id } => { + json(create_group_path(runtime, state, &path, parent_id)?) + } + ConnectionCommand::UpdateConnectionGroup { + id, + name, + collapsed, + sort_order, + } => json(update_group( + runtime, state, &id, name, collapsed, sort_order, + )?), + ConnectionCommand::MoveGroupToParent { id, parent_id } => { + json(move_group(runtime, state, &id, parent_id)?) + } + ConnectionCommand::DeleteConnectionGroup { id } => { + delete_group(runtime, state, &id)?; + Ok(Value::Null) + } + ConnectionCommand::MoveConnectionToGroup { + connection_id, + group_id, + sort_order, + } => json(move_connection( + runtime, + state, + &connection_id, + group_id, + sort_order, + )?), + ConnectionCommand::ReorderGroups { group_orders } => { + reorder_groups(runtime, state, group_orders)?; + Ok(Value::Null) + } + ConnectionCommand::ReorderConnectionsInGroup { connection_orders } => { + reorder_connections(runtime, state, connection_orders)?; + Ok(Value::Null) + } + ConnectionCommand::ListConnectionTags => json(load_file(runtime)?.tags), + ConnectionCommand::CreateConnectionTag { name, color } => { + let mut file = load_file(runtime)?; + let tag = crate::connection_tags::create_tag_impl(&mut file, &name, &color)?; + save_file(runtime, state, &file)?; + json(tag) + } + ConnectionCommand::UpdateConnectionTag { id, name, color } => { + let mut file = load_file(runtime)?; + crate::connection_tags::update_tag_impl(&mut file, &id, &name, &color)?; + save_file(runtime, state, &file)?; + Ok(Value::Null) + } + ConnectionCommand::DeleteConnectionTag { id } => { + let mut file = load_file(runtime)?; + crate::connection_tags::delete_tag_impl(&mut file, &id)?; + save_file(runtime, state, &file)?; + Ok(Value::Null) + } + ConnectionCommand::SetConnectionTags { + connection_id, + tag_ids, + } => { + let mut file = load_file(runtime)?; + crate::connection_tags::set_connection_tags_impl(&mut file, &connection_id, &tag_ids)?; + save_file(runtime, state, &file)?; + Ok(Value::Null) + } + ConnectionCommand::GetRegisteredDrivers => { + json(crate::drivers::registry::list_drivers().await) + } + ConnectionCommand::GetDriverManifest { driver_id } => { + let manifest = crate::drivers::registry::get_driver(&driver_id) + .await + .map( + |driver| crate::plugins::connection_metadata::DriverManifestDetails { + manifest: driver.manifest().clone(), + connection_metadata: driver.has_connection_metadata().then_some(true), + }, + ); + json(manifest) + } + ConnectionCommand::GetActiveConnections => { + json(active_connections(state, session_id).await) + } + ConnectionCommand::RegisterActiveConnection { connection_id } => { + register_active_connection(runtime, Some(state), session_id, connection_id).await; + Ok(Value::Null) + } + ConnectionCommand::DisconnectConnection { connection_id } => { + disconnect_connection(runtime, Some(state), session_id, &connection_id).await?; + Ok(Value::Null) + } + 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?) + } + } +} + +pub fn load_connections(path: &Path) -> Result, String> { + crate::persistence::load_connections(path) +} + +pub fn load_redacted_connections(path: &Path) -> Result, String> { + load_connections(path).map(redacted_connections) +} + +/// Driver id of a saved connection, without resolving secrets or tunnels. +pub(crate) fn saved_connection_driver( + runtime: &RuntimeContext, + connection_id: &str, +) -> Result { + Ok(find_connection(&load_file(runtime)?, connection_id)? + .params + .driver) +} + +pub(crate) fn resolve_saved_connection_params( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, +) -> Result<(String, ConnectionParams), String> { + let saved = find_connection(&load_file(runtime)?, connection_id)?; + let driver_id = saved.params.driver.clone(); + let plugin_secrets = load_plugin_secrets(runtime, &saved); + let mut params = saved.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 = + crate::application::tunnels::resolve_connection_params(runtime, ¶ms, session_id)?; + Ok((driver_id, params)) +} + +pub fn store_icon_upload( + data_dir: &Path, + session_id: Uuid, + bytes: &[u8], +) -> Result { + if bytes.is_empty() { + return Err("The uploaded icon is empty".to_string()); + } + if bytes.len() as u64 > crate::connection_appearance::MAX_ICON_BYTES { + return Err("The uploaded icon exceeds 512 KB".to_string()); + } + let token = Uuid::new_v4().to_string(); + let directory = upload_directory(data_dir, session_id); + fs::create_dir_all(&directory).map_err(|error| error.to_string())?; + let mut pending = 0; + for entry in fs::read_dir(&directory).map_err(|error| error.to_string())? { + let entry = entry.map_err(|error| error.to_string())?; + let metadata = entry.metadata().map_err(|error| error.to_string())?; + let age = metadata + .modified() + .ok() + .and_then(|modified| SystemTime::now().duration_since(modified).ok()) + .unwrap_or(Duration::ZERO); + if age > ICON_UPLOAD_TTL || entry.path().extension().is_some_and(|ext| ext == "tmp") { + let _ = fs::remove_file(entry.path()); + } else if metadata.is_file() { + pending += 1; + } + } + if pending >= MAX_PENDING_ICON_UPLOADS_PER_SESSION { + return Err("Too many pending connection icon uploads".to_string()); + } + let destination = directory.join(&token); + let temporary = directory.join(format!("{token}.tmp")); + fs::write(&temporary, bytes).map_err(|error| error.to_string())?; + fs::rename(&temporary, &destination).map_err(|error| { + let _ = fs::remove_file(&temporary); + error.to_string() + })?; + Ok(token) +} + +pub fn resolve_icon_asset(data_dir: &Path, relative_path: &str) -> Result { + let filename = relative_path + .strip_prefix("connection-icons/") + .filter(|filename| { + !filename.is_empty() + && !filename.contains('/') + && !filename.contains('\\') + && *filename != "." + && *filename != ".." + }) + .ok_or_else(|| "Invalid connection icon path".to_string())?; + let path = data_dir.join("connection-icons").join(filename); + if !path.is_file() { + return Err("Connection icon not found".to_string()); + } + Ok(path) +} + +fn load_file(runtime: &RuntimeContext) -> Result { + crate::persistence::load_connections_file(&runtime.paths.connections_file()) +} + +fn save_file( + runtime: &RuntimeContext, + state: &Arc, + file: &ConnectionsFile, +) -> Result<(), String> { + crate::persistence::save_connections_file(&runtime.paths.connections_file(), file)?; + state.connection_cache.invalidate(); + Ok(()) +} + +fn find_connection(file: &ConnectionsFile, id: &str) -> Result { + file.connections + .iter() + .find(|connection| connection.id == id) + .cloned() + .ok_or_else(|| "Connection not found".to_string()) +} + +fn redacted_connections(connections: Vec) -> Vec { + connections.into_iter().map(redact_connection).collect() +} + +fn redact_connection(mut connection: SavedConnection) -> SavedConnection { + connection.params.password = None; + connection.params.connection_uri = None; + connection.params.ssh_password = None; + connection.params.ssh_key_passphrase = None; + connection.params.connection_id = None; + connection +} + +fn validate_environment(environment: Option) -> Result, String> { + match environment.as_deref() { + None | Some("") => Ok(None), + Some("development" | "staging" | "production") => Ok(environment), + Some(other) => Err(format!("Invalid environment: {other}")), + } +} + +/// 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}") +} + +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()); + } + writes.set(runtime, secret_account(id, CONNECTION_URI_SUFFIX), uri)?; + params.connection_uri_in_keychain = Some(true); + params.connection_uri = None; + } + persist_passwords(runtime, id, params, writes) +} + +fn persist_passwords( + runtime: &RuntimeContext, + id: &str, + params: &mut ConnectionParams, + writes: &mut SecretWrites, +) -> Result<(), String> { + if !params.save_in_keychain.unwrap_or(false) { + return Ok(()); + } + let mut password_writes = SecretWrites::default(); + let result = (|| { + for (suffix, value) in [ + (DB_SECRET_SUFFIX, params.password.as_deref()), + (SSH_SECRET_SUFFIX, params.ssh_password.as_deref()), + (SSH_PASSPHRASE_SUFFIX, params.ssh_key_passphrase.as_deref()), + ] { + if let Some(value) = value { + if value.is_empty() { + password_writes.delete(runtime, secret_account(id, suffix))?; + } else { + password_writes.set(runtime, secret_account(id, suffix), value)?; + } + } + } + Ok::<(), String>(()) + })(); + if let Err(error) = result { + password_writes.rollback(runtime); + log::warn!("Keychain unavailable for connection {id}; storing passwords in the config file: {error}"); + crate::persistence::apply_secret_persistence(params, false); + } else { + writes.append(password_writes); + crate::persistence::apply_secret_persistence(params, true); + } + Ok(()) +} + +fn merge_and_persist_update_secrets( + runtime: &RuntimeContext, + id: &str, + existing: &ConnectionParams, + params: &mut ConnectionParams, + writes: &mut SecretWrites, +) -> Result<(), String> { + let keychain = params.save_in_keychain.unwrap_or(false); + if let Some(uri) = non_empty(params.connection_uri.as_ref()) { + if !keychain { + return Err("Connection URIs must be stored in the OS keychain".to_string()); + } + writes.set(runtime, secret_account(id, CONNECTION_URI_SUFFIX), uri)?; + params.connection_uri_in_keychain = Some(true); + } else if keychain + && existing.driver == params.driver + && existing.connection_uri_in_keychain.unwrap_or(false) + && params.connection_uri_in_keychain != Some(false) + { + params.connection_uri_in_keychain = Some(true); + } else if existing.connection_uri_in_keychain.unwrap_or(false) { + writes.delete(runtime, secret_account(id, CONNECTION_URI_SUFFIX))?; + params.connection_uri_in_keychain = None; + } else { + params.connection_uri_in_keychain = None; + } + 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), + ( + &mut params.ssh_password, + &existing.ssh_password, + SSH_SECRET_SUFFIX, + ), + ( + &mut params.ssh_key_passphrase, + &existing.ssh_key_passphrase, + SSH_PASSPHRASE_SUFFIX, + ), + ] { + if field.is_none() { + *field = if existing.save_in_keychain.unwrap_or(false) { + runtime.secrets.get(&secret_account(id, suffix))? + } else { + previous.clone() + }; + } + } + 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(()) +} + +fn delete_connection_secrets(runtime: &RuntimeContext, id: &str) -> Result<(), String> { + for suffix in [ + DB_SECRET_SUFFIX, + SSH_SECRET_SUFFIX, + SSH_PASSPHRASE_SUFFIX, + CONNECTION_URI_SUFFIX, + ] { + runtime.secrets.delete(&secret_account(id, suffix))?; + } + Ok(()) +} + +pub(crate) fn restore_connection_secrets( + runtime: &RuntimeContext, + id: &str, + params: &mut ConnectionParams, +) -> Result<(), String> { + restore_secrets(runtime, id, params) +} + +pub(crate) fn plugin_secret_account(connection_id: &str, driver: &str, key: &str) -> String { + format!("{connection_id}:plugin:{driver}:{key}") +} + +/// Stored plugin-owned secrets of `connection`. Lenient like the desktop path: +/// an unreadable key is logged and left unset so the plugin reports it. +pub(crate) fn load_plugin_secrets( + runtime: &RuntimeContext, + connection: &SavedConnection, +) -> std::collections::HashMap { + let driver = &connection.params.driver; + crate::plugin_secrets::resolve_secret_values( + &connection.id, + &connection.plugin_secret_keys, + |key| { + runtime + .secrets + .get(&plugin_secret_account(&connection.id, driver, key)) + }, + ) + .values +} + +/// Applies the modal's plugin secret changes to the keychain and returns the +/// key list to persist. Values never stay in `params.extra`. +fn persist_plugin_secrets( + runtime: &RuntimeContext, + id: &str, + previous: Option<(&str, &[String])>, + params: &mut ConnectionParams, + changes: &PluginSecretChanges, + writes: &mut SecretWrites, +) -> Result, String> { + let same_driver = previous.is_none_or(|(driver, _)| driver == params.driver); + let existing = previous.map(|(_, keys)| keys).unwrap_or_default(); + let keys = crate::plugin_secrets::next_secret_keys(existing, same_driver, changes)?; + if let Some((old_driver, old_keys)) = previous.filter(|_| !same_driver) { + for key in old_keys { + writes.delete(runtime, plugin_secret_account(id, old_driver, key))?; + } + } + for (key, value) in changes { + params.extra.remove(key); + let account = plugin_secret_account(id, ¶ms.driver, key); + match value { + Some(value) => writes.set(runtime, account, value)?, + None => writes.delete(runtime, account)?, + } + } + Ok(keys) +} + +/// Secrets a plugin SQL builder may forward: the connection URI, the database +/// password and the plugin-owned secrets. Never fails (see +/// `commands::apply_sql_builder_secrets`); SSH secrets are skipped because the +/// builders never open tunnels. +pub(crate) fn bind_sql_builder_secrets(runtime: &RuntimeContext, connection: &mut SavedConnection) { + let id = connection.id.clone(); + crate::commands::apply_sql_builder_secrets( + &mut connection.params, + &id, + |stored| { + if stored { + runtime + .secrets + .get(&secret_account(&id, CONNECTION_URI_SUFFIX)) + } else { + Ok(None) + } + }, + || { + runtime + .secrets + .get(&secret_account(&id, DB_SECRET_SUFFIX))? + .ok_or_else(|| "No password stored".to_string()) + }, + ); + let plugin_secrets = load_plugin_secrets(runtime, connection); + connection.params.extra.extend(plugin_secrets); +} + +fn delete_plugin_secrets(runtime: &RuntimeContext, connection: &SavedConnection) { + for key in &connection.plugin_secret_keys { + let account = plugin_secret_account(&connection.id, &connection.params.driver, key); + if let Err(error) = runtime.secrets.delete(&account) { + log::warn!("Failed to remove plugin secret '{key}': {error}"); + } + } +} + +fn restore_secrets( + runtime: &RuntimeContext, + id: &str, + params: &mut ConnectionParams, +) -> Result<(), String> { + if params.save_in_keychain.unwrap_or(false) { + // 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) { + params.ssh_password = runtime + .secrets + .get(&secret_account(id, SSH_SECRET_SUFFIX))?; + } + if params + .ssh_key_passphrase + .as_deref() + .is_none_or(str::is_empty) + { + params.ssh_key_passphrase = runtime + .secrets + .get(&secret_account(id, SSH_PASSPHRASE_SUFFIX))?; + } + } + if params.connection_uri_in_keychain.unwrap_or(false) + && params.connection_uri.as_deref().is_none_or(str::is_empty) + { + params.connection_uri = runtime + .secrets + .get(&secret_account(id, CONNECTION_URI_SUFFIX))?; + } + 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, + name: String, + mut params: ConnectionParams, + plugin_secret_changes: PluginSecretChanges, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + let mut file = load_file(runtime)?; + let id = Uuid::new_v4().to_string(); + let environment = validate_environment(environment)?; + let mut writes = SecretWrites::default(); + let result = (|| { + params.connection_id = None; + let plugin_secret_keys = persist_plugin_secrets( + runtime, + &id, + None, + &mut params, + &plugin_secret_changes, + &mut writes, + )?; + persist_secrets_for_create(runtime, &id, &mut params, &mut writes)?; + let connection = SavedConnection { + id, + name, + params, + plugin_secret_keys, + group_id: None, + sort_order: None, + detect_json_in_text_columns, + appearance: None, + tag_ids: None, + environment, + }; + file.connections.push(connection.clone()); + save_file(runtime, state, &file)?; + if !connection.params.save_in_keychain.unwrap_or(false) { + for suffix in [DB_SECRET_SUFFIX, SSH_SECRET_SUFFIX, SSH_PASSPHRASE_SUFFIX] { + if let Err(error) = runtime + .secrets + .delete(&secret_account(&connection.id, suffix)) + { + log::warn!("Failed to remove unused connection credential: {error}"); + } + } + } + Ok(redact_connection(connection)) + })(); + if result.is_err() { + writes.rollback(runtime); + } + 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( + runtime: &RuntimeContext, + connection_id: &str, + driver_ids: [&String; 2], +) { + let mut metadata_changed = false; + for driver_id in driver_ids { + if let Some(driver) = crate::drivers::registry::get_driver(driver_id).await { + if driver.has_connection_metadata() { + driver + .invalidate_connection_metadata(Some(connection_id)) + .await; + metadata_changed = true; + } + } + } + if metadata_changed { + let _ = runtime.events.emit( + "connection-metadata-invalidated", + serde_json::json!({ "connectionId": connection_id }), + ); + } +} + +fn update_connection( + runtime: &RuntimeContext, + state: &Arc, + id: String, + name: String, + mut params: ConnectionParams, + plugin_secret_changes: PluginSecretChanges, + detect_json_in_text_columns: Option, + environment: Option, +) -> Result { + let mut file = load_file(runtime)?; + let index = file + .connections + .iter() + .position(|connection| connection.id == id) + .ok_or_else(|| "Connection not found".to_string())?; + let existing = file.connections[index].clone(); + let environment = validate_environment(environment)?; + let mut writes = SecretWrites::default(); + let result = (|| { + params.connection_id = None; + let plugin_secret_keys = persist_plugin_secrets( + runtime, + &id, + Some((&existing.params.driver, &existing.plugin_secret_keys)), + &mut params, + &plugin_secret_changes, + &mut writes, + )?; + merge_and_persist_update_secrets(runtime, &id, &existing.params, &mut params, &mut writes)?; + let connection = SavedConnection { + id, + name, + params, + plugin_secret_keys, + group_id: existing.group_id, + sort_order: existing.sort_order, + detect_json_in_text_columns, + appearance: existing.appearance, + tag_ids: existing.tag_ids, + environment, + }; + file.connections[index] = connection.clone(); + save_file(runtime, state, &file)?; + if !connection.params.save_in_keychain.unwrap_or(false) { + for suffix in [DB_SECRET_SUFFIX, SSH_SECRET_SUFFIX, SSH_PASSPHRASE_SUFFIX] { + if let Err(error) = runtime + .secrets + .delete(&secret_account(&connection.id, suffix)) + { + log::warn!("Failed to remove unused connection credential: {error}"); + } + } + } + crate::credential_cache::invalidate_all_for_connection( + &state.credential_cache, + &connection.id, + ); + if let Some(database) = crate::models::single_db_before_multi_transition( + &existing.params.database, + &connection.params.database, + ) { + if let Err(error) = super::productivity::backfill_saved_queries_for_connection( + runtime.paths.config_dir(), + &connection.id, + &database, + ) { + log::warn!("Failed to backfill saved query database: {error}"); + } + if let Err(error) = super::productivity::backfill_query_history_for_connection( + runtime.paths.config_dir(), + &connection.id, + &database, + ) { + log::warn!("Failed to backfill query history database: {error}"); + } + } + Ok(redact_connection(connection)) + })(); + if result.is_err() { + writes.rollback(runtime); + } + result +} + +fn delete_connection( + runtime: &RuntimeContext, + state: &Arc, + id: &str, +) -> Result<(), String> { + let mut file = load_file(runtime)?; + let removed = file + .connections + .iter() + .find(|connection| connection.id == id) + .cloned(); + file.connections.retain(|connection| connection.id != id); + save_file(runtime, state, &file)?; + 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); + if let Err(error) = crate::connection_appearance::cascade_delete_if_image( + runtime.paths.data_dir(), + 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( + runtime: &RuntimeContext, + state: &Arc, + id: &str, +) -> Result { + let mut file = load_file(runtime)?; + let mut original = find_connection(&file, id)?; + let new_id = Uuid::new_v4().to_string(); + let mut writes = SecretWrites::default(); + let result = (|| { + { + for suffix in [ + DB_SECRET_SUFFIX, + SSH_SECRET_SUFFIX, + SSH_PASSPHRASE_SUFFIX, + CONNECTION_URI_SUFFIX, + ] { + 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) + }; + if !should_copy { + continue; + } + if let Some(secret) = runtime.secrets.get(&secret_account(id, suffix))? { + writes.set(runtime, secret_account(&new_id, suffix), &secret)?; + } else if suffix == CONNECTION_URI_SUFFIX { + original.params.connection_uri_in_keychain = None; + } + } + } + // A secret that can no longer be read is not copied, and the + // duplicate does not list it. + let plugin_secrets = load_plugin_secrets(runtime, &original); + for (key, value) in &plugin_secrets { + writes.set( + runtime, + plugin_secret_account(&new_id, &original.params.driver, key), + value, + )?; + } + let mut plugin_secret_keys: Vec = plugin_secrets.into_keys().collect(); + plugin_secret_keys.sort(); + let appearance = duplicate_appearance(runtime.paths.data_dir(), &original, &new_id); + let duplicate = SavedConnection { + id: new_id, + name: format!("{} (Copy)", original.name), + params: original.params, + plugin_secret_keys, + group_id: original.group_id, + sort_order: None, + detect_json_in_text_columns: original.detect_json_in_text_columns, + appearance, + tag_ids: original.tag_ids, + environment: validate_environment(original.environment).unwrap_or(None), + }; + file.connections.push(duplicate.clone()); + save_file(runtime, state, &file)?; + Ok(redact_connection(duplicate)) + })(); + if result.is_err() { + writes.rollback(runtime); + } + result +} + +fn duplicate_appearance( + data_dir: &Path, + original: &SavedConnection, + new_id: &str, +) -> Option { + let mut appearance = original.appearance.clone()?; + if let Some(crate::models::IconOverride::Image { path }) = appearance.icon.clone() { + match crate::connection_appearance::copy_icon_for_duplicate(data_dir, &path, new_id) { + Ok(path) => appearance.icon = Some(crate::models::IconOverride::Image { path }), + Err(_) => appearance.icon = None, + } + } + (appearance.icon.is_some() || appearance.accent_color.is_some()).then_some(appearance) +} + +fn create_group( + runtime: &RuntimeContext, + state: &Arc, + name: String, + parent_id: Option, +) -> Result { + let mut file = load_file(runtime)?; + validate_parent(&file, parent_id.as_deref())?; + let sort_order = next_group_order(&file, &parent_id); + let group = ConnectionGroup { + id: Uuid::new_v4().to_string(), + name, + collapsed: false, + sort_order, + parent_id, + }; + file.groups.push(group.clone()); + save_file(runtime, state, &file)?; + Ok(group) +} + +fn create_group_path( + runtime: &RuntimeContext, + state: &Arc, + path: &str, + parent_id: Option, +) -> Result { + let mut file = load_file(runtime)?; + validate_parent(&file, parent_id.as_deref())?; + let segments = crate::commands::parse_group_path(path)?; + let mut current_parent = parent_id; + let mut last = None; + for name in segments { + if let Some(existing) = + crate::commands::find_child_group(&file.groups, &name, ¤t_parent).cloned() + { + current_parent = Some(existing.id.clone()); + last = Some(existing); + continue; + } + let group = ConnectionGroup { + id: Uuid::new_v4().to_string(), + name, + collapsed: false, + sort_order: next_group_order(&file, ¤t_parent), + parent_id: current_parent, + }; + current_parent = Some(group.id.clone()); + last = Some(group.clone()); + file.groups.push(group); + } + save_file(runtime, state, &file)?; + last.ok_or_else(|| "Group path resolved to an empty hierarchy".to_string()) +} + +fn validate_parent(file: &ConnectionsFile, parent_id: Option<&str>) -> Result<(), String> { + if let Some(parent_id) = parent_id { + if !file.groups.iter().any(|group| group.id == parent_id) { + return Err(format!("Parent group with ID {parent_id} not found")); + } + } + Ok(()) +} + +fn next_group_order(file: &ConnectionsFile, parent_id: &Option) -> i32 { + file.groups + .iter() + .filter(|group| group.parent_id == *parent_id) + .map(|group| group.sort_order) + .max() + .unwrap_or(-1) + + 1 +} + +fn update_group( + runtime: &RuntimeContext, + state: &Arc, + id: &str, + name: Option, + collapsed: Option, + sort_order: Option, +) -> Result { + let mut file = load_file(runtime)?; + let group = file + .groups + .iter_mut() + .find(|group| group.id == id) + .ok_or_else(|| format!("Group with ID {id} not found"))?; + if let Some(name) = name { + group.name = name; + } + if let Some(collapsed) = collapsed { + group.collapsed = collapsed; + } + if let Some(sort_order) = sort_order { + group.sort_order = sort_order; + } + let updated = group.clone(); + save_file(runtime, state, &file)?; + Ok(updated) +} + +fn move_group( + runtime: &RuntimeContext, + state: &Arc, + id: &str, + parent_id: Option, +) -> Result { + let mut file = load_file(runtime)?; + if !file.groups.iter().any(|group| group.id == id) { + return Err(format!("Group with ID {id} not found")); + } + validate_parent(&file, parent_id.as_deref())?; + crate::commands::reject_if_would_create_cycle(&file.groups, id, parent_id.as_deref())?; + let group = file + .groups + .iter_mut() + .find(|group| group.id == id) + .expect("group existence checked above"); + group.parent_id = parent_id; + let updated = group.clone(); + save_file(runtime, state, &file)?; + Ok(updated) +} + +fn delete_group( + runtime: &RuntimeContext, + state: &Arc, + id: &str, +) -> Result<(), String> { + let mut file = load_file(runtime)?; + if !file.groups.iter().any(|group| group.id == id) { + return Err(format!("Group with ID {id} not found")); + } + let deleted = crate::models::collect_group_subtree(&file.groups, id); + file.groups.retain(|group| !deleted.contains(&group.id)); + 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( + runtime: &RuntimeContext, + state: &Arc, + connection_id: &str, + group_id: Option, + sort_order: Option, +) -> Result { + let mut file = load_file(runtime)?; + validate_parent(&file, group_id.as_deref())?; + let connection = file + .connections + .iter_mut() + .find(|connection| connection.id == connection_id) + .ok_or_else(|| format!("Connection with ID {connection_id} not found"))?; + connection.group_id = group_id; + if let Some(sort_order) = sort_order { + connection.sort_order = Some(sort_order); + } + let updated = connection.clone(); + save_file(runtime, state, &file)?; + Ok(redact_connection(updated)) +} + +fn reorder_groups( + runtime: &RuntimeContext, + state: &Arc, + orders: Vec<(String, i32)>, +) -> Result<(), String> { + let mut file = load_file(runtime)?; + for (id, order) in orders { + if let Some(group) = file.groups.iter_mut().find(|group| group.id == id) { + group.sort_order = order; + } + } + save_file(runtime, state, &file) +} + +fn reorder_connections( + runtime: &RuntimeContext, + state: &Arc, + orders: Vec<(String, i32)>, +) -> Result<(), String> { + let mut file = load_file(runtime)?; + for (id, order) in orders { + if let Some(connection) = file + .connections + .iter_mut() + .find(|connection| connection.id == id) + { + connection.sort_order = Some(order); + } + } + save_file(runtime, state, &file) +} + +async fn active_connections(state: &ApplicationState, session_id: Option) -> Vec { + let Some(session_id) = session_id else { + return crate::health_check::active_connections().await; + }; + state + .web_active_connections + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(&session_id) + .map(|connections| connections.iter().cloned().collect()) + .unwrap_or_default() +} + +pub async fn register_active_connection( + runtime: &RuntimeContext, + state: Option<&ApplicationState>, + session_id: Option, + connection_id: String, +) { + if let (Some(state), Some(session_id)) = (state, session_id) { + state + .web_active_connections + .lock() + .unwrap_or_else(|error| error.into_inner()) + .entry(session_id) + .or_default() + .insert(connection_id.clone()); + } + crate::health_check::register_connection(connection_id).await; + emit_active_connections(runtime, state, session_id).await; +} + +async fn emit_active_connections( + runtime: &RuntimeContext, + state: Option<&ApplicationState>, + session_id: Option, +) { + let active = if let (Some(state), Some(session_id)) = (state, session_id) { + active_connections(state, Some(session_id)).await + } else { + crate::health_check::active_connections().await + }; + let payload = serde_json::to_value(active).unwrap_or(Value::Null); + let _ = if let Some(session_id) = session_id { + runtime + .events + .emit_to(session_id, "connections:active-changed", payload) + } else { + runtime.events.emit("connections:active-changed", payload) + }; +} + +pub async fn disconnect_connection( + runtime: &RuntimeContext, + state: Option<&ApplicationState>, + session_id: Option, + connection_id: &str, +) -> Result<(), String> { + super::query_sessions::release_connection(runtime, session_id, connection_id).await; + let still_owned = if let (Some(state), Some(session_id)) = (state, session_id) { + let mut sessions = state + .web_active_connections + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(connections) = sessions.get_mut(&session_id) { + connections.remove(connection_id); + if connections.is_empty() { + sessions.remove(&session_id); + } + } + sessions + .iter() + .any(|(_, connections)| connections.contains(connection_id)) + } else { + false + }; + + if !still_owned { + crate::health_check::unregister_connection(connection_id).await; + if let Ok(saved) = find_connection(&load_file(runtime)?, connection_id) { + if let Some(driver) = crate::drivers::registry::get_driver(&saved.params.driver).await { + driver + .invalidate_connection_metadata(Some(connection_id)) + .await; + } + } + let saved = find_connection(&load_file(runtime)?, connection_id)?; + crate::pool_manager::close_pools_for_connection_id(&saved.params.driver, connection_id) + .await; + } + emit_active_connections(runtime, state, session_id).await; + Ok(()) +} + +/// 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, + 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(); + 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) && !iam_auth { + request.params.password = saved.params.password; + } + 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| { + emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + "resolve", + error, + ) + })?; + let tunnel_step = if expanded.ssh_enabled.unwrap_or(false) { + Some("sshTunnel") + } else if expanded.k8s_enabled.unwrap_or(false) { + Some("k8sForward") + } else if expanded.ssm_enabled.unwrap_or(false) { + Some("ssmForward") + } else { + None + }; + if let Some(step) = tunnel_step { + emit_test_progress( + runtime, + session_id, + progress_id.as_deref(), + step, + "start", + if step == "sshTunnel" { + Some(format!( + "{}@{}:{}", + expanded.ssh_user.as_deref().unwrap_or("?"), + expanded.ssh_host.as_deref().unwrap_or("?"), + expanded.ssh_port.unwrap_or(22), + )) + } else if step == "ssmForward" { + expanded.ssm_target.clone() + } else { + expanded.k8s_resource_name.clone() + }, + ); + } + + let runtime_for_tunnel = runtime.clone(); + let mut expanded_for_tunnel = expanded.clone(); + // Per-connection proxy overrides are keyed by id, so set it before resolving. + if let Some(connection_id) = request.connection_id.as_deref() { + expanded_for_tunnel.connection_id = Some(connection_id.to_string()); + } + let resolved = tokio::task::spawn_blocking(move || { + crate::application::tunnels::resolve_connection_params( + &runtime_for_tunnel, + &expanded_for_tunnel, + session_id, + ) + }) + .await + .map_err(|error| error.to_string())? + .map_err(|error| { + emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + tunnel_step.unwrap_or("resolve"), + error, + ) + })?; + if let Some(step) = tunnel_step { + emit_test_progress( + runtime, + session_id, + progress_id.as_deref(), + step, + "ok", + resolved.port.map(|port| format!("127.0.0.1:{port}")), + ); + } + + let driver = crate::drivers::registry::get_driver(&resolved.driver) + .await + .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", + Some(db_target), + ); + let capabilities = &driver.manifest().capabilities; + if capabilities.file_based + && crate::fs_path::requires_existing_database_file( + capabilities.in_memory, + resolved.database.primary(), + ) + { + let path = if resolved.driver == "sqlite" { + crate::sqlite_database::expand_sqlite_filename(resolved.database.primary()) + } else { + PathBuf::from(resolved.database.primary()) + }; + if !path.exists() { + return Err(emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + "dbConnect", + format!("Database file not found: {}", resolved.database), + )); + } + } + driver.test_connection(&resolved).await.map_err(|error| { + emit_test_failure( + runtime, + session_id, + progress_id.as_deref(), + "dbConnect", + error, + ) + })?; + driver + .invalidate_connection_metadata(resolved.connection_id.as_deref()) + .await; + emit_test_progress( + runtime, + session_id, + progress_id.as_deref(), + "dbConnect", + "ok", + None, + ); + Ok("Connection successful!".to_string()) +} + +fn emit_test_progress( + runtime: &RuntimeContext, + session_id: Option, + progress_id: Option<&str>, + step: &str, + status: &str, + detail: Option, +) { + let Some(id) = progress_id else { + return; + }; + let payload = serde_json::json!({ + "id": id, + "step": step, + "status": status, + "detail": detail, + }); + let _ = match session_id { + Some(session_id) => runtime + .events + .emit_to(session_id, "connection-test-progress", payload), + None => runtime.events.emit("connection-test-progress", payload), + }; +} + +fn emit_test_failure( + runtime: &RuntimeContext, + session_id: Option, + progress_id: Option<&str>, + step: &str, + error: String, +) -> String { + emit_test_progress( + runtime, + session_id, + progress_id, + step, + "error", + Some(error.clone()), + ); + error +} + +fn upload_directory(data_dir: &Path, session_id: Uuid) -> PathBuf { + data_dir + .join("web-uploads") + .join("connection-icons") + .join(session_id.to_string()) +} + +fn consume_icon_upload( + runtime: &RuntimeContext, + session_id: Uuid, + token: &str, +) -> Result { + let token = Uuid::parse_str(token).map_err(|_| "Invalid icon upload token".to_string())?; + let path = upload_directory(runtime.paths.data_dir(), session_id).join(token.to_string()); + let metadata = fs::metadata(&path).map_err(|_| "Icon upload token not found".to_string())?; + let modified = metadata.modified().map_err(|error| error.to_string())?; + let age = SystemTime::now() + .duration_since(modified) + .unwrap_or(Duration::ZERO); + if age > ICON_UPLOAD_TTL { + let _ = fs::remove_file(&path); + return Err("Icon upload token expired".to_string()); + } + if !metadata.is_file() { + return Err("Icon upload token is invalid".to_string()); + } + Ok(path) +} + +fn delete_icon(data_dir: &Path, relative_path: &str) -> Result<(), String> { + let path = match resolve_icon_asset(data_dir, relative_path) { + Ok(path) => path, + Err(error) if error == "Connection icon not found" => return Ok(()), + Err(error) => return Err(error), + }; + fs::remove_file(path).map_err(|error| error.to_string()) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "connections_tests.rs"] +mod tests; + +pub async fn set_selected_databases( + runtime: &RuntimeContext, + connection_id: &str, + mut databases: Vec, +) -> Result<(), String> { + if databases.is_empty() { + return Err("Database selection cannot be empty".to_string()); + } + if databases.iter().any(|db| db.trim().is_empty()) { + return Err("Database names cannot be empty".to_string()); + } + let mut file = load_file(runtime)?; + let connection = file + .connections + .iter_mut() + .find(|connection| connection.id == connection_id) + .ok_or("Connection not found")?; + let is_schema_based = crate::drivers::registry::get_driver(&connection.params.driver) + .await + .map(|driver| driver.manifest().capabilities.schemas) + .unwrap_or(false); + connection.params.database = if databases.len() == 1 && !is_schema_based { + crate::models::DatabaseSelection::Single(databases.remove(0)) + } else { + crate::models::DatabaseSelection::Multiple(databases) + }; + crate::persistence::save_connections_file(&runtime.paths.connections_file(), &file) +} diff --git a/src-tauri/src/application/connections_tests.rs b/src-tauri/src/application/connections_tests.rs new file mode 100644 index 000000000..445c83591 --- /dev/null +++ b/src-tauri/src/application/connections_tests.rs @@ -0,0 +1,1069 @@ +use super::*; +use crate::models::DatabaseSelection; +use crate::runtime::events::{NoopRuntimeEvents, RuntimeEvents}; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use std::collections::HashMap; +use std::sync::Mutex; + +#[derive(Default)] +struct MemorySecrets { + values: Mutex>, +} + +#[derive(Default)] +struct RecordingEvents { + values: Mutex>, +} + +impl RuntimeEvents for RecordingEvents { + fn emit(&self, event: &str, payload: Value) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push((event.to_string(), payload)); + Ok(()) + } +} + +impl RuntimeSecrets for MemorySecrets { + fn get(&self, account: &str) -> Result, String> { + Ok(self + .values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(account) + .cloned()) + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .insert(account.to_string(), secret.to_string()); + Ok(()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(account); + Ok(()) + } +} + +fn fixture() -> (tempfile::TempDir, RuntimeContext, Arc) { + let temp = tempfile::tempdir().unwrap(); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(MemorySecrets::default()), + ); + (temp, runtime, Arc::new(ApplicationState::default())) +} + +fn connection_params(password: &str) -> ConnectionParams { + ConnectionParams { + driver: "postgres".to_string(), + host: Some("127.0.0.1".to_string()), + port: Some(5432), + username: Some("browser-user".to_string()), + password: Some(password.to_string()), + database: DatabaseSelection::Single("browser-db".to_string()), + save_in_keychain: Some(true), + ..ConnectionParams::default() + } +} + +#[tokio::test] +async fn browser_connection_responses_keep_stored_secrets_write_only() { + let (_temp, runtime, state) = fixture(); + let saved = execute( + &runtime, + &state, + ConnectionCommand::SaveConnection { + name: "Browser connection".to_string(), + params: connection_params("stored-secret"), + plugin_secret_changes: None, + detect_json_in_text_columns: None, + environment: Some("development".to_string()), + }, + ) + .await + .unwrap(); + + assert!(saved["params"]["password"].is_null()); + let id = saved["id"].as_str().unwrap(); + assert_eq!( + runtime.secrets.get(&format!("{id}:db")).unwrap().as_deref(), + Some("stored-secret") + ); + let persisted = + crate::persistence::load_connections_file(&runtime.paths.connections_file()).unwrap(); + assert!(persisted.connections[0].params.password.is_none()); + + let listed = execute( + &runtime, + &state, + ConnectionCommand::GetConnectionsWithGroups, + ) + .await + .unwrap(); + assert!(listed["connections"][0]["params"]["password"].is_null()); +} + +#[tokio::test] +async fn connection_groups_tags_ordering_and_duplication_share_one_service() { + let (_temp, runtime, state) = fixture(); + let mut params = connection_params("plaintext-secret"); + params.save_in_keychain = Some(false); + let saved = execute( + &runtime, + &state, + ConnectionCommand::SaveConnection { + name: "Original".to_string(), + params, + plugin_secret_changes: None, + detect_json_in_text_columns: Some(true), + environment: Some("staging".to_string()), + }, + ) + .await + .unwrap(); + let connection_id = saved["id"].as_str().unwrap().to_string(); + + let group = execute( + &runtime, + &state, + ConnectionCommand::CreateGroupPath { + path: "Work/Reporting".to_string(), + parent_id: None, + }, + ) + .await + .unwrap(); + let group_id = group["id"].as_str().unwrap().to_string(); + execute( + &runtime, + &state, + ConnectionCommand::MoveConnectionToGroup { + connection_id: connection_id.clone(), + group_id: Some(group_id.clone()), + sort_order: Some(4), + }, + ) + .await + .unwrap(); + + let tag = execute( + &runtime, + &state, + ConnectionCommand::CreateConnectionTag { + name: "Reporting".to_string(), + color: "#336699".to_string(), + }, + ) + .await + .unwrap(); + execute( + &runtime, + &state, + ConnectionCommand::SetConnectionTags { + connection_id: connection_id.clone(), + tag_ids: vec![tag["id"].as_str().unwrap().to_string()], + }, + ) + .await + .unwrap(); + + let duplicate = execute( + &runtime, + &state, + ConnectionCommand::DuplicateConnection { + id: connection_id.clone(), + }, + ) + .await + .unwrap(); + assert_eq!(duplicate["name"], "Original (Copy)"); + assert_eq!(duplicate["group_id"], group_id); + assert!(duplicate["params"]["password"].is_null()); + + let file = + crate::persistence::load_connections_file(&runtime.paths.connections_file()).unwrap(); + assert_eq!(file.groups.len(), 2); + assert_eq!(file.tags.len(), 1); + assert_eq!(file.connections.len(), 2); + assert_eq!(file.connections[0].sort_order, Some(4)); + assert_eq!(file.connections[0].tag_ids.as_ref().unwrap().len(), 1); + + execute( + &runtime, + &state, + ConnectionCommand::DeleteConnection { id: connection_id }, + ) + .await + .unwrap(); + let file = + crate::persistence::load_connections_file(&runtime.paths.connections_file()).unwrap(); + assert_eq!(file.connections.len(), 1); +} + +#[tokio::test] +async fn connection_test_failures_emit_correlated_progress() { + let temp = tempfile::tempdir().unwrap(); + let events = Arc::new(RecordingEvents::default()); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().to_path_buf(), + )), + events.clone(), + Arc::new(MemorySecrets::default()), + ); + let state = Arc::new(ApplicationState::default()); + let mut params = connection_params(""); + params.ssh_enabled = Some(true); + + let error = execute( + &runtime, + &state, + ConnectionCommand::TestConnection { + request: TestConnectionRequest { + params, + connection_id: None, + plugin_secret_changes: Default::default(), + progress_id: Some("progress-1".to_string()), + }, + }, + ) + .await + .unwrap_err(); + + assert!(error.contains("Missing SSH Host")); + let emitted = events + .values + .lock() + .unwrap_or_else(|error| error.into_inner()); + assert_eq!(emitted.len(), 2); + assert_eq!(emitted[0].0, "connection-test-progress"); + assert_eq!(emitted[0].1["id"], "progress-1"); + assert_eq!(emitted[0].1["step"], "sshTunnel"); + assert_eq!(emitted[0].1["status"], "start"); + assert_eq!(emitted[1].1["step"], "sshTunnel"); + assert_eq!(emitted[1].1["status"], "error"); +} + +#[tokio::test] +async fn browser_active_connections_are_isolated_by_session() { + let (_temp, runtime, state) = fixture(); + let session_a = Uuid::new_v4(); + let session_b = Uuid::new_v4(); + + execute_for_session( + &runtime, + &state, + Some(session_a), + ConnectionCommand::RegisterActiveConnection { + connection_id: "connection-a".to_string(), + }, + ) + .await + .unwrap(); + execute_for_session( + &runtime, + &state, + Some(session_b), + ConnectionCommand::RegisterActiveConnection { + connection_id: "connection-b".to_string(), + }, + ) + .await + .unwrap(); + + let active_a = execute_for_session( + &runtime, + &state, + Some(session_a), + ConnectionCommand::GetActiveConnections, + ) + .await + .unwrap(); + let active_b = execute_for_session( + &runtime, + &state, + Some(session_b), + ConnectionCommand::GetActiveConnections, + ) + .await + .unwrap(); + assert_eq!(active_a, serde_json::json!(["connection-a"])); + assert_eq!(active_b, serde_json::json!(["connection-b"])); + + register_active_connection( + &runtime, + Some(&state), + Some(session_a), + "shared-connection".to_string(), + ) + .await; + register_active_connection( + &runtime, + Some(&state), + Some(session_b), + "shared-connection".to_string(), + ) + .await; + disconnect_connection(&runtime, Some(&state), Some(session_a), "shared-connection") + .await + .unwrap(); + let session_b_connections = active_connections(&state, Some(session_b)).await; + assert!(session_b_connections.contains(&"shared-connection".to_string())); + assert!(crate::health_check::active_connections() + .await + .contains(&"shared-connection".to_string())); + + crate::health_check::unregister_connection("connection-a").await; + crate::health_check::unregister_connection("connection-b").await; + crate::health_check::unregister_connection("shared-connection").await; +} + +#[tokio::test] +async fn icon_upload_tokens_are_bound_to_the_authenticated_session() { + let (_temp, runtime, state) = fixture(); + let owner = Uuid::new_v4(); + let other = Uuid::new_v4(); + let token = + store_icon_upload(runtime.paths.data_dir(), owner, &[0x89, b'P', b'N', b'G']).unwrap(); + + let rejected = execute( + &runtime, + &state, + ConnectionCommand::SaveConnectionIcon { + connection_id: "connection-1".to_string(), + upload_token: token.clone(), + session_id: other, + }, + ) + .await; + assert_eq!(rejected.unwrap_err(), "Icon upload token not found"); + + let stored = execute( + &runtime, + &state, + ConnectionCommand::SaveConnectionIcon { + connection_id: "connection-1".to_string(), + upload_token: token, + session_id: owner, + }, + ) + .await + .unwrap(); + assert!(stored.as_str().unwrap().starts_with("connection-icons/")); +} + +struct FailingSecrets { + memory: MemorySecrets, + fail_suffix: Option<&'static str>, + block_config: Mutex>, +} + +impl RuntimeSecrets for FailingSecrets { + fn get(&self, account: &str) -> Result, String> { + self.memory.get(account) + } + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + if self + .fail_suffix + .is_some_and(|suffix| account.ends_with(suffix)) + { + return Err("Keychain unavailable".into()); + } + self.memory.set(account, secret)?; + if let Some(path) = self.block_config.lock().unwrap().take() { + if path.is_file() { + std::fs::remove_file(&path).unwrap(); + } + std::fs::create_dir(&path).unwrap(); + } + Ok(()) + } + fn delete(&self, account: &str) -> Result<(), String> { + self.memory.delete(account) + } +} + +#[test] +fn keychain_failure_persists_passwords_and_reports_fallback_without_exposing_them() { + let (temp, _, state) = fixture(); + let secrets = Arc::new(FailingSecrets { + memory: MemorySecrets::default(), + fail_suffix: Some(":ssh"), + block_config: Mutex::new(None), + }); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().into(), + temp.path().into(), + )), + Arc::new(NoopRuntimeEvents), + 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)); + assert_eq!(saved.params.password, None); + let persisted = find_connection(&load_file(&runtime).unwrap(), &saved.id).unwrap(); + assert_eq!(persisted.params.password.as_deref(), Some("db-secret")); + assert_eq!(persisted.params.ssh_password.as_deref(), Some("ssh-secret")); + assert!(secrets.memory.values.lock().unwrap().is_empty()); +} + +#[test] +fn failed_config_save_rolls_back_new_credentials() { + let (temp, runtime, state) = fixture(); + let secrets = Arc::new(FailingSecrets { + memory: MemorySecrets::default(), + fail_suffix: None, + block_config: Mutex::new(Some(runtime.paths.connections_file())), + }); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().into(), + temp.path().into(), + )), + Arc::new(NoopRuntimeEvents), + secrets.clone(), + ); + assert!(save_connection( + &runtime, + &state, + "Failure".into(), + connection_params("secret"), + Default::default(), + None, + None + ) + .is_err()); + assert!(secrets.memory.values.lock().unwrap().is_empty()); +} + +#[test] +fn duplicate_clears_a_missing_uri_marker() { + let (_temp, runtime, state) = fixture(); + let mut params = connection_params("secret"); + params.connection_uri = Some("postgres://user:secret@localhost/db".into()); + let original = + save_connection(&runtime, &state, "Original".into(), params, Default::default(), None, None).unwrap(); + runtime + .secrets + .delete(&secret_account(&original.id, CONNECTION_URI_SUFFIX)) + .unwrap(); + let duplicate = duplicate_connection(&runtime, &state, &original.id).unwrap(); + assert_eq!(duplicate.params.connection_uri_in_keychain, None); +} + +#[test] +fn update_omitted_password_retains_the_secret_when_disabling_keychain() { + let (_temp, runtime, state) = fixture(); + let saved = save_connection( + &runtime, + &state, + "Original".into(), + connection_params("secret"), + Default::default(), + None, + None, + ) + .unwrap(); + let mut params = saved.params; + params.save_in_keychain = Some(false); + update_connection( + &runtime, + &state, + saved.id.clone(), + "Edited".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + let persisted = find_connection(&load_file(&runtime).unwrap(), &saved.id).unwrap(); + assert_eq!(persisted.params.password.as_deref(), Some("secret")); + assert_eq!( + runtime + .secrets + .get(&secret_account(&saved.id, DB_SECRET_SUFFIX)) + .unwrap(), + None + ); +} + +#[tokio::test] +async fn switching_to_multiple_databases_backfills_saved_queries_and_history() { + use super::super::productivity::{self, ProductivityCommand}; + let (_temp, runtime, state) = fixture(); + let saved = save_connection( + &runtime, + &state, + "Original".into(), + connection_params("secret"), + Default::default(), + None, + None, + ) + .unwrap(); + let config = runtime.paths.config_dir(); + productivity::execute( + config, + ProductivityCommand::SaveQuery { + connection_id: saved.id.clone(), + name: "Query".into(), + sql: "SELECT 1".into(), + database: None, + }, + ) + .await + .unwrap(); + productivity::execute( + config, + ProductivityCommand::AddQueryHistoryEntry { + connection_id: saved.id.clone(), + sql: "SELECT 1".into(), + executed_at: "2026-10-15".into(), + execution_time_ms: None, + status: "success".into(), + rows_affected: None, + error: None, + database: None, + }, + ) + .await + .unwrap(); + let mut params = saved.params; + params.database = DatabaseSelection::Multiple(vec!["browser-db".into(), "other".into()]); + update_connection( + &runtime, + &state, + saved.id.clone(), + "Edited".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + let queries = productivity::execute( + config, + ProductivityCommand::GetSavedQueries { + connection_id: saved.id.clone(), + }, + ) + .await + .unwrap(); + let history = productivity::execute( + config, + ProductivityCommand::GetQueryHistory { + connection_id: saved.id, + }, + ) + .await + .unwrap(); + assert_eq!(queries[0]["database"], "browser-db"); + assert_eq!(history["entries"][0]["database"], "browser-db"); +} + +#[test] +fn switching_driver_does_not_keep_the_previous_drivers_uri() { + let (_temp, runtime, state) = fixture(); + let mut params = connection_params("secret"); + params.connection_uri = Some("postgres://user:secret@localhost/db".into()); + let saved = save_connection(&runtime, &state, "Original".into(), params, Default::default(), None, None).unwrap(); + let mut params = saved.params; + params.driver = "mysql".into(); + let updated = update_connection( + &runtime, + &state, + saved.id.clone(), + "Edited".into(), + params, + Default::default(), + None, + None, + ) + .unwrap(); + assert_eq!(updated.params.connection_uri_in_keychain, None); + assert_eq!( + runtime + .secrets + .get(&secret_account(&saved.id, CONNECTION_URI_SUFFIX)) + .unwrap(), + None + ); +} + +#[test] +fn unreadable_existing_secret_is_not_overwritten_or_deleted() { + struct UnreadableSecrets(Mutex>); + impl RuntimeSecrets for UnreadableSecrets { + fn get(&self, _account: &str) -> Result, String> { + Err("Read denied".into()) + } + fn set(&self, _account: &str, _secret: &str) -> Result<(), String> { + self.0.lock().unwrap().push("set".into()); + Ok(()) + } + fn delete(&self, _account: &str) -> Result<(), String> { + self.0.lock().unwrap().push("delete".into()); + Ok(()) + } + } + let (temp, _, _) = fixture(); + let secrets = Arc::new(UnreadableSecrets(Mutex::new(Vec::new()))); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().into(), + temp.path().into(), + )), + Arc::new(NoopRuntimeEvents), + secrets.clone(), + ); + let mut writes = SecretWrites::default(); + assert!(writes + .set(&runtime, "existing:db".into(), "replacement") + .is_err()); + writes.rollback(&runtime); + assert!(secrets.0.lock().unwrap().is_empty()); +} + +#[test] +fn plugin_secrets_live_in_the_keychain_for_the_whole_connection_lifecycle() { + let (_temp, runtime, state) = fixture(); + let mut params = connection_params("db-secret"); + params.driver = "test-plugin".to_string(); + params + .extra + .insert("token".to_string(), "inline-token".to_string()); + let changes = HashMap::from([("token".to_string(), Some("stored-token".to_string()))]); + let saved = + save_connection(&runtime, &state, "Plugin".into(), params, changes, None, None).unwrap(); + let account = |id: &str| format!("{id}:plugin:test-plugin:token"); + + assert_eq!(saved.plugin_secret_keys, vec!["token"]); + let persisted = find_connection(&load_file(&runtime).unwrap(), &saved.id).unwrap(); + assert!(!persisted.params.extra.contains_key("token")); + assert_eq!( + runtime.secrets.get(&account(&saved.id)).unwrap().as_deref(), + Some("stored-token") + ); + assert_eq!( + load_plugin_secrets(&runtime, &persisted) + .get("token") + .map(String::as_str), + Some("stored-token") + ); + + let duplicate = duplicate_connection(&runtime, &state, &saved.id).unwrap(); + assert_eq!(duplicate.plugin_secret_keys, vec!["token"]); + assert_eq!( + runtime + .secrets + .get(&account(&duplicate.id)) + .unwrap() + .as_deref(), + Some("stored-token") + ); + + let cleared = HashMap::from([("token".to_string(), None)]); + let updated = update_connection( + &runtime, + &state, + saved.id.clone(), + "Plugin".into(), + persisted.params, + cleared, + None, + None, + ) + .unwrap(); + assert!(updated.plugin_secret_keys.is_empty()); + assert_eq!(runtime.secrets.get(&account(&saved.id)).unwrap(), None); + + delete_connection(&runtime, &state, &duplicate.id).unwrap(); + assert_eq!(runtime.secrets.get(&account(&duplicate.id)).unwrap(), None); +} + +#[test] +fn sql_builder_secrets_bind_stored_plugin_secrets_and_tolerate_missing_ones() { + let (_temp, runtime, _state) = fixture(); + runtime + .secrets + .set("conn-1:plugin:test-plugin:credential", "stored-credential") + .unwrap(); + let mut connection = SavedConnection { + id: "conn-1".to_string(), + name: "Plugin".to_string(), + params: ConnectionParams { + driver: "test-plugin".to_string(), + host: Some("db.internal".to_string()), + ssh_enabled: Some(true), + ..ConnectionParams::default() + }, + plugin_secret_keys: vec!["credential".to_string(), "missing".to_string()], + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + }; + + bind_sql_builder_secrets(&runtime, &mut connection); + let built = crate::commands::sql_builder_params(&connection, Some("analytics".into())); + + assert_eq!( + built.extra.get("credential").map(String::as_str), + Some("stored-credential") + ); + assert!(!built.extra.contains_key("missing")); + assert_eq!(built.host.as_deref(), Some("db.internal")); + assert_eq!( + built.database, + 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/database_objects.rs b/src-tauri/src/application/database_objects.rs new file mode 100644 index 000000000..55ea0eb9d --- /dev/null +++ b/src-tauri/src/application/database_objects.rs @@ -0,0 +1,1374 @@ +use crate::drivers::driver_trait::DatabaseDriver; +use crate::models::{ + ColumnDefinition, ConnectionParams, DbPrivilegeCatalog, DbUserGrantSet, DbUserInfo, + RoutineCallArg, RoutineParameter, +}; +use crate::runtime::RuntimeContext; +use serde::Serialize; +use serde_json::Value; +use std::sync::Arc; +use uuid::Uuid; + +#[derive(Debug)] +pub enum DatabaseObjectCommand { + GetTableQueryTemplate { + connection_id: String, + request: crate::models::TableQueryTemplateRequest, + database: Option, + }, + GetColumnStats { + connection_id: String, + request: crate::models::ColumnStatsRequest, + database: Option, + }, + GetDropTableSql { + connection_id: String, + table: String, + schema: Option, + database: Option, + }, + GetDataTypes { + driver: String, + }, + MapInferredColumnTypes { + driver: String, + kinds: Vec, + connection_id: Option, + }, + ExecuteClipboardImport { + req: crate::clipboard_import::ClipboardImportRequest, + }, + GetViewDefinition { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + CreateView { + connection_id: String, + view_name: String, + definition: String, + schema: Option, + database: Option, + }, + AlterView { + connection_id: String, + view_name: String, + definition: String, + schema: Option, + database: Option, + }, + DropView { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + RefreshMaterializedView { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + GetRoutineParameters { + connection_id: String, + routine_name: String, + schema: Option, + database: Option, + identity_args: Option, + }, + GetRoutineDefinition { + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, + }, + BuildRoutineCallSql { + connection_id: String, + routine_name: String, + routine_type: String, + args: Vec, + schema: Option, + }, + GetRoutineCreateTemplate { + connection_id: String, + routine_type: String, + schema: Option, + database: Option, + }, + GetRoutineEditScript { + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, + }, + DropRoutine { + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, + }, + GetTriggerDefinition { + connection_id: String, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, + }, + CreateTrigger { + connection_id: String, + trigger_sql: String, + schema: Option, + database: Option, + }, + DropTrigger { + connection_id: String, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, + }, + GetCreateTableSql { + connection_id: String, + table_name: String, + columns: Vec, + schema: Option, + database: Option, + }, + GetAddColumnSql { + connection_id: String, + table: String, + column: ColumnDefinition, + schema: Option, + database: Option, + }, + GetAlterColumnSql { + connection_id: String, + table: String, + old_column: ColumnDefinition, + new_column: ColumnDefinition, + schema: Option, + database: Option, + }, + GetCreateIndexSql { + connection_id: String, + table: String, + index_name: String, + columns: Vec, + is_unique: bool, + schema: Option, + database: Option, + }, + GetCreateForeignKeySql { + 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, + }, + DropIndex { + connection_id: String, + table: String, + index_name: String, + schema: Option, + database: Option, + }, + DropForeignKey { + connection_id: String, + table: String, + fk_name: String, + schema: Option, + database: Option, + }, + GetDbPrivilegeCatalog { + connection_id: String, + }, + GetDbUsers { + connection_id: String, + }, + GetDbUserGrants { + connection_id: String, + user: String, + host: String, + }, + GetDbUserPrivileges { + connection_id: String, + user: String, + host: String, + }, + CreateDbUser { + connection_id: String, + user: String, + host: String, + password: String, + }, + DropDbUser { + connection_id: String, + user: String, + host: String, + }, + SetDbUserPassword { + connection_id: String, + user: String, + host: String, + password: String, + }, + ApplyDbUserPrivileges { + connection_id: String, + user: String, + host: String, + database: Option, + table: Option, + privileges: Vec, + grant: bool, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + session_id: Option, + command: DatabaseObjectCommand, +) -> Result { + match command { + DatabaseObjectCommand::GetTableQueryTemplate { + connection_id, + request, + database, + } => json( + get_table_query_template(runtime, session_id, &connection_id, request, database) + .await?, + ), + DatabaseObjectCommand::GetColumnStats { + connection_id, + request, + database, + } => json(get_column_stats(runtime, session_id, &connection_id, request, database).await?), + DatabaseObjectCommand::GetDropTableSql { + connection_id, + table, + schema, + database, + } => json(get_drop_table_sql(runtime, &connection_id, table, schema, database).await?), + DatabaseObjectCommand::GetDataTypes { driver } => { + json(crate::commands::get_data_types(driver).await?) + } + DatabaseObjectCommand::MapInferredColumnTypes { + driver, + kinds, + connection_id, + } => json( + map_inferred_column_types(runtime, session_id, driver, kinds, connection_id).await?, + ), + DatabaseObjectCommand::ExecuteClipboardImport { req } => { + json(crate::clipboard_import::import_with_runtime(runtime, session_id, req).await?) + } + DatabaseObjectCommand::GetViewDefinition { + connection_id, + view_name, + schema, + database, + } => json( + get_view_definition( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?, + ), + DatabaseObjectCommand::CreateView { + connection_id, + view_name, + definition, + schema, + database, + } => { + create_view( + runtime, + session_id, + &connection_id, + view_name, + definition, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::AlterView { + connection_id, + view_name, + definition, + schema, + database, + } => { + alter_view( + runtime, + session_id, + &connection_id, + view_name, + definition, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::DropView { + connection_id, + view_name, + schema, + database, + } => { + drop_view( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::RefreshMaterializedView { + connection_id, + view_name, + schema, + database, + } => { + refresh_materialized_view( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::GetRoutineParameters { + connection_id, + routine_name, + schema, + database, + identity_args, + } => json( + get_routine_parameters( + runtime, + session_id, + &connection_id, + routine_name, + schema, + database, + identity_args, + ) + .await?, + ), + DatabaseObjectCommand::GetRoutineDefinition { + connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + } => json( + get_routine_definition( + runtime, + session_id, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await?, + ), + DatabaseObjectCommand::BuildRoutineCallSql { + connection_id, + routine_name, + routine_type, + args, + schema, + } => json( + build_routine_call_sql( + runtime, + session_id, + &connection_id, + routine_name, + routine_type, + args, + schema, + ) + .await?, + ), + DatabaseObjectCommand::GetRoutineCreateTemplate { + connection_id, + routine_type, + schema, + database, + } => json( + get_routine_create_template(runtime, &connection_id, routine_type, schema, database) + .await?, + ), + DatabaseObjectCommand::GetRoutineEditScript { + connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + } => json( + get_routine_edit_script( + runtime, + session_id, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await?, + ), + DatabaseObjectCommand::DropRoutine { + connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + } => { + drop_routine( + runtime, + session_id, + &connection_id, + routine_name, + routine_type, + schema, + database, + identity_args, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::GetTriggerDefinition { + connection_id, + trigger_name, + table_name, + schema, + database, + } => json( + get_trigger_definition( + runtime, + session_id, + &connection_id, + trigger_name, + table_name, + schema, + database, + ) + .await?, + ), + DatabaseObjectCommand::CreateTrigger { + connection_id, + trigger_sql, + schema, + database, + } => { + create_trigger( + runtime, + session_id, + &connection_id, + trigger_sql, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::DropTrigger { + connection_id, + trigger_name, + table_name, + schema, + database, + } => { + drop_trigger( + runtime, + session_id, + &connection_id, + trigger_name, + table_name, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::GetCreateTableSql { + connection_id, + table_name, + columns, + schema, + database, + } => json( + get_create_table_sql(runtime, &connection_id, table_name, columns, schema, database) + .await?, + ), + DatabaseObjectCommand::GetAddColumnSql { + connection_id, + table, + column, + schema, + database, + } => json( + get_add_column_sql(runtime, &connection_id, table, column, schema, database).await?, + ), + DatabaseObjectCommand::GetAlterColumnSql { + connection_id, + table, + old_column, + new_column, + schema, + database, + } => json( + get_alter_column_sql( + runtime, + &connection_id, + table, + old_column, + new_column, + schema, + database, + ) + .await?, + ), + DatabaseObjectCommand::GetCreateIndexSql { + connection_id, + table, + index_name, + columns, + is_unique, + schema, + database, + } => json( + get_create_index_sql( + runtime, + &connection_id, + table, + index_name, + columns, + is_unique, + schema, + database, + ) + .await?, + ), + DatabaseObjectCommand::GetCreateForeignKeySql { + connection_id, + table, + fk_name, + column, + ref_table, + ref_column, + on_delete, + on_update, + schema, + database, + } => json( + get_create_foreign_key_sql( + runtime, + &connection_id, + table, + fk_name, + column, + ref_table, + ref_column, + on_delete, + on_update, + schema, + database, + ) + .await?, + ), + DatabaseObjectCommand::DropIndex { + connection_id, + table, + index_name, + schema, + database, + } => { + drop_index( + runtime, + session_id, + &connection_id, + table, + index_name, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::DropForeignKey { + connection_id, + table, + fk_name, + schema, + database, + } => { + drop_foreign_key( + runtime, + session_id, + &connection_id, + table, + fk_name, + schema, + database, + ) + .await?; + Ok(Value::Null) + } + DatabaseObjectCommand::GetDbPrivilegeCatalog { connection_id } => { + json(get_db_privilege_catalog(runtime, &connection_id).await?) + } + DatabaseObjectCommand::GetDbUsers { connection_id } => { + json(get_db_users(runtime, session_id, &connection_id).await?) + } + DatabaseObjectCommand::GetDbUserGrants { + connection_id, + user, + host, + } => json(get_db_user_grants(runtime, session_id, &connection_id, user, host).await?), + DatabaseObjectCommand::GetDbUserPrivileges { + connection_id, + user, + host, + } => json(get_db_user_privileges(runtime, session_id, &connection_id, user, host).await?), + DatabaseObjectCommand::CreateDbUser { + connection_id, + user, + host, + password, + } => { + create_db_user(runtime, session_id, &connection_id, user, host, password).await?; + Ok(Value::Null) + } + DatabaseObjectCommand::DropDbUser { + connection_id, + user, + host, + } => { + drop_db_user(runtime, session_id, &connection_id, user, host).await?; + Ok(Value::Null) + } + DatabaseObjectCommand::SetDbUserPassword { + connection_id, + user, + host, + password, + } => { + set_db_user_password(runtime, session_id, &connection_id, user, host, password).await?; + Ok(Value::Null) + } + DatabaseObjectCommand::ApplyDbUserPrivileges { + connection_id, + user, + host, + database, + table, + privileges, + grant, + } => { + apply_db_user_privileges( + runtime, + session_id, + &connection_id, + user, + host, + database, + table, + privileges, + grant, + ) + .await?; + Ok(Value::Null) + } + } +} + +async fn saved_driver_and_params( + runtime: &RuntimeContext, + connection_id: &str, +) -> Result<(Arc, ConnectionParams), String> { + let saved = + crate::application::connections::load_connections(&runtime.paths.connections_file())? + .into_iter() + .find(|connection| connection.id == connection_id) + .ok_or_else(|| "Connection not found".to_string())?; + let driver = driver_for(&saved.params.driver).await?; + // Pure SQL builders still need no credentials for static drivers. Only + // discovery-enabled plugins resolve credentials and tunnels here. + if !driver.has_connection_metadata() { + return Ok((driver, saved.params)); + } + let runtime_for_resolution = runtime.clone(); + let connection_id_for_resolution = connection_id.to_string(); + let (_, params) = tokio::task::spawn_blocking(move || { + crate::application::connections::resolve_saved_connection_params( + &runtime_for_resolution, + None, + &connection_id_for_resolution, + ) + }) + .await + .map_err(|error| error.to_string())??; + let driver = crate::drivers::registry::get_connection_driver(¶ms).await?; + Ok((driver, saved.params)) +} + +/// Driver and params for the SQL-preview builders. Built-in drivers build SQL +/// without credentials, so they keep the registered instance and the saved +/// params. Plugin drivers get the saved params (secrets read leniently, the +/// browsed `database` applied) bound to a driver snapshot. No tunnel is +/// opened, so a preview works while the server is unreachable. +async fn sql_builder_driver_and_params( + runtime: &RuntimeContext, + connection_id: &str, + database: Option, +) -> Result<(Arc, ConnectionParams), String> { + let mut saved = + crate::application::connections::load_connections(&runtime.paths.connections_file())? + .into_iter() + .find(|connection| connection.id == connection_id) + .ok_or_else(|| "Connection not found".to_string())?; + let driver = driver_for(&saved.params.driver).await?; + if driver.manifest().is_builtin { + return Ok((driver, saved.params)); + } + crate::application::connections::bind_sql_builder_secrets(runtime, &mut saved); + let params = crate::commands::sql_builder_params(&saved, database); + let driver = driver.bind_connection_params(¶ms).unwrap_or(driver); + Ok((driver, params)) +} + +async fn connected_driver_and_params( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + database: Option, +) -> Result<(Arc, ConnectionParams), String> { + let (_driver_id, mut params) = + crate::application::connections::resolve_saved_connection_params( + runtime, + session_id, + connection_id, + )?; + if let Some(db) = database.filter(|db| !db.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(db); + } + Ok(( + crate::drivers::registry::get_connection_driver(¶ms).await?, + params, + )) +} + +async fn driver_for(driver_id: &str) -> Result, String> { + crate::drivers::registry::get_driver(driver_id) + .await + .ok_or_else(|| format!("Driver not found: {driver_id}")) +} + +pub async fn get_view_definition( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_view_definition(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn create_view( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + definition: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .create_view(¶ms, &view_name, &definition, schema.as_deref()) + .await +} + +pub async fn alter_view( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + definition: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .alter_view(¶ms, &view_name, &definition, schema.as_deref()) + .await +} + +pub async fn drop_view( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .drop_view(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn refresh_materialized_view( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .refresh_materialized_view(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn get_routine_parameters( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + routine_name: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_routine_parameters( + ¶ms, + &routine_name, + schema.as_deref(), + identity_args.as_deref(), + ) + .await +} + +pub async fn get_routine_definition( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_routine_definition( + ¶ms, + &routine_name, + &routine_type, + schema.as_deref(), + identity_args.as_deref(), + ) + .await +} + +pub async fn build_routine_call_sql( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + routine_name: String, + routine_type: String, + args: Vec, + schema: Option, +) -> Result { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver + .build_routine_call_sql( + ¶ms, + &routine_name, + &routine_type, + &args, + schema.as_deref(), + ) + .await +} + +pub async fn get_routine_create_template( + runtime: &RuntimeContext, + connection_id: &str, + routine_type: String, + schema: Option, + database: Option, +) -> Result { + let (driver, _) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .routine_create_template(&routine_type, schema.as_deref()) + .await +} + +pub async fn get_routine_edit_script( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_routine_edit_script( + ¶ms, + &routine_name, + &routine_type, + schema.as_deref(), + identity_args.as_deref(), + ) + .await +} + +pub async fn drop_routine( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .drop_routine( + ¶ms, + &routine_name, + &routine_type, + schema.as_deref(), + identity_args.as_deref(), + ) + .await +} + +pub async fn get_trigger_definition( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, +) -> Result { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_trigger_definition(¶ms, &trigger_name, &table_name, schema.as_deref()) + .await +} + +pub async fn create_trigger( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + trigger_sql: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .create_trigger(¶ms, &trigger_sql, schema.as_deref()) + .await +} + +pub async fn drop_trigger( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .drop_trigger(¶ms, &trigger_name, &table_name, schema.as_deref()) + .await +} + +pub async fn get_create_table_sql( + runtime: &RuntimeContext, + connection_id: &str, + table_name: String, + columns: Vec, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, _) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_create_table_sql(&table_name, columns, schema.as_deref()) + .await +} + +pub async fn get_add_column_sql( + runtime: &RuntimeContext, + connection_id: &str, + table: String, + column: ColumnDefinition, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, _) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_add_column_sql(&table, column, schema.as_deref()) + .await +} + +pub async fn get_alter_column_sql( + runtime: &RuntimeContext, + connection_id: &str, + table: String, + old_column: ColumnDefinition, + new_column: ColumnDefinition, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, _) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_alter_column_sql(&table, old_column, new_column, schema.as_deref()) + .await +} + +pub async fn get_create_index_sql( + runtime: &RuntimeContext, + connection_id: &str, + table: String, + index_name: String, + columns: Vec, + is_unique: bool, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, _) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_create_index_sql(&table, &index_name, columns, is_unique, schema.as_deref()) + .await +} + +#[allow(clippy::too_many_arguments)] +pub async fn get_create_foreign_key_sql( + runtime: &RuntimeContext, + connection_id: &str, + 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> { + let (driver, params) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_create_foreign_key_sql( + ¶ms, + &table, + &fk_name, + &column, + &ref_table, + &ref_column, + on_delete.as_deref(), + on_update.as_deref(), + schema.as_deref(), + ) + .await +} + +pub async fn drop_index( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + index_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .drop_index(¶ms, &table, &index_name, schema.as_deref()) + .await +} + +pub async fn drop_foreign_key( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + fk_name: String, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .drop_foreign_key(¶ms, &table, &fk_name, schema.as_deref()) + .await +} + +pub async fn get_db_privilege_catalog( + runtime: &RuntimeContext, + connection_id: &str, +) -> Result { + let (driver, _) = saved_driver_and_params(runtime, connection_id).await?; + driver.get_db_privilege_catalog().await +} + +pub async fn get_db_users( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver.get_db_users(¶ms).await +} + +pub async fn get_db_user_grants( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver.get_db_user_grants(¶ms, &user, &host).await +} + +pub async fn get_db_user_privileges( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver.get_db_user_privileges(¶ms, &user, &host).await +} + +pub async fn create_db_user( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, + password: String, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver + .create_db_user(¶ms, &user, &host, &password) + .await +} + +pub async fn drop_db_user( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver.drop_db_user(¶ms, &user, &host).await +} + +pub async fn set_db_user_password( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, + password: String, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver + .set_db_user_password(¶ms, &user, &host, &password) + .await +} + +#[allow(clippy::too_many_arguments)] +pub async fn apply_db_user_privileges( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + user: String, + host: String, + database: Option, + table: Option, + privileges: Vec, + grant: bool, +) -> Result<(), String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, None).await?; + driver + .apply_db_user_privileges( + ¶ms, + &user, + &host, + database.as_deref(), + table.as_deref(), + &privileges, + grant, + ) + .await +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +/// Column statistics through the optional plugin RPC. `None` means the driver +/// doesn't provide them; the frontend then falls back to its generic SQL. +pub async fn get_column_stats( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + request: crate::models::ColumnStatsRequest, + database: Option, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + driver.get_column_stats(¶ms, &request).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. +pub async fn get_drop_table_sql( + runtime: &RuntimeContext, + connection_id: &str, + table: String, + schema: Option, + database: Option, +) -> Result, String> { + let driver_id = crate::application::connections::saved_connection_driver(runtime, connection_id)?; + let driver = driver_for(&driver_id).await?; + if driver.manifest().is_builtin || !driver.manifest().capabilities.drop_table_sql { + return Ok(None); + } + let (driver, params) = sql_builder_driver_and_params(runtime, connection_id, database).await?; + driver + .get_drop_table_sql(¶ms, &table, schema.as_deref()) + .await +} + +pub async fn get_table_query_template( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + request: crate::models::TableQueryTemplateRequest, + database: Option, +) -> Result, String> { + let (driver, params) = + connected_driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_table_query_template(¶ms, &request).await +} + +pub async fn map_inferred_column_types( + runtime: &RuntimeContext, + session_id: Option, + driver: String, + kinds: Vec, + connection_id: Option, +) -> Result, String> { + let drv = if let Some(id) = connection_id { + let saved_driver = super::connections::saved_connection_driver(runtime, &id)?; + if saved_driver != driver { + return Err("Connection driver does not match the requested driver".into()); + } + let drv = driver_for(&driver).await?; + if drv.has_connection_metadata() { + connected_driver_and_params(runtime, session_id, &id, None) + .await? + .0 + } else { + drv + } + } else { + crate::drivers::registry::get_driver(&driver) + .await + .ok_or_else(|| format!("Unsupported driver: {driver}"))? + }; + Ok(kinds + .iter() + .map(|kind| drv.map_inferred_type(kind)) + .collect()) +} diff --git a/src-tauri/src/application/database_transfers.rs b/src-tauri/src/application/database_transfers.rs new file mode 100644 index 000000000..1dee42840 --- /dev/null +++ b/src-tauri/src/application/database_transfers.rs @@ -0,0 +1,1125 @@ +use super::connection_files::GeneratedFile; +use super::file_transfers::{ClaimedUpload, FileTransferStore}; +use crate::commands::{register_abort_handle, unregister_abort_handle, AbortHandleMap}; +use crate::drivers::driver_trait::DatabaseDriver; +use crate::drivers::{mysql, postgres, sqlite}; +use crate::dump_utils::DumpDialect; +use crate::models::{ConnectionParams, Pagination, TableColumn}; +use crate::pool_manager::{get_mysql_pool, get_postgres_pool, get_sqlite_pool}; +use crate::runtime::RuntimeContext; +use futures::TryStreamExt; +use serde::{Deserialize, Serialize}; +use sqlx::Row; +use std::collections::HashSet; +use std::fs::{self, File}; +use std::io::{BufRead, BufReader, BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use tokio_util::io::ReaderStream; +use uuid::Uuid; +use zip::ZipArchive; + +pub const DATABASE_IMPORT_PURPOSE: &str = "database-import"; +const SQL_MIME_TYPE: &str = "application/sql"; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DatabaseTransferCommand { + Dump { + connection_id: String, + options: DumpOptions, + schema: Option, + database: Option, + }, + CancelDump { + connection_id: String, + }, + Import { + connection_id: String, + upload_token: String, + schema: Option, + database: Option, + }, + CancelImport { + connection_id: String, + }, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DumpOptions { + pub structure: bool, + pub data: bool, + pub tables: Option>, +} + +#[derive(Default)] +pub struct DumpCancellationState { + pub handles: Arc>, +} + +#[derive(Clone, Debug, Serialize)] +pub struct DumpProgress { + pub connection_id: String, + pub tables_processed: usize, + pub total_tables: usize, + pub percentage: f32, + pub current_operation: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct ImportProgress { + pub connection_id: String, + pub statements_executed: usize, + pub total_statements: usize, + pub percentage: f32, + pub current_operation: String, +} + +pub enum DumpDestination { + ServerPath(PathBuf), + SessionDownload(Uuid), +} + +pub enum ImportSource { + ServerPath(PathBuf), + SessionUpload { owner: Uuid, token: String }, +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &DumpCancellationState, + session_id: Option, + command: DatabaseTransferCommand, +) -> Result { + match command { + DatabaseTransferCommand::Dump { + connection_id, + options, + schema, + database, + } => { + let owner = session_id.ok_or_else(|| "A browser session is required".to_string())?; + json( + dump_database( + runtime, + state, + session_id, + connection_id, + DumpDestination::SessionDownload(owner), + options, + schema, + database, + ) + .await? + .ok_or_else(|| "The browser dump did not create a download".to_string())?, + ) + } + DatabaseTransferCommand::CancelDump { connection_id } => { + cancel_job(state, session_id, JobKind::Dump, &connection_id)?; + Ok(serde_json::Value::Null) + } + DatabaseTransferCommand::Import { + connection_id, + upload_token, + schema, + database, + } => { + let owner = session_id.ok_or_else(|| "A browser session is required".to_string())?; + import_database( + runtime, + state, + session_id, + connection_id, + ImportSource::SessionUpload { + owner, + token: upload_token, + }, + schema, + database, + ) + .await?; + Ok(serde_json::Value::Null) + } + DatabaseTransferCommand::CancelImport { connection_id } => { + cancel_job(state, session_id, JobKind::Import, &connection_id)?; + Ok(serde_json::Value::Null) + } + } +} + +pub async fn dump_database( + runtime: &RuntimeContext, + state: &DumpCancellationState, + session_id: Option, + connection_id: String, + destination: DumpDestination, + options: DumpOptions, + schema: Option, + database: Option, +) -> Result, String> { + dump_database_job(runtime, state, session_id, connection_id, destination, options, schema, database, None, None).await +} + +pub struct DumpRequest { + pub slot_key: String, + pub connection_id: String, + pub file_path: String, + pub options: DumpOptions, + pub schema: Option, + pub database: Option, +} + +pub const DUMP_CANCELLED: &str = "Dump cancelled"; + +pub fn db_backup_slot_key(connection_id: &str) -> String { + format!("{connection_id}_db_backup") +} + +pub(crate) fn abort_slot(handles: &Mutex, slot_key: &str) -> bool { + let entries = handles.lock().unwrap().remove(slot_key).unwrap_or_default(); + for handle in &entries { handle.abort(); } + !entries.is_empty() +} + +pub(crate) async fn await_cancellable_dump( + handles: &Arc>, + slot_key: String, + task: tokio::task::JoinHandle>, + cancel_requested: Option<&AtomicBool>, +) -> Result { + let mut registration = JobRegistration::new(handles.clone(), slot_key, Arc::new(task.abort_handle())); + if cancel_requested.is_some_and(|flag| flag.load(Ordering::SeqCst)) { task.abort(); } + let result = task.await; + registration.complete(); + join_job(result, "Dump") +} + +pub async fn dump_database_with_handles( + runtime: &RuntimeContext, + handles: &Arc>, + request: DumpRequest, + cancel_requested: Option<&AtomicBool>, +) -> Result<(), String> { + let state = DumpCancellationState { handles: handles.clone() }; + dump_database_job(runtime, &state, None, request.connection_id, + DumpDestination::ServerPath(PathBuf::from(request.file_path)), request.options, + request.schema, request.database, Some(request.slot_key), cancel_requested).await.map(|_| ()) +} + +async fn dump_database_job( + runtime: &RuntimeContext, + state: &DumpCancellationState, + session_id: Option, + connection_id: String, + destination: DumpDestination, + options: DumpOptions, + schema: Option, + database: Option, + slot_key: Option, + cancel_requested: Option<&AtomicBool>, +) -> Result, String> { + if cancel_requested.is_some_and(|flag| flag.load(Ordering::SeqCst)) { return Err(DUMP_CANCELLED.to_string()); } + if !options.structure && !options.data { + return Err("Select structure, data, or both for the dump".to_string()); + } + let (driver, mut params) = + super::connections::resolve_saved_connection_params(runtime, session_id, &connection_id)?; + if let Some(database) = database.as_ref().filter(|database| !database.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(database.clone()); + } + let download_file_name = format!( + "{}_dump.sql", + safe_name(database_name(¶ms, &connection_id)), + ); + let (file_path, download_owner, temporary) = match destination { + DumpDestination::ServerPath(path) => (path, None, None), + DumpDestination::SessionDownload(owner) => { + let directory = runtime.paths.data_dir().join("database-dump-jobs"); + create_private_directory(&directory)?; + let path = directory.join(format!(".pending-{}.sql", Uuid::new_v4())); + let guard = TemporaryFile::new(path.clone()); + (path, Some(owner), Some(guard)) + } + }; + let runtime_for_task = runtime.clone(); + let connection_for_task = connection_id.clone(); + let task = tokio::spawn(async move { + write_dump( + &runtime_for_task, + session_id, + &connection_for_task, + &file_path, + ¶ms, + &driver, + schema.as_deref(), + &options, + ) + .await?; + Ok::<(PathBuf, Option, Option), String>(( + file_path, + download_owner, + temporary, + )) + }); + let (file_path, download_owner, temporary) = await_cancellable_dump( + &state.handles, + slot_key.unwrap_or_else(|| job_key(session_id, JobKind::Dump, &connection_id)), + task, + cancel_requested, + ).await?; + + let Some(owner) = download_owner else { + return Ok(None); + }; + let file = tokio::fs::File::open(&file_path) + .await + .map_err(|error| error.to_string())?; + let metadata = FileTransferStore::new(runtime.paths.data_dir()) + .store_download( + owner, + "database-dump", + &download_file_name, + Some(SQL_MIME_TYPE), + ReaderStream::new(file), + ) + .await?; + drop(temporary); + Ok(Some(GeneratedFile::Download { + file_name: metadata.file_name, + mime_type: metadata.mime_type, + token: metadata.token, + size: metadata.size, + })) +} + +pub async fn import_database( + runtime: &RuntimeContext, + state: &DumpCancellationState, + session_id: Option, + connection_id: String, + source: ImportSource, + schema: Option, + database: Option, +) -> Result<(), String> { + let (driver, mut params) = + super::connections::resolve_saved_connection_params(runtime, session_id, &connection_id)?; + if let Some(database) = database.filter(|database| !database.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(database); + } + let (file_path, is_zip, claimed_upload) = resolve_import_source(runtime, source)?; + let runtime_for_task = runtime.clone(); + let connection_for_task = connection_id.clone(); + let task = tokio::spawn(async move { + let _claimed_upload = claimed_upload; + execute_import( + &runtime_for_task, + session_id, + &file_path, + is_zip, + &connection_for_task, + ¶ms, + &driver, + schema.as_deref(), + ) + .await + }); + let mut registration = JobRegistration::new( + state.handles.clone(), + job_key(session_id, JobKind::Import, &connection_id), + Arc::new(task.abort_handle()), + ); + let result = task.await; + registration.complete(); + join_job(result, "Import") +} + +pub fn cancel_job( + state: &DumpCancellationState, + session_id: Option, + kind: JobKind, + connection_id: &str, +) -> Result<(), String> { + let key = job_key(session_id, kind, connection_id); + let entries = state + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&key) + .unwrap_or_default(); + if entries.is_empty() { + return Err(format!("No active {} process found", kind.label())); + } + for handle in entries { + handle.abort(); + } + Ok(()) +} + +pub fn cancel_session_jobs(state: &DumpCancellationState, session_id: Uuid) { + let prefix = format!("web:{session_id}:"); + let pending = { + let mut handles = state + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()); + let keys = handles + .keys() + .filter(|key| key.starts_with(&prefix)) + .cloned() + .collect::>(); + keys.into_iter() + .flat_map(|key| handles.remove(&key).unwrap_or_default()) + .collect::>() + }; + for handle in pending { + handle.abort(); + } +} + +#[derive(Clone, Copy)] +pub enum JobKind { + Dump, + Import, +} + +impl JobKind { + fn label(self) -> &'static str { + match self { + Self::Dump => "dump", + Self::Import => "import", + } + } +} + +async fn write_dump( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + file_path: &Path, + params: &ConnectionParams, + driver: &str, + schema: Option<&str>, + options: &DumpOptions, +) -> Result<(), String> { + let file = File::create(file_path).map_err(|error| error.to_string())?; + let mut writer = BufWriter::new(file); + writeln!(writer, "-- Tabularis Dump").map_err(|error| error.to_string())?; + let database_label = if session_id.is_some() { + connection_id + } else { + params.database.primary() + }; + writeln!(writer, "-- Database: {database_label}").map_err(|error| error.to_string())?; + writeln!(writer, "-- Date: {}\n", chrono::Local::now().to_rfc3339()) + .map_err(|error| error.to_string())?; + + let drv = crate::drivers::registry::get_connection_driver(params).await?; + // Quoting, schema qualification and literal syntax follow the driver's + // capabilities, so plugin drivers get statements their engine accepts. + let dialect = DumpDialect::from_capabilities(driver, &drv.manifest().capabilities); + let schema = dialect.resolve_schema(schema); + // Flat multi-db drivers list by params.database, not by schema. + let schema = dialect.scoped_schema(schema.as_deref()); + let all_tables = drv.get_tables(params, schema).await?; + let tables = options + .tables + .clone() + .unwrap_or_else(|| all_tables.into_iter().map(|table| table.name).collect()); + emit_progress( + runtime, + session_id, + "dump_progress", + &DumpProgress { + connection_id: connection_id.to_string(), + tables_processed: 0, + total_tables: tables.len(), + percentage: 0.0, + current_operation: "Starting dump...".to_string(), + }, + ); + + for (index, table) in tables.iter().enumerate() { + if options.structure { + writeln!( + writer, + "-- Structure for table {}", + dialect.table_ref(schema, table) + ) + .map_err(|error| error.to_string())?; + // Never emit DROP unless the driver can also recreate the table. + match drv.get_table_ddl(params, table, schema).await { + Ok(ddl) => { + writeln!(writer, "{}", dialect.drop_table_if_exists(schema, table)) + .map_err(|error| error.to_string())?; + writeln!(writer, "{}\n", ddl).map_err(|error| error.to_string())?; + } + Err(error) => { + writeln!( + writer, + "-- WARNING: could not generate DDL for {}: {} (table left unchanged)\n", + dialect.table_ref(schema, table), + error + ) + .map_err(|error| error.to_string())?; + } + } + } + if options.data { + writeln!( + writer, + "-- Data for table {}", + dialect.table_ref(schema, table) + ) + .map_err(|error| error.to_string())?; + export_table_data(&mut writer, &drv, params, driver, &dialect, table, schema).await?; + writeln!(writer).map_err(|error| error.to_string())?; + } + let processed = index + 1; + emit_progress( + runtime, + session_id, + "dump_progress", + &DumpProgress { + connection_id: connection_id.to_string(), + tables_processed: processed, + total_tables: tables.len(), + percentage: percentage(processed, tables.len()), + current_operation: format!("Dumped table {table}"), + }, + ); + } + writer.flush().map_err(|error| error.to_string())?; + Ok(()) +} + +async fn export_table_data( + writer: &mut BufWriter, + drv: &Arc, + params: &ConnectionParams, + driver: &str, + dialect: &DumpDialect, + table: &str, + schema: Option<&str>, +) -> Result<(), String> { + let query = format!("SELECT * FROM {}", dialect.table_ref(schema, table)); + match driver { + "mysql" => { + let pool = get_mysql_pool(params).await?; + let mut rows = sqlx::query(&query).fetch(&pool); + let mut batch = Vec::new(); + while let Some(row) = rows.try_next().await.map_err(|error| error.to_string())? { + let values = (0..row.columns().len()) + .map(|index| { + use sqlx::{Column, TypeInfo}; + let value = mysql::extract::extract_value(&row, index, None); + // JSON columns are extracted as parsed values and must be + // written back as JSON literals, not as their string content. + if row.column(index).type_info().name() == "JSON" { + dialect.escape_json_value(value) + } else { + dialect.escape_value(value) + } + }) + .collect::>(); + write_insert_batch(writer, dialect, schema, table, &mut batch, values)?; + } + flush_insert_batch(writer, dialect, schema, table, &mut batch)?; + } + "postgres" => { + let pool = get_postgres_pool(params).await?; + let client = pool.get().await.map_err(|error| error.to_string())?; + let query_params: Vec = Vec::new(); + let mut rows = std::pin::pin!(client + .query_raw(&query, &query_params) + .await + .map_err(|error| error.to_string())?); + let mut batch = Vec::new(); + while let Some(row) = rows.try_next().await.map_err(|error| error.to_string())? { + let values = (0..row.columns().len()) + .map(|index| { + let value = postgres::extract::extract_value(&row, index, None); + let column_type = row.columns()[index].type_(); + if *column_type == tokio_postgres::types::Type::JSON + || *column_type == tokio_postgres::types::Type::JSONB + { + dialect.escape_json_value(value) + } else { + dialect.escape_value(value) + } + }) + .collect::>(); + write_insert_batch(writer, dialect, schema, table, &mut batch, values)?; + } + flush_insert_batch(writer, dialect, schema, table, &mut batch)?; + } + "sqlite" => { + let pool = get_sqlite_pool(params).await?; + let mut rows = sqlx::query(&query).fetch(&pool); + let mut batch = Vec::new(); + while let Some(row) = rows.try_next().await.map_err(|error| error.to_string())? { + let values = (0..row.columns().len()) + .map(|index| { + dialect.escape_value(sqlite::extract::extract_value(&row, index, None)) + }) + .collect::>(); + write_insert_batch(writer, dialect, schema, table, &mut batch, values)?; + } + flush_insert_batch(writer, dialect, schema, table, &mut batch)?; + } + _ => { + // Already scoped: `None` for a plugin without schemas, whose + // "schema" RPC parameter may mean something else entirely. + let fallback_schema = schema; + let json_columns = + json_column_names(&drv.get_columns(params, table, fallback_schema).await?); + let mut batch = Vec::new(); + let mut page = 1u32; + loop { + let result = drv + .execute_query(params, &query, Some(1000), page, fallback_schema) + .await?; + let fetched = result.rows.len() as u32; + for row in result.rows { + batch.push(format_row_values( + row, + &result.columns, + &json_columns, + dialect, + )); + if batch.len() >= 100 { + flush_insert_batch(writer, dialect, schema, table, &mut batch)?; + } + } + if fetched == 0 || !plugin_dump_has_more(result.pagination, fetched, 1000) { + break; + } + page += 1; + } + flush_insert_batch(writer, dialect, schema, table, &mut batch)?; + } + } + Ok(()) +} + +fn write_insert_batch( + writer: &mut BufWriter, + dialect: &DumpDialect, + schema: Option<&str>, + table: &str, + batch: &mut Vec, + values: Vec, +) -> Result<(), String> { + batch.push(format!("({})", values.join(", "))); + if batch.len() >= 100 { + flush_insert_batch(writer, dialect, schema, table, batch)?; + } + Ok(()) +} + +fn flush_insert_batch( + writer: &mut BufWriter, + dialect: &DumpDialect, + schema: Option<&str>, + table: &str, + batch: &mut Vec, +) -> Result<(), String> { + if batch.is_empty() { + return Ok(()); + } + writeln!( + writer, + "{}", + dialect.insert_into_statement(schema, table, &batch.join(", ")) + ) + .map_err(|error| error.to_string())?; + batch.clear(); + Ok(()) +} + +/// Whether the plugin-driver fallback's paginated fetch loop (in +/// `export_table_data`) should request another page. +/// +/// A plugin's `execute_query` RPC may not populate `pagination` at all — +/// defaulting the "no pagination info" case to `false` (as if the table +/// were exhausted) would silently truncate a dump the moment a table has +/// more rows than one page, with no error raised. Falling back to whether +/// the page came back full instead matches `export.rs`'s established +/// pattern for the same "driver doesn't report pagination" gap: it may +/// cost one extra empty-page fetch when a table's row count is an exact +/// multiple of the page size, but it never drops rows. +fn plugin_dump_has_more(pagination: Option, fetched: u32, page_size: u32) -> bool { + pagination + .map(|p| p.has_more) + .unwrap_or(fetched >= page_size) +} + +/// Column names whose PostgreSQL type is `json`/`jsonb`. Used to decide +/// which cells in a row fetched through the generic (plugin-driver) +/// `execute_query` RPC need `DumpDialect::escape_json_value` rather than +/// `DumpDialect::escape_value` — see `export_table_data`'s fallback arm. Unlike the +/// builtin drivers' own extraction (which sees the source column type +/// directly), `QueryResult` only carries column *names*, so a JSON column +/// can't be told apart from a plain text column by inspecting a cell's +/// value alone — both arrive as a `serde_json::Value::String`. +fn json_column_names(columns: &[TableColumn]) -> HashSet { + columns + .iter() + .filter(|c| { + let t = c.data_type.to_ascii_lowercase(); + t == "json" || t == "jsonb" + }) + .map(|c| c.name.clone()) + .collect() +} + +/// Formats one row from the generic `execute_query` RPC into a parenthesized +/// SQL value list, e.g. `(1, 'Alice', NULL)`. `columns` must be the same +/// `QueryResult.columns` the row's values came from, in the same order. +fn format_row_values( + row: Vec, + columns: &[String], + json_columns: &HashSet, + dialect: &DumpDialect, +) -> String { + let values: Vec = row + .into_iter() + .zip(columns.iter()) + .map(|(val, col_name)| { + if json_columns.contains(col_name) { + dialect.escape_json_value(val) + } else { + dialect.escape_value(val) + } + }) + .collect(); + format!("({})", values.join(", ")) +} + +async fn execute_import( + runtime: &RuntimeContext, + session_id: Option, + file_path: &Path, + is_zip: bool, + connection_id: &str, + params: &ConnectionParams, + driver: &str, + schema: Option<&str>, +) -> Result<(), String> { + let file = File::open(file_path).map_err(|error| error.to_string())?; + let (reader, extracted_sql) = create_sql_reader(file, is_zip, runtime.paths.data_dir())?; + let _extracted_sql = extracted_sql; + let mut stream = SqlStatementStream::new(reader); + emit_progress( + runtime, + session_id, + "import_progress", + &ImportProgress { + connection_id: connection_id.to_string(), + statements_executed: 0, + total_statements: 0, + percentage: 0.0, + current_operation: "Starting import...".to_string(), + }, + ); + + match driver { + "mysql" => { + let pool = get_mysql_pool(params).await?; + let mut tx = pool.begin().await.map_err(|error| error.to_string())?; + for statement in [ + "SET FOREIGN_KEY_CHECKS=0", + "SET UNIQUE_CHECKS=0", + "SET AUTOCOMMIT=0", + ] { + sqlx::query(statement) + .execute(&mut *tx) + .await + .map_err(|error| error.to_string())?; + } + let mut executed = 0; + while let Some(statement) = stream.next_statement()? { + sqlx::query(&statement) + .execute(&mut *tx) + .await + .map_err(|error| statement_error(executed, error, &statement))?; + executed += 1; + emit_import_interval(runtime, session_id, connection_id, executed); + } + for statement in [ + "SET FOREIGN_KEY_CHECKS=1", + "SET UNIQUE_CHECKS=1", + "SET AUTOCOMMIT=1", + ] { + sqlx::query(statement) + .execute(&mut *tx) + .await + .map_err(|error| error.to_string())?; + } + tx.commit().await.map_err(|error| error.to_string())?; + emit_import_complete(runtime, session_id, connection_id, executed); + } + "postgres" => { + let pool = get_postgres_pool(params).await?; + let mut client = pool.get().await.map_err(|error| error.to_string())?; + let tx = client + .transaction() + .await + .map_err(|error| error.to_string())?; + tx.execute( + &format!( + "SET search_path TO \"{}\"", + schema.unwrap_or("public").replace('"', "\"\"") + ), + &[], + ) + .await + .map_err(|error| error.to_string())?; + tx.execute("SET CONSTRAINTS ALL DEFERRED", &[]) + .await + .map_err(|error| error.to_string())?; + tx.execute("SET LOCAL synchronous_commit=OFF", &[]) + .await + .map_err(|error| error.to_string())?; + let mut executed = 0; + while let Some(statement) = stream.next_statement()? { + tx.execute(&statement, &[]) + .await + .map_err(|error| statement_error(executed, error, &statement))?; + executed += 1; + emit_import_interval(runtime, session_id, connection_id, executed); + } + tx.commit().await.map_err(|error| error.to_string())?; + emit_import_complete(runtime, session_id, connection_id, executed); + } + "sqlite" => { + let pool = get_sqlite_pool(params).await?; + let mut tx = pool.begin().await.map_err(|error| error.to_string())?; + let mut executed = 0; + while let Some(statement) = stream.next_statement()? { + sqlx::query(&statement) + .execute(&mut *tx) + .await + .map_err(|error| statement_error(executed, error, &statement))?; + executed += 1; + emit_import_interval(runtime, session_id, connection_id, executed); + } + tx.commit().await.map_err(|error| error.to_string())?; + emit_import_complete(runtime, session_id, connection_id, executed); + } + _ => { + let drv = crate::drivers::registry::get_connection_driver(params).await?; + let is_postgres = + DumpDialect::from_capabilities(driver, &drv.manifest().capabilities).postgres; + let fallback_schema = if is_postgres { + Some(schema.unwrap_or("public")) + } else { + schema + }; + // Plugin RPC calls are independent: a failed import can leave prior statements committed. + let mut executed = 0; + while let Some(statement) = stream.next_statement()? { + drv.execute_query(params, &statement, None, 1, fallback_schema) + .await + .map_err(|error| statement_error(executed, error, &statement))?; + executed += 1; + emit_import_interval(runtime, session_id, connection_id, executed); + } + emit_import_complete(runtime, session_id, connection_id, executed); + } + } + Ok(()) +} + +fn emit_import_interval( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + executed: usize, +) { + if executed % 500 == 0 { + emit_progress( + runtime, + session_id, + "import_progress", + &ImportProgress { + connection_id: connection_id.to_string(), + statements_executed: executed, + total_statements: 0, + percentage: 0.0, + current_operation: format!("Imported {executed} statements"), + }, + ); + } +} + +fn emit_import_complete( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + executed: usize, +) { + emit_progress( + runtime, + session_id, + "import_progress", + &ImportProgress { + connection_id: connection_id.to_string(), + statements_executed: executed, + total_statements: executed, + percentage: 100.0, + current_operation: "Import completed".to_string(), + }, + ); +} + +fn statement_error(executed: usize, error: impl std::fmt::Display, statement: &str) -> String { + format!( + "Error at statement {}: {error}\nQuery: {statement}", + executed + 1 + ) +} + +struct SqlStatementStream { + reader: R, + current_statement: String, + line_buffer: String, +} + +impl SqlStatementStream { + fn new(reader: R) -> Self { + Self { + reader, + current_statement: String::new(), + line_buffer: String::new(), + } + } + + fn next_statement(&mut self) -> Result, String> { + loop { + self.line_buffer.clear(); + let read = self + .reader + .read_line(&mut self.line_buffer) + .map_err(|error| error.to_string())?; + if read == 0 { + if self.current_statement.trim().is_empty() { + return Ok(None); + } + return Ok(Some( + std::mem::take(&mut self.current_statement) + .trim() + .to_string(), + )); + } + let trimmed = self.line_buffer.trim(); + if trimmed.starts_with("--") || trimmed.is_empty() { + continue; + } + self.current_statement.push_str(&self.line_buffer); + if trimmed.ends_with(';') { + return Ok(Some( + std::mem::take(&mut self.current_statement) + .trim() + .to_string(), + )); + } + } + } +} + +fn create_sql_reader( + file: File, + is_zip: bool, + data_dir: &Path, +) -> Result<(Box, Option), String> { + if !is_zip { + return Ok((Box::new(BufReader::with_capacity(128 * 1024, file)), None)); + } + let mut archive = + ZipArchive::new(file).map_err(|error| format!("Failed to open zip: {error}"))?; + for index in 0..archive.len() { + let zipped = archive.by_index(index).map_err(|error| error.to_string())?; + if zipped.name().to_ascii_lowercase().ends_with(".sql") { + let directory = data_dir.join("database-import-jobs"); + create_private_directory(&directory)?; + let path = directory.join(format!(".extracted-{}.sql", Uuid::new_v4())); + let guard = TemporaryFile::new(path.clone()); + let mut extracted = File::create(&path).map_err(|error| error.to_string())?; + let max_bytes = super::file_transfers::MAX_FILE_TRANSFER_BYTES; + let copied = std::io::copy(&mut zipped.take(max_bytes + 1), &mut extracted) + .map_err(|error| error.to_string())?; + extracted.flush().map_err(|error| error.to_string())?; + if copied > max_bytes { + return Err(format!( + "Extracted SQL exceeds the {max_bytes} byte import limit" + )); + } + drop(extracted); + let reader = File::open(&path).map_err(|error| error.to_string())?; + return Ok(( + Box::new(BufReader::with_capacity(128 * 1024, reader)), + Some(guard), + )); + } + } + Err("No .sql file found in zip archive".to_string()) +} + +fn resolve_import_source( + runtime: &RuntimeContext, + source: ImportSource, +) -> Result<(PathBuf, bool, Option), String> { + match source { + ImportSource::ServerPath(path) => { + let is_zip = has_zip_extension(&path); + Ok((path, is_zip, None)) + } + ImportSource::SessionUpload { owner, token } => { + let claimed = FileTransferStore::new(runtime.paths.data_dir()).claim_upload( + owner, + &token, + DATABASE_IMPORT_PURPOSE, + )?; + let is_zip = claimed + .metadata() + .file_name + .to_ascii_lowercase() + .ends_with(".zip"); + Ok((claimed.path().to_path_buf(), is_zip, Some(claimed))) + } + } +} + +fn has_zip_extension(path: &Path) -> bool { + path.extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("zip")) +} + +fn emit_progress( + runtime: &RuntimeContext, + session_id: Option, + event: &str, + payload: &T, +) { + let Ok(payload) = serde_json::to_value(payload) else { + return; + }; + let _ = if let Some(session_id) = session_id { + runtime.events.emit_to(session_id, event, payload) + } else { + runtime.events.emit(event, payload) + }; +} + +fn percentage(processed: usize, total: usize) -> f32 { + if total == 0 { + 100.0 + } else { + processed as f32 * 100.0 / total as f32 + } +} + +fn job_key(session_id: Option, kind: JobKind, connection_id: &str) -> String { + match session_id { + Some(session_id) => format!("web:{session_id}:{}:{connection_id}", kind.label()), + None => format!("desktop:{}:{connection_id}", kind.label()), + } +} + +fn join_job( + result: Result, tokio::task::JoinError>, + label: &str, +) -> Result { + match result { + Ok(result) => result, + Err(error) if error.is_cancelled() => Err(format!("{label} cancelled")), + Err(error) => Err(format!("{label} task failed: {error}")), + } +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +fn database_name<'a>(params: &'a ConnectionParams, fallback: &'a str) -> &'a str { + match ¶ms.database { + crate::models::DatabaseSelection::Single(value) => value, + crate::models::DatabaseSelection::Multiple(values) => { + values.first().map_or(fallback, String::as_str) + } + } +} + +fn safe_name(value: &str) -> String { + super::file_transfers::safe_file_name(value).replace([' ', '.'], "_") +} + +fn create_private_directory(path: &Path) -> Result<(), String> { + fs::create_dir_all(path).map_err(|error| error.to_string())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +struct TemporaryFile { + path: PathBuf, +} + +impl TemporaryFile { + fn new(path: PathBuf) -> Self { + Self { path } + } +} + +impl Drop for TemporaryFile { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +struct JobRegistration { + handles: Arc>, + key: String, + handle: Arc, + completed: bool, +} + +impl JobRegistration { + fn new( + handles: Arc>, + key: String, + handle: Arc, + ) -> Self { + register_abort_handle(&handles, key.clone(), handle.clone()); + Self { + handles, + key, + handle, + completed: false, + } + } + + fn complete(&mut self) { + unregister_abort_handle(&self.handles, &self.key, &self.handle); + self.completed = true; + } +} + +impl Drop for JobRegistration { + fn drop(&mut self) { + unregister_abort_handle(&self.handles, &self.key, &self.handle); + if !self.completed { + self.handle.abort(); + } + } +} + +#[cfg(test)] +#[path = "database_transfers_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/database_transfers_tests.rs b/src-tauri/src/application/database_transfers_tests.rs new file mode 100644 index 000000000..2ecad0ad0 --- /dev/null +++ b/src-tauri/src/application/database_transfers_tests.rs @@ -0,0 +1,259 @@ +use super::*; +use serde_json::json; +use std::io::Cursor; +use std::sync::Mutex as StdMutex; +use std::time::Duration; + +#[derive(Default)] +struct RecordingEvents { + scoped: StdMutex>, +} + +impl crate::runtime::events::RuntimeEvents for RecordingEvents { + fn emit(&self, _event: &str, _payload: serde_json::Value) -> Result<(), String> { + Ok(()) + } + + fn emit_to( + &self, + session_id: Uuid, + event: &str, + payload: serde_json::Value, + ) -> Result<(), String> { + self.scoped + .lock() + .unwrap() + .push((session_id, event.to_string(), payload)); + Ok(()) + } +} + +#[test] +fn streams_sql_statements_and_ignores_line_comments() { + let input = Cursor::new( + b"-- dump header\nCREATE TABLE users (id INTEGER);\n\nINSERT INTO users VALUES (1);\n" + .to_vec(), + ); + let mut stream = SqlStatementStream::new(BufReader::new(input)); + + assert_eq!( + stream.next_statement().unwrap().as_deref(), + Some("CREATE TABLE users (id INTEGER);") + ); + assert_eq!( + stream.next_statement().unwrap().as_deref(), + Some("INSERT INTO users VALUES (1);") + ); + assert_eq!(stream.next_statement().unwrap(), None); +} + +#[test] +fn reads_the_first_sql_file_from_a_zip_upload() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("database.zip"); + let file = File::create(&path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let options: zip::write::FileOptions<()> = zip::write::FileOptions::default(); + zip.start_file("README.txt", options).unwrap(); + zip.write_all(b"ignore").unwrap(); + zip.start_file("database.sql", options).unwrap(); + zip.write_all(b"SELECT 1;").unwrap(); + zip.finish().unwrap(); + + let (mut reader, extracted) = + create_sql_reader(File::open(path).unwrap(), true, directory.path()).unwrap(); + assert!(extracted.is_some()); + let mut sql = String::new(); + reader.read_to_string(&mut sql).unwrap(); + assert_eq!(sql, "SELECT 1;"); +} + +#[test] +fn progress_events_are_scoped_to_the_owning_browser_session() { + let directory = tempfile::tempdir().unwrap(); + let events = Arc::new(RecordingEvents::default()); + let runtime = RuntimeContext::new( + Arc::new(crate::runtime::paths::FixedRuntimePaths::new( + directory.path().to_path_buf(), + directory.path().to_path_buf(), + )), + events.clone(), + Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), + ); + let owner = Uuid::new_v4(); + + emit_progress( + &runtime, + Some(owner), + "dump_progress", + &DumpProgress { + connection_id: "connection-1".to_string(), + tables_processed: 1, + total_tables: 2, + percentage: 50.0, + current_operation: "Dumped table users".to_string(), + }, + ); + + let recorded = events.scoped.lock().unwrap(); + assert_eq!(recorded.len(), 1); + assert_eq!(recorded[0].0, owner); + assert_eq!(recorded[0].1, "dump_progress"); + assert_eq!(recorded[0].2["connection_id"], "connection-1"); +} + +#[tokio::test] +async fn dropping_a_job_registration_aborts_and_unregisters_the_job() { + let state = DumpCancellationState::default(); + let task = tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(60)).await; + }); + let key = "web:test:dump:connection".to_string(); + let registration = JobRegistration::new( + state.handles.clone(), + key.clone(), + Arc::new(task.abort_handle()), + ); + assert!(state.handles.lock().unwrap().contains_key(&key)); + + drop(registration); + assert!(!state.handles.lock().unwrap().contains_key(&key)); + assert!(task.await.unwrap_err().is_cancelled()); +} + +#[tokio::test] +async fn session_cleanup_only_aborts_jobs_owned_by_that_session() { + let state = DumpCancellationState::default(); + let owner = Uuid::new_v4(); + let other = Uuid::new_v4(); + let owner_task = tokio::spawn(std::future::pending::<()>()); + let other_task = tokio::spawn(std::future::pending::<()>()); + register_abort_handle( + &state.handles, + job_key(Some(owner), JobKind::Import, "connection"), + Arc::new(owner_task.abort_handle()), + ); + register_abort_handle( + &state.handles, + job_key(Some(other), JobKind::Import, "connection"), + Arc::new(other_task.abort_handle()), + ); + + cancel_session_jobs(&state, owner); + + assert!(owner_task.await.unwrap_err().is_cancelled()); + assert!(!other_task.is_finished()); + other_task.abort(); +} + +fn postgres_dialect() -> DumpDialect { + let pg = crate::drivers::postgres::PostgresDriver::new(); + DumpDialect::from_capabilities("postgres", &pg.manifest().capabilities) +} + +fn column(name: &str, data_type: &str) -> TableColumn { + TableColumn { + name: name.to_string(), + data_type: data_type.to_string(), + is_pk: false, + is_nullable: true, + is_auto_increment: false, + is_generated: false, + default_value: None, + character_maximum_length: None, + comment: None, + numeric_precision: None, + numeric_scale: None, + } +} + +#[test] +fn test_json_column_names_matches_json_and_jsonb_case_insensitively() { + let columns = vec![ + column("id", "integer"), + column("payload", "jsonb"), + column("meta", "JSON"), + column("name", "text"), + ]; + let json_cols = json_column_names(&columns); + assert_eq!(json_cols.len(), 2); + assert!(json_cols.contains("payload")); + assert!(json_cols.contains("meta")); + assert!(!json_cols.contains("id")); + assert!(!json_cols.contains("name")); +} + +#[test] +fn test_json_column_names_empty_for_no_json_columns() { + let columns = vec![column("id", "integer"), column("name", "text")]; + assert!(json_column_names(&columns).is_empty()); +} + +#[test] +fn test_format_row_values_escapes_json_column_differently_from_plain_text() { + // Same underlying serde_json::Value::String("hi") in two columns: + // the plain text column keeps it literal, the JSON column re-encodes + // it as a JSON string literal (surrounding quotes preserved) -- + // this is the whole reason json_column_names exists (#822 dump fix + // for plugin-backed drivers: QueryResult only carries column names, + // not types, so this can't be inferred from the value alone). + let columns = vec!["name".to_string(), "payload".to_string()]; + let mut json_cols = HashSet::new(); + json_cols.insert("payload".to_string()); + + let row = vec![json!("hi"), json!("hi")]; + assert_eq!( + format_row_values(row, &columns, &json_cols, &postgres_dialect()), + r#"('hi', '"hi"')"# + ); +} + +#[test] +fn test_format_row_values_regression_json_object_and_null_round_trip() { + let columns = vec!["id".to_string(), "payload".to_string(), "note".to_string()]; + let mut json_cols = HashSet::new(); + json_cols.insert("payload".to_string()); + + let row = vec![json!(1), json!({"a": 1}), serde_json::Value::Null]; + assert_eq!( + format_row_values(row, &columns, &json_cols, &postgres_dialect()), + r#"(1, '{"a":1}', NULL)"# + ); +} + +fn pagination(has_more: bool) -> Pagination { + Pagination { + page: 1, + page_size: 1000, + total_rows: None, + has_more, + } +} + +#[test] +fn test_plugin_dump_has_more_trusts_real_pagination_over_the_fallback() { + // A full page that the driver explicitly says is the last one must + // not be reinterpreted as "more rows" just because it's full. + assert!(!plugin_dump_has_more(Some(pagination(false)), 1000, 1000)); + // A short page the driver explicitly says has more must still be + // honored, even though the fallback heuristic alone would say no. + assert!(plugin_dump_has_more(Some(pagination(true)), 10, 1000)); +} + +#[test] +fn test_plugin_dump_has_more_regression_a_full_page_without_pagination_is_not_treated_as_the_end() { + // Regression: a plugin's execute_query RPC that never populates + // `pagination` used to default this to `false`, silently truncating + // any table with more rows than one page. + assert!(plugin_dump_has_more(None, 1000, 1000)); +} + +#[test] +fn test_plugin_dump_has_more_a_short_page_without_pagination_ends_the_fetch() { + assert!(!plugin_dump_has_more(None, 10, 1000)); +} + +#[test] +fn test_plugin_dump_has_more_an_empty_page_without_pagination_ends_the_fetch() { + assert!(!plugin_dump_has_more(None, 0, 1000)); +} diff --git a/src-tauri/src/application/file_transfers.rs b/src-tauri/src/application/file_transfers.rs new file mode 100644 index 000000000..0534dc03b --- /dev/null +++ b/src-tauri/src/application/file_transfers.rs @@ -0,0 +1,686 @@ +use bytes::Bytes; +use chrono::{SecondsFormat, Utc}; +use futures::{Stream, StreamExt}; +use serde::{Deserialize, Serialize}; +use std::fmt::Display; +use std::fs; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, ReadBuf}; +use uuid::Uuid; + +pub const MAX_FILE_TRANSFER_BYTES: u64 = 512 * 1024 * 1024; +const DEFAULT_TRANSFER_TTL: Duration = Duration::from_secs(15 * 60); +const MAX_PENDING_TRANSFERS_PER_SESSION: usize = 64; +const CONTENT_FILE: &str = "content"; +const MANIFEST_FILE: &str = "metadata.json"; +const SWEEP_INTERVAL: Duration = Duration::from_secs(30); + +#[derive(Clone, Debug)] +pub struct FileTransferStore { + root: PathBuf, + limits: TransferLimits, +} + +#[derive(Clone, Debug)] +struct TransferLimits { + max_bytes: u64, + ttl: Duration, + max_pending_per_session: usize, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileTransferMetadata { + pub token: String, + pub file_name: String, + pub mime_type: String, + pub size: u64, + pub expires_at: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct TransferManifest { + #[serde(flatten)] + metadata: FileTransferMetadata, + owner: Uuid, + purpose: String, + kind: TransferKind, + expires_at_millis: u64, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "lowercase")] +enum TransferKind { + Upload, + Download, +} + +pub struct TransferReader { + metadata: FileTransferMetadata, + file: tokio::fs::File, + cleanup_directory: Option, +} + +pub struct ClaimedUpload { + metadata: FileTransferMetadata, + content_path: PathBuf, + cleanup_directory: Option, +} + +struct PendingDirectory { + path: Option, +} + +/// Why storing an upload failed; `TooLarge` maps to HTTP 413. +#[derive(Debug)] +pub enum UploadError { + TooLarge(String), + Failed(String), +} + +impl Display for UploadError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooLarge(message) | Self::Failed(message) => formatter.write_str(message), + } + } +} + +impl From for UploadError { + fn from(message: String) -> Self { + Self::Failed(message) + } +} + +/// The request body hit the router's body-size limit while streaming. +fn exceeds_body_limit(error: &(dyn std::error::Error + 'static)) -> bool { + let mut current = Some(error); + while let Some(error) = current { + if error.is::() { + return true; + } + current = error.source(); + } + false +} + +impl FileTransferStore { + pub fn new(data_dir: &Path) -> Self { + Self { + root: data_dir.join("web-file-transfers"), + limits: TransferLimits { + max_bytes: MAX_FILE_TRANSFER_BYTES, + ttl: DEFAULT_TRANSFER_TTL, + max_pending_per_session: MAX_PENDING_TRANSFERS_PER_SESSION, + }, + } + } + + #[cfg(test)] + fn with_limits(data_dir: &Path, max_bytes: u64, ttl: Duration) -> Self { + Self { + root: data_dir.join("web-file-transfers"), + limits: TransferLimits { + max_bytes, + ttl, + max_pending_per_session: MAX_PENDING_TRANSFERS_PER_SESSION, + }, + } + } + + pub async fn store_upload( + &self, + owner: Uuid, + purpose: &str, + file_name: &str, + content_type: Option<&str>, + stream: S, + ) -> Result + where + S: Stream>, + E: std::error::Error + 'static, + { + let stream = stream.map(|chunk| { + chunk.map_err(|error| { + if exceeds_body_limit(&error) { + UploadError::TooLarge("The upload exceeds its byte limit".to_string()) + } else { + UploadError::Failed(format!("File transfer interrupted: {error}")) + } + }) + }); + self.store_stream( + owner, + purpose, + file_name, + content_type, + TransferKind::Upload, + stream, + ) + .await + } + + pub async fn store_download_bytes( + &self, + owner: Uuid, + purpose: &str, + file_name: &str, + content_type: Option<&str>, + bytes: Vec, + ) -> Result { + self.store_download( + owner, + purpose, + file_name, + content_type, + futures::stream::once(async move { + Ok::(Bytes::from(bytes)) + }), + ) + .await + } + + pub async fn store_download( + &self, + owner: Uuid, + purpose: &str, + file_name: &str, + content_type: Option<&str>, + stream: S, + ) -> Result + where + S: Stream>, + E: Display, + { + let stream = stream.map(|chunk| { + chunk + .map_err(|error| UploadError::Failed(format!("File transfer interrupted: {error}"))) + }); + self.store_stream( + owner, + purpose, + file_name, + content_type, + TransferKind::Download, + stream, + ) + .await + .map_err(|error| error.to_string()) + } + + pub async fn open_upload( + &self, + owner: Uuid, + token: &str, + purpose: &str, + ) -> Result { + self.sweep_expired().await; + let directory = self.token_directory(owner, TransferKind::Upload, token)?; + let manifest = + self.read_manifest(&directory, owner, TransferKind::Upload, Some(purpose))?; + let file = tokio::fs::File::open(directory.join(CONTENT_FILE)) + .await + .map_err(|_| "File upload token is missing or expired".to_string())?; + Ok(TransferReader { + metadata: manifest.metadata, + file, + cleanup_directory: None, + }) + } + + pub fn claim_upload( + &self, + owner: Uuid, + token: &str, + purpose: &str, + ) -> Result { + let directory = self.token_directory(owner, TransferKind::Upload, token)?; + let manifest = + self.read_manifest(&directory, owner, TransferKind::Upload, Some(purpose))?; + let claimed = directory.with_file_name(format!(".claimed-{}", Uuid::new_v4())); + fs::rename(&directory, &claimed) + .map_err(|_| "File upload token is missing, expired, or already used".to_string())?; + Ok(ClaimedUpload { + metadata: manifest.metadata, + content_path: claimed.join(CONTENT_FILE), + cleanup_directory: Some(claimed), + }) + } + + pub async fn consume_download( + &self, + owner: Uuid, + token: &str, + ) -> Result { + self.sweep_expired().await; + let directory = self.token_directory(owner, TransferKind::Download, token)?; + let manifest = self.read_manifest(&directory, owner, TransferKind::Download, None)?; + let claimed = directory.with_file_name(format!(".claimed-{}", Uuid::new_v4())); + fs::rename(&directory, &claimed) + .map_err(|_| "File download token is missing, expired, or already used".to_string())?; + let file = match tokio::fs::File::open(claimed.join(CONTENT_FILE)).await { + Ok(file) => file, + Err(_) => { + let _ = fs::remove_dir_all(&claimed); + return Err("File download token is missing or expired".to_string()); + } + }; + Ok(TransferReader { + metadata: manifest.metadata, + file, + cleanup_directory: Some(claimed), + }) + } + + pub fn cleanup_session(&self, owner: Uuid) { + let _ = fs::remove_dir_all(self.root.join(owner.to_string())); + } + + /// Removes expired transfers of every session. A token's own expiry is + /// checked on use, so this only reclaims disk space: it runs at most every + /// `SWEEP_INTERVAL` per root and off the async worker threads. + async fn sweep_expired(&self) { + static LAST_SWEEP: std::sync::Mutex< + Option>, + > = std::sync::Mutex::new(None); + { + let mut last = LAST_SWEEP.lock().unwrap_or_else(|error| error.into_inner()); + let last = last.get_or_insert_with(Default::default); + let now = std::time::Instant::now(); + if last + .get(&self.root) + .is_some_and(|previous| now.duration_since(*previous) < SWEEP_INTERVAL) + { + return; + } + last.insert(self.root.clone(), now); + } + let root = self.root.clone(); + let ttl = self.limits.ttl; + let result = tokio::task::spawn_blocking(move || remove_expired_transfers(&root, ttl)) + .await + .map_err(|error| error.to_string()) + .and_then(|result| result); + if let Err(error) = result { + log::warn!("Failed to sweep expired file transfers: {error}"); + } + } + + async fn store_stream( + &self, + owner: Uuid, + purpose: &str, + file_name: &str, + content_type: Option<&str>, + kind: TransferKind, + stream: S, + ) -> Result + where + S: Stream>, + { + validate_purpose(purpose)?; + self.sweep_expired().await; + let parent = self.root.join(owner.to_string()).join(kind.directory()); + create_private_directory(&parent)?; + if pending_transfer_count(&parent)? >= self.limits.max_pending_per_session { + return Err("Too many pending file transfers for this session" + .to_string() + .into()); + } + + let token = Uuid::new_v4().to_string(); + let pending_path = parent.join(format!(".pending-{}", Uuid::new_v4())); + create_private_directory(&pending_path)?; + let mut pending = PendingDirectory { + path: Some(pending_path.clone()), + }; + let content_path = pending_path.join(CONTENT_FILE); + let mut file = create_private_file(&content_path).await?; + let mut size = 0_u64; + futures::pin_mut!(stream); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + size = size + .checked_add(chunk.len() as u64) + .ok_or_else(|| "File transfer size overflow".to_string())?; + if size > self.limits.max_bytes { + return Err(UploadError::TooLarge(format!( + "File transfer exceeds the {} byte limit", + self.limits.max_bytes + ))); + } + file.write_all(&chunk) + .await + .map_err(|error| format!("Failed to store file transfer: {error}"))?; + } + file.flush() + .await + .map_err(|error| format!("Failed to store file transfer: {error}"))?; + drop(file); + + let safe_name = safe_file_name(file_name); + let mime_type = detected_content_type(&content_path) + .await + .unwrap_or_else(|| safe_content_type(content_type)); + let expires_at_time = SystemTime::now() + .checked_add(self.limits.ttl) + .ok_or_else(|| "Invalid file transfer expiration".to_string())?; + let expires_at_millis = unix_millis(expires_at_time)?; + let expires_at = chrono::DateTime::::from(expires_at_time) + .to_rfc3339_opts(SecondsFormat::Secs, true); + let metadata = FileTransferMetadata { + token: token.clone(), + file_name: safe_name, + mime_type, + size, + expires_at, + }; + let manifest = TransferManifest { + metadata: metadata.clone(), + owner, + purpose: purpose.to_string(), + kind, + expires_at_millis, + }; + let manifest_bytes = serde_json::to_vec(&manifest).map_err(|error| error.to_string())?; + write_private_bytes(&pending_path.join(MANIFEST_FILE), &manifest_bytes).await?; + let final_path = parent.join(&token); + fs::rename(&pending_path, &final_path) + .map_err(|error| format!("Failed to finalize file transfer: {error}"))?; + pending.path = None; + Ok(metadata) + } + + fn token_directory( + &self, + owner: Uuid, + kind: TransferKind, + token: &str, + ) -> Result { + validate_token(token)?; + Ok(self + .root + .join(owner.to_string()) + .join(kind.directory()) + .join(token)) + } + + fn read_manifest( + &self, + directory: &Path, + owner: Uuid, + kind: TransferKind, + purpose: Option<&str>, + ) -> Result { + let bytes = fs::read(directory.join(MANIFEST_FILE)) + .map_err(|_| "File transfer token is missing or expired".to_string())?; + let manifest = serde_json::from_slice::(&bytes) + .map_err(|_| "File transfer token is invalid".to_string())?; + let now = unix_millis(SystemTime::now())?; + if manifest.owner == owner && manifest.kind == kind && manifest.expires_at_millis <= now { + let _ = fs::remove_dir_all(directory); + } + if manifest.owner != owner + || manifest.kind != kind + || manifest.expires_at_millis <= now + || purpose.is_some_and(|purpose| manifest.purpose != purpose) + { + return Err("File transfer token is missing or expired".to_string()); + } + Ok(manifest) + } +} + +/// Deletes every expired upload and download below `root`. +fn remove_expired_transfers(root: &Path, ttl: Duration) -> Result<(), String> { + let sessions = match fs::read_dir(root) { + Ok(sessions) => sessions, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.to_string()), + }; + let now = unix_millis(SystemTime::now())?; + for session in sessions { + let session = session.map_err(|error| error.to_string())?; + if !session + .file_type() + .map_err(|error| error.to_string())? + .is_dir() + { + continue; + } + for kind in [TransferKind::Upload, TransferKind::Download] { + let entries = match fs::read_dir(session.path().join(kind.directory())) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => return Err(error.to_string()), + }; + for entry in entries { + let entry = entry.map_err(|error| error.to_string())?; + if !entry + .file_type() + .map_err(|error| error.to_string())? + .is_dir() + { + continue; + } + let expires_at = fs::read(entry.path().join(MANIFEST_FILE)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .map(|manifest| manifest.expires_at_millis) + .or_else(|| fallback_expiry(&entry.path(), ttl)); + if expires_at.is_some_and(|expires_at| expires_at <= now) { + let _ = fs::remove_dir_all(entry.path()); + } + } + } + } + Ok(()) +} + +impl TransferKind { + fn directory(self) -> &'static str { + match self { + Self::Upload => "uploads", + Self::Download => "downloads", + } + } +} + +impl TransferReader { + pub fn metadata(&self) -> &FileTransferMetadata { + &self.metadata + } +} + +impl AsyncRead for TransferReader { + fn poll_read( + mut self: Pin<&mut Self>, + context: &mut Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.file).poll_read(context, buffer) + } +} + +impl Drop for TransferReader { + fn drop(&mut self) { + if let Some(directory) = self.cleanup_directory.take() { + let _ = fs::remove_dir_all(directory); + } + } +} + +impl ClaimedUpload { + pub fn metadata(&self) -> &FileTransferMetadata { + &self.metadata + } + + pub fn path(&self) -> &Path { + &self.content_path + } +} + +impl Drop for ClaimedUpload { + fn drop(&mut self) { + if let Some(directory) = self.cleanup_directory.take() { + let _ = fs::remove_dir_all(directory); + } + } +} + +impl Drop for PendingDirectory { + fn drop(&mut self) { + if let Some(path) = self.path.take() { + let _ = fs::remove_dir_all(path); + } + } +} + +fn validate_token(token: &str) -> Result<(), String> { + match Uuid::parse_str(token) { + Ok(parsed) if parsed.get_version_num() == 4 => Ok(()), + _ => Err("Invalid file transfer token".to_string()), + } +} + +fn validate_purpose(purpose: &str) -> Result<(), String> { + if purpose.is_empty() + || purpose.len() > 64 + || !purpose + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + return Err("Invalid file transfer purpose".to_string()); + } + Ok(()) +} + +pub fn safe_file_name(file_name: &str) -> String { + let normalized = file_name.replace('\\', "/"); + let base = normalized + .split('/') + .filter(|part| !part.is_empty()) + .next_back() + .unwrap_or("download.bin"); + let mut safe = String::with_capacity(base.len().min(128)); + for character in base.chars() { + if safe.len() >= 128 { + break; + } + if character.is_ascii_alphanumeric() + || matches!(character, '.' | '-' | '_' | ' ' | '(' | ')') + { + safe.push(character); + } else { + safe.push('_'); + } + } + let safe = safe.trim().trim_matches('.'); + if safe.is_empty() || matches!(safe, "." | "..") { + "download.bin".to_string() + } else { + safe.to_string() + } +} + +async fn detected_content_type(path: &Path) -> Option { + let mut file = tokio::fs::File::open(path).await.ok()?; + let mut header = vec![0_u8; 8192]; + let read = file.read(&mut header).await.ok()?; + header.truncate(read); + infer::get(&header).map(|kind| kind.mime_type().to_string()) +} + +pub fn safe_content_type(content_type: Option<&str>) -> String { + let Some(content_type) = content_type else { + return "application/octet-stream".to_string(); + }; + let content_type = content_type + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + let Some((kind, subtype)) = content_type.split_once('/') else { + return "application/octet-stream".to_string(); + }; + if kind.is_empty() + || subtype.is_empty() + || content_type.len() > 127 + || !kind.bytes().all(content_type_byte_is_safe) + || !subtype.bytes().all(content_type_byte_is_safe) + { + return "application/octet-stream".to_string(); + } + content_type +} + +fn content_type_byte_is_safe(byte: u8) -> bool { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-' + ) +} + +async fn create_private_file(path: &Path) -> Result { + let mut options = tokio::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + options.open(path).await.map_err(|error| error.to_string()) +} + +async fn write_private_bytes(path: &Path, bytes: &[u8]) -> Result<(), String> { + let mut file = create_private_file(path).await?; + file.write_all(bytes) + .await + .map_err(|error| error.to_string())?; + file.flush().await.map_err(|error| error.to_string()) +} + +fn create_private_directory(path: &Path) -> Result<(), String> { + fs::create_dir_all(path).map_err(|error| error.to_string())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +fn pending_transfer_count(parent: &Path) -> Result { + fs::read_dir(parent) + .map_err(|error| error.to_string())? + .try_fold(0_usize, |count, entry| { + let entry = entry.map_err(|error| error.to_string())?; + Ok(count + + usize::from( + entry + .file_type() + .map_err(|error| error.to_string())? + .is_dir(), + )) + }) +} + +fn fallback_expiry(path: &Path, ttl: Duration) -> Option { + let modified = fs::metadata(path).ok()?.modified().ok()?; + unix_millis(modified.checked_add(ttl)?).ok() +} + +fn unix_millis(time: SystemTime) -> Result { + let millis = time + .duration_since(UNIX_EPOCH) + .map_err(|_| "Invalid file transfer timestamp".to_string())? + .as_millis(); + u64::try_from(millis).map_err(|_| "Invalid file transfer timestamp".to_string()) +} + +#[cfg(test)] +#[path = "file_transfers_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/file_transfers_tests.rs b/src-tauri/src/application/file_transfers_tests.rs new file mode 100644 index 000000000..8a6533df6 --- /dev/null +++ b/src-tauri/src/application/file_transfers_tests.rs @@ -0,0 +1,285 @@ +use super::{ + remove_expired_transfers, safe_content_type, safe_file_name, FileTransferStore, UploadError, +}; +use bytes::Bytes; +use futures::stream; +use std::io; +use std::time::Duration; +use tokio::io::AsyncReadExt; +use uuid::Uuid; + +fn bytes_stream( + chunks: impl IntoIterator, +) -> impl futures::Stream> { + stream::iter( + chunks + .into_iter() + .map(|chunk| Ok(Bytes::from_static(chunk))), + ) +} + +#[tokio::test] +async fn uploads_are_streamed_safely_and_bound_to_owner_and_purpose() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::new(temp.path()); + let owner = Uuid::new_v4(); + let metadata = store + .store_upload( + owner, + "connection-import", + "../../quarterly\nreport.csv", + Some("text/csv; charset=utf-8"), + bytes_stream([b"region,".as_slice(), b"total\nwest,42\n".as_slice()]), + ) + .await + .unwrap(); + + assert_eq!(metadata.file_name, "quarterly_report.csv"); + assert_eq!(metadata.mime_type, "text/csv"); + assert_eq!(metadata.size, 21); + assert!(!metadata + .token + .contains(temp.path().to_string_lossy().as_ref())); + assert!(store + .open_upload(Uuid::new_v4(), &metadata.token, "connection-import") + .await + .is_err()); + assert!(store + .open_upload(owner, &metadata.token, "notebook-import") + .await + .is_err()); + + let mut reader = store + .open_upload(owner, &metadata.token, "connection-import") + .await + .unwrap(); + let mut bytes = Vec::new(); + reader.read_to_end(&mut bytes).await.unwrap(); + assert_eq!(bytes, b"region,total\nwest,42\n"); +} + +#[tokio::test] +async fn traversal_and_guessed_tokens_never_select_files() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::new(temp.path()); + let owner = Uuid::new_v4(); + + assert!(store + .open_upload(owner, "../../config.json", "connection-import") + .await + .is_err()); + assert!(store + .open_upload( + owner, + "00000000-0000-4000-8000-000000000000", + "connection-import", + ) + .await + .is_err()); + assert_eq!(safe_file_name("C:\\fakepath\\report.sql"), "report.sql"); + assert_eq!(safe_file_name("../.."), "download.bin"); + assert_eq!( + safe_content_type(Some("text/html\r\nx-unsafe: yes")), + "application/octet-stream" + ); +} + +#[tokio::test] +async fn downloads_are_single_use_and_cleanup_when_streaming_stops() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::new(temp.path()); + let owner = Uuid::new_v4(); + let metadata = store + .store_download( + owner, + "query-export", + "results.csv", + Some("text/csv"), + bytes_stream([b"a,b\n".as_slice(), b"1,2\n".as_slice()]), + ) + .await + .unwrap(); + + let mut reader = store + .consume_download(owner, &metadata.token) + .await + .unwrap(); + let mut prefix = [0_u8; 2]; + reader.read_exact(&mut prefix).await.unwrap(); + assert_eq!(&prefix, b"a,"); + assert!(store + .consume_download(owner, &metadata.token) + .await + .is_err()); + drop(reader); + + let downloads = store.root.join(owner.to_string()).join("downloads"); + assert_eq!(std::fs::read_dir(downloads).unwrap().count(), 0); +} + +#[tokio::test] +async fn interrupted_and_oversized_uploads_leave_no_transfer_token() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::with_limits(temp.path(), 8, Duration::from_secs(60)); + let owner = Uuid::new_v4(); + let interrupted = stream::iter(vec![ + Ok(Bytes::from_static(b"partial")), + Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "disconnected", + )), + ]); + + assert!(store + .store_upload( + owner, + "connection-import", + "partial.sql", + Some("text/plain"), + interrupted, + ) + .await + .unwrap_err() + .to_string() + .contains("interrupted")); + assert!(matches!( + store + .store_upload( + owner, + "connection-import", + "large.sql", + Some("text/plain"), + bytes_stream([b"123456789".as_slice()]), + ) + .await, + Err(UploadError::TooLarge(message)) if message.contains("8 byte limit") + )); + + let uploads = store.root.join(owner.to_string()).join("uploads"); + assert_eq!(std::fs::read_dir(uploads).unwrap().count(), 0); +} + +#[tokio::test] +async fn session_cleanup_revokes_every_pending_transfer() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::new(temp.path()); + let owner = Uuid::new_v4(); + let upload = store + .store_upload( + owner, + "connection-import", + "connections.json", + Some("application/json"), + bytes_stream([b"{}".as_slice()]), + ) + .await + .unwrap(); + let download = store + .store_download( + owner, + "query-export", + "results.csv", + Some("text/csv"), + bytes_stream([b"id\n1\n".as_slice()]), + ) + .await + .unwrap(); + + store.cleanup_session(owner); + + assert!(store + .open_upload(owner, &upload.token, "connection-import") + .await + .is_err()); + assert!(store + .consume_download(owner, &download.token) + .await + .is_err()); +} + +#[tokio::test] +async fn expired_tokens_are_removed_before_use() { + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::with_limits(temp.path(), 1024, Duration::ZERO); + let owner = Uuid::new_v4(); + let metadata = store + .store_upload( + owner, + "notebook-import", + "notebook.json", + Some("application/json"), + bytes_stream([b"{}".as_slice()]), + ) + .await + .unwrap(); + + assert!(store + .open_upload(owner, &metadata.token, "notebook-import") + .await + .is_err()); + assert!(!store + .root + .join(owner.to_string()) + .join("uploads") + .join(metadata.token) + .exists()); +} + +#[tokio::test] +async fn sweeping_removes_expired_transfers_of_every_session() { + let temp = tempfile::tempdir().unwrap(); + let expired = FileTransferStore::with_limits(temp.path(), 1024, Duration::ZERO); + let fresh = FileTransferStore::with_limits(temp.path(), 1024, Duration::from_secs(60)); + let stale_owner = Uuid::new_v4(); + let live_owner = Uuid::new_v4(); + let stale = expired + .store_upload( + stale_owner, + "notebook-import", + "old.json", + None, + bytes_stream([b"{}".as_slice()]), + ) + .await + .unwrap(); + let live = fresh + .store_upload( + live_owner, + "notebook-import", + "new.json", + None, + bytes_stream([b"{}".as_slice()]), + ) + .await + .unwrap(); + + remove_expired_transfers(&fresh.root, Duration::from_secs(60)).unwrap(); + + let uploads = |owner: Uuid, token: &str| { + fresh + .root + .join(owner.to_string()) + .join("uploads") + .join(token) + }; + assert!(!uploads(stale_owner, &stale.token).exists()); + assert!(uploads(live_owner, &live.token).exists()); +} + +#[tokio::test] +async fn a_body_cut_off_by_the_router_limit_is_too_large() { + use http_body_util::{Full, Limited}; + let temp = tempfile::tempdir().unwrap(); + let store = FileTransferStore::with_limits(temp.path(), 1024, Duration::from_secs(60)); + // RequestBodyLimitLayer wraps chunked bodies the same way. + let body = axum::body::Body::new(Limited::new( + Full::new(Bytes::from_static(b"0123456789")), + 4, + )) + .into_data_stream(); + let error = store + .store_upload(Uuid::new_v4(), "notebook-import", "big.json", None, body) + .await + .unwrap_err(); + assert!(matches!(error, UploadError::TooLarge(_)), "{error}"); +} diff --git a/src-tauri/src/application/generic_exports.rs b/src-tauri/src/application/generic_exports.rs new file mode 100644 index 000000000..93d5ca8b8 --- /dev/null +++ b/src-tauri/src/application/generic_exports.rs @@ -0,0 +1,561 @@ +use super::connection_files::GeneratedFile; +use super::file_transfers::{FileTransferStore, MAX_FILE_TRANSFER_BYTES}; +use crate::ai_activity::{self, EventFilter}; +use crate::ai_notebook_export::{self, NotebookExport}; +use crate::commands::{register_abort_handle, unregister_abort_handle}; +use crate::export::{ExportCancellationState, ExportFormat}; +use crate::logger::SharedLogBuffer; +use crate::models::DatabaseSelection; +use crate::runtime::RuntimeContext; +use serde::Deserialize; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use tokio_util::io::ReaderStream; +use uuid::Uuid; + +const QUERY_EXPORT_PURPOSE: &str = "query-export"; +const LOG_EXPORT_PURPOSE: &str = "logs-export"; +const TEXT_MIME_TYPE: &str = "text/plain"; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GenericExportCommand { + ExportQuery { + connection_id: String, + query: String, + format: String, + csv_delimiter: Option, + database: Option, + query_session_id: Option, + }, + CancelExport { + connection_id: String, + }, + ExportAiActivityJson, + ExportAiActivityCsv, + ExportAiSessionAsNotebook { + session_id: String, + }, + ExportLogs, +} + +pub enum ExportDestination { + ServerPath(PathBuf), + SessionDownload(Uuid), +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &ExportCancellationState, + session_id: Option, + command: GenericExportCommand, +) -> Result { + match command { + GenericExportCommand::ExportQuery { + connection_id, + query, + format, + csv_delimiter, + database, + query_session_id, + } => { + let owner = session_id.ok_or_else(|| "A browser session is required".to_string())?; + json( + export_query( + runtime, + state, + session_id, + connection_id, + query, + ExportDestination::SessionDownload(owner), + format, + csv_delimiter, + database, + query_session_id, + ) + .await? + .ok_or_else(|| "The browser export did not create a download".to_string())?, + ) + } + GenericExportCommand::CancelExport { connection_id } => { + cancel_export(state, session_id, &connection_id)?; + Ok(serde_json::Value::Null) + } + GenericExportCommand::ExportAiActivityJson => json(generate_ai_activity_json().await?), + GenericExportCommand::ExportAiActivityCsv => json(generate_ai_activity_csv().await?), + GenericExportCommand::ExportAiSessionAsNotebook { session_id } => { + json(generate_ai_session_notebook(session_id).await?) + } + GenericExportCommand::ExportLogs => { + let owner = session_id.ok_or_else(|| "A browser session is required".to_string())?; + json( + export_logs( + runtime, + crate::runtime::bootstrap::get_log_buffer(), + ExportDestination::SessionDownload(owner), + ) + .await? + .ok_or_else(|| "The browser log export did not create a download".to_string())?, + ) + } + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn export_query( + runtime: &RuntimeContext, + state: &ExportCancellationState, + session_id: Option, + connection_id: String, + query: String, + destination: ExportDestination, + format: String, + csv_delimiter: Option, + database: Option, + query_session_id: Option, +) -> Result, String> { + let query = sanitize_query(&query); + if query.is_empty() { + return Err("Export query cannot be empty".to_string()); + } + let export_format = ExportFormat::parse(&format)?; + let delimiter = crate::export::parse_csv_delimiter(csv_delimiter.as_deref()); + let extension = export_format.extension(); + let mime_type = export_format.mime_type(); + let (driver, mut params) = + super::connections::resolve_saved_connection_params(runtime, session_id, &connection_id)?; + if let Some(database) = database { + params.database = DatabaseSelection::Single(database); + } + + let (file_path, download_owner, temporary) = match destination { + ExportDestination::ServerPath(path) => (path, None, None), + ExportDestination::SessionDownload(owner) => { + let directory = runtime.paths.data_dir().join("query-export-jobs"); + create_private_directory(&directory)?; + let path = directory.join(format!(".pending-{}.{}", Uuid::new_v4(), extension)); + let temporary = TemporaryFile::new(path.clone()); + (path, Some(owner), Some(temporary)) + } + }; + + let driver_session = query_session_id + .as_deref() + .map(|id| super::query_sessions::key(session_id, &connection_id, id)); + let runtime_for_task = runtime.clone(); + let connection_for_task = connection_id.clone(); + let task_path = file_path.clone(); + let enforce_browser_limit = download_owner.is_some(); + let task = tokio::spawn(async move { + let writer = BufWriter::new(create_private_file(&task_path)?); + let writer = if enforce_browser_limit { + ExportWriter::Limited(LimitedWriter::new(writer, MAX_FILE_TRANSFER_BYTES)) + } else { + ExportWriter::Plain(writer) + }; + let progress_runtime = runtime_for_task.clone(); + let progress_connection = connection_for_task.clone(); + crate::export::run_export( + &driver, + ¶ms, + &query, + writer, + export_format, + delimiter, + driver_session.as_deref(), + move |rows_processed| { + let payload = serde_json::json!({ + "connection_id": progress_connection, + "rows_processed": rows_processed, + }); + let _ = match session_id { + Some(owner) => { + progress_runtime + .events + .emit_to(owner, "export_progress", payload) + } + None => progress_runtime.events.emit("export_progress", payload), + }; + }, + ) + .await + }); + let mut registration = ExportRegistration::new( + state.handles.clone(), + export_key(session_id, &connection_id), + Arc::new(task.abort_handle()), + ); + let result = task.await; + registration.complete(); + match result { + Ok(result) => result?, + Err(error) if error.is_cancelled() => return Err("Export cancelled".to_string()), + Err(error) => return Err(format!("Export task failed: {error}")), + } + + let Some(owner) = download_owner else { + return Ok(None); + }; + let file = tokio::fs::File::open(&file_path) + .await + .map_err(|error| error.to_string())?; + let metadata = FileTransferStore::new(runtime.paths.data_dir()) + .store_download( + owner, + QUERY_EXPORT_PURPOSE, + &format!("result.{extension}"), + Some(mime_type), + ReaderStream::new(file), + ) + .await?; + drop(temporary); + Ok(Some(GeneratedFile::Download { + file_name: metadata.file_name, + mime_type: metadata.mime_type, + token: metadata.token, + size: metadata.size, + })) +} + +pub fn cancel_export( + state: &ExportCancellationState, + session_id: Option, + connection_id: &str, +) -> Result<(), String> { + let handles = state + .handles + .lock() + .map_err(|_| "Export cancellation state is unavailable".to_string())? + .remove(&export_key(session_id, connection_id)) + .unwrap_or_default(); + for handle in handles { + handle.abort(); + } + Ok(()) +} + +pub fn cancel_session_exports(state: &ExportCancellationState, session_id: Uuid) { + let prefix = format!("{session_id}:"); + let handles = { + let mut registered = state + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()); + let keys = registered + .keys() + .filter(|key| key.starts_with(&prefix)) + .cloned() + .collect::>(); + keys.into_iter() + .flat_map(|key| registered.remove(&key).unwrap_or_default()) + .collect::>() + }; + for handle in handles { + handle.abort(); + } +} + +pub async fn generate_ai_activity_json() -> Result { + let events = tokio::task::spawn_blocking(|| ai_activity::read_events(&EventFilter::default())) + .await + .map_err(|error| error.to_string())??; + let timezone = display_timezone(); + let mut output = String::new(); + for mut event in events { + event.timestamp = ai_activity::to_local_rfc3339(&event.timestamp, timezone.as_deref()); + output.push_str(&serde_json::to_string(&event).map_err(|error| error.to_string())?); + output.push('\n'); + } + Ok(output) +} + +pub async fn generate_ai_activity_csv() -> Result { + let events = tokio::task::spawn_blocking(|| ai_activity::read_events(&EventFilter::default())) + .await + .map_err(|error| error.to_string())??; + let mut writer = csv::Writer::from_writer(Vec::new()); + writer + .write_record([ + "id", + "session_id", + "timestamp", + "tool", + "connection_id", + "connection_name", + "database", + "query", + "query_kind", + "duration_ms", + "status", + "rows", + "error", + "client_hint", + "approval_id", + ]) + .map_err(|error| error.to_string())?; + let timezone = display_timezone(); + for event in events { + writer + .write_record([ + event.id, + event.session_id, + ai_activity::to_local_rfc3339(&event.timestamp, timezone.as_deref()), + event.tool, + event.connection_id.unwrap_or_default(), + event.connection_name.unwrap_or_default(), + event.database.unwrap_or_default(), + event.query.unwrap_or_default(), + event.query_kind.unwrap_or_default(), + event.duration_ms.to_string(), + event.status, + event.rows.map(|rows| rows.to_string()).unwrap_or_default(), + event.error.unwrap_or_default(), + event.client_hint.unwrap_or_default(), + event.approval_id.unwrap_or_default(), + ]) + .map_err(|error| error.to_string())?; + } + let bytes = writer.into_inner().map_err(|error| error.to_string())?; + String::from_utf8(bytes).map_err(|error| error.to_string()) +} + +pub async fn generate_ai_session_notebook(session_id: String) -> Result { + let timezone = display_timezone(); + tokio::task::spawn_blocking(move || { + ai_notebook_export::export_session(&session_id, timezone.as_deref()) + }) + .await + .map_err(|error| error.to_string())? +} + +pub async fn export_logs( + runtime: &RuntimeContext, + log_buffer: SharedLogBuffer, + destination: ExportDestination, +) -> Result, String> { + let (file_path, download_owner, temporary) = match destination { + ExportDestination::ServerPath(path) => (path, None, None), + ExportDestination::SessionDownload(owner) => { + let directory = runtime.paths.data_dir().join("log-export-jobs"); + create_private_directory(&directory)?; + let path = directory.join(format!(".pending-{}.log", Uuid::new_v4())); + let temporary = TemporaryFile::new(path.clone()); + (path, Some(owner), Some(temporary)) + } + }; + write_logs_to_path(&log_buffer, &file_path)?; + + let Some(owner) = download_owner else { + return Ok(None); + }; + let file = tokio::fs::File::open(&file_path) + .await + .map_err(|error| error.to_string())?; + let metadata = FileTransferStore::new(runtime.paths.data_dir()) + .store_download( + owner, + LOG_EXPORT_PURPOSE, + "tabularis-logs.log", + Some(TEXT_MIME_TYPE), + ReaderStream::new(file), + ) + .await?; + drop(temporary); + Ok(Some(GeneratedFile::Download { + file_name: metadata.file_name, + mime_type: metadata.mime_type, + token: metadata.token, + size: metadata.size, + })) +} + +pub fn write_logs_to_path(log_buffer: &SharedLogBuffer, path: &Path) -> Result<(), String> { + let entries = log_buffer + .lock() + .map_err(|_| "Log buffer is unavailable".to_string())? + .get_entries(None, None); + if entries.is_empty() { + return Err("No logs to export".to_string()); + } + let mut writer = BufWriter::new(create_private_file(path)?); + writer + .write_all(b"Tabularis Application Logs\n==========================\n\n") + .map_err(|error| format!("Failed to write log file: {error}"))?; + for entry in entries { + write!( + writer, + "[{}] [{}] {}", + entry.timestamp, + entry.level.to_uppercase(), + entry.message + ) + .map_err(|error| format!("Failed to write log file: {error}"))?; + if let Some(target) = entry.target { + write!(writer, " (target: {target})") + .map_err(|error| format!("Failed to write log file: {error}"))?; + } + writeln!(writer).map_err(|error| format!("Failed to write log file: {error}"))?; + } + writer + .flush() + .map_err(|error| format!("Failed to write log file: {error}")) +} + +fn display_timezone() -> Option { + crate::config::load_config_from_disk().display_timezone +} + +fn sanitize_query(query: &str) -> String { + query.trim().trim_end_matches(';').to_string() +} + +fn export_key(session_id: Option, connection_id: &str) -> String { + session_id.map_or_else( + || connection_id.to_string(), + |session_id| format!("{session_id}:{connection_id}"), + ) +} + +fn create_private_directory(path: &Path) -> Result<(), String> { + fs::create_dir_all(path).map_err(|error| error.to_string())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +fn create_private_file(path: &Path) -> Result { + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options + .open(path) + .map_err(|error| format!("Failed to create export file: {error}")) +} + +enum ExportWriter { + Plain(W), + Limited(LimitedWriter), +} + +impl Write for ExportWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + match self { + Self::Plain(writer) => writer.write(bytes), + Self::Limited(writer) => writer.write(bytes), + } + } + + fn flush(&mut self) -> std::io::Result<()> { + match self { + Self::Plain(writer) => writer.flush(), + Self::Limited(writer) => writer.flush(), + } + } +} + +struct LimitedWriter { + inner: W, + written: u64, + limit: u64, +} + +impl LimitedWriter { + fn new(inner: W, limit: u64) -> Self { + Self { + inner, + written: 0, + limit, + } + } +} + +impl Write for LimitedWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let next = self + .written + .checked_add(bytes.len() as u64) + .ok_or_else(|| std::io::Error::other("Export size overflow"))?; + if next > self.limit { + return Err(std::io::Error::other(format!( + "Export exceeds the {} byte browser download limit", + self.limit + ))); + } + let written = self.inner.write(bytes)?; + self.written += written as u64; + Ok(written) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +struct ExportRegistration { + handles: Arc>, + key: String, + handle: Arc, + completed: bool, +} + +impl ExportRegistration { + fn new( + handles: Arc>, + key: String, + handle: Arc, + ) -> Self { + register_abort_handle(&handles, key.clone(), handle.clone()); + Self { + handles, + key, + handle, + completed: false, + } + } + + fn complete(&mut self) { + unregister_abort_handle(&self.handles, &self.key, &self.handle); + self.completed = true; + } +} + +impl Drop for ExportRegistration { + fn drop(&mut self) { + unregister_abort_handle(&self.handles, &self.key, &self.handle); + if !self.completed { + self.handle.abort(); + } + } +} + +struct TemporaryFile(PathBuf); + +impl TemporaryFile { + fn new(path: PathBuf) -> Self { + Self(path) + } +} + +impl Drop for TemporaryFile { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "generic_exports_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/generic_exports_tests.rs b/src-tauri/src/application/generic_exports_tests.rs new file mode 100644 index 000000000..718bfda64 --- /dev/null +++ b/src-tauri/src/application/generic_exports_tests.rs @@ -0,0 +1,215 @@ +use super::*; +use crate::logger::{create_log_buffer, LogEntry}; +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use crate::runtime::RuntimeContext; +use std::sync::Arc; +use tokio::io::AsyncReadExt; + +struct NoopSecrets; + +impl RuntimeSecrets for NoopSecrets { + 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(()) + } +} + +fn fixture() -> (tempfile::TempDir, RuntimeContext) { + let temp = tempfile::tempdir().unwrap(); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoopSecrets), + ); + (temp, runtime) +} + +#[test] +fn browser_export_writer_enforces_the_transfer_limit_while_streaming() { + let mut writer = LimitedWriter::new(Vec::new(), 8); + writer.write_all(b"1234").unwrap(); + writer.write_all(b"5678").unwrap(); + let error = writer.write_all(b"9").unwrap_err(); + assert!(error.to_string().contains("8 byte browser download limit")); + assert_eq!(writer.inner, b"12345678"); +} + +#[tokio::test] +async fn large_query_exports_stream_through_disk_backed_single_use_downloads() { + crate::drivers::registry::register_driver(crate::drivers::sqlite::SqliteDriver::new()).await; + let (_temp, runtime) = fixture(); + let database_path = runtime.paths.data_dir().join("large-export.sqlite"); + File::create(&database_path).unwrap(); + let params = crate::models::ConnectionParams { + driver: "sqlite".to_string(), + database: DatabaseSelection::Single(database_path.to_string_lossy().into_owned()), + ..Default::default() + }; + crate::drivers::sqlite::execute_query( + ¶ms, + "CREATE TABLE numbers (value INTEGER PRIMARY KEY, label TEXT NOT NULL)", + None, + 1, + ) + .await + .unwrap(); + crate::drivers::sqlite::execute_query( + ¶ms, + "WITH RECURSIVE seq(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM seq WHERE value < 50000) INSERT INTO numbers SELECT value, printf('row-%08d', value) FROM seq", + None, + 1, + ) + .await + .unwrap(); + crate::persistence::save_connections_file( + &runtime.paths.connections_file(), + &crate::models::ConnectionsFile { + connections: vec![crate::models::SavedConnection { + id: "large-export".to_string(), + name: "Large export".to_string(), + params, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + }], + ..Default::default() + }, + ) + .unwrap(); + + let owner = Uuid::new_v4(); + let result = export_query( + &runtime, + &ExportCancellationState::default(), + Some(owner), + "large-export".to_string(), + "SELECT value, label FROM numbers ORDER BY value".to_string(), + ExportDestination::SessionDownload(owner), + "csv".to_string(), + None, + None, + None, + ) + .await + .unwrap() + .unwrap(); + let GeneratedFile::Download { token, size, .. } = result else { + panic!("browser query exports must use a download token"); + }; + assert!(size > 500_000, "fixture must exercise a large export"); + assert_eq!( + fs::read_dir(runtime.paths.data_dir().join("query-export-jobs")) + .unwrap() + .count(), + 0, + "the intermediate export must be removed after token creation", + ); + + let mut reader = FileTransferStore::new(runtime.paths.data_dir()) + .consume_download(owner, &token) + .await + .unwrap(); + let mut chunk = [0_u8; 8192]; + let mut streamed = 0_u64; + loop { + let read = reader.read(&mut chunk).await.unwrap(); + if read == 0 { + break; + } + streamed += read as u64; + } + assert_eq!(streamed, size); + drop(reader); + assert!(FileTransferStore::new(runtime.paths.data_dir()) + .consume_download(owner, &token) + .await + .is_err()); +} + +#[tokio::test] +async fn log_exports_stream_to_downloads_and_remove_intermediate_files() { + let (_temp, runtime) = fixture(); + let logs = create_log_buffer(10); + logs.lock().unwrap().push(LogEntry { + timestamp: "2026-08-22 00:00:00.000".to_string(), + level: "INFO".to_string(), + message: "Started".to_string(), + target: Some("fixture".to_string()), + }); + let owner = Uuid::new_v4(); + let result = export_logs(&runtime, logs, ExportDestination::SessionDownload(owner)) + .await + .unwrap() + .unwrap(); + let GeneratedFile::Download { token, .. } = result else { + panic!("browser log exports must use a download token"); + }; + assert_eq!( + fs::read_dir(runtime.paths.data_dir().join("log-export-jobs")) + .unwrap() + .count(), + 0, + ); + let mut reader = FileTransferStore::new(runtime.paths.data_dir()) + .consume_download(owner, &token) + .await + .unwrap(); + let mut content = String::new(); + reader.read_to_string(&mut content).await.unwrap(); + assert!(content.contains("[INFO] Started (target: fixture)")); +} + +#[tokio::test] +async fn interrupted_export_registrations_abort_jobs_and_remove_handles() { + let state = ExportCancellationState::default(); + let task = tokio::spawn(std::future::pending::<()>()); + let registration = ExportRegistration::new( + state.handles.clone(), + "interrupted".to_string(), + Arc::new(task.abort_handle()), + ); + drop(registration); + + assert!(task.await.unwrap_err().is_cancelled()); + assert!(state.handles.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn session_cleanup_aborts_only_the_owners_exports() { + let state = ExportCancellationState::default(); + let owner = Uuid::new_v4(); + let other = Uuid::new_v4(); + let owned_task = tokio::spawn(std::future::pending::<()>()); + let other_task = tokio::spawn(std::future::pending::<()>()); + register_abort_handle( + &state.handles, + export_key(Some(owner), "connection"), + Arc::new(owned_task.abort_handle()), + ); + register_abort_handle( + &state.handles, + export_key(Some(other), "connection"), + Arc::new(other_task.abort_handle()), + ); + + cancel_session_exports(&state, owner); + assert!(owned_task.await.unwrap_err().is_cancelled()); + assert!(!other_task.is_finished()); + other_task.abort(); +} diff --git a/src-tauri/src/application/host_settings.rs b/src-tauri/src/application/host_settings.rs new file mode 100644 index 000000000..82d8dfb85 --- /dev/null +++ b/src-tauri/src/application/host_settings.rs @@ -0,0 +1,61 @@ +//! Host-level settings shared by the desktop app and the Web UI: proxy +//! credentials kept in the OS keychain and the custom storage location. +//! +//! Paths are always paths on the machine running Tabularis. The browser RPC +//! layer confines them to the configured server file-browser roots before +//! building a [`HostSettingsCommand`]. + +use serde::Serialize; +use serde_json::Value; +use std::path::PathBuf; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostSettingsCommand { + ProxyPasswordIsSet { slot: String }, + SetProxyPassword { slot: String, password: String }, + DeleteProxyPassword { slot: String }, + GetStorageLocation, + InspectStorageLocation { path: PathBuf }, + SetStorageLocation { path: PathBuf, copy_data: bool }, + ResetStorageLocation, + GetAppDataDir, +} + +pub fn execute(command: HostSettingsCommand) -> Result { + match command { + HostSettingsCommand::ProxyPasswordIsSet { slot } => { + json(crate::proxy::proxy_password_is_set(slot)?) + } + HostSettingsCommand::SetProxyPassword { slot, password } => { + crate::proxy::set_proxy_password(slot, password)?; + Ok(Value::Null) + } + HostSettingsCommand::DeleteProxyPassword { slot } => { + crate::proxy::delete_proxy_password(slot)?; + Ok(Value::Null) + } + HostSettingsCommand::GetStorageLocation => { + json(crate::storage_location::get_storage_location()) + } + HostSettingsCommand::InspectStorageLocation { path } => json( + crate::storage_location::inspect_storage_location(path_text(path)?)?, + ), + HostSettingsCommand::SetStorageLocation { path, copy_data } => json( + crate::storage_location::set_storage_location(path_text(path)?, copy_data)?, + ), + HostSettingsCommand::ResetStorageLocation => { + json(crate::storage_location::reset_storage_location()?) + } + HostSettingsCommand::GetAppDataDir => json(crate::storage_location::get_app_data_dir()), + } +} + +fn path_text(path: PathBuf) -> Result { + path.into_os_string() + .into_string() + .map_err(|_| "The storage path is not valid UTF-8".to_string()) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} diff --git a/src-tauri/src/application/mcp_host.rs b/src-tauri/src/application/mcp_host.rs new file mode 100644 index 000000000..0c21d0a14 --- /dev/null +++ b/src-tauri/src/application/mcp_host.rs @@ -0,0 +1,270 @@ +use directories::BaseDirs; +use serde::Serialize; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; + +#[cfg(test)] +mod tests; + +/// Host-side MCP client configuration operations shared by desktop and Web UI transports. +#[derive(Clone, Debug)] +pub enum McpHostCommand { + GetStatus, + InstallConfig { client_id: String }, +} + +/// "file" means a standard mcpServers JSON file; "command" uses a client CLI. +#[derive(Clone, Debug, Serialize)] +pub struct McpClientStatus { + pub client_id: String, + pub client_name: String, + pub installed: bool, + pub config_path: Option, + pub executable_path: String, + pub client_type: String, + pub manual_command: Option, +} + +struct McpClient { + id: &'static str, + name: &'static str, + config_path: Option, + client_type: &'static str, +} + +pub async fn execute(command: McpHostCommand) -> Result { + match command { + McpHostCommand::GetStatus => serde_json::to_value(get_status().await?) + .map_err(|error| format!("Failed to serialize MCP status: {error}")), + McpHostCommand::InstallConfig { client_id } => { + serde_json::to_value(install_config(client_id).await?) + .map_err(|error| format!("Failed to serialize MCP install result: {error}")) + } + } +} + +pub async fn get_status() -> Result, String> { + tokio::task::spawn_blocking(get_status_blocking) + .await + .map_err(|error| format!("Failed to inspect MCP host configuration: {error}"))? +} + +pub async fn install_config(client_id: String) -> Result { + tokio::task::spawn_blocking(move || install_config_blocking(&client_id)) + .await + .map_err(|error| format!("Failed to update MCP host configuration: {error}"))? +} + +fn get_status_blocking() -> Result, String> { + let executable_path = std::env::current_exe() + .map_err(|error| format!("Failed to get executable path: {error}"))? + .to_string_lossy() + .to_string(); + + Ok(get_all_clients() + .into_iter() + .map(|client| { + let installed = match client.client_type { + "command" => client + .config_path + .as_ref() + .is_some_and(is_command_client_installed), + _ => client + .config_path + .as_ref() + .is_some_and(is_tabularis_in_mcp_servers), + }; + McpClientStatus { + client_id: client.id.to_string(), + client_name: client.name.to_string(), + installed, + config_path: client + .config_path + .map(|path| path.to_string_lossy().to_string()), + executable_path: executable_path.clone(), + client_type: client.client_type.to_string(), + manual_command: build_manual_command(client.id, &executable_path), + } + }) + .collect()) +} + +fn install_config_blocking(client_id: &str) -> Result { + let executable_path = std::env::current_exe() + .map_err(|error| format!("Failed to get executable path: {error}"))?; + let executable = executable_path.to_string_lossy().to_string(); + let clients = get_all_clients(); + let client = clients + .iter() + .find(|client| client.id == client_id) + .ok_or_else(|| format!("Unknown client: {client_id}"))?; + + if client.client_type == "command" { + let (program, args) = build_command_client_invocation(client.id, &executable) + .ok_or_else(|| format!("Unsupported command client: {}", client.id))?; + let manual_command = build_manual_command(client.id, &executable) + .unwrap_or_else(|| format!("{} {}", program, args.join(" "))); + let output = std::process::Command::new(&program) + .args(&args) + .output() + .map_err(|error| { + format!( + "{} CLI not found. Run manually:\n{}\n(Error: {})", + client.name, manual_command, error + ) + })?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!("{program} mcp add failed: {stderr}")); + } + + return Ok(client.name.to_string()); + } + + let config_path = client + .config_path + .as_ref() + .ok_or("Could not determine config path for this OS")?; + if let Some(parent) = config_path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + + let mut config: Value = if config_path.exists() { + let content = fs::read_to_string(config_path).map_err(|error| error.to_string())?; + serde_json::from_str(&content).unwrap_or_else(|_| json!({})) + } else { + json!({}) + }; + if config.get("mcpServers").is_none() { + config["mcpServers"] = json!({}); + } + config["mcpServers"]["tabularis"] = json!({ + "command": executable, + "args": ["--mcp"] + }); + + let content = serde_json::to_string_pretty(&config).map_err(|error| error.to_string())?; + fs::write(config_path, content).map_err(|error| error.to_string())?; + Ok(client.name.to_string()) +} + +fn get_all_clients() -> Vec { + let base = BaseDirs::new(); + let claude_path = base.as_ref().map(|base| { + base.config_dir() + .join("Claude") + .join("claude_desktop_config.json") + }); + + vec![ + McpClient { + id: "claude", + name: "Claude Desktop", + config_path: claude_path, + client_type: "file", + }, + McpClient { + id: "claude_code", + name: "Claude Code", + config_path: base + .as_ref() + .map(|base| base.home_dir().join(".claude.json")), + client_type: "command", + }, + McpClient { + id: "codex", + name: "Codex", + config_path: base + .as_ref() + .map(|base| base.home_dir().join(".codex/config.toml")), + client_type: "command", + }, + McpClient { + id: "cursor", + name: "Cursor", + config_path: base + .as_ref() + .map(|base| base.home_dir().join(".cursor/mcp.json")), + client_type: "file", + }, + McpClient { + id: "windsurf", + name: "Windsurf", + config_path: base + .as_ref() + .map(|base| base.home_dir().join(".codeium/windsurf/mcp_config.json")), + client_type: "file", + }, + McpClient { + id: "antigravity", + name: "Antigravity", + config_path: base + .as_ref() + .map(|base| base.home_dir().join(".gemini/antigravity/mcp_config.json")), + client_type: "file", + }, + ] +} + +fn is_tabularis_in_mcp_servers(path: &PathBuf) -> bool { + if !path.exists() { + return false; + } + fs::read_to_string(path) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .and_then(|config| config.get("mcpServers").cloned()) + .is_some_and(|servers| servers.get("tabularis").is_some()) +} + +fn is_command_client_installed(path: &PathBuf) -> bool { + if !path.exists() { + return false; + } + fs::read_to_string(path) + .map(|content| { + content.contains("\"tabularis\"") + || content.contains("[mcp_servers.tabularis]") + || content.contains("[mcp_servers.\"tabularis\"]") + }) + .unwrap_or(false) +} + +fn build_command_client_invocation( + client_id: &str, + executable: &str, +) -> Option<(String, Vec)> { + match client_id { + "claude_code" => Some(( + "claude".to_string(), + vec![ + "mcp", + "add", + "--scope", + "user", + "tabularis", + executable, + "--", + "--mcp", + ] + .into_iter() + .map(str::to_string) + .collect(), + )), + "codex" => Some(( + "codex".to_string(), + vec!["mcp", "add", "tabularis", "--", executable, "--mcp"] + .into_iter() + .map(str::to_string) + .collect(), + )), + _ => None, + } +} + +fn build_manual_command(client_id: &str, executable: &str) -> Option { + let (program, args) = build_command_client_invocation(client_id, executable)?; + Some(format!("{} {}", program, args.join(" "))) +} diff --git a/src-tauri/src/application/mcp_host/tests.rs b/src-tauri/src/application/mcp_host/tests.rs new file mode 100644 index 000000000..39096c479 --- /dev/null +++ b/src-tauri/src/application/mcp_host/tests.rs @@ -0,0 +1,79 @@ +use super::*; + +#[test] +fn lists_codex_as_command_client() { + let clients = get_all_clients(); + let codex = clients + .iter() + .find(|client| client.id == "codex") + .expect("Codex should be listed as an MCP client"); + + assert_eq!(codex.name, "Codex"); + assert_eq!(codex.client_type, "command"); + assert!( + codex + .config_path + .as_ref() + .is_some_and(|path| path.ends_with(".codex/config.toml")), + "Codex config path should point to ~/.codex/config.toml" + ); +} + +#[test] +fn builds_codex_manual_command() { + assert_eq!( + build_manual_command("codex", "/Applications/Tabularis.app/tabularis").as_deref(), + Some("codex mcp add tabularis -- /Applications/Tabularis.app/tabularis --mcp") + ); +} + +#[test] +fn builds_claude_code_manual_command() { + assert_eq!( + build_manual_command("claude_code", "/Applications/Tabularis.app/tabularis").as_deref(), + Some( + "claude mcp add --scope user tabularis /Applications/Tabularis.app/tabularis -- --mcp" + ) + ); +} + +#[test] +fn detects_codex_toml_config() { + let temp_dir = tempfile::tempdir().unwrap(); + let config_path = temp_dir.path().join("config.toml"); + fs::write( + &config_path, + r#" +[mcp_servers.tabularis] +command = "/Applications/Tabularis.app/tabularis" +args = ["--mcp"] +"#, + ) + .unwrap(); + + assert!(is_command_client_installed(&config_path)); +} + +#[test] +fn rejects_unknown_host_client_without_writing_configuration() { + let error = install_config_blocking("unknown-client") + .expect_err("unknown MCP clients must be rejected"); + + assert_eq!(error, "Unknown client: unknown-client"); +} + +#[test] +fn claude_desktop_config_is_directly_under_the_os_claude_directory() { + let clients = get_all_clients(); + let claude = clients.iter().find(|client| client.id == "claude").unwrap(); + assert_eq!( + claude.config_path, + Some( + BaseDirs::new() + .unwrap() + .config_dir() + .join("Claude") + .join("claude_desktop_config.json") + ) + ); +} diff --git a/src-tauri/src/application/metadata.rs b/src-tauri/src/application/metadata.rs new file mode 100644 index 000000000..859e35e27 --- /dev/null +++ b/src-tauri/src/application/metadata.rs @@ -0,0 +1,610 @@ +use crate::drivers::driver_trait::DatabaseDriver; +use crate::models::{ + ConnectionParams, ForeignKey, Index, RoutineInfo, TableColumn, TableInfo, TableSchema, + TriggerInfo, ViewInfo, +}; +use crate::runtime::RuntimeContext; +use serde::Serialize; +use serde_json::Value; +use std::sync::Arc; +use uuid::Uuid; + +#[derive(Debug)] +pub enum MetadataCommand { + GetConnectionMetadata { + connection_id: String, + }, + GetAvailableDatabases { + connection_id: String, + }, + GetSchemas { + connection_id: String, + database: Option, + }, + GetTables { + connection_id: String, + schema: Option, + database: Option, + }, + GetColumns { + connection_id: String, + table_name: String, + schema: Option, + database: Option, + }, + GetForeignKeys { + connection_id: String, + table_name: String, + schema: Option, + database: Option, + }, + GetIndexes { + connection_id: String, + table_name: String, + schema: Option, + database: Option, + }, + GetViews { + connection_id: String, + schema: Option, + database: Option, + }, + GetViewColumns { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + GetMaterializedViews { + connection_id: String, + schema: Option, + database: Option, + }, + GetMaterializedViewColumns { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + GetMaterializedViewDefinition { + connection_id: String, + view_name: String, + schema: Option, + database: Option, + }, + GetRoutines { + connection_id: String, + schema: Option, + database: Option, + }, + GetTriggers { + connection_id: String, + schema: Option, + database: Option, + }, + GetSchemaSnapshot { + connection_id: String, + schema: Option, + database: Option, + }, + GetSelectedSchemas { + connection_id: String, + database: Option, + }, + SetSelectedSchemas { + connection_id: String, + schemas: Vec, + database: Option, + }, + GetSchemaPreference { + connection_id: String, + database: Option, + }, + SetSchemaPreference { + connection_id: String, + schema: String, + database: Option, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + session_id: Option, + command: MetadataCommand, +) -> Result { + match command { + MetadataCommand::GetConnectionMetadata { connection_id } => { + json(get_connection_metadata(runtime, session_id, &connection_id).await?) + } + MetadataCommand::GetAvailableDatabases { connection_id } => { + json(get_available_databases(runtime, session_id, &connection_id).await?) + } + MetadataCommand::GetSchemas { + connection_id, + database, + } => json(get_schemas(runtime, session_id, &connection_id, database).await?), + MetadataCommand::GetTables { + connection_id, + schema, + database, + } => json(get_tables(runtime, session_id, &connection_id, schema, database).await?), + MetadataCommand::GetColumns { + connection_id, + table_name, + schema, + database, + } => json( + get_columns( + runtime, + session_id, + &connection_id, + table_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetForeignKeys { + connection_id, + table_name, + schema, + database, + } => json( + get_foreign_keys( + runtime, + session_id, + &connection_id, + table_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetIndexes { + connection_id, + table_name, + schema, + database, + } => json( + get_indexes( + runtime, + session_id, + &connection_id, + table_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetViews { + connection_id, + schema, + database, + } => json(get_views(runtime, session_id, &connection_id, schema, database).await?), + MetadataCommand::GetViewColumns { + connection_id, + view_name, + schema, + database, + } => json( + get_view_columns( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetMaterializedViews { + connection_id, + schema, + database, + } => json( + get_materialized_views(runtime, session_id, &connection_id, schema, database).await?, + ), + MetadataCommand::GetMaterializedViewColumns { + connection_id, + view_name, + schema, + database, + } => json( + get_materialized_view_columns( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetMaterializedViewDefinition { + connection_id, + view_name, + schema, + database, + } => json( + get_materialized_view_definition( + runtime, + session_id, + &connection_id, + view_name, + schema, + database, + ) + .await?, + ), + MetadataCommand::GetRoutines { + connection_id, + schema, + database, + } => json(get_routines(runtime, session_id, &connection_id, schema, database).await?), + MetadataCommand::GetTriggers { + connection_id, + schema, + database, + } => json(get_triggers(runtime, session_id, &connection_id, schema, database).await?), + MetadataCommand::GetSchemaSnapshot { + connection_id, + schema, + database, + } => { + json(get_schema_snapshot(runtime, session_id, &connection_id, schema, database).await?) + } + MetadataCommand::GetSelectedSchemas { + connection_id, + database, + } => json(get_selected_schemas(runtime, &connection_id, database)), + MetadataCommand::SetSelectedSchemas { + connection_id, + schemas, + database, + } => { + set_selected_schemas(runtime, connection_id, schemas, database)?; + Ok(Value::Null) + } + MetadataCommand::GetSchemaPreference { + connection_id, + database, + } => json(get_schema_preference(runtime, &connection_id, database)), + MetadataCommand::SetSchemaPreference { + connection_id, + schema, + database, + } => { + set_schema_preference(runtime, connection_id, schema, database)?; + Ok(Value::Null) + } + } +} + +async fn driver_and_params( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + database: Option, +) -> Result<(Arc, ConnectionParams), String> { + let runtime_for_resolution = runtime.clone(); + let connection_id_for_resolution = connection_id.to_string(); + let (_driver_id, mut params) = tokio::task::spawn_blocking(move || { + crate::application::connections::resolve_saved_connection_params( + &runtime_for_resolution, + session_id, + &connection_id_for_resolution, + ) + }) + .await + .map_err(|error| error.to_string())??; + if let Some(db) = database.filter(|db| !db.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(db); + } + let driver = crate::drivers::registry::get_connection_driver(¶ms).await?; + Ok((driver, params)) +} + +/// Capabilities and type catalog reported by a connection's driver. Only +/// plugins that discover them per connection answer; static drivers return +/// `None` so the frontend keeps using their manifest. +pub async fn get_connection_metadata( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, +) -> Result, String> { + let driver_id = + crate::application::connections::saved_connection_driver(runtime, connection_id)?; + let driver = crate::drivers::registry::get_driver(&driver_id) + .await + .ok_or_else(|| format!("Unsupported driver: {driver_id}"))?; + if !driver.has_connection_metadata() { + return Ok(None); + } + let (driver, _params) = driver_and_params(runtime, session_id, connection_id, None).await?; + Ok(Some( + crate::plugins::connection_metadata::ConnectionMetadata { + capabilities: driver.manifest().capabilities.clone(), + data_types: driver.get_data_types(), + type_mappings: driver.manifest().type_mappings.clone(), + }, + )) +} + +pub async fn get_ai_schema_context( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).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, + )) +} + +pub async fn get_available_databases( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, None).await?; + driver.get_databases(¶ms).await +} + +pub async fn get_schemas( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_schemas(¶ms).await +} + +pub async fn get_tables( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_tables(¶ms, schema.as_deref()).await +} + +pub async fn get_columns( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_columns(¶ms, &table_name, schema.as_deref()) + .await +} + +pub async fn get_foreign_keys( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_foreign_keys(¶ms, &table_name, schema.as_deref()) + .await +} + +pub async fn get_indexes( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table_name: String, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_indexes(¶ms, &table_name, schema.as_deref()) + .await +} + +pub async fn get_views( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_views(¶ms, schema.as_deref()).await +} + +pub async fn get_view_columns( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_view_columns(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn get_materialized_views( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_materialized_views(¶ms, schema.as_deref()) + .await +} + +pub async fn get_materialized_view_columns( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_materialized_view_columns(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn get_materialized_view_definition( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + view_name: String, + schema: Option, + database: Option, +) -> Result { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver + .get_materialized_view_definition(¶ms, &view_name, schema.as_deref()) + .await +} + +pub async fn get_routines( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_routines(¶ms, schema.as_deref()).await +} + +pub async fn get_triggers( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_triggers(¶ms, schema.as_deref()).await +} + +pub async fn get_schema_snapshot( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + schema: Option, + database: Option, +) -> Result, String> { + let (driver, params) = driver_and_params(runtime, session_id, connection_id, database).await?; + + driver.get_schema_snapshot(¶ms, schema.as_deref()).await +} + +pub fn get_selected_schemas( + runtime: &RuntimeContext, + connection_id: &str, + database: Option, +) -> Vec { + load_config(runtime) + .selected_schemas + .and_then(|schemas| { + schemas + .get(&crate::config::schema_storage_key( + connection_id, + database.as_deref(), + )) + .cloned() + }) + .unwrap_or_default() +} + +pub fn set_selected_schemas( + runtime: &RuntimeContext, + connection_id: String, + schemas: Vec, + database: Option, +) -> Result<(), String> { + crate::application::persistence::set_selected_schemas( + runtime, + crate::config::schema_storage_key(&connection_id, database.as_deref()), + schemas, + ) +} + +pub fn get_schema_preference( + runtime: &RuntimeContext, + connection_id: &str, + database: Option, +) -> Option { + load_config(runtime) + .schema_preferences + .and_then(|preferences| { + crate::config::resolve_schema_preference( + &preferences, + connection_id, + database.as_deref(), + ) + }) +} + +pub fn set_schema_preference( + runtime: &RuntimeContext, + connection_id: String, + schema: String, + database: Option, +) -> Result<(), String> { + crate::application::persistence::set_schema_preference( + runtime, + crate::config::schema_storage_key(&connection_id, database.as_deref()), + schema, + ) +} + +fn load_config(runtime: &RuntimeContext) -> crate::config::AppConfig { + crate::application::persistence::load_config(runtime) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "metadata_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/metadata_tests.rs b/src-tauri/src/application/metadata_tests.rs new file mode 100644 index 000000000..aa44f1ea1 --- /dev/null +++ b/src-tauri/src/application/metadata_tests.rs @@ -0,0 +1,138 @@ +use super::*; +use crate::runtime::{ + events::NoopRuntimeEvents, paths::FixedRuntimePaths, secrets::RuntimeSecrets, +}; +use std::fs; + +#[derive(Default)] +struct NoopSecrets; + +impl RuntimeSecrets for NoopSecrets { + 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(()) + } +} + +fn runtime(root: &std::path::Path) -> RuntimeContext { + RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + root.to_path_buf(), + root.to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoopSecrets), + ) +} + +#[test] +fn persists_and_clears_selected_schemas_without_losing_other_settings() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + fs::write( + temp.path().join("config.json"), + serde_json::json!({ "theme": "light" }).to_string(), + ) + .unwrap(); + + set_selected_schemas( + &runtime, + "connection-1".to_string(), + vec!["public".to_string(), "analytics".to_string()], + None, + ) + .unwrap(); + assert_eq!( + get_selected_schemas(&runtime, "connection-1", None), + vec!["public", "analytics"] + ); + + set_selected_schemas(&runtime, "connection-1".to_string(), Vec::new(), None).unwrap(); + assert!(get_selected_schemas(&runtime, "connection-1", None).is_empty()); + assert_eq!(load_config(&runtime).theme.as_deref(), Some("light")); +} + +#[test] +fn persists_schema_preferences_per_connection() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + + set_schema_preference( + &runtime, + "connection-1".to_string(), + "public".to_string(), + None, + ) + .unwrap(); + set_schema_preference( + &runtime, + "connection-2".to_string(), + "analytics".to_string(), + None, + ) + .unwrap(); + + assert_eq!( + get_schema_preference(&runtime, "connection-1", None).as_deref(), + Some("public") + ); + assert_eq!( + get_schema_preference(&runtime, "connection-2", None).as_deref(), + Some("analytics") + ); +} + +#[test] +fn schema_selection_and_preferences_are_scoped_to_database() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + set_schema_preference(&runtime, "connection".into(), "legacy".into(), None).unwrap(); + assert_eq!( + get_schema_preference(&runtime, "connection", Some("one".into())), + Some("legacy".into()) + ); + set_schema_preference( + &runtime, + "connection".into(), + "analytics".into(), + Some("one".into()), + ) + .unwrap(); + assert_eq!( + get_schema_preference(&runtime, "connection", Some("one".into())), + Some("analytics".into()) + ); + assert_eq!( + get_schema_preference(&runtime, "connection", Some("two".into())), + Some("legacy".into()) + ); + set_selected_schemas( + &runtime, + "connection".into(), + vec!["public".into()], + Some("one".into()), + ) + .unwrap(); + set_selected_schemas( + &runtime, + "connection".into(), + vec!["reporting".into()], + Some("two".into()), + ) + .unwrap(); + assert_eq!( + get_selected_schemas(&runtime, "connection", Some("one".into())), + vec!["public"] + ); + assert_eq!( + get_selected_schemas(&runtime, "connection", Some("two".into())), + vec!["reporting"] + ); +} diff --git a/src-tauri/src/application/mod.rs b/src-tauri/src/application/mod.rs new file mode 100644 index 000000000..c0a282438 --- /dev/null +++ b/src-tauri/src/application/mod.rs @@ -0,0 +1,30 @@ +pub mod ai; +pub mod api; +pub mod connection_files; +pub mod connections; +pub mod database_objects; +pub mod database_transfers; +pub mod file_transfers; +pub mod generic_exports; +pub mod host_settings; +pub mod mcp_host; +pub mod metadata; +pub mod notebooks; +pub mod operations; +pub mod persistence; +pub mod plugin_assets; +pub mod plugins; +pub mod productivity; +#[cfg(test)] +mod productivity_tests; +pub mod queries; +pub mod query_sessions; +pub mod records; +pub mod themes; +pub mod tunnels; +pub mod ui_state; + +pub use api::{ + ApplicationApi, ApplicationError, ApplicationRequestContext, AuthorizationLevel, + RuntimeApplicationApi, +}; diff --git a/src-tauri/src/application/notebooks.rs b/src-tauri/src/application/notebooks.rs new file mode 100644 index 000000000..0f759db59 --- /dev/null +++ b/src-tauri/src/application/notebooks.rs @@ -0,0 +1,254 @@ +use super::productivity::atomic_write; +use chrono::{DateTime, Utc}; +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; + +const NOTEBOOKS_DIR: &str = "notebooks"; +const NOTEBOOK_EXTENSION: &str = ".tabularis-notebook"; + +static NOTEBOOK_STORAGE_LOCK: Lazy> = Lazy::new(|| Mutex::new(())); + +#[cfg(test)] +#[path = "notebooks/tests.rs"] +mod tests; + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct NotebookMetadata { + pub id: String, + pub title: String, + pub created_at: Option, + pub updated_at: Option, +} + +#[derive(Debug)] +pub enum NotebookCommand { + Create { + connection_id: String, + notebook_id: String, + content: String, + }, + Save { + connection_id: String, + notebook_id: String, + content: String, + }, + Load { + connection_id: String, + notebook_id: String, + }, + Delete { + connection_id: String, + notebook_id: String, + }, + Rename { + connection_id: String, + notebook_id: String, + title: String, + }, + List { + connection_id: String, + }, +} + +pub fn execute(config_dir: &Path, command: NotebookCommand) -> Result { + let _guard = NOTEBOOK_STORAGE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let root = config_dir.join(NOTEBOOKS_DIR); + + match command { + NotebookCommand::Create { + connection_id, + notebook_id, + content, + } + | NotebookCommand::Save { + connection_id, + notebook_id, + content, + } => { + write_in(&root, &connection_id, ¬ebook_id, &content)?; + Ok(Value::Null) + } + NotebookCommand::Load { + connection_id, + notebook_id, + } => json(load_in(&root, &connection_id, ¬ebook_id)?), + NotebookCommand::Delete { + connection_id, + notebook_id, + } => { + delete_in(&root, &connection_id, ¬ebook_id)?; + Ok(Value::Null) + } + NotebookCommand::Rename { + connection_id, + notebook_id, + title, + } => { + rename_in(&root, &connection_id, ¬ebook_id, &title)?; + Ok(Value::Null) + } + NotebookCommand::List { connection_id } => json(list_in(&root, &connection_id)?), + } +} + +fn validate_id(id: &str) -> Result<(), String> { + if id.is_empty() || id.contains('/') || id.contains('\\') || id.contains("..") { + return Err(format!("Invalid id: {id}")); + } + Ok(()) +} + +fn connection_dir(root: &Path, connection_id: &str) -> Result { + validate_id(connection_id)?; + Ok(root.join(connection_id)) +} + +fn notebook_path(root: &Path, connection_id: &str, notebook_id: &str) -> Result { + validate_id(notebook_id)?; + let dir = connection_dir(root, connection_id)?; + Ok(dir.join(format!("{notebook_id}{NOTEBOOK_EXTENSION}"))) +} + +fn legacy_notebook_path(root: &Path, notebook_id: &str) -> Result { + validate_id(notebook_id)?; + Ok(root.join(format!("{notebook_id}{NOTEBOOK_EXTENSION}"))) +} + +fn write_in( + root: &Path, + connection_id: &str, + notebook_id: &str, + content: &str, +) -> Result<(), String> { + let path = notebook_path(root, connection_id, notebook_id)?; + atomic_write(&path, content.as_bytes()) + .map_err(|error| format!("Failed to write notebook: {error}")) +} + +fn load_in(root: &Path, connection_id: &str, notebook_id: &str) -> Result, String> { + let path = notebook_path(root, connection_id, notebook_id)?; + if path.exists() { + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read notebook: {error}"))?; + return Ok(Some(content)); + } + + let legacy = legacy_notebook_path(root, notebook_id)?; + if legacy.exists() { + let content = fs::read_to_string(&legacy) + .map_err(|error| format!("Failed to read notebook: {error}"))?; + let directory = connection_dir(root, connection_id)?; + fs::create_dir_all(&directory) + .map_err(|error| format!("Failed to create notebooks directory: {error}"))?; + if fs::rename(&legacy, &path).is_err() { + atomic_write(&path, content.as_bytes()) + .map_err(|error| format!("Failed to migrate notebook: {error}"))?; + let _ = fs::remove_file(&legacy); + } + return Ok(Some(content)); + } + + Ok(None) +} + +fn delete_in(root: &Path, connection_id: &str, notebook_id: &str) -> Result<(), String> { + let path = notebook_path(root, connection_id, notebook_id)?; + if path.exists() { + fs::remove_file(&path).map_err(|error| format!("Failed to delete notebook: {error}"))?; + } + if let Ok(legacy) = legacy_notebook_path(root, notebook_id) { + if legacy.exists() { + let _ = fs::remove_file(&legacy); + } + } + Ok(()) +} + +fn rename_in( + root: &Path, + connection_id: &str, + notebook_id: &str, + title: &str, +) -> Result<(), String> { + let path = notebook_path(root, connection_id, notebook_id)?; + if !path.exists() { + return Err(format!("Notebook not found: {notebook_id}")); + } + let content = + fs::read_to_string(&path).map_err(|error| format!("Failed to read notebook: {error}"))?; + let mut value: Value = serde_json::from_str(&content) + .map_err(|error| format!("Invalid notebook file: {error}"))?; + let object = value + .as_object_mut() + .ok_or_else(|| "Notebook file is not a JSON object".to_string())?; + object.insert("title".to_string(), Value::String(title.to_string())); + let serialized = serde_json::to_vec_pretty(&value) + .map_err(|error| format!("Failed to serialize notebook: {error}"))?; + atomic_write(&path, &serialized).map_err(|error| format!("Failed to save notebook: {error}")) +} + +fn list_in(root: &Path, connection_id: &str) -> Result, String> { + let directory = connection_dir(root, connection_id)?; + if !directory.exists() { + return Ok(Vec::new()); + } + + let entries = fs::read_dir(&directory) + .map_err(|error| format!("Failed to read notebooks directory: {error}"))?; + let mut notebooks = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + let id = match path.file_name().and_then(|name| name.to_str()) { + Some(name) if name.ends_with(NOTEBOOK_EXTENSION) => { + name.trim_end_matches(NOTEBOOK_EXTENSION).to_string() + } + _ => continue, + }; + let content = match fs::read_to_string(&path) { + Ok(content) => content, + Err(_) => continue, + }; + let value: Value = match serde_json::from_str(&content) { + Ok(value) => value, + Err(_) => continue, + }; + let title = value + .get("title") + .and_then(Value::as_str) + .unwrap_or("Notebook") + .to_string(); + let created_at = value + .get("createdAt") + .and_then(Value::as_str) + .map(str::to_string); + let updated_at = entry + .metadata() + .ok() + .and_then(|metadata| metadata.modified().ok()) + .map(system_time_to_rfc3339); + notebooks.push(NotebookMetadata { + id, + title, + created_at, + updated_at, + }); + } + Ok(notebooks) +} + +fn system_time_to_rfc3339(time: SystemTime) -> String { + let datetime: DateTime = time.into(); + datetime.to_rfc3339() +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} diff --git a/src-tauri/src/application/notebooks/tests.rs b/src-tauri/src/application/notebooks/tests.rs new file mode 100644 index 000000000..6487db68b --- /dev/null +++ b/src-tauri/src/application/notebooks/tests.rs @@ -0,0 +1,184 @@ +use super::*; +use tempfile::TempDir; + +const CONNECTION_ID: &str = "conn_1"; + +fn sample(title: &str) -> String { + format!( + r#"{{"version":2,"title":"{title}","createdAt":"2026-01-01T00:00:00Z","cells":[{{"type":"sql","content":"SELECT 1"}}]}}"# + ) +} + +#[test] +fn write_then_load_round_trips() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("Hello")).unwrap(); + let loaded = load_in(root, CONNECTION_ID, "nb_a").unwrap(); + assert_eq!(loaded.as_deref(), Some(sample("Hello").as_str())); +} + +#[test] +fn write_creates_per_connection_directory() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("Hello")).unwrap(); + assert!(root + .join(CONNECTION_ID) + .join("nb_a.tabularis-notebook") + .exists()); +} + +#[test] +fn load_missing_returns_none() { + let temporary = TempDir::new().unwrap(); + assert!(load_in(temporary.path(), CONNECTION_ID, "nope") + .unwrap() + .is_none()); +} + +#[test] +fn list_returns_metadata() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("First")).unwrap(); + write_in(root, CONNECTION_ID, "nb_b", &sample("Second")).unwrap(); + + let mut list = list_in(root, CONNECTION_ID).unwrap(); + list.sort_by(|left, right| left.id.cmp(&right.id)); + + assert_eq!(list.len(), 2); + assert_eq!(list[0].id, "nb_a"); + assert_eq!(list[0].title, "First"); + assert_eq!(list[0].created_at.as_deref(), Some("2026-01-01T00:00:00Z")); + assert!(list[0].updated_at.is_some()); + assert_eq!(list[1].id, "nb_b"); + assert_eq!(list[1].title, "Second"); +} + +#[test] +fn list_missing_connection_is_empty() { + let temporary = TempDir::new().unwrap(); + assert!(list_in(temporary.path(), "ghost").unwrap().is_empty()); +} + +#[test] +fn list_ignores_unrelated_and_malformed_files() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + let directory = root.join(CONNECTION_ID); + fs::create_dir_all(&directory).unwrap(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("Valid")).unwrap(); + fs::write(directory.join("notes.txt"), "ignore me").unwrap(); + fs::write(directory.join("broken.tabularis-notebook"), "{not json").unwrap(); + + let list = list_in(root, CONNECTION_ID).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].id, "nb_a"); +} + +#[test] +fn rename_updates_title_and_preserves_cells() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("Old")).unwrap(); + rename_in(root, CONNECTION_ID, "nb_a", "New Name").unwrap(); + + let loaded = load_in(root, CONNECTION_ID, "nb_a").unwrap().unwrap(); + let value: Value = serde_json::from_str(&loaded).unwrap(); + assert_eq!(value["title"], "New Name"); + assert_eq!(value["cells"][0]["content"], "SELECT 1"); + assert_eq!(value["version"], 2); +} + +#[test] +fn rename_missing_notebook_errors() { + let temporary = TempDir::new().unwrap(); + assert!(rename_in(temporary.path(), CONNECTION_ID, "nope", "x").is_err()); +} + +#[test] +fn delete_removes_file() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + write_in(root, CONNECTION_ID, "nb_a", &sample("Bye")).unwrap(); + delete_in(root, CONNECTION_ID, "nb_a").unwrap(); + + assert!(load_in(root, CONNECTION_ID, "nb_a").unwrap().is_none()); +} + +#[test] +fn delete_missing_is_ok() { + let temporary = TempDir::new().unwrap(); + assert!(delete_in(temporary.path(), CONNECTION_ID, "nope").is_ok()); +} + +#[test] +fn legacy_flat_notebook_is_migrated_on_load() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + fs::create_dir_all(root).unwrap(); + + let legacy = root.join("nb_legacy.tabularis-notebook"); + fs::write(&legacy, sample("Legacy")).unwrap(); + + let loaded = load_in(root, CONNECTION_ID, "nb_legacy").unwrap(); + assert_eq!(loaded.as_deref(), Some(sample("Legacy").as_str())); + assert!(root + .join(CONNECTION_ID) + .join("nb_legacy.tabularis-notebook") + .exists()); + assert!(!legacy.exists()); + + let list = list_in(root, CONNECTION_ID).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].id, "nb_legacy"); +} + +#[test] +fn ids_with_path_traversal_are_rejected() { + let temporary = TempDir::new().unwrap(); + let root = temporary.path(); + + assert!(load_in(root, CONNECTION_ID, "../escape").is_err()); + assert!(load_in(root, "../escape", "nb_a").is_err()); + assert!(write_in(root, CONNECTION_ID, "a/b", "{}").is_err()); + assert!(rename_in(root, "..", "nb_a", "x").is_err()); +} + +#[test] +fn command_service_scopes_storage_to_config_directory() { + let temporary = TempDir::new().unwrap(); + let content = sample("Shared service"); + execute( + temporary.path(), + NotebookCommand::Create { + connection_id: CONNECTION_ID.to_string(), + notebook_id: "nb_shared".to_string(), + content: content.clone(), + }, + ) + .unwrap(); + + let loaded = execute( + temporary.path(), + NotebookCommand::Load { + connection_id: CONNECTION_ID.to_string(), + notebook_id: "nb_shared".to_string(), + }, + ) + .unwrap(); + assert_eq!(loaded, Value::String(content)); + assert!(temporary + .path() + .join(NOTEBOOKS_DIR) + .join(CONNECTION_ID) + .join("nb_shared.tabularis-notebook") + .exists()); +} diff --git a/src-tauri/src/application/operations.rs b/src-tauri/src/application/operations.rs new file mode 100644 index 000000000..a1b07b328 --- /dev/null +++ b/src-tauri/src/application/operations.rs @@ -0,0 +1,376 @@ +use crate::drivers::registry; +use crate::logger::{LogEntry, SharedLogBuffer}; +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashSet; +use std::sync::Mutex; +use sysinfo::{get_current_pid, Pid, ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System}; + +static SYSTEM: Lazy> = Lazy::new(|| { + Mutex::new(System::new_with_specifics( + RefreshKind::new().with_processes( + ProcessRefreshKind::new() + .with_cpu() + .with_disk_usage() + .with_memory(), + ), + )) +}); + +#[derive(Debug)] +pub enum OperationalCommand { + LogFrontendEvent { level: String, message: String }, + GetLogs(GetLogsRequest), + ClearLogs, + GetLogSettings, + SetLogEnabled { enabled: bool }, + SetLogMaxSize { max_size: usize }, + GetProcessList, + GetSystemStats, + GetTabularisChildren, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct GetLogsRequest { + pub limit: Option, + pub level_filter: Option, +} + +#[derive(Debug, Serialize)] +pub struct LogSettings { + pub enabled: bool, + pub max_size: usize, + pub current_count: usize, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ChildProcessInfo { + pub pid: u32, + pub cpu_percent: f32, + pub memory_bytes: u64, + pub disk_read_bytes: u64, + pub disk_write_bytes: u64, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ProcessInfo { + pub plugin_id: String, + pub plugin_name: String, + pub pid: Option, + pub cpu_percent: f32, + pub memory_bytes: u64, + pub disk_read_bytes: u64, + pub disk_write_bytes: u64, + pub status: String, + pub children: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct TabularisChildProcess { + pub pid: u32, + pub name: String, + pub cpu_percent: f32, + pub memory_bytes: u64, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct TabularisSelfStats { + pub pid: u32, + pub self_memory_bytes: u64, + pub total_memory_bytes: u64, + pub cpu_percent: f32, + pub disk_read_bytes: u64, + pub disk_write_bytes: u64, + pub child_count: usize, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct SystemStats { + pub cpu_percent: f32, + pub memory_used: u64, + pub memory_total: u64, + pub disk_read_bytes: u64, + pub disk_write_bytes: u64, + pub process_count: usize, + pub tabularis: Option, +} + +pub async fn execute(command: OperationalCommand) -> Result { + match command { + OperationalCommand::LogFrontendEvent { level, message } => { + crate::log_commands::log_frontend_event(level, message); + Ok(Value::Null) + } + OperationalCommand::GetLogs(request) => json(get_logs(&log_buffer(), request)), + OperationalCommand::ClearLogs => { + clear_logs(&log_buffer())?; + Ok(Value::Null) + } + OperationalCommand::GetLogSettings => json(get_log_settings(&log_buffer())), + OperationalCommand::SetLogEnabled { enabled } => { + set_log_enabled(&log_buffer(), enabled)?; + Ok(Value::Null) + } + OperationalCommand::SetLogMaxSize { max_size } => { + set_log_max_size(&log_buffer(), max_size)?; + Ok(Value::Null) + } + OperationalCommand::GetProcessList => json(get_process_list().await?), + OperationalCommand::GetSystemStats => json(get_system_stats().await?), + OperationalCommand::GetTabularisChildren => json(get_tabularis_children().await?), + } +} + +fn log_buffer() -> SharedLogBuffer { + crate::runtime::bootstrap::get_log_buffer() +} + +pub fn get_logs(log_buffer: &SharedLogBuffer, request: GetLogsRequest) -> Vec { + let entries = { + let buffer = log_buffer.lock().unwrap_or_else(|error| error.into_inner()); + buffer.get_entries(request.limit, request.level_filter) + }; + log::trace!("Returning {} log entries", entries.len()); + entries +} + +pub fn clear_logs(log_buffer: &SharedLogBuffer) -> Result<(), String> { + let mut buffer = log_buffer + .lock() + .map_err(|_| "Log buffer is unavailable".to_string())?; + buffer.clear(); + Ok(()) +} + +pub fn get_log_settings(log_buffer: &SharedLogBuffer) -> LogSettings { + let buffer = log_buffer.lock().unwrap_or_else(|error| error.into_inner()); + LogSettings { + enabled: buffer.is_enabled(), + max_size: buffer.get_max_size(), + current_count: buffer.get_entries(None, None).len(), + } +} + +pub fn set_log_enabled(log_buffer: &SharedLogBuffer, enabled: bool) -> Result<(), String> { + let mut buffer = log_buffer + .lock() + .map_err(|_| "Log buffer is unavailable".to_string())?; + buffer.set_enabled(enabled); + Ok(()) +} + +pub fn set_log_max_size(log_buffer: &SharedLogBuffer, max_size: usize) -> Result<(), String> { + if max_size == 0 || max_size > 10_000 { + return Err("Max size must be between 1 and 10000".to_string()); + } + let mut buffer = log_buffer + .lock() + .map_err(|_| "Log buffer is unavailable".to_string())?; + buffer.set_max_size(max_size); + Ok(()) +} + +pub async fn get_process_list() -> Result, String> { + let drivers = registry::list_drivers_with_pid().await; + let plugin_pids = drivers + .into_iter() + .filter(|(manifest, _)| !manifest.is_builtin) + .map(|(manifest, pid)| (manifest.id, manifest.name, pid)) + .collect(); + + tokio::task::spawn_blocking(move || refresh_and_collect_process_stats(plugin_pids)) + .await + .map_err(|error| format!("Failed to collect process stats: {error}")) +} + +pub async fn get_system_stats() -> Result { + tokio::task::spawn_blocking(refresh_and_collect_system_stats) + .await + .map_err(|error| format!("Failed to collect system stats: {error}")) +} + +pub async fn get_tabularis_children() -> Result, String> { + tokio::task::spawn_blocking(collect_tabularis_children) + .await + .map_err(|error| format!("Failed to collect tabularis children: {error}")) +} + +fn refresh_and_collect_process_stats( + plugin_pids: Vec<(String, String, Option)>, +) -> Vec { + let mut system = SYSTEM.lock().unwrap_or_else(|error| error.into_inner()); + refresh_processes(&mut system, true); + + let mut processes = plugin_pids + .into_iter() + .map(|(plugin_id, plugin_name, pid)| { + let (cpu_percent, memory_bytes, disk_read_bytes, disk_write_bytes, status, children) = + match pid { + Some(pid) => process_stats(&system, pid), + None => (0.0, 0, 0, 0, "stopped".to_string(), Vec::new()), + }; + ProcessInfo { + plugin_id, + plugin_name, + pid, + cpu_percent, + memory_bytes, + disk_read_bytes, + disk_write_bytes, + status, + children, + } + }) + .collect::>(); + processes.sort_by(|left, right| left.plugin_name.cmp(&right.plugin_name)); + processes +} + +fn process_stats(system: &System, pid: u32) -> (f32, u64, u64, u64, String, Vec) { + let system_pid = Pid::from(pid as usize); + let Some(process) = system.process(system_pid) else { + return (0.0, 0, 0, 0, "unknown".to_string(), Vec::new()); + }; + let disk = process.disk_usage(); + let mut children = system + .processes() + .iter() + .filter(|(_, child)| child.parent() == Some(system_pid)) + .map(|(child_pid, child)| { + let disk = child.disk_usage(); + ChildProcessInfo { + pid: child_pid.as_u32(), + cpu_percent: child.cpu_usage(), + memory_bytes: child.memory(), + disk_read_bytes: disk.read_bytes, + disk_write_bytes: disk.written_bytes, + } + }) + .collect::>(); + children.sort_by_key(|child| child.pid); + ( + process.cpu_usage(), + process.memory(), + disk.read_bytes, + disk.written_bytes, + "running".to_string(), + children, + ) +} + +fn refresh_and_collect_system_stats() -> SystemStats { + let mut system = SYSTEM.lock().unwrap_or_else(|error| error.into_inner()); + refresh_processes(&mut system, true); + system.refresh_memory(); + + let (disk_read_bytes, disk_write_bytes) = + system + .processes() + .values() + .fold((0_u64, 0_u64), |(read, write), process| { + let disk = process.disk_usage(); + ( + read.saturating_add(disk.read_bytes), + write.saturating_add(disk.written_bytes), + ) + }); + + SystemStats { + cpu_percent: system.global_cpu_usage(), + memory_used: system.used_memory(), + memory_total: system.total_memory(), + disk_read_bytes, + disk_write_bytes, + process_count: system.processes().len(), + tabularis: get_current_pid() + .ok() + .map(|pid| collect_tabularis_stats(&system, pid)), + } +} + +fn collect_tabularis_stats(system: &System, self_pid: Pid) -> TabularisSelfStats { + let descendants = descendants(system, self_pid); + let self_memory_bytes = system + .process(self_pid) + .map(|process| process.memory()) + .unwrap_or(0); + let mut total_memory_bytes = self_memory_bytes; + let mut cpu_percent = 0.0; + let mut disk_read_bytes = 0_u64; + let mut disk_write_bytes = 0_u64; + + for pid in std::iter::once(&self_pid).chain(descendants.iter()) { + if let Some(process) = system.process(*pid) { + cpu_percent += process.cpu_usage(); + if *pid != self_pid { + total_memory_bytes = total_memory_bytes.saturating_add(process.memory()); + } + let disk = process.disk_usage(); + disk_read_bytes = disk_read_bytes.saturating_add(disk.read_bytes); + disk_write_bytes = disk_write_bytes.saturating_add(disk.written_bytes); + } + } + + TabularisSelfStats { + pid: self_pid.as_u32(), + self_memory_bytes, + total_memory_bytes, + cpu_percent, + disk_read_bytes, + disk_write_bytes, + child_count: descendants.len(), + } +} + +fn collect_tabularis_children() -> Vec { + let mut system = SYSTEM.lock().unwrap_or_else(|error| error.into_inner()); + refresh_processes(&mut system, false); + let Ok(self_pid) = get_current_pid() else { + return Vec::new(); + }; + let mut children = descendants(&system, self_pid) + .into_iter() + .filter_map(|pid| { + system.process(pid).map(|process| TabularisChildProcess { + pid: pid.as_u32(), + name: process.name().to_string_lossy().to_string(), + cpu_percent: process.cpu_usage(), + memory_bytes: process.memory(), + }) + }) + .collect::>(); + children.sort_by_key(|child| child.pid); + children +} + +fn refresh_processes(system: &mut System, include_disk: bool) { + let refresh = ProcessRefreshKind::new().with_cpu().with_memory(); + let refresh = if include_disk { + refresh.with_disk_usage() + } else { + refresh + }; + system.refresh_processes_specifics(ProcessesToUpdate::All, true, refresh); + system.refresh_cpu_usage(); +} + +fn descendants(system: &System, root: Pid) -> HashSet { + let mut descendants = HashSet::new(); + let mut pending = vec![root]; + while let Some(parent) = pending.pop() { + for (pid, process) in system.processes() { + if process.parent() == Some(parent) && descendants.insert(*pid) { + pending.push(*pid); + } + } + } + descendants +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/application/operations/tests.rs b/src-tauri/src/application/operations/tests.rs new file mode 100644 index 000000000..f9244a19d --- /dev/null +++ b/src-tauri/src/application/operations/tests.rs @@ -0,0 +1,77 @@ +use super::*; +use crate::logger::{create_log_buffer, LogEntry}; + +fn entry(level: &str, message: &str) -> LogEntry { + LogEntry { + timestamp: "2026-08-22 09:00:00.000".to_string(), + level: level.to_string(), + message: message.to_string(), + target: Some("operations-test".to_string()), + } +} + +#[test] +fn log_operations_filter_limit_resize_and_clear_the_shared_buffer() { + let buffer = create_log_buffer(4); + { + let mut logs = buffer.lock().unwrap(); + logs.push(entry("INFO", "first")); + logs.push(entry("ERROR", "second")); + logs.push(entry("ERROR", "third")); + } + + let errors = get_logs( + &buffer, + GetLogsRequest { + limit: Some(1), + level_filter: Some("error".to_string()), + }, + ); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].message, "third"); + assert_eq!(get_log_settings(&buffer).current_count, 3); + + set_log_max_size(&buffer, 2).unwrap(); + assert_eq!(get_log_settings(&buffer).max_size, 2); + assert_eq!(get_log_settings(&buffer).current_count, 2); + + clear_logs(&buffer).unwrap(); + assert_eq!(get_log_settings(&buffer).current_count, 0); +} + +#[test] +fn log_operations_validate_size_and_enabled_state() { + let buffer = create_log_buffer(4); + + assert_eq!( + set_log_max_size(&buffer, 0).unwrap_err(), + "Max size must be between 1 and 10000" + ); + assert_eq!( + set_log_max_size(&buffer, 10_001).unwrap_err(), + "Max size must be between 1 and 10000" + ); + + set_log_enabled(&buffer, false).unwrap(); + buffer.lock().unwrap().push(entry("INFO", "disabled")); + assert!(!get_log_settings(&buffer).enabled); + assert!(get_logs( + &buffer, + GetLogsRequest { + limit: None, + level_filter: None, + } + ) + .is_empty()); +} + +#[test] +fn process_collectors_return_serializable_snapshots() { + let system = refresh_and_collect_system_stats(); + assert!(system.memory_used <= system.memory_total); + serde_json::to_value(system).unwrap(); + + let children = collect_tabularis_children(); + assert!(children.windows(2).all(|pair| pair[0].pid <= pair[1].pid)); + serde_json::to_value(children).unwrap(); +} diff --git a/src-tauri/src/application/persistence.rs b/src-tauri/src/application/persistence.rs new file mode 100644 index 000000000..0ac024e1f --- /dev/null +++ b/src-tauri/src/application/persistence.rs @@ -0,0 +1,761 @@ +use crate::config::AppConfig; +use crate::preferences::EditorPreferences; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use once_cell::sync::Lazy; +use serde_json::Value; +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use uuid::Uuid; + +const CONFIG_FILE: &str = "config.json"; +const KEYBINDINGS_FILE: &str = "keybindings.json"; +const PREFERENCES_DIR: &str = "preferences"; + +const DEFAULT_SYSTEM_PROMPT: &str = "You are an expert SQL assistant. Your task is to generate a SQL query based on the user's request and the provided database schema.\nReturn ONLY the SQL query, without any markdown formatting, explanations, or code blocks.\n\nSchema:\n{{SCHEMA}}"; +const DEFAULT_EXPLAIN_PROMPT: &str = + "You are a helpful SQL assistant. Explain SQL queries in {{LANGUAGE}}."; +const DEFAULT_EXPLAINPLAN_PROMPT: &str = + "You are a database performance expert. Analyze the following SQL query and its EXPLAIN plan output. Identify performance bottlenecks, suggest index improvements, and explain the execution strategy. Respond in {{LANGUAGE}}."; +const DEFAULT_CELLNAME_PROMPT: &str = "You are an assistant that generates concise, descriptive names for notebook cells.\nGiven a SQL query or Markdown content, return ONLY a short name (3-6 words max) that describes what the cell does or what it is about.\nDo not include quotes, punctuation, or explanations. Just the name."; +const DEFAULT_TABRENAME_PROMPT: &str = "You are an assistant that generates concise, descriptive names for SQL query result tabs.\nGiven a SQL query, return ONLY a short name (3-6 words max) that describes what the query does.\nDo not include quotes, punctuation, or explanations. Just the name."; + +static PERSISTENCE_WRITE_LOCK: Lazy> = Lazy::new(|| Mutex::new(())); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PromptKind { + System, + Explain, + ExplainPlan, + CellName, + TabRename, +} + +impl PromptKind { + fn filename(self) -> &'static str { + match self { + Self::System => "prompt_query.txt", + Self::Explain => "prompt_explain.txt", + Self::ExplainPlan => "prompt_explainplan.txt", + Self::CellName => "prompt_cellname.txt", + Self::TabRename => "prompt_tabrename.txt", + } + } + + fn default_prompt(self) -> &'static str { + match self { + Self::System => DEFAULT_SYSTEM_PROMPT, + Self::Explain => DEFAULT_EXPLAIN_PROMPT, + Self::ExplainPlan => DEFAULT_EXPLAINPLAN_PROMPT, + Self::CellName => DEFAULT_CELLNAME_PROMPT, + Self::TabRename => DEFAULT_TABRENAME_PROMPT, + } + } +} + +#[derive(Debug)] +pub enum PersistenceCommand { + GetConfig, + SaveConfig(AppConfig), + GetConfigJson, + SaveConfigJson(String), + GetKeybindings, + SaveKeybindings(Value), + GetAllThemes, + SaveCustomTheme(Value), + DeleteCustomTheme(String), + GetPrompt(PromptKind), + SavePrompt(PromptKind, String), + ResetPrompt(PromptKind), + LoadEditorPreferences(String), + SaveEditorPreferences(String, EditorPreferences), + DeleteEditorPreferences(String), + GetLastActiveConnection, + SetLastActiveConnection(Option), + GetLastOpenConnections, + SetLastOpenConnections(Vec), +} + +#[derive(Clone, Debug, Default)] +pub struct WebSessionPreferences { + pub last_active_connection_id: Option, + pub last_open_connection_ids: Vec, + pub editor_preferences: HashMap, +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + command: PersistenceCommand, +) -> Result { + match command { + PersistenceCommand::GetConfig => json(config_for_session(runtime, state, session_id)), + PersistenceCommand::SaveConfig(config) => { + save_config_for_session(runtime, state, session_id, config)?; + Ok(Value::Null) + } + PersistenceCommand::GetConfigJson => json(get_config_json(runtime, state, session_id)?), + PersistenceCommand::SaveConfigJson(content) => { + save_config_json(runtime, session_id, &content)?; + Ok(Value::Null) + } + PersistenceCommand::GetKeybindings => get_keybindings(runtime), + PersistenceCommand::SaveKeybindings(keybindings) => { + save_keybindings(runtime, &keybindings)?; + Ok(Value::Null) + } + PersistenceCommand::GetAllThemes => json(get_all_themes(runtime)?), + PersistenceCommand::SaveCustomTheme(theme) => { + save_custom_theme(runtime, theme)?; + Ok(Value::Null) + } + PersistenceCommand::DeleteCustomTheme(theme_id) => { + delete_custom_theme(runtime, &theme_id)?; + Ok(Value::Null) + } + PersistenceCommand::GetPrompt(kind) => json(get_prompt(runtime, kind)), + PersistenceCommand::SavePrompt(kind, prompt) => { + save_prompt(runtime, kind, &prompt)?; + Ok(Value::Null) + } + PersistenceCommand::ResetPrompt(kind) => json(reset_prompt(runtime, kind)?), + PersistenceCommand::LoadEditorPreferences(connection_id) => json(load_editor_preferences( + runtime, + state, + session_id, + &connection_id, + )?), + PersistenceCommand::SaveEditorPreferences(connection_id, preferences) => { + save_editor_preferences(runtime, state, session_id, &connection_id, preferences)?; + Ok(Value::Null) + } + PersistenceCommand::DeleteEditorPreferences(connection_id) => { + delete_editor_preferences(runtime, state, session_id, &connection_id)?; + Ok(Value::Null) + } + PersistenceCommand::GetLastActiveConnection => { + json(last_active_connection(runtime, state, session_id)) + } + PersistenceCommand::SetLastActiveConnection(connection_id) => { + set_last_active_connection(runtime, state, session_id, connection_id)?; + Ok(Value::Null) + } + PersistenceCommand::GetLastOpenConnections => { + json(last_open_connections(runtime, state, session_id)) + } + PersistenceCommand::SetLastOpenConnections(connection_ids) => { + set_last_open_connections(runtime, state, session_id, connection_ids)?; + Ok(Value::Null) + } + } +} + +pub fn load_config(runtime: &RuntimeContext) -> AppConfig { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let config = load_config_path(&runtime.paths.config_dir().join(CONFIG_FILE)); + crate::config::cache_config(&config); + config +} + +pub fn save_config(runtime: &RuntimeContext, update: AppConfig) -> Result { + let proxy_changed = update.proxy.is_some(); + let saved = update_config(runtime, |config| merge_config(config, update))?; + if proxy_changed { + // Drop cached TCP forwards / SSH tunnels that may have been built + // with the previous proxy (password rotation, protocol switch, …). + crate::proxy::stop_all_forwards(); + crate::ssh_tunnel::stop_all_tunnels(); + } + Ok(saved) +} + +pub fn set_selected_schemas( + runtime: &RuntimeContext, + connection_id: String, + schemas: Vec, +) -> Result<(), String> { + update_config(runtime, |config| { + let selections = config + .selected_schemas + .get_or_insert_with(std::collections::HashMap::new); + if schemas.is_empty() { + selections.remove(&connection_id); + } else { + selections.insert(connection_id, schemas); + } + }) + .map(|_| ()) +} + +pub fn set_schema_preference( + runtime: &RuntimeContext, + connection_id: String, + schema: String, +) -> Result<(), String> { + update_config(runtime, |config| { + config + .schema_preferences + .get_or_insert_with(std::collections::HashMap::new) + .insert(connection_id, schema); + }) + .map(|_| ()) +} + +fn update_config( + runtime: &RuntimeContext, + update: impl FnOnce(&mut AppConfig), +) -> Result { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = runtime.paths.config_dir().join(CONFIG_FILE); + let mut config = load_config_path(&path); + update(&mut config); + write_config(&path, &config)?; + Ok(config) +} + +fn config_for_session( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, +) -> AppConfig { + let mut config = load_config(runtime); + if let Some(session_id) = session_id { + let sessions = state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()); + let preferences = sessions.get(&session_id); + config.last_active_connection_id = + preferences.and_then(|value| value.last_active_connection_id.clone()); + config.last_open_connection_ids = Some( + preferences + .map(|value| value.last_open_connection_ids.clone()) + .unwrap_or_default(), + ); + } + config +} + +fn save_config_for_session( + runtime: &RuntimeContext, + _state: &ApplicationState, + session_id: Option, + mut update: AppConfig, +) -> Result<(), String> { + if session_id.is_some() { + update.last_active_connection_id = None; + update.last_open_connection_ids = None; + } + save_config(runtime, update).map(|_| ()) +} + +fn load_config_path(path: &Path) -> AppConfig { + let mut config = fs::read_to_string(path) + .ok() + .and_then(|content| serde_json::from_str(&content).ok()) + .unwrap_or_default(); + crate::plugins::compat::migrate_legacy_config(&mut config); + config +} + +fn write_config(path: &Path, config: &AppConfig) -> Result<(), String> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let content = serde_json::to_string_pretty(config).map_err(|error| error.to_string())?; + fs::write(path, content).map_err(|error| error.to_string())?; + crate::config::cache_config(config); + Ok(()) +} + +fn merge_config(existing: &mut AppConfig, update: AppConfig) { + macro_rules! merge_fields { + ($($field:ident),+ $(,)?) => { + $(if update.$field.is_some() { existing.$field = update.$field; })+ + }; + } + + merge_fields!( + cell_double_click_action, + column_masking_enabled, + column_masking_overrides, + column_masking_patterns, + result_zebra_stripes, + row_editor_follow_selection, + group_sidebar_connections_by_folder, + sticky_column_headers, + default_sort_direction, + plugin_shutdown_grace_seconds, + editor_highlight_invisible_characters, + autocomplete_keyword_case, + theme, + follow_system_theme, + light_theme_id, + dark_theme_id, + language, + result_page_size, + font_family, + font_size, + result_color_by_type, + result_type_colors, + ai_enabled, + ai_provider, + ai_model, + ai_custom_models, + ai_ollama_port, + ai_custom_openai_url, + ai_custom_openai_model, + check_for_updates, + auto_check_updates_on_startup, + last_dismissed_version, + notified_plugin_versions, + er_diagram_default_layout, + schema_preferences, + selected_schemas, + max_blob_size, + copy_format, + csv_delimiter, + csv_include_headers, + active_external_drivers, + tabularium_registry_url, + release_channel, + plugins, + plugin_call_timeout_seconds, + editor_theme, + result_font_family, + editor_font_family, + editor_font_size, + editor_line_height, + editor_tab_size, + editor_word_wrap, + editor_show_line_numbers, + editor_accept_suggestion_on_enter, + run_statement_under_cursor, + safety_confirmation_delay_enabled, + notify_long_queries, + notify_long_queries_threshold_sec, + formatter_keyword_case, + formatter_indent_style, + formatter_tab_width, + formatter_use_tabs, + formatter_function_case, + formatter_lines_between_queries, + formatter_dense_operators, + ping_interval, + query_history_max_entries, + show_welcome, + start_maximized, + window_decorations, + display_timezone, + ai_audit_enabled, + ai_audit_max_entries, + ai_session_gap_minutes, + mcp_output_format, + mcp_readonly_default, + mcp_readonly_connections, + mcp_approval_mode, + mcp_approval_timeout_seconds, + mcp_preflight_explain, + mcp_approval_always_on_top, + mcp_approval_notify_sound, + backup_mode, + backup_directory, + backup_interval_minutes, + backup_retention, + backup_target, + backup_webdav_url, + backup_webdav_username, + database_backup_plan, + auto_connect_last_connection, + last_active_connection_id, + last_open_connection_ids, + postgres_plugin_migration_banner_dismissed, + postgres_plugin_migration_banner_dismissed_for, + driver_migration_history, + known_capability_gaps, + migration_mode_by_driver, + proxy, + ai_provider_proxies + ); +} + +pub fn get_config_json( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, +) -> Result { + if session_id.is_none() { + return get_config_json_for_desktop(runtime); + } + serde_json::to_string_pretty(&config_for_session(runtime, state, session_id)) + .map_err(|error| error.to_string()) +} + +pub fn get_config_json_for_desktop(runtime: &RuntimeContext) -> Result { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = runtime.paths.config_dir().join(CONFIG_FILE); + if path.exists() { + fs::read_to_string(path).map_err(|error| error.to_string()) + } else { + Ok("{}".to_string()) + } +} + +pub fn save_config_json( + runtime: &RuntimeContext, + session_id: Option, + content: &str, +) -> Result<(), String> { + let mut config: AppConfig = serde_json::from_str(content) + .map_err(|error| format!("Invalid configuration JSON: {error}"))?; + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = runtime.paths.config_dir().join(CONFIG_FILE); + if session_id.is_some() { + let existing = load_config_path(&path); + config.last_active_connection_id = existing.last_active_connection_id; + config.last_open_connection_ids = existing.last_open_connection_ids; + } + write_config(&path, &config) +} + +pub fn save_config_json_for_desktop(runtime: &RuntimeContext, content: &str) -> Result<(), String> { + save_config_json(runtime, None, content) +} + +pub fn get_keybindings(runtime: &RuntimeContext) -> Result { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = runtime.paths.config_dir().join(KEYBINDINGS_FILE); + if !path.exists() { + return Ok(Value::Object(serde_json::Map::new())); + } + let content = fs::read_to_string(path).map_err(|error| error.to_string())?; + serde_json::from_str(&content).map_err(|error| error.to_string()) +} + +pub fn save_keybindings(runtime: &RuntimeContext, keybindings: &Value) -> Result<(), String> { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + fs::create_dir_all(runtime.paths.config_dir()).map_err(|error| error.to_string())?; + let content = serde_json::to_string_pretty(keybindings).map_err(|error| error.to_string())?; + fs::write(runtime.paths.config_dir().join(KEYBINDINGS_FILE), content) + .map_err(|error| error.to_string()) +} + +/// Personal legacy themes, read from the host-owned theme catalog so browser +/// and desktop sessions see the same themes as `theme_commands::get_all_themes`. +pub fn get_all_themes(runtime: &RuntimeContext) -> Result, String> { + crate::theme_packages::read_theme_catalog( + runtime.paths.config_dir(), + &crate::paths::get_default_app_data_dir(), + env!("CARGO_PKG_VERSION"), + ) + .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() +} + +pub fn save_custom_theme(runtime: &RuntimeContext, theme: Value) -> Result<(), String> { + crate::theme_packages::save_legacy_theme(runtime.paths.config_dir(), theme)?; + notify_theme_catalog_changed(runtime); + Ok(()) +} + +pub fn delete_custom_theme(runtime: &RuntimeContext, theme_id: &str) -> Result<(), String> { + crate::theme_packages::remove_personal_theme(runtime.paths.config_dir(), theme_id)?; + notify_theme_catalog_changed(runtime); + Ok(()) +} + +fn notify_theme_catalog_changed(runtime: &RuntimeContext) { + super::themes::notify_catalog_changed(runtime); +} + +pub fn get_prompt(runtime: &RuntimeContext, kind: PromptKind) -> String { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + fs::read_to_string(runtime.paths.config_dir().join(kind.filename())) + .unwrap_or_else(|_| kind.default_prompt().to_string()) +} + +pub fn save_prompt(runtime: &RuntimeContext, kind: PromptKind, prompt: &str) -> Result<(), String> { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + fs::create_dir_all(runtime.paths.config_dir()).map_err(|error| error.to_string())?; + fs::write(runtime.paths.config_dir().join(kind.filename()), prompt) + .map_err(|error| error.to_string()) +} + +pub fn reset_prompt(runtime: &RuntimeContext, kind: PromptKind) -> Result { + let path = runtime.paths.config_dir().join(kind.filename()); + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + if path.exists() { + fs::remove_file(path).map_err(|error| error.to_string())?; + } + Ok(kind.default_prompt().to_string()) +} + +pub fn load_editor_preferences_for_desktop( + runtime: &RuntimeContext, + connection_id: &str, +) -> Result, String> { + validate_storage_key(connection_id, "connection id")?; + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = editor_preferences_path(runtime, connection_id); + if !path.exists() { + return Ok(None); + } + let content = fs::read_to_string(path).map_err(|error| error.to_string())?; + serde_json::from_str(&content) + .map(Some) + .map_err(|error| error.to_string()) +} + +pub fn load_editor_preferences( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + connection_id: &str, +) -> Result, String> { + validate_storage_key(connection_id, "connection id")?; + if let Some(session_id) = session_id { + return Ok(state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(&session_id) + .and_then(|session| session.editor_preferences.get(connection_id).cloned())); + } + load_editor_preferences_for_desktop(runtime, connection_id) +} + +pub fn save_editor_preferences_for_desktop( + runtime: &RuntimeContext, + connection_id: &str, + preferences: &EditorPreferences, +) -> Result<(), String> { + validate_storage_key(connection_id, "connection id")?; + let path = editor_preferences_path(runtime, connection_id); + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let content = serde_json::to_string_pretty(preferences).map_err(|error| error.to_string())?; + fs::write(path, content).map_err(|error| error.to_string()) +} + +pub fn save_editor_preferences( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + connection_id: &str, + preferences: EditorPreferences, +) -> Result<(), String> { + validate_storage_key(connection_id, "connection id")?; + if let Some(session_id) = session_id { + state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .entry(session_id) + .or_default() + .editor_preferences + .insert(connection_id.to_string(), preferences); + return Ok(()); + } + save_editor_preferences_for_desktop(runtime, connection_id, &preferences) +} + +pub fn delete_editor_preferences_for_desktop( + runtime: &RuntimeContext, + connection_id: &str, +) -> Result<(), String> { + validate_storage_key(connection_id, "connection id")?; + let path = editor_preferences_path(runtime, connection_id); + if path.exists() { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + fs::remove_file(path).map_err(|error| error.to_string())?; + } + Ok(()) +} + +pub fn delete_editor_preferences( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + connection_id: &str, +) -> Result<(), String> { + validate_storage_key(connection_id, "connection id")?; + if let Some(session_id) = session_id { + if let Some(session) = state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get_mut(&session_id) + { + session.editor_preferences.remove(connection_id); + } + return Ok(()); + } + delete_editor_preferences_for_desktop(runtime, connection_id) +} + +fn editor_preferences_path(runtime: &RuntimeContext, connection_id: &str) -> PathBuf { + runtime + .paths + .config_dir() + .join(PREFERENCES_DIR) + .join(connection_id) + .join("preferences.json") +} + +pub fn last_active_connection( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, +) -> Option { + if let Some(session_id) = session_id { + return state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(&session_id) + .and_then(|session| session.last_active_connection_id.clone()); + } + load_config(runtime).last_active_connection_id +} + +pub fn set_last_active_connection_for_desktop( + runtime: &RuntimeContext, + connection_id: Option, +) -> Result<(), String> { + let _guard = PERSISTENCE_WRITE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let path = runtime.paths.config_dir().join(CONFIG_FILE); + let mut config = load_config_path(&path); + config.last_active_connection_id = connection_id; + write_config(&path, &config) +} + +pub fn set_last_active_connection( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + connection_id: Option, +) -> Result<(), String> { + if let Some(session_id) = session_id { + state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .entry(session_id) + .or_default() + .last_active_connection_id = connection_id; + return Ok(()); + } + set_last_active_connection_for_desktop(runtime, connection_id) +} + +pub fn last_open_connections( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, +) -> Vec { + if let Some(session_id) = session_id { + return state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get(&session_id) + .map(|session| session.last_open_connection_ids.clone()) + .unwrap_or_default(); + } + load_config(runtime) + .last_open_connection_ids + .unwrap_or_default() +} + +pub fn set_last_open_connections_for_desktop( + runtime: &RuntimeContext, + connection_ids: Vec, +) -> Result<(), String> { + save_config( + runtime, + AppConfig { + last_open_connection_ids: Some(connection_ids), + ..Default::default() + }, + ) + .map(|_| ()) +} + +pub fn set_last_open_connections( + runtime: &RuntimeContext, + state: &ApplicationState, + session_id: Option, + connection_ids: Vec, +) -> Result<(), String> { + if let Some(session_id) = session_id { + state + .web_preferences + .lock() + .unwrap_or_else(|error| error.into_inner()) + .entry(session_id) + .or_default() + .last_open_connection_ids = connection_ids; + return Ok(()); + } + set_last_open_connections_for_desktop(runtime, connection_ids) +} + +fn validate_storage_key(value: &str, label: &str) -> Result<(), String> { + if value.is_empty() + || value.len() > 255 + || value == "." + || value == ".." + || value + .chars() + .any(|character| character == '/' || character == '\\' || character == '\0') + { + return Err(format!("Invalid {label}")); + } + Ok(()) +} + +fn json(value: impl serde::Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "persistence_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/persistence_tests.rs b/src-tauri/src/application/persistence_tests.rs new file mode 100644 index 000000000..7dd2d4704 --- /dev/null +++ b/src-tauri/src/application/persistence_tests.rs @@ -0,0 +1,363 @@ +use super::*; +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::KeyringRuntimeSecrets; +use std::sync::Arc; + +fn runtime(root: &Path) -> RuntimeContext { + RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + root.to_path_buf(), + root.to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(KeyringRuntimeSecrets), + ) +} + +fn editor_preferences(title: &str) -> EditorPreferences { + EditorPreferences { + tabs: vec![serde_json::json!({"id": "tab-1", "title": title})], + active_tab_id: Some("tab-1".to_string()), + } +} + +fn custom_theme(id: &str) -> Value { + serde_json::json!({ + "id": id, + "name": "Custom", + "isPreset": false, + "isReadOnly": false, + "colors": { + "bg": {"base": "#000", "elevated": "#111", "overlay": "#222", "input": "#111", "tooltip": "#222"}, + "surface": {"primary": "#111", "secondary": "#222", "tertiary": "#333", "hover": "#444", "active": "#555", "disabled": "#666"}, + "text": {"primary": "#fff", "secondary": "#ddd", "muted": "#aaa", "disabled": "#777", "accent": "#09f", "inverse": "#000"}, + "accent": {"primary": "#09f", "secondary": "#08e", "success": "#0a0", "warning": "#fa0", "error": "#f00", "info": "#0af"}, + "border": {"subtle": "#222", "default": "#333", "strong": "#444", "focus": "#09f"}, + "semantic": {"string": "#f99", "number": "#9f9", "boolean": "#99f", "date": "#f9f", "null": "#999", "primaryKey": "#ff0", "foreignKey": "#0ff", "index": "#f0f", "connectionActive": "#0f0", "connectionInactive": "#999", "modified": "#fa0", "deleted": "#f00", "new": "#0f0"} + }, + "typography": { + "fontFamily": {"base": "sans-serif", "mono": "monospace"}, + "fontSize": {"xs": "10px", "sm": "12px", "base": "14px", "lg": "16px", "xl": "18px"} + }, + "layout": { + "borderRadius": {"sm": "2px", "base": "4px", "lg": "8px", "xl": "12px"}, + "spacing": {"xs": "2px", "sm": "4px", "base": "8px", "lg": "12px", "xl": "16px"} + }, + "monacoTheme": {"base": "vs-dark", "inherit": true} + }) +} + +#[tokio::test] +async fn browser_editor_and_connection_preferences_are_isolated_by_session() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let state = ApplicationState::default(); + let session_a = Uuid::new_v4(); + let session_b = Uuid::new_v4(); + + execute( + &runtime, + &state, + Some(session_a), + PersistenceCommand::SaveEditorPreferences( + "connection-1".to_string(), + editor_preferences("Session A"), + ), + ) + .await + .unwrap(); + execute( + &runtime, + &state, + Some(session_a), + PersistenceCommand::SetLastOpenConnections(vec!["connection-1".to_string()]), + ) + .await + .unwrap(); + execute( + &runtime, + &state, + Some(session_a), + PersistenceCommand::SetLastActiveConnection(Some("connection-1".to_string())), + ) + .await + .unwrap(); + + assert_eq!( + execute( + &runtime, + &state, + Some(session_a), + PersistenceCommand::LoadEditorPreferences("connection-1".to_string()), + ) + .await + .unwrap(), + serde_json::to_value(editor_preferences("Session A")).unwrap() + ); + assert_eq!( + execute( + &runtime, + &state, + Some(session_b), + PersistenceCommand::LoadEditorPreferences("connection-1".to_string()), + ) + .await + .unwrap(), + Value::Null + ); + assert_eq!( + execute( + &runtime, + &state, + Some(session_b), + PersistenceCommand::GetLastOpenConnections, + ) + .await + .unwrap(), + serde_json::json!([]) + ); + assert!(!temp.path().join(PREFERENCES_DIR).exists()); + assert!(!temp.path().join(CONFIG_FILE).exists()); +} + +#[tokio::test] +async fn desktop_preferences_keep_the_existing_disk_locations() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let state = ApplicationState::default(); + let preferences = editor_preferences("Desktop"); + + execute( + &runtime, + &state, + None, + PersistenceCommand::SaveEditorPreferences("connection-1".to_string(), preferences.clone()), + ) + .await + .unwrap(); + execute( + &runtime, + &state, + None, + PersistenceCommand::SetLastOpenConnections(vec!["connection-1".to_string()]), + ) + .await + .unwrap(); + execute( + &runtime, + &state, + None, + PersistenceCommand::SetLastActiveConnection(None), + ) + .await + .unwrap(); + + assert_eq!( + load_editor_preferences(&runtime, &state, None, "connection-1").unwrap(), + Some(preferences) + ); + let config = load_config(&runtime); + assert_eq!(config.last_open_connection_ids.unwrap(), ["connection-1"]); + assert!(config.last_active_connection_id.is_none()); +} + +#[tokio::test] +async fn runtime_api_clears_browser_preferences_when_a_session_ends() { + use crate::application::{ApplicationApi, RuntimeApplicationApi}; + + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let state = Arc::new(ApplicationState::default()); + let session_id = Uuid::new_v4(); + state + .web_preferences + .lock() + .unwrap() + .insert(session_id, WebSessionPreferences::default()); + state + .web_active_connections + .lock() + .unwrap() + .insert(session_id, std::collections::HashSet::new()); + let query = tokio::spawn(std::future::pending::<()>()); + crate::commands::register_abort_handle( + &state.query_cancellation.handles, + format!("web-query:{session_id}:12:connection-1:request-1"), + Arc::new(query.abort_handle()), + ); + + RuntimeApplicationApi::new(runtime, state.clone()).clear_session(session_id); + + assert!(!state + .web_preferences + .lock() + .unwrap() + .contains_key(&session_id)); + assert!(!state + .web_active_connections + .lock() + .unwrap() + .contains_key(&session_id)); + assert!(query.await.unwrap_err().is_cancelled()); + assert!(state.query_cancellation.handles.lock().unwrap().is_empty()); +} + +#[test] +fn config_updates_merge_without_clobbering_other_user_preferences() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + + save_config( + &runtime, + AppConfig { + language: Some("en".to_string()), + theme: Some("tabularis-dark".to_string()), + formatter_tab_width: Some(2), + ..Default::default() + }, + ) + .unwrap(); + let config = save_config( + &runtime, + AppConfig { + language: Some("it".to_string()), + ..Default::default() + }, + ) + .unwrap(); + + assert_eq!(config.language.as_deref(), Some("it")); + assert_eq!(config.theme.as_deref(), Some("tabularis-dark")); + assert_eq!(config.formatter_tab_width, Some(2)); +} + +#[tokio::test] +async fn browser_config_writes_cannot_replace_desktop_restore_state() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let state = ApplicationState::default(); + save_config( + &runtime, + AppConfig { + last_active_connection_id: Some("desktop".to_string()), + last_open_connection_ids: Some(vec!["desktop".to_string()]), + ..Default::default() + }, + ) + .unwrap(); + + execute( + &runtime, + &state, + Some(Uuid::new_v4()), + PersistenceCommand::SaveConfig(AppConfig { + language: Some("de".to_string()), + last_active_connection_id: Some("browser".to_string()), + last_open_connection_ids: Some(vec!["browser".to_string()]), + ..Default::default() + }), + ) + .await + .unwrap(); + + let config = load_config(&runtime); + assert_eq!(config.language.as_deref(), Some("de")); + assert_eq!(config.last_active_connection_id.as_deref(), Some("desktop")); + assert_eq!(config.last_open_connection_ids.unwrap(), ["desktop"]); +} + +#[test] +fn persists_and_deletes_custom_themes_in_the_shared_config_directory() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let theme = custom_theme("custom-test"); + + save_custom_theme(&runtime, theme).unwrap(); + let themes = get_all_themes(&runtime).unwrap(); + assert_eq!(themes.len(), 1); + assert_eq!(themes[0]["id"], "custom-test"); + delete_custom_theme(&runtime, "custom-test").unwrap(); + assert!(get_all_themes(&runtime).unwrap().is_empty()); +} + +#[test] +fn rejects_path_traversal_in_browser_controlled_storage_keys() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let state = ApplicationState::default(); + + assert!(save_editor_preferences( + &runtime, + &state, + Some(Uuid::new_v4()), + "../outside", + editor_preferences("unsafe"), + ) + .is_err()); + assert!(delete_custom_theme(&runtime, "../outside").is_err()); +} + +#[test] +fn config_merge_keeps_plugin_timeouts_and_query_notifications() { + let mut config = AppConfig::default(); + merge_config( + &mut config, + AppConfig { + plugin_call_timeout_seconds: Some(90), + notify_long_queries: Some(true), + notify_long_queries_threshold_sec: Some(30), + ..Default::default() + }, + ); + assert_eq!(config.plugin_call_timeout_seconds, Some(90)); + assert_eq!(config.notify_long_queries, Some(true)); + assert_eq!(config.notify_long_queries_threshold_sec, Some(30)); +} + +#[test] +fn saves_all_grid_preferences_and_preserves_them_on_partial_updates() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let preferences = serde_json::json!({ + "cellDoubleClickAction": "edit", + "columnMaskingEnabled": false, + "columnMaskingOverrides": {"connection.table": {"include": ["secret"]}}, + "columnMaskingPatterns": ["password"], + "resultZebraStripes": false, + "rowEditorFollowSelection": false, + "stickyColumnHeaders": false + }); + save_config( + &runtime, + serde_json::from_value(preferences.clone()).unwrap(), + ) + .unwrap(); + save_config( + &runtime, + serde_json::from_value(serde_json::json!({"language": "de"})).unwrap(), + ) + .unwrap(); + let reloaded = serde_json::to_value(load_config(&runtime)).unwrap(); + for (key, expected) in preferences.as_object().unwrap() { + assert_eq!( + &reloaded[key], expected, + "preference {key} must survive save and reload" + ); + } + assert_eq!(reloaded["language"], "de"); +} + +#[test] +fn database_backup_plan_survives_unrelated_config_updates() { + let temp = tempfile::tempdir().unwrap(); + let runtime = runtime(temp.path()); + let plan: crate::config::DatabaseBackupPlan = serde_json::from_value(serde_json::json!({ + "enabled": true, "connectionId": "sqlite-review", "time": "03:15", "timezone": "UTC", + "destinationDirectory": "/backups", "retention": 3, + "includeStructure": true, "includeData": true + })).unwrap(); + save_config(&runtime, AppConfig { database_backup_plan: Some(plan.clone()), ..Default::default() }).unwrap(); + save_config(&runtime, AppConfig { language: Some("de".to_string()), ..Default::default() }).unwrap(); + assert_eq!(load_config(&runtime).database_backup_plan, Some(plan)); +} diff --git a/src-tauri/src/application/plugin_assets.rs b/src-tauri/src/application/plugin_assets.rs new file mode 100644 index 000000000..603ed3858 --- /dev/null +++ b/src-tauri/src/application/plugin_assets.rs @@ -0,0 +1,133 @@ +use crate::plugins::installer; +use crate::plugins::manager::ConfigManifest; +use std::path::{Component, Path, PathBuf}; + +const MAX_PLUGIN_ASSET_BYTES: u64 = 8 * 1024 * 1024; + +#[derive(Debug)] +pub struct PluginAsset { + pub bytes: Vec, + pub content_type: &'static str, +} + +pub fn read_plugin_asset( + plugins_dir: &Path, + plugin_id: &str, + asset_path: &str, +) -> Result { + super::plugins::validate_plugin_id(plugin_id)?; + let normalized_path = normalize_relative_path(asset_path)?; + let plugin_dir = crate::plugins::layout::resolve_driver(plugins_dir, plugin_id)?; + let manifest: ConfigManifest = installer::read_manifest(&plugin_dir) + .map_err(|error| format!("Failed to read manifest for '{plugin_id}': {error}"))?; + let content_type = authorized_content_type(&manifest, &normalized_path)?; + + let canonical_plugin_dir = plugin_dir + .canonicalize() + .map_err(|_| "Plugin asset was not found".to_string())?; + let full_path = canonical_plugin_dir.join(&normalized_path); + let canonical_asset = full_path + .canonicalize() + .map_err(|_| "Plugin asset was not found".to_string())?; + if !canonical_asset.starts_with(&canonical_plugin_dir) || !canonical_asset.is_file() { + return Err("Plugin asset was not found".to_string()); + } + let metadata = std::fs::metadata(&canonical_asset) + .map_err(|_| "Plugin asset was not found".to_string())?; + if metadata.len() > MAX_PLUGIN_ASSET_BYTES { + return Err("Plugin asset exceeds the 8 MiB limit".to_string()); + } + let bytes = + std::fs::read(canonical_asset).map_err(|_| "Plugin asset was not found".to_string())?; + Ok(PluginAsset { + bytes, + content_type, + }) +} + +pub fn read_plugin_asset_text( + plugins_dir: &Path, + plugin_id: &str, + asset_path: &str, +) -> Result { + let asset = read_plugin_asset(plugins_dir, plugin_id, asset_path)?; + String::from_utf8(asset.bytes).map_err(|_| "Plugin asset is not valid UTF-8".to_string()) +} + +fn authorized_content_type( + manifest: &ConfigManifest, + normalized_path: &Path, +) -> Result<&'static str, String> { + if is_declared_ui_module(manifest, normalized_path) { + return match normalized_path.extension().and_then(|value| value.to_str()) { + Some("js" | "mjs") => Ok("text/javascript; charset=utf-8"), + _ => Err("Plugin UI modules must be JavaScript bundles".to_string()), + }; + } + if is_locale_asset(normalized_path) { + return Ok("application/json; charset=utf-8"); + } + Err("Plugin asset is not declared for UI use".to_string()) +} + +fn is_declared_ui_module(manifest: &ConfigManifest, normalized_path: &Path) -> bool { + manifest + .ui_extensions + .as_deref() + .unwrap_or_default() + .iter() + .map(|entry| &entry.module) + .chain( + manifest + .explain_parsers + .as_deref() + .unwrap_or_default() + .iter() + .map(|entry| &entry.module), + ) + .filter_map(|module| normalize_relative_path(module).ok()) + .any(|module| module == normalized_path) +} + +fn is_locale_asset(path: &Path) -> bool { + let components = path + .components() + .filter_map(|component| match component { + Component::Normal(value) => value.to_str(), + _ => None, + }) + .collect::>(); + if components.len() != 2 || components[0] != "locales" { + return false; + } + let Some(language) = components[1].strip_suffix(".json") else { + return false; + }; + !language.is_empty() + && language.len() <= 35 + && language + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) +} + +fn normalize_relative_path(value: &str) -> Result { + if value.is_empty() || value.len() > 512 { + return Err("Invalid plugin asset path".to_string()); + } + let normalized_separators = value.replace('\\', "/"); + let mut normalized = PathBuf::new(); + for component in Path::new(&normalized_separators).components() { + match component { + Component::CurDir => {} + Component::Normal(segment) if !segment.is_empty() => normalized.push(segment), + _ => return Err("Invalid plugin asset path".to_string()), + } + } + if normalized.as_os_str().is_empty() { + return Err("Invalid plugin asset path".to_string()); + } + Ok(normalized) +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/application/plugin_assets/tests.rs b/src-tauri/src/application/plugin_assets/tests.rs new file mode 100644 index 000000000..fb8b4e694 --- /dev/null +++ b/src-tauri/src/application/plugin_assets/tests.rs @@ -0,0 +1,90 @@ +use super::*; +use std::fs; +use tempfile::tempdir; + +fn plugin_fixture() -> tempfile::TempDir { + let root = tempdir().expect("temp dir"); + let plugin = root.path().join("example-plugin"); + fs::create_dir_all(plugin.join("ui/dist")).expect("ui dir"); + fs::create_dir_all(plugin.join("locales")).expect("locales dir"); + fs::write( + plugin.join(".tabularium"), + r#"{ + "id": "example-plugin", + "name": "Example Plugin", + "version": "1.0.0", + "description": "Fixture", + "ui_extensions": [{ + "slot": "data-grid.toolbar.actions", + "module": "./ui/dist/index.js", + "api_version": "0.1.1" + }] +}"#, + ) + .expect("manifest"); + fs::write(plugin.join("ui/dist/index.js"), "window.loaded = true;").expect("bundle"); + fs::write(plugin.join("ui/dist/private.txt"), "private").expect("private file"); + fs::write(plugin.join("locales/en.json"), r#"{"label":"Run"}"#).expect("locale"); + root +} + +#[test] +fn reads_only_declared_ui_bundles_and_locales() { + let root = plugin_fixture(); + let bundle = read_plugin_asset(root.path(), "example-plugin", "ui/dist/index.js") + .expect("declared bundle"); + assert_eq!(bundle.content_type, "text/javascript; charset=utf-8"); + assert_eq!(bundle.bytes, b"window.loaded = true;"); + + let locale = + read_plugin_asset_text(root.path(), "example-plugin", "locales/en.json").expect("locale"); + assert_eq!(locale, r#"{"label":"Run"}"#); + + assert!(read_plugin_asset(root.path(), "example-plugin", "ui/dist/private.txt").is_err()); +} + +#[test] +fn rejects_traversal_and_invalid_identifiers() { + let root = plugin_fixture(); + assert!(read_plugin_asset(root.path(), "../example-plugin", "ui/dist/index.js").is_err()); + assert!(read_plugin_asset(root.path(), "example-plugin", "../.tabularium").is_err()); + assert!(read_plugin_asset(root.path(), "example-plugin", "/etc/passwd").is_err()); + assert!(read_plugin_asset(root.path(), "example-plugin", "locales/nested/en.json").is_err()); +} + +#[cfg(unix)] +#[test] +fn rejects_symlinks_that_escape_the_plugin_directory() { + use std::os::unix::fs::symlink; + + let root = plugin_fixture(); + let plugin = root.path().join("example-plugin"); + let outside = root.path().join("outside.js"); + fs::write(&outside, "window.outside = true;").expect("outside file"); + fs::remove_file(plugin.join("ui/dist/index.js")).expect("remove bundle"); + symlink(outside, plugin.join("ui/dist/index.js")).expect("symlink"); + + assert!(read_plugin_asset(root.path(), "example-plugin", "ui/dist/index.js").is_err()); +} + +#[test] +fn serves_declared_explain_parser_bundles_with_the_ui_asset_limits() { + let root = plugin_fixture(); + let plugin = root.path().join("example-plugin"); + let manifest_path = plugin.join(".tabularium"); + let mut manifest: serde_json::Value = + serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap(); + manifest["explain_parsers"] = serde_json::json!([ + {"engine": "example", "format": "example-json", "module": "./ui/dist/parser.mjs"}, + {"engine": "example", "format": "private", "module": "ui/dist/private.txt"}, + {"engine": "example", "format": "escape", "module": "../outside.js"} + ]); + fs::write(manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + fs::write(plugin.join("ui/dist/parser.mjs"), "window.parser = true;").unwrap(); + let asset = read_plugin_asset(root.path(), "example-plugin", "ui/dist/parser.mjs").unwrap(); + assert_eq!(asset.content_type, "text/javascript; charset=utf-8"); + assert_eq!(asset.bytes, b"window.parser = true;"); + assert!(read_plugin_asset(root.path(), "example-plugin", "ui/dist/private.txt").is_err()); + assert!(read_plugin_asset(root.path(), "example-plugin", "../outside.js").is_err()); + assert!(read_plugin_asset(root.path(), "example-plugin", "ui/dist/undeclared.js").is_err()); +} diff --git a/src-tauri/src/application/plugins.rs b/src-tauri/src/application/plugins.rs new file mode 100644 index 000000000..140a4c8f3 --- /dev/null +++ b/src-tauri/src/application/plugins.rs @@ -0,0 +1,582 @@ +use crate::config::AppConfig; +use crate::drivers::driver_trait::PluginManifest; +use crate::plugins::installer::{self, InstalledPluginInfo}; +use crate::plugins::manager::{ConfigManifest, PluginLoadError}; +use crate::plugins::registry::{ + self, PluginReadme, RegistryPlugin, RegistryPluginWithStatus, RegistryReleaseWithStatus, +}; +use crate::runtime::RuntimeContext; +use serde_json::Value; +use tokio::time::{sleep, Duration}; + +const MAX_PLUGIN_ID_LENGTH: usize = 128; + +#[derive(Clone, Debug)] +pub enum PluginCommand { + GetRuntimeWarnings, + FetchRegistry, + FetchPreview { + slug: String, + registry_url: Option, + version: Option, + }, + FetchReadme { + slug: String, + locale: Option, + registry_url: Option, + }, + Install { + plugin_id: String, + version: Option, + registry_url: Option, + }, + CancelInstall { + plugin_id: String, + }, + Uninstall { + plugin_id: String, + }, + GetInstalled, + Disable { + plugin_id: String, + }, + Enable { + plugin_id: String, + }, + GetManifest { + plugin_id: String, + }, + GetStartupErrors, + KillProcess { + plugin_id: String, + }, + RestartProcess { + plugin_id: String, + }, +} + +pub async fn execute(runtime: &RuntimeContext, command: PluginCommand) -> Result { + match command { + PluginCommand::FetchRegistry => json(fetch_plugin_registry(runtime).await?), + PluginCommand::FetchPreview { + slug, + registry_url, + version, + } => json(fetch_plugin_preview(runtime, slug, registry_url, version).await?), + PluginCommand::FetchReadme { + slug, + locale, + registry_url, + } => json(fetch_plugin_readme(runtime, slug, locale, registry_url).await?), + PluginCommand::Install { + plugin_id, + version, + registry_url, + } => { + install_plugin(runtime, plugin_id.clone(), version, registry_url).await?; + // Browser clients cannot publish events themselves, so the host + // tells every session that the installed set changed. + let _ = runtime.events.emit( + PLUGIN_INSTALLED_EVENT, + serde_json::json!({ "slug": plugin_id }), + ); + Ok(Value::Null) + } + PluginCommand::CancelInstall { plugin_id } => json(cancel_plugin_install(plugin_id)?), + PluginCommand::Uninstall { plugin_id } => { + uninstall_plugin(runtime, plugin_id).await?; + Ok(Value::Null) + } + PluginCommand::GetInstalled => json(get_installed_plugins(runtime)), + PluginCommand::Disable { plugin_id } => { + disable_plugin(plugin_id).await?; + Ok(Value::Null) + } + PluginCommand::Enable { plugin_id } => { + enable_plugin(runtime, plugin_id).await?; + Ok(Value::Null) + } + PluginCommand::GetManifest { plugin_id } => json(get_plugin_manifest(runtime, plugin_id)?), + PluginCommand::GetStartupErrors => json(get_plugin_startup_errors()), + PluginCommand::GetRuntimeWarnings => { + json(crate::plugins::runtime_version::get_plugin_runtime_warnings()) + } + PluginCommand::KillProcess { plugin_id } => { + kill_plugin_process(plugin_id).await?; + Ok(Value::Null) + } + PluginCommand::RestartProcess { plugin_id } => { + restart_plugin_process(runtime, plugin_id).await?; + Ok(Value::Null) + } + } +} + +/// Emitted after a plugin install completes. +pub const PLUGIN_INSTALLED_EVENT: &str = "tabularis://plugin-installed"; + +pub async fn fetch_plugin_registry( + runtime: &RuntimeContext, +) -> Result, String> { + let config = super::persistence::load_config(runtime); + let base_url = registry_base_url(&config).trim_end_matches('/').to_string(); + let legacy_url = crate::plugins::compat::legacy_registry_url(&config); + let installed = get_installed_plugins(runtime); + let installed_ids: Vec = installed.iter().map(|plugin| plugin.id.clone()).collect(); + let remote = + crate::plugins::compat::resolve_registry(&base_url, &legacy_url, &installed_ids).await?; + let platform = registry::get_current_platform(); + // Themes are declarative packages tracked by the theme catalog, never by + // the executable plugin installer. Read the catalog once for the whole list. + let themes = InstalledThemes::load(runtime); + + Ok(remote + .plugins + .into_iter() + // Unknown or ambiguous kinds have no install path; keep them out of the + // Plugin Center so the kind filter only ever offers drivers and themes. + .filter(|plugin| matches!(plugin.kind.as_deref(), None | Some("driver") | Some("theme"))) + .map(|plugin| { + let (installed_version, platform) = if plugin.kind.as_deref() == Some("theme") { + (themes.version_of(&plugin.id), "universal") + } else { + ( + installed + .iter() + .find(|installed| installed.id == plugin.id) + .map(|installed| installed.version.clone()), + platform.as_str(), + ) + }; + to_plugin_with_status(plugin, installed_version, platform) + }) + .collect()) +} + +/// Installed declarative theme packages, resolved from the +/// host-owned theme catalog so theme status never touches driver discovery. +struct InstalledThemes { + catalog: crate::theme_packages::ThemeCatalog, +} + +impl InstalledThemes { + fn load(runtime: &RuntimeContext) -> Self { + Self { + catalog: crate::theme_packages::read_theme_catalog( + runtime.paths.config_dir(), + &crate::paths::get_default_app_data_dir(), + env!("CARGO_PKG_VERSION"), + ), + } + } + + fn version_of(&self, package_name: &str) -> Option { + self.catalog + .themes + .iter() + .find(|entry| { + entry.origin["kind"] == "installed" + && entry.origin["identity"]["packageName"] == package_name + }) + .and_then(|entry| entry.origin["packageVersion"].as_str()) + .map(str::to_string) + } +} + +pub async fn install_plugin( + runtime: &RuntimeContext, + plugin_id: String, + version: Option, + registry_url: Option, +) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + let install_guard = crate::plugins::install_cancellation::begin(&plugin_id)?; + let cancellation = install_guard.cancellation(); + cancellation.check()?; + + let config = super::persistence::load_config(runtime); + let platform = registry::get_current_platform(); + let (base, has_selected_registry) = + install_registry_base_url(&config, registry_url.as_deref())?; + let (download_url, expected_sha256, target_version) = if let Some(result) = + crate::plugins::compat::resolve_static_asset( + &base, + &plugin_id, + version.as_deref(), + &platform, + ) + .await + { + let asset = result?; + (asset.download_url, asset.expected_sha256, asset.version) + } else { + match resolve_api_install_asset(&base, &plugin_id, version.as_deref(), &platform).await { + Ok(resolved) => resolved, + Err(api_error) + if has_selected_registry || api_error == crate::plugins::package_kind::KIND_ERROR => + { + return Err(api_error) + } + Err(api_error) => { + let legacy_url = crate::plugins::compat::legacy_registry_url(&config); + match crate::plugins::compat::fetch_static_asset( + &legacy_url, + &plugin_id, + version.as_deref(), + &platform, + ) + .await + { + Ok(asset) => (asset.download_url, asset.expected_sha256, asset.version), + Err(_) => return Err(api_error), + } + } + } + }; + + cancellation.check()?; + let plugins_dir = runtime.paths.plugins_dir(); + installer::download_and_install_into( + &plugins_dir, + &plugin_id, + &download_url, + expected_sha256.as_deref(), + Some(&target_version), + cancellation, + ) + .await?; + + let (interpreter_override, settings) = plugin_configuration(&config, &plugin_id); + let plugin_dir = crate::plugins::layout::resolve_driver(&plugins_dir, &plugin_id)?; + crate::plugins::manager::load_plugin_from_dir(&plugin_dir, interpreter_override, settings) + .await + .map_err(|error| format!("Plugin installed but failed to load: {error}"))?; + notify_plugin_reload(runtime, &plugin_id); + Ok(()) +} + +pub fn cancel_plugin_install(plugin_id: String) -> Result { + validate_plugin_id(&plugin_id)?; + Ok(crate::plugins::install_cancellation::cancel(&plugin_id)) +} + +pub async fn uninstall_plugin(runtime: &RuntimeContext, plugin_id: String) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + crate::drivers::registry::unregister_driver(&plugin_id).await; + crate::drivers::registry::unregister_manifest(&plugin_id).await; + installer::uninstall_from(&runtime.paths.plugins_dir(), &plugin_id) +} + +pub fn get_installed_plugins(runtime: &RuntimeContext) -> Vec { + installer::list_installed_from(&runtime.paths.plugins_dir()) +} + +pub async fn disable_plugin(plugin_id: String) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + crate::drivers::registry::unregister_driver(&plugin_id).await; + crate::drivers::registry::unregister_manifest(&plugin_id).await; + Ok(()) +} + +pub async fn enable_plugin(runtime: &RuntimeContext, plugin_id: String) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + let config = super::persistence::load_config(runtime); + load_plugin(runtime, &config, &plugin_id).await?; + notify_plugin_reload(runtime, &plugin_id); + Ok(()) +} + +pub fn get_plugin_manifest( + runtime: &RuntimeContext, + plugin_id: String, +) -> Result { + validate_plugin_id(&plugin_id)?; + let plugin_dir = crate::plugins::layout::resolve_driver(&runtime.paths.plugins_dir(), &plugin_id)?; + let config: ConfigManifest = installer::read_manifest(&plugin_dir) + .map_err(|error| format!("Failed to read manifest for '{plugin_id}': {error}"))?; + Ok(plugin_manifest(config)) +} + +pub fn get_plugin_startup_errors() -> Vec { + crate::plugins::manager::take_plugin_startup_errors() +} + +pub async fn fetch_plugin_preview( + runtime: &RuntimeContext, + slug: String, + registry_url: Option, + version: Option, +) -> Result { + validate_plugin_id(&slug)?; + let config = super::persistence::load_config(runtime); + let base = registry_url + .as_deref() + .map(str::to_string) + .unwrap_or_else(|| registry_base_url(&config).to_string()); + let mut plugin = crate::plugins::tabularium::fetch_plugin_detail(&base, &slug).await?; + plugin.registry_base_url = Some(base.trim_end_matches('/').to_string()); + + // Declarative previews must not traverse driver discovery/startup paths. + let (installed_version, platform) = if plugin.kind.as_deref() == Some("theme") { + crate::theme_packages::registry_key(&base)?; + ( + InstalledThemes::load(runtime).version_of(&slug), + "universal".to_string(), + ) + } else { + ( + get_installed_plugins(runtime) + .into_iter() + .find(|installed| installed.id == slug) + .map(|installed| installed.version), + registry::get_current_platform(), + ) + }; + let target = version + .as_deref() + .filter(|value| !value.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| plugin.latest_version.clone()); + let action = registry::classify_install(installed_version.as_deref(), &target); + let mut result = to_plugin_with_status(plugin, installed_version, &platform); + result.install_action = Some(action); + result.signature = + Some(crate::plugins::tabularium::check_release_signature(&base, &slug, &target).await); + Ok(result) +} + +pub async fn fetch_plugin_readme( + runtime: &RuntimeContext, + slug: String, + locale: Option, + registry_url: Option, +) -> Result { + validate_plugin_id(&slug)?; + let config = super::persistence::load_config(runtime); + let base = registry_url + .as_deref() + .map(str::to_string) + .unwrap_or_else(|| registry_base_url(&config).to_string()); + crate::plugins::tabularium::fetch_plugin_readme(&base, &slug, locale.as_deref()).await +} + +pub async fn kill_plugin_process(plugin_id: String) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + crate::drivers::registry::unregister_driver(&plugin_id).await; + Ok(()) +} + +pub async fn restart_plugin_process( + runtime: &RuntimeContext, + plugin_id: String, +) -> Result<(), String> { + validate_plugin_id(&plugin_id)?; + crate::drivers::registry::unregister_driver(&plugin_id).await; + sleep(Duration::from_millis(500)).await; + let config = super::persistence::load_config(runtime); + load_plugin(runtime, &config, &plugin_id) + .await + .map_err(|error| format!("Failed to restart plugin '{plugin_id}': {error}"))?; + notify_plugin_reload(runtime, &plugin_id); + Ok(()) +} + +/// Tells the frontend that connection metadata derived from this driver may +/// 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", + serde_json::json!({ "driverId": plugin_id }), + ); +} + +fn registry_base_url(config: &AppConfig) -> &str { + config + .tabularium_registry_url + .as_deref() + .unwrap_or(registry::DEFAULT_TABULARIUM_URL) +} + +fn install_registry_base_url( + config: &AppConfig, + selected_registry: Option<&str>, +) -> Result<(String, bool), String> { + let Some(selected_registry) = selected_registry else { + return Ok((registry_base_url(config).to_string(), false)); + }; + let parsed = url::Url::parse(selected_registry) + .map_err(|_| "The selected plugin registry URL is invalid".to_string())?; + if !matches!(parsed.scheme(), "http" | "https") + || parsed.host_str().is_none() + || !parsed.username().is_empty() + || parsed.password().is_some() + || parsed.query().is_some() + || parsed.fragment().is_some() + { + return Err("The selected plugin registry URL is invalid".to_string()); + } + Ok((selected_registry.trim_end_matches('/').to_string(), true)) +} + +pub(crate) fn validate_plugin_id(plugin_id: &str) -> Result<(), String> { + let mut characters = plugin_id.chars(); + let valid_first = characters + .next() + .is_some_and(|character| character.is_ascii_alphanumeric()); + let valid_rest = characters + .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')); + if plugin_id.len() > MAX_PLUGIN_ID_LENGTH || !valid_first || !valid_rest { + return Err(format!("Invalid plugin identifier: '{plugin_id}'")); + } + Ok(()) +} + +fn plugin_configuration( + config: &AppConfig, + plugin_id: &str, +) -> ( + Option, + std::collections::HashMap, +) { + let plugin = config + .plugins + .as_ref() + .and_then(|plugins| plugins.get(plugin_id)); + ( + plugin.and_then(|plugin| plugin.interpreter.clone()), + plugin + .map(|plugin| plugin.settings.clone()) + .unwrap_or_default(), + ) +} + +async fn load_plugin( + runtime: &RuntimeContext, + config: &AppConfig, + plugin_id: &str, +) -> Result<(), String> { + let plugin_dir = crate::plugins::layout::resolve_driver(&runtime.paths.plugins_dir(), plugin_id)?; + let (interpreter_override, settings) = plugin_configuration(config, plugin_id); + crate::plugins::manager::load_plugin_from_dir(&plugin_dir, interpreter_override, settings).await +} + +fn plugin_manifest(config: ConfigManifest) -> PluginManifest { + PluginManifest { + id: config.id.unwrap_or_else(|| config.name.clone()), + name: config.name, + version: config.version, + description: config.description, + default_port: config.default_port, + capabilities: config.capabilities, + is_builtin: false, + engine: config.engine, + paradigms: config.paradigms, + default_username: config.default_username.unwrap_or_default(), + color: config.color, + icon: config.icon, + settings: config.settings, + ui_extensions: config.ui_extensions, + explain_parsers: config.explain_parsers, + connection_fields: config.connection_fields, + type_mappings: config.type_mappings, + // `deprecated` is a built-in-only concept stamped at registration; + // external plugins read from disk are never deprecated by the app. + deprecated: None, + } +} + +fn to_plugin_with_status( + plugin: RegistryPlugin, + installed_version: Option, + platform: &str, +) -> RegistryPluginWithStatus { + let releases: Vec = plugin + .releases + .iter() + .map(|release| RegistryReleaseWithStatus { + version: release.version.clone(), + min_tabularis_version: release.min_tabularis_version.clone(), + platform_supported: release.assets.contains_key(platform) + || release.assets.contains_key("universal"), + }) + .collect(); + let platform_supported = releases + .iter() + .any(|release| release.version == plugin.latest_version && release.platform_supported); + let update_available = matches!( + registry::classify_install(installed_version.as_deref(), &plugin.latest_version), + registry::InstallAction::Update + ); + + RegistryPluginWithStatus { + id: plugin.id, + name: plugin.name, + description: plugin.description, + author: plugin.author, + homepage: plugin.homepage, + latest_version: plugin.latest_version, + releases, + installed_version, + update_available, + platform_supported, + icon: plugin.icon, + repo_url: plugin.repo_url, + kind: plugin.kind, + tags: plugin.tags, + category: plugin.category, + downloads: plugin.downloads, + registry_base_url: plugin.registry_base_url, + engine: plugin.engine, + paradigms: plugin.paradigms, + verified: plugin.verified, + install_action: None, + signature: None, + } +} + +async fn resolve_api_install_asset( + base: &str, + plugin_id: &str, + version: Option<&str>, + platform: &str, +) -> Result<(String, Option, String), String> { + let detail = crate::plugins::tabularium::fetch_plugin_detail(base, plugin_id).await?; + if !matches!(detail.kind.as_deref(), None | Some("driver")) { + return Err(crate::plugins::package_kind::KIND_ERROR.into()); + } + let target_version = match version { + Some(version) => version.to_string(), + None => { + if !detail.latest_version.is_empty() { + detail.latest_version + } else { + detail + .releases + .first() + .map(|release| release.version.clone()) + .ok_or_else(|| { + format!("Plugin '{plugin_id}' has no releases on the registry") + })? + } + } + }; + let asset = + registry::resolve_tabularium_asset(base, plugin_id, &target_version, platform).await?; + let download_url = match version { + Some(_) => crate::plugins::tabularium::tracked_download_url( + base, + plugin_id, + &target_version, + platform, + ), + None => crate::plugins::tabularium::tracked_latest_download_url(base, plugin_id, platform), + }; + Ok((download_url, asset.expected_sha256, target_version)) +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/application/plugins/tests.rs b/src-tauri/src/application/plugins/tests.rs new file mode 100644 index 000000000..6521ea21c --- /dev/null +++ b/src-tauri/src/application/plugins/tests.rs @@ -0,0 +1,118 @@ +use super::{ + cancel_plugin_install, get_installed_plugins, get_plugin_manifest, install_registry_base_url, + validate_plugin_id, +}; +use crate::config::AppConfig; +use crate::runtime::{ + events::NoopRuntimeEvents, paths::FixedRuntimePaths, secrets::KeyringRuntimeSecrets, + RuntimeContext, +}; +use std::fs; +use std::sync::Arc; +use tempfile::tempdir; + +fn runtime(root: &std::path::Path) -> RuntimeContext { + RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + root.join("config"), + root.join("data"), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(KeyringRuntimeSecrets), + ) +} + +#[test] +fn plugin_identifiers_reject_paths_and_accept_registry_slugs() { + for valid in ["postgres-driver", "oracle_23.ai", "Driver2"] { + assert!(validate_plugin_id(valid).is_ok(), "{valid}"); + } + for invalid in [ + "", + ".hidden", + "../outside", + "nested/plugin", + "nested\\plugin", + ] { + assert!(validate_plugin_id(invalid).is_err(), "{invalid}"); + } +} + +#[test] +fn selected_install_registries_are_explicit_and_safe() { + let config = AppConfig::default(); + assert_eq!( + install_registry_base_url(&config, None), + Ok(( + crate::plugins::registry::DEFAULT_TABULARIUM_URL.to_string(), + false, + )), + ); + assert_eq!( + install_registry_base_url(&config, Some("https://registry.example/api/")), + Ok(("https://registry.example/api".to_string(), true)), + ); + assert_eq!( + install_registry_base_url(&config, Some("http://127.0.0.1:9000/registry")), + Ok(("http://127.0.0.1:9000/registry".to_string(), true)), + ); + + for invalid in [ + "file:///tmp/plugins", + "https://user:secret@registry.example", + "https://registry.example/api?token=secret", + "https://registry.example/api#release", + ] { + assert!( + install_registry_base_url(&config, Some(invalid)).is_err(), + "{invalid}", + ); + } +} + +#[test] +fn installed_plugins_and_manifests_use_runtime_scoped_paths() { + let root = tempdir().expect("temp dir"); + let runtime = runtime(root.path()); + let plugin_dir = runtime.paths.plugins_dir().join("contract-driver"); + fs::create_dir_all(&plugin_dir).expect("plugin dir"); + fs::write( + plugin_dir.join(".tabularium"), + r#"{ + "name": "contract-driver", + "version": "1.2.3", + "description": "Contract driver", + "default_port": 5432, + "capabilities": { + "schemas": true, + "views": true, + "routines": false, + "file_based": false, + "folder_based": false, + "identifier_quote": "\"", + "alter_primary_key": false + } +}"#, + ) + .expect("manifest"); + + let installed = get_installed_plugins(&runtime); + assert_eq!(installed.len(), 1); + assert_eq!(installed[0].id, "contract-driver"); + + let manifest = + get_plugin_manifest(&runtime, "contract-driver".to_string()).expect("plugin manifest"); + assert_eq!(manifest.id, "contract-driver"); + assert_eq!(manifest.default_port, Some(5432)); +} + +#[test] +fn lifecycle_inputs_are_validated_before_global_state_or_filesystem_access() { + assert!(cancel_plugin_install("../outside".to_string()).is_err()); + + let root = tempdir().expect("temp dir"); + let runtime = runtime(root.path()); + let error = get_plugin_manifest(&runtime, "../outside".to_string()) + .expect_err("path-like plugin id must fail"); + assert!(error.contains("Invalid plugin identifier")); +} diff --git a/src-tauri/src/application/productivity.rs b/src-tauri/src/application/productivity.rs new file mode 100644 index 000000000..36fb45709 --- /dev/null +++ b/src-tauri/src/application/productivity.rs @@ -0,0 +1,718 @@ +use crate::config::AppConfig; +use crate::saved_query_folders::{self, SavedQueryFolder}; +use chrono::Utc; +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; +use uuid::Uuid; + +const DEFAULT_MAX_HISTORY_ENTRIES: u32 = 500; +const SAVED_QUERIES_DIR: &str = "saved_queries"; +const SAVED_QUERIES_META_FILE: &str = "meta.json"; +const SAVED_QUERY_FOLDERS_FILE: &str = "folders.json"; +const QUERY_HISTORY_DIR: &str = "query_history"; + +static PRODUCTIVITY_STORAGE_LOCK: Lazy> = Lazy::new(|| Mutex::new(())); + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct SavedQueryMeta { + pub id: String, + pub name: String, + pub filename: String, + pub connection_id: String, + #[serde(default)] + pub database: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + /// `None` means Unfiled. Omitted from meta.json when unset so files from + /// before folders existed keep their exact shape. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder_id: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct SavedQuery { + pub id: String, + pub name: String, + pub sql: String, + pub connection_id: String, + #[serde(default)] + pub database: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + #[serde(default)] + pub folder_id: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct QueryHistoryEntry { + pub id: String, + pub sql: String, + pub executed_at: String, + pub execution_time_ms: Option, + pub status: String, + pub rows_affected: Option, + pub error: Option, + #[serde(default)] + pub database: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +#[serde(rename_all = "camelCase")] +pub struct QueryHistoryResponse { + pub entries: Vec, + pub recovered_backup_path: Option, +} + +#[derive(Debug)] +pub enum ProductivityCommand { + GetSavedQueries { + connection_id: String, + }, + SaveQuery { + connection_id: String, + name: String, + sql: String, + database: Option, + }, + UpdateSavedQuery { + connection_id: Option, + id: String, + name: String, + sql: String, + database: Option, + }, + DeleteSavedQuery { + connection_id: Option, + id: String, + }, + GetSavedQueryFolders { + connection_id: String, + }, + CreateSavedQueryFolder { + connection_id: String, + name: String, + }, + RenameSavedQueryFolder { + connection_id: Option, + id: String, + name: String, + }, + DeleteSavedQueryFolder { + connection_id: Option, + id: String, + }, + MoveSavedQuery { + connection_id: Option, + id: String, + folder_id: Option, + }, + GetQueryHistory { + connection_id: String, + }, + AddQueryHistoryEntry { + connection_id: String, + sql: String, + executed_at: String, + execution_time_ms: Option, + status: String, + rows_affected: Option, + error: Option, + database: Option, + }, + DeleteQueryHistoryEntry { + connection_id: String, + id: String, + }, + ClearQueryHistory { + connection_id: String, + }, +} + +pub async fn execute(config_dir: &Path, command: ProductivityCommand) -> Result { + let _guard = PRODUCTIVITY_STORAGE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + + match command { + ProductivityCommand::GetSavedQueries { connection_id } => { + json(get_saved_queries(config_dir, &connection_id)?) + } + ProductivityCommand::SaveQuery { + connection_id, + name, + sql, + database, + } => json(save_query(config_dir, connection_id, name, sql, database)?), + ProductivityCommand::UpdateSavedQuery { + connection_id, + id, + name, + sql, + database, + } => json(update_saved_query( + config_dir, + connection_id.as_deref(), + &id, + name, + sql, + database, + )?), + ProductivityCommand::DeleteSavedQuery { connection_id, id } => { + delete_saved_query(config_dir, connection_id.as_deref(), &id)?; + Ok(Value::Null) + } + ProductivityCommand::GetSavedQueryFolders { connection_id } => { + json(saved_query_folders::list_folders_for_connection( + &saved_query_folders_path(config_dir)?, + &connection_id, + )) + } + ProductivityCommand::CreateSavedQueryFolder { + connection_id, + name, + } => { + let path = saved_query_folders_path(config_dir)?; + let mut folders = saved_query_folders::read_folders_file(&path)?; + let folder = saved_query_folders::create_folder( + &mut folders, + &connection_id, + &name, + &Utc::now().to_rfc3339(), + )?; + saved_query_folders::write_folders_file(&path, &folders)?; + json(folder) + } + ProductivityCommand::RenameSavedQueryFolder { + connection_id, + id, + name, + } => { + let path = saved_query_folders_path(config_dir)?; + let mut folders = saved_query_folders::read_folders_file(&path)?; + ensure_folder_owner(&folders, connection_id.as_deref(), &id)?; + let folder = saved_query_folders::rename_folder(&mut folders, &id, &name)?; + saved_query_folders::write_folders_file(&path, &folders)?; + json(folder) + } + ProductivityCommand::DeleteSavedQueryFolder { connection_id, id } => { + let path = saved_query_folders_path(config_dir)?; + let mut folders = saved_query_folders::read_folders_file(&path)?; + ensure_folder_owner(&folders, connection_id.as_deref(), &id)?; + let meta = read_saved_query_meta(config_dir)?; + saved_query_folders::delete_folder(&mut folders, &meta, &id)?; + saved_query_folders::write_folders_file(&path, &folders)?; + Ok(Value::Null) + } + ProductivityCommand::MoveSavedQuery { + connection_id, + id, + folder_id, + } => { + let mut meta = read_saved_query_meta(config_dir)?; + find_saved_query(&meta, connection_id.as_deref(), &id)?; + let folders = + saved_query_folders::read_folders_file(&saved_query_folders_path(config_dir)?)?; + saved_query_folders::move_query(&mut meta, &folders, &id, folder_id.as_deref())?; + write_saved_query_meta(config_dir, &meta)?; + Ok(Value::Null) + } + ProductivityCommand::GetQueryHistory { connection_id } => { + json(get_query_history(config_dir, &connection_id)?) + } + ProductivityCommand::AddQueryHistoryEntry { + connection_id, + sql, + executed_at, + execution_time_ms, + status, + rows_affected, + error, + database, + } => json(add_query_history_entry( + config_dir, + &connection_id, + sql, + executed_at, + execution_time_ms, + status, + rows_affected, + error, + database, + )?), + ProductivityCommand::DeleteQueryHistoryEntry { connection_id, id } => { + delete_query_history_entry(config_dir, &connection_id, &id)?; + Ok(Value::Null) + } + ProductivityCommand::ClearQueryHistory { connection_id } => { + clear_query_history(config_dir, &connection_id)?; + Ok(Value::Null) + } + } +} + +pub fn backfill_saved_query_metadata( + meta_list: &mut [SavedQueryMeta], + connection_id: &str, + database: &str, +) -> usize { + let mut updated = 0; + for meta in meta_list { + if meta.connection_id == connection_id && meta.database.is_none() { + meta.database = Some(database.to_string()); + updated += 1; + } + } + updated +} + +pub fn backfill_history_entries(entries: &mut [QueryHistoryEntry], database: &str) -> usize { + let mut updated = 0; + for entry in entries { + if entry.database.is_none() { + entry.database = Some(database.to_string()); + updated += 1; + } + } + updated +} + +pub fn backfill_saved_queries_for_connection( + config_dir: &Path, + connection_id: &str, + database: &str, +) -> Result { + let _guard = PRODUCTIVITY_STORAGE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut meta = read_saved_query_meta(config_dir)?; + let updated = backfill_saved_query_metadata(&mut meta, connection_id, database); + if updated > 0 { + write_saved_query_meta(config_dir, &meta)?; + } + Ok(updated) +} + +pub fn backfill_query_history_for_connection( + config_dir: &Path, + connection_id: &str, + database: &str, +) -> Result { + let _guard = PRODUCTIVITY_STORAGE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut entries = read_query_history(config_dir, connection_id)?; + let updated = backfill_history_entries(&mut entries, database); + if updated > 0 { + write_query_history(config_dir, connection_id, &entries)?; + } + Ok(updated) +} + +pub fn remove_query_history_for_connection( + config_dir: &Path, + connection_id: &str, +) -> Result<(), String> { + let _guard = PRODUCTIVITY_STORAGE_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + clear_query_history(config_dir, connection_id) +} + +fn get_saved_queries(config_dir: &Path, connection_id: &str) -> Result, String> { + let meta = read_saved_query_meta(config_dir)?; + let folders = saved_query_folders::read_folders_file_lenient(&saved_query_folders_path( + config_dir, + )?); + let directory = saved_queries_dir(config_dir)?; + meta.into_iter() + .filter(|item| item.connection_id == connection_id) + .map(|item| { + validate_storage_filename(&item.filename)?; + let path = directory.join(&item.filename); + let sql = if path.exists() { + fs::read_to_string(path).unwrap_or_default() + } else { + String::new() + }; + let folder_id = saved_query_folders::resolve_folder_id(&item, &folders); + Ok(SavedQuery { + id: item.id, + name: item.name, + sql, + connection_id: item.connection_id, + database: item.database, + created_at: item.created_at, + updated_at: item.updated_at, + folder_id, + }) + }) + .collect() +} + +fn save_query( + config_dir: &Path, + connection_id: String, + name: String, + sql: String, + database: Option, +) -> Result { + let mut meta = read_saved_query_meta(config_dir)?; + let directory = saved_queries_dir(config_dir)?; + let id = Uuid::new_v4().to_string(); + let filename = format!("{id}.sql"); + let path = directory.join(&filename); + atomic_write(&path, sql.as_bytes())?; + + let now = Utc::now().to_rfc3339(); + meta.push(SavedQueryMeta { + id: id.clone(), + name: name.clone(), + filename, + connection_id: connection_id.clone(), + database: database.clone(), + created_at: Some(now.clone()), + updated_at: Some(now.clone()), + folder_id: None, + }); + if let Err(error) = write_saved_query_meta(config_dir, &meta) { + let _ = fs::remove_file(path); + return Err(error); + } + + Ok(SavedQuery { + id, + name, + sql, + connection_id, + database, + created_at: Some(now.clone()), + updated_at: Some(now), + folder_id: None, + }) +} + +fn update_saved_query( + config_dir: &Path, + connection_id: Option<&str>, + id: &str, + name: String, + sql: String, + database: Option, +) -> Result { + let mut meta = read_saved_query_meta(config_dir)?; + let index = find_saved_query(&meta, connection_id, id)?; + validate_storage_filename(&meta[index].filename)?; + let path = saved_queries_dir(config_dir)?.join(&meta[index].filename); + atomic_write(&path, sql.as_bytes())?; + + let now = Utc::now().to_rfc3339(); + meta[index].name = name.clone(); + meta[index].database = database.clone(); + meta[index].updated_at = Some(now.clone()); + write_saved_query_meta(config_dir, &meta)?; + let folders = saved_query_folders::read_folders_file_lenient(&saved_query_folders_path( + config_dir, + )?); + + Ok(SavedQuery { + id: meta[index].id.clone(), + name, + sql, + connection_id: meta[index].connection_id.clone(), + database, + created_at: meta[index].created_at.clone(), + updated_at: Some(now), + folder_id: saved_query_folders::resolve_folder_id(&meta[index], &folders), + }) +} + +fn delete_saved_query( + config_dir: &Path, + connection_id: Option<&str>, + id: &str, +) -> Result<(), String> { + let mut meta = read_saved_query_meta(config_dir)?; + let index = find_saved_query(&meta, connection_id, id)?; + let removed = meta.remove(index); + validate_storage_filename(&removed.filename)?; + write_saved_query_meta(config_dir, &meta)?; + let path = saved_queries_dir(config_dir)?.join(removed.filename); + if path.exists() { + let _ = fs::remove_file(path); + } + Ok(()) +} + +/// Web sessions name the connection they act on; a folder of another +/// connection is reported as missing rather than touched. +fn ensure_folder_owner( + folders: &[SavedQueryFolder], + connection_id: Option<&str>, + id: &str, +) -> Result<(), String> { + let Some(expected) = connection_id else { + return Ok(()); + }; + if folders + .iter() + .any(|folder| folder.id == id && folder.connection_id == expected) + { + Ok(()) + } else { + Err("Folder not found".to_string()) + } +} + +fn find_saved_query( + meta: &[SavedQueryMeta], + connection_id: Option<&str>, + id: &str, +) -> Result { + meta.iter() + .position(|item| { + item.id == id + && connection_id + .map(|expected| item.connection_id == expected) + .unwrap_or(true) + }) + .ok_or_else(|| "Query not found".to_string()) +} + +fn get_query_history( + config_dir: &Path, + connection_id: &str, +) -> Result { + let (entries, backup) = read_query_history_with_recovery(config_dir, connection_id)?; + Ok(QueryHistoryResponse { + entries, + recovered_backup_path: backup.map(|path| path.to_string_lossy().into_owned()), + }) +} + +#[allow(clippy::too_many_arguments)] +fn add_query_history_entry( + config_dir: &Path, + connection_id: &str, + sql: String, + executed_at: String, + execution_time_ms: Option, + status: String, + rows_affected: Option, + error: Option, + database: Option, +) -> Result { + let mut entries = read_query_history(config_dir, connection_id)?; + let max_entries = load_history_limit(config_dir); + + if let Some(first) = entries.first_mut() { + if first.sql == sql && first.database == database { + first.executed_at = executed_at; + first.execution_time_ms = execution_time_ms; + first.status = status; + first.rows_affected = rows_affected; + first.error = error; + let updated = first.clone(); + write_query_history(config_dir, connection_id, &entries)?; + return Ok(updated); + } + } + + let entry = QueryHistoryEntry { + id: Uuid::new_v4().to_string(), + sql, + executed_at, + execution_time_ms, + status, + rows_affected, + error, + database, + }; + entries.insert(0, entry.clone()); + entries.truncate(max_entries); + write_query_history(config_dir, connection_id, &entries)?; + Ok(entry) +} + +fn delete_query_history_entry( + config_dir: &Path, + connection_id: &str, + id: &str, +) -> Result<(), String> { + let mut entries = read_query_history(config_dir, connection_id)?; + let original_len = entries.len(); + entries.retain(|entry| entry.id != id); + if entries.len() == original_len { + return Err("History entry not found".to_string()); + } + write_query_history(config_dir, connection_id, &entries) +} + +fn clear_query_history(config_dir: &Path, connection_id: &str) -> Result<(), String> { + let path = query_history_path(config_dir, connection_id)?; + if path.exists() { + fs::remove_file(path).map_err(|error| error.to_string())?; + } + Ok(()) +} + +fn read_saved_query_meta(config_dir: &Path) -> Result, String> { + let path = saved_query_meta_path(config_dir)?; + if !path.exists() { + return Ok(Vec::new()); + } + let content = fs::read_to_string(path).map_err(|error| error.to_string())?; + serde_json::from_str(&content).map_err(|error| error.to_string()) +} + +fn write_saved_query_meta(config_dir: &Path, meta: &[SavedQueryMeta]) -> Result<(), String> { + let path = saved_query_meta_path(config_dir)?; + let content = serde_json::to_vec_pretty(meta).map_err(|error| error.to_string())?; + atomic_write(&path, &content) +} + +fn read_query_history( + config_dir: &Path, + connection_id: &str, +) -> Result, String> { + read_query_history_with_recovery(config_dir, connection_id).map(|(entries, _)| entries) +} + +fn read_query_history_with_recovery( + config_dir: &Path, + connection_id: &str, +) -> Result<(Vec, Option), String> { + let path = query_history_path(config_dir, connection_id)?; + if !path.exists() { + return Ok((Vec::new(), None)); + } + let content = fs::read_to_string(&path).map_err(|error| error.to_string())?; + match serde_json::from_str(&content) { + Ok(entries) => Ok((entries, None)), + Err(parse_error) => { + let backup = backup_corrupt_file(&path).map_err(|error| { + format!( + "Query history JSON parse failed and backup also failed: {error} (parse error: {parse_error})" + ) + })?; + log::warn!( + "Query history file for connection '{}' was corrupt ({}); moved to {}", + connection_id, + parse_error, + backup.display() + ); + Ok((Vec::new(), Some(backup))) + } + } +} + +fn write_query_history( + config_dir: &Path, + connection_id: &str, + entries: &[QueryHistoryEntry], +) -> Result<(), String> { + let path = query_history_path(config_dir, connection_id)?; + let content = serde_json::to_vec_pretty(entries).map_err(|error| error.to_string())?; + atomic_write(&path, &content) +} + +fn saved_queries_dir(config_dir: &Path) -> Result { + let path = config_dir.join(SAVED_QUERIES_DIR); + fs::create_dir_all(&path).map_err(|error| error.to_string())?; + Ok(path) +} + +fn saved_query_folders_path(config_dir: &Path) -> Result { + Ok(saved_queries_dir(config_dir)?.join(SAVED_QUERY_FOLDERS_FILE)) +} + +fn saved_query_meta_path(config_dir: &Path) -> Result { + Ok(saved_queries_dir(config_dir)?.join(SAVED_QUERIES_META_FILE)) +} + +fn query_history_path(config_dir: &Path, connection_id: &str) -> Result { + validate_storage_key(connection_id)?; + let directory = config_dir.join(QUERY_HISTORY_DIR); + fs::create_dir_all(&directory).map_err(|error| error.to_string())?; + Ok(directory.join(format!("{connection_id}.json"))) +} + +fn validate_storage_key(value: &str) -> Result<(), String> { + let mut components = Path::new(value).components(); + let is_single_normal = + matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none(); + if value.is_empty() + || value == "." + || value == ".." + || value.contains('/') + || value.contains('\\') + || !is_single_normal + { + return Err("Invalid connection identifier".to_string()); + } + Ok(()) +} + +fn validate_storage_filename(value: &str) -> Result<(), String> { + validate_storage_key(value).map_err(|_| "Invalid saved query filename".to_string()) +} + +fn load_history_limit(config_dir: &Path) -> usize { + let config = fs::read_to_string(config_dir.join("config.json")) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .unwrap_or_default(); + config + .query_history_max_entries + .unwrap_or(DEFAULT_MAX_HISTORY_ENTRIES) as usize +} + +pub(crate) fn backup_corrupt_file(path: &Path) -> Result { + let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S%3f"); + let base = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("history.json"); + let mut backup = path.with_file_name(format!("{base}.corrupt-{timestamp}")); + if backup.exists() { + backup = path.with_file_name(format!( + "{base}.corrupt-{timestamp}-{}", + Uuid::new_v4().simple() + )); + } + fs::rename(path, &backup).map_err(|error| error.to_string())?; + Ok(backup) +} + +pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> { + let directory = path + .parent() + .ok_or_else(|| "storage path has no parent".to_string())?; + fs::create_dir_all(directory).map_err(|error| error.to_string())?; + let file_name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("data.json"); + let temporary = directory.join(format!(".{file_name}.tmp.{}", Uuid::new_v4().simple())); + if let Err(error) = fs::write(&temporary, bytes) { + let _ = fs::remove_file(&temporary); + return Err(error.to_string()); + } + if let Err(error) = fs::rename(&temporary, path) { + let _ = fs::remove_file(&temporary); + return Err(error.to_string()); + } + Ok(()) +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} diff --git a/src-tauri/src/application/productivity_tests.rs b/src-tauri/src/application/productivity_tests.rs new file mode 100644 index 000000000..6b0aebe37 --- /dev/null +++ b/src-tauri/src/application/productivity_tests.rs @@ -0,0 +1,246 @@ +use super::productivity::*; +use futures::future::join_all; +use serde_json::from_value; +use std::sync::Arc; + +fn save_command(connection_id: &str, index: usize) -> ProductivityCommand { + ProductivityCommand::SaveQuery { + connection_id: connection_id.to_string(), + name: format!("Query {index}"), + sql: format!("SELECT {index}"), + database: Some("app".to_string()), + } +} + +#[tokio::test] +async fn saved_query_crud_is_connection_scoped() { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path(); + let saved: SavedQuery = from_value( + execute(config_dir, save_command("connection-a", 1)) + .await + .unwrap(), + ) + .unwrap(); + + let connection_a: Vec = from_value( + execute( + config_dir, + ProductivityCommand::GetSavedQueries { + connection_id: "connection-a".to_string(), + }, + ) + .await + .unwrap(), + ) + .unwrap(); + let connection_b: Vec = from_value( + execute( + config_dir, + ProductivityCommand::GetSavedQueries { + connection_id: "connection-b".to_string(), + }, + ) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(connection_a.len(), 1); + assert!(connection_b.is_empty()); + + let update_error = execute( + config_dir, + ProductivityCommand::UpdateSavedQuery { + connection_id: Some("connection-b".to_string()), + id: saved.id.clone(), + name: "Other".to_string(), + sql: "SELECT 2".to_string(), + database: None, + }, + ) + .await + .unwrap_err(); + assert_eq!(update_error, "Query not found"); + + let updated: SavedQuery = from_value( + execute( + config_dir, + ProductivityCommand::UpdateSavedQuery { + connection_id: Some("connection-a".to_string()), + id: saved.id.clone(), + name: "Updated".to_string(), + sql: "SELECT 2".to_string(), + database: Some("analytics".to_string()), + }, + ) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(updated.name, "Updated"); + assert_eq!(updated.database.as_deref(), Some("analytics")); + + assert!(execute( + config_dir, + ProductivityCommand::DeleteSavedQuery { + connection_id: Some("connection-b".to_string()), + id: saved.id.clone(), + }, + ) + .await + .is_err()); + execute( + config_dir, + ProductivityCommand::DeleteSavedQuery { + connection_id: Some("connection-a".to_string()), + id: saved.id, + }, + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn concurrent_sessions_do_not_lose_saved_queries() { + let temp = tempfile::tempdir().unwrap(); + let config_dir = Arc::new(temp.path().to_path_buf()); + let writes = (0..32).map(|index| { + let config_dir = config_dir.clone(); + tokio::spawn(async move { + execute(&config_dir, save_command("shared-connection", index)) + .await + .unwrap(); + }) + }); + for result in join_all(writes).await { + result.unwrap(); + } + + let queries: Vec = from_value( + execute( + &config_dir, + ProductivityCommand::GetSavedQueries { + connection_id: "shared-connection".to_string(), + }, + ) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(queries.len(), 32); +} + +#[tokio::test] +async fn concurrent_sessions_do_not_lose_or_cross_scope_history_entries() { + let temp = tempfile::tempdir().unwrap(); + let config_dir = Arc::new(temp.path().to_path_buf()); + let writes = (0..24).map(|index| { + let config_dir = config_dir.clone(); + let connection_id = if index % 2 == 0 { + "connection-a" + } else { + "connection-b" + }; + tokio::spawn(async move { + execute( + &config_dir, + ProductivityCommand::AddQueryHistoryEntry { + connection_id: connection_id.to_string(), + sql: format!("SELECT {index}"), + executed_at: format!("2026-08-22T00:00:{index:02}Z"), + execution_time_ms: Some(index as f64), + status: "success".to_string(), + rows_affected: Some(1), + error: None, + database: Some("app".to_string()), + }, + ) + .await + .unwrap(); + }) + }); + for result in join_all(writes).await { + result.unwrap(); + } + + for connection_id in ["connection-a", "connection-b"] { + let history: QueryHistoryResponse = from_value( + execute( + &config_dir, + ProductivityCommand::GetQueryHistory { + connection_id: connection_id.to_string(), + }, + ) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(history.entries.len(), 12); + assert!(history + .entries + .iter() + .all(|entry| entry.sql != "SELECT 100")); + } +} + +#[tokio::test] +async fn query_history_crud_preserves_recovery_and_deduplication_contracts() { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path(); + let add = |executed_at: &str| ProductivityCommand::AddQueryHistoryEntry { + connection_id: "connection-a".to_string(), + sql: "SELECT 1".to_string(), + executed_at: executed_at.to_string(), + execution_time_ms: Some(1.0), + status: "success".to_string(), + rows_affected: Some(1), + error: None, + database: Some("app".to_string()), + }; + let first: QueryHistoryEntry = from_value( + execute(config_dir, add("2026-08-22T00:00:00Z")) + .await + .unwrap(), + ) + .unwrap(); + let deduplicated: QueryHistoryEntry = from_value( + execute(config_dir, add("2026-08-22T00:01:00Z")) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(deduplicated.id, first.id); + assert_eq!(deduplicated.executed_at, "2026-08-22T00:01:00Z"); + + execute( + config_dir, + ProductivityCommand::DeleteQueryHistoryEntry { + connection_id: "connection-a".to_string(), + id: first.id, + }, + ) + .await + .unwrap(); + execute( + config_dir, + ProductivityCommand::ClearQueryHistory { + connection_id: "connection-a".to_string(), + }, + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn rejects_history_connection_path_traversal() { + let temp = tempfile::tempdir().unwrap(); + let error = execute( + temp.path(), + ProductivityCommand::GetQueryHistory { + connection_id: "../outside".to_string(), + }, + ) + .await + .unwrap_err(); + assert_eq!(error, "Invalid connection identifier"); +} diff --git a/src-tauri/src/application/queries.rs b/src-tauri/src/application/queries.rs new file mode 100644 index 000000000..c82bf89bd --- /dev/null +++ b/src-tauri/src/application/queries.rs @@ -0,0 +1,804 @@ +use crate::drivers::driver_trait::{BatchProgressFn, DatabaseDriver}; +use crate::models::{BatchStatementResult, ExplainQueryOutput, QueryResult}; +use crate::runtime::{state::ApplicationState, RuntimeContext}; +use serde::Serialize; +use serde_json::Value; +use std::sync::Arc; +use tokio::task::AbortHandle; +use uuid::Uuid; + +pub const WEB_MAX_ROWS_PER_PAGE: u32 = 10_000; +pub const WEB_MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum QueryResponsePolicy { + Unbounded, + WebBounded, +} + +#[derive(Debug)] +pub enum QueryCommand { + Execute { + connection_id: String, + query: String, + limit: Option, + page: Option, + schema: Option, + query_session_id: Option, + database: Option, + }, + ExecuteBatch { + connection_id: String, + queries: Vec, + limit: Option, + page: Option, + schema: Option, + query_session_id: Option, + batch_id: Option, + database: Option, + }, + Count { + connection_id: String, + query: String, + schema: Option, + query_session_id: Option, + database: Option, + }, + Explain { + connection_id: String, + query: String, + analyze: bool, + schema: Option, + database: Option, + }, + ReleaseSession { + connection_id: String, + query_session_id: String, + }, + GetServerNow { + connection_id: String, + }, +} + +#[derive(Clone, Copy)] +pub struct QueryRequestScope<'a> { + pub session_id: Option, + pub request_id: Option<&'a str>, +} + +struct QueryTaskRegistration { + handles: Arc>, + slot: String, + handle: Arc, +} + +impl QueryTaskRegistration { + fn new( + cancellation: &crate::commands::QueryCancellationState, + slot: String, + handle: Arc, + ) -> Self { + crate::commands::register_abort_handle(&cancellation.handles, slot.clone(), handle.clone()); + Self { + handles: cancellation.handles.clone(), + slot, + handle, + } + } +} + +impl Drop for QueryTaskRegistration { + fn drop(&mut self) { + self.handle.abort(); + crate::commands::unregister_abort_handle(&self.handles, &self.slot, &self.handle); + } +} + +impl QueryRequestScope<'_> { + pub const DESKTOP: Self = Self { + session_id: None, + request_id: None, + }; +} + +pub async fn execute( + runtime: &RuntimeContext, + state: &Arc, + session_id: Option, + request_id: &str, + command: QueryCommand, +) -> Result { + let scope = QueryRequestScope { + session_id, + request_id: Some(request_id), + }; + let connection_id = command.connection_id().to_string(); + emit_query_status(runtime, scope, &connection_id, "started"); + + let result = match command { + QueryCommand::Execute { + connection_id, + query, + limit, + page, + schema, + query_session_id, + database, + } => execute_query( + runtime, + &state.query_cancellation, + scope, + QueryResponsePolicy::WebBounded, + connection_id, + query, + limit, + page, + schema, + query_session_id, + database, + ) + .await + .and_then(json), + QueryCommand::ExecuteBatch { + connection_id, + queries, + limit, + page, + schema, + query_session_id, + batch_id, + database, + } => execute_query_batch( + runtime, + &state.query_cancellation, + scope, + QueryResponsePolicy::WebBounded, + connection_id, + queries, + limit, + page, + schema, + query_session_id, + batch_id, + database, + ) + .await + .and_then(json), + QueryCommand::Count { + connection_id, + query, + schema, + query_session_id, + database, + } => count_query( + runtime, + scope.session_id, + connection_id, + query, + schema, + query_session_id, + database, + ) + .await + .and_then(json), + QueryCommand::Explain { + connection_id, + query, + analyze, + schema, + database, + } => explain_query_plan( + runtime, + &state.query_cancellation, + scope, + connection_id, + query, + analyze, + schema, + database, + ) + .await + .and_then(json), + QueryCommand::ReleaseSession { + connection_id, + query_session_id, + } => { + super::query_sessions::release( + runtime, + scope.session_id, + &connection_id, + &query_session_id, + ) + .await?; + Ok(Value::Null) + } + QueryCommand::GetServerNow { connection_id } => { + get_server_now(runtime, scope.session_id, connection_id) + .await + .and_then(json) + } + }; + + emit_query_status( + runtime, + scope, + &connection_id, + if result.is_ok() { + "completed" + } else { + "failed" + }, + ); + result +} + +impl QueryCommand { + fn connection_id(&self) -> &str { + match self { + Self::Execute { connection_id, .. } + | Self::ExecuteBatch { connection_id, .. } + | Self::Count { connection_id, .. } + | Self::Explain { connection_id, .. } + | Self::GetServerNow { connection_id } + | Self::ReleaseSession { connection_id, .. } => connection_id, + } + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn execute_query( + runtime: &RuntimeContext, + cancellation: &crate::commands::QueryCancellationState, + scope: QueryRequestScope<'_>, + policy: QueryResponsePolicy, + connection_id: String, + query: String, + limit: Option, + page: Option, + schema: Option, + query_session_id: Option, + database: Option, +) -> Result { + log::info!( + "Executing query on connection: {} | Query: {}", + connection_id, + query + ); + let sanitized_query = sanitize_user_query(&query); + let dropped = crate::sql_database_statements::dropped_database(&sanitized_query); + let (driver, params) = + driver_and_params(runtime, scope.session_id, &connection_id, database).await?; + + let effective_limit = response_limit(policy, limit); + let driver_session = query_session_id.as_deref().map(|id| { + super::query_sessions::register(scope.session_id, &connection_id, id, driver.clone()) + }); + let session_driver = driver.clone(); + let task_session = driver_session.clone(); + let task = tokio::spawn(async move { + driver + .execute_query_in_session( + ¶ms, + &sanitized_query, + effective_limit, + page.unwrap_or(1), + schema.as_deref(), + task_session.as_deref(), + ) + .await + }); + let _registration = QueryTaskRegistration::new( + cancellation, + cancellation_slot(scope, &connection_id), + Arc::new(task.abort_handle()), + ); + let result = task.await; + if !matches!(&result, Ok(Ok(_))) { + if let Some(id) = driver_session.as_deref() { + let in_transaction = session_driver + .session_in_transaction(id) + .await + .unwrap_or(false); + super::query_sessions::report( + runtime, + scope.session_id, + &connection_id, + query_session_id.as_deref(), + in_transaction, + ); + } + } + + match result { + Ok(Ok((query_result, in_transaction))) => { + super::query_sessions::report( + runtime, + scope.session_id, + &connection_id, + query_session_id.as_deref(), + in_transaction, + ); + enforce_response_size(policy, &query_result)?; + log::info!( + "Query executed successfully, returned {} rows", + query_result.rows.len() + ); + if let Some(database) = dropped { + emit_database_dropped(runtime, scope.session_id, &connection_id, &database); + } + Ok(query_result) + } + Ok(Err(error)) => { + log::error!("Query execution failed: {error}"); + Err(error) + } + Err(error) if error.is_cancelled() => { + emit_query_cancelled(runtime, scope, &connection_id); + log::warn!("Query was cancelled"); + Err("Query cancelled".to_string()) + } + Err(error) => Err(format!("Query task failed: {error}")), + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn execute_query_batch( + runtime: &RuntimeContext, + cancellation: &crate::commands::QueryCancellationState, + scope: QueryRequestScope<'_>, + policy: QueryResponsePolicy, + connection_id: String, + queries: Vec, + limit: Option, + page: Option, + schema: Option, + query_session_id: Option, + batch_id: Option, + database: Option, +) -> Result, String> { + log::info!( + "Executing query batch on connection: {} | {} statement(s)", + connection_id, + queries.len() + ); + let sanitized_queries: Vec = queries + .iter() + .map(|query| sanitize_user_query(query)) + .collect(); + let dropped_per_statement: Vec> = sanitized_queries + .iter() + .map(|query| crate::sql_database_statements::dropped_database(query)) + .collect(); + let (driver, params) = + driver_and_params(runtime, scope.session_id, &connection_id, database).await?; + + let progress: Option> = batch_id.map(|batch_id| { + let events = runtime.events.clone(); + let session_id = scope.session_id; + Arc::new(move |index, statement: &BatchStatementResult| { + if enforce_response_size(policy, statement).is_err() { + return; + } + let payload = serde_json::json!({ + "batch_id": batch_id, + "index": index, + "statement": statement, + }); + let _ = emit_event(&*events, session_id, "batch-statement-complete", payload); + }) as Arc + }); + let effective_limit = response_limit(policy, limit); + let driver_session = query_session_id.as_deref().map(|id| { + super::query_sessions::register(scope.session_id, &connection_id, id, driver.clone()) + }); + let session_driver = driver.clone(); + let task_session = driver_session.clone(); + let task = tokio::spawn(async move { + driver + .execute_batch_in_session( + ¶ms, + &sanitized_queries, + effective_limit, + page.unwrap_or(1), + schema.as_deref(), + task_session.as_deref(), + progress.as_deref(), + ) + .await + }); + let _registration = QueryTaskRegistration::new( + cancellation, + cancellation_slot(scope, &connection_id), + Arc::new(task.abort_handle()), + ); + let result = task.await; + if !matches!(&result, Ok(Ok(_))) { + if let Some(id) = driver_session.as_deref() { + let in_transaction = session_driver + .session_in_transaction(id) + .await + .unwrap_or(false); + super::query_sessions::report( + runtime, + scope.session_id, + &connection_id, + query_session_id.as_deref(), + in_transaction, + ); + } + } + + match result { + Ok(Ok((batch_results, in_transaction))) => { + super::query_sessions::report( + runtime, + scope.session_id, + &connection_id, + query_session_id.as_deref(), + in_transaction, + ); + enforce_response_size(policy, &batch_results)?; + for (dropped, statement) in dropped_per_statement.iter().zip(&batch_results) { + if let Some(database) = dropped { + if statement.result.is_some() { + emit_database_dropped(runtime, scope.session_id, &connection_id, database); + } + } + } + Ok(batch_results) + } + Ok(Err(error)) => Err(error), + Err(error) if error.is_cancelled() => { + emit_query_cancelled(runtime, scope, &connection_id); + Err("Query cancelled".to_string()) + } + Err(error) => Err(format!("Query task failed: {error}")), + } +} + +pub async fn explain_query_plan( + runtime: &RuntimeContext, + cancellation: &crate::commands::QueryCancellationState, + scope: QueryRequestScope<'_>, + connection_id: String, + query: String, + analyze: bool, + schema: Option, + database: Option, +) -> Result { + let sanitized_query = sanitize_user_query(&query); + let (driver, params) = + driver_and_params(runtime, scope.session_id, &connection_id, database).await?; + // Leading comments are skipped with the driver's own comment rules, so a + // `# note` header on MySQL does not hide an explainable statement. + let hash_comments = + crate::drivers::sql_syntax::SqlSyntax::resolve(&driver.manifest().capabilities) + .hash_comments; + if !crate::drivers::common::is_explainable_query_for(&sanitized_query, hash_comments) { + return Err( + "EXPLAIN is only supported for DML statements (SELECT, INSERT, UPDATE, DELETE, REPLACE). DDL statements like CREATE, DROP, or ALTER cannot be explained." + .to_string(), + ); + } + + let task = tokio::spawn(async move { + driver + .explain_query(¶ms, &sanitized_query, analyze, schema.as_deref()) + .await + }); + let _registration = QueryTaskRegistration::new( + cancellation, + cancellation_slot(scope, &connection_id), + Arc::new(task.abort_handle()), + ); + let result = task.await; + + match result { + Ok(result) => result, + Err(error) if error.is_cancelled() => { + emit_query_cancelled(runtime, scope, &connection_id); + Err("Explain query cancelled".to_string()) + } + Err(error) => Err(format!("Explain query task failed: {error}")), + } +} + +pub async fn count_query( + runtime: &RuntimeContext, + session_id: Option, + connection_id: String, + query: String, + schema: Option, + query_session_id: Option, + database: Option, +) -> Result { + let (driver, params) = driver_and_params(runtime, session_id, &connection_id, database).await?; + + let sanitized = query.trim().trim_end_matches(';'); + let count_query = format!("SELECT COUNT(*) FROM ({sanitized}) as count_wrapper"); + let result = match query_session_id.as_deref() { + Some(id) => { + let id = super::query_sessions::key(session_id, &connection_id, id); + crate::commands::read_in_open_transaction( + driver.as_ref(), + ¶ms, + &count_query, + None, + 1, + schema.as_deref(), + &id, + ) + .await? + } + None => { + driver + .execute_query(¶ms, &count_query, None, 1, schema.as_deref()) + .await? + } + }; + Ok(result + .rows + .first() + .and_then(|row| row.first()) + .and_then(Value::as_i64) + .map(|count| count as u64) + .unwrap_or(0)) +} + +pub async fn get_server_now( + runtime: &RuntimeContext, + session_id: Option, + connection_id: String, +) -> Result { + let (driver, params) = driver_and_params(runtime, session_id, &connection_id, None).await?; + let query = if params.driver == "sqlite" { + "SELECT datetime('now', 'localtime')" + } else { + "SELECT NOW()" + }; + let result = driver + .execute_query(¶ms, query, Some(1), 1, None) + .await?; + result + .rows + .first() + .and_then(|row| row.first()) + .map(|value| match value { + Value::String(value) => value.clone(), + other => other.to_string(), + }) + .ok_or_else(|| "No timestamp returned from server".to_string()) +} + +pub fn cancel_query( + cancellation: &crate::commands::QueryCancellationState, + session_id: Option, + connection_id: &str, + query_request_id: Option<&str>, +) -> Result<(), String> { + cancel_registered_queries(cancellation, session_id, connection_id, query_request_id) +} + +pub fn cancel_session_queries( + cancellation: &crate::commands::QueryCancellationState, + session_id: Uuid, +) { + let prefix = format!("web-query:{session_id}:"); + let handles = { + let mut registered = cancellation + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()); + let slots = registered + .keys() + .filter(|slot| slot.starts_with(&prefix)) + .cloned() + .collect::>(); + slots + .into_iter() + .flat_map(|slot| registered.remove(&slot).unwrap_or_default()) + .collect::>() + }; + for handle in handles { + handle.abort(); + } +} + +pub(crate) fn cancel_registered_queries( + cancellation: &crate::commands::QueryCancellationState, + session_id: Option, + connection_id: &str, + query_request_id: Option<&str>, +) -> Result<(), String> { + let slots = + cancellation_slots_for_cancel(cancellation, session_id, connection_id, query_request_id); + if slots.is_empty() { + return Err("No running query found".to_string()); + } + + let mut handles = Vec::>::new(); + { + let mut registered = cancellation + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()); + for slot in slots { + handles.extend(registered.remove(&slot).unwrap_or_default()); + } + } + if handles.is_empty() { + return Err("No running query found".to_string()); + } + for handle in handles { + handle.abort(); + } + Ok(()) +} + +fn response_limit(policy: QueryResponsePolicy, requested: Option) -> Option { + match policy { + QueryResponsePolicy::Unbounded => requested, + QueryResponsePolicy::WebBounded => Some( + requested + .unwrap_or(WEB_MAX_ROWS_PER_PAGE) + .min(WEB_MAX_ROWS_PER_PAGE), + ), + } +} + +fn enforce_response_size( + policy: QueryResponsePolicy, + response: &T, +) -> Result<(), String> { + if policy == QueryResponsePolicy::Unbounded { + return Ok(()); + } + let bytes = serde_json::to_vec(response).map_err(|error| error.to_string())?; + if bytes.len() > WEB_MAX_RESPONSE_BYTES { + return Err(format!( + "Query response exceeds the web limit of {WEB_MAX_RESPONSE_BYTES} bytes; use pagination with at most {WEB_MAX_ROWS_PER_PAGE} rows per page" + )); + } + Ok(()) +} + +async fn driver_and_params( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + database: Option, +) -> Result<(Arc, crate::models::ConnectionParams), String> { + let runtime = runtime.clone(); + let connection_id = connection_id.to_string(); + let (_driver_id, mut params) = tokio::task::spawn_blocking(move || { + crate::application::connections::resolve_saved_connection_params( + &runtime, + session_id, + &connection_id, + ) + }) + .await + .map_err(|error| error.to_string())??; + if let Some(db) = database.filter(|db| !db.is_empty()) { + params.database = crate::models::DatabaseSelection::Single(db); + } + let driver = crate::drivers::registry::get_connection_driver(¶ms).await?; + Ok((driver, params)) +} + +fn cancellation_slot(scope: QueryRequestScope<'_>, connection_id: &str) -> String { + match (scope.session_id, scope.request_id) { + (Some(session_id), Some(request_id)) => format!( + "web-query:{session_id}:{}:{connection_id}:{request_id}", + connection_id.len() + ), + _ => connection_id.to_string(), + } +} + +fn cancellation_slots_for_cancel( + state: &crate::commands::QueryCancellationState, + session_id: Option, + connection_id: &str, + query_request_id: Option<&str>, +) -> Vec { + let Some(session_id) = session_id else { + return vec![connection_id.to_string()]; + }; + let prefix = format!( + "web-query:{session_id}:{}:{connection_id}:", + connection_id.len() + ); + if let Some(request_id) = query_request_id { + return vec![format!("{prefix}{request_id}")]; + } + state + .handles + .lock() + .unwrap_or_else(|error| error.into_inner()) + .keys() + .filter(|slot| slot.starts_with(&prefix)) + .cloned() + .collect() +} + +fn sanitize_user_query(query: &str) -> String { + query + .trim() + .trim_end_matches(';') + .replace('\u{2018}', "'") + .replace('\u{2019}', "'") + .replace(['\u{201C}', '\u{201D}'], "\"") +} + +fn emit_database_dropped( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + database: &str, +) { + let payload = serde_json::json!({ + "connectionId": connection_id, + "database": database, + }); + let _ = emit_event(&*runtime.events, session_id, "database-dropped", payload); +} + +fn emit_query_status( + runtime: &RuntimeContext, + scope: QueryRequestScope<'_>, + connection_id: &str, + status: &str, +) { + let (Some(session_id), Some(request_id)) = (scope.session_id, scope.request_id) else { + return; + }; + let _ = runtime.events.emit_to( + session_id, + "query-status", + serde_json::json!({ + "requestId": request_id, + "connectionId": connection_id, + "status": status, + }), + ); +} + +fn emit_query_cancelled( + runtime: &RuntimeContext, + scope: QueryRequestScope<'_>, + connection_id: &str, +) { + let (Some(session_id), Some(request_id)) = (scope.session_id, scope.request_id) else { + return; + }; + let _ = runtime.events.emit_to( + session_id, + "query-cancelled", + serde_json::json!({ + "requestId": request_id, + "connectionId": connection_id, + }), + ); +} + +fn emit_event( + events: &dyn crate::runtime::events::RuntimeEvents, + session_id: Option, + event: &str, + payload: Value, +) -> Result<(), String> { + if let Some(session_id) = session_id { + events.emit_to(session_id, event, payload) + } else { + events.emit(event, payload) + } +} + +fn json(value: T) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "queries_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/queries_tests.rs b/src-tauri/src/application/queries_tests.rs new file mode 100644 index 000000000..939d94cf1 --- /dev/null +++ b/src-tauri/src/application/queries_tests.rs @@ -0,0 +1,135 @@ +use super::*; +use crate::commands::{register_abort_handle, QueryCancellationState}; +use std::time::Duration; + +async fn sleeper() -> tokio::task::JoinHandle<()> { + tokio::spawn(async { tokio::time::sleep(Duration::from_secs(10)).await }) +} + +#[test] +fn web_policy_caps_rows_and_rejects_oversized_payloads() { + assert_eq!( + response_limit(QueryResponsePolicy::WebBounded, None), + Some(WEB_MAX_ROWS_PER_PAGE) + ); + assert_eq!( + response_limit( + QueryResponsePolicy::WebBounded, + Some(WEB_MAX_ROWS_PER_PAGE + 1) + ), + Some(WEB_MAX_ROWS_PER_PAGE) + ); + assert_eq!(response_limit(QueryResponsePolicy::Unbounded, None), None); + + let oversized = "x".repeat(WEB_MAX_RESPONSE_BYTES); + let error = enforce_response_size(QueryResponsePolicy::WebBounded, &oversized).unwrap_err(); + assert!(error.contains("use pagination")); + assert!(enforce_response_size(QueryResponsePolicy::Unbounded, &oversized).is_ok()); +} + +#[test] +fn sanitizes_editor_quotes_and_trailing_semicolons() { + assert_eq!( + sanitize_user_query(" SELECT ‘value’, “column”;;; "), + "SELECT 'value', \"column\"" + ); +} + +#[tokio::test] +async fn dropping_a_query_registration_aborts_and_unregisters_the_task() { + let state = QueryCancellationState::default(); + let task = sleeper().await; + let handle = Arc::new(task.abort_handle()); + let registration = QueryTaskRegistration::new(&state, "query-slot".to_string(), handle); + assert!(state.handles.lock().unwrap().contains_key("query-slot")); + + drop(registration); + + assert!(task.await.unwrap_err().is_cancelled()); + assert!(!state.handles.lock().unwrap().contains_key("query-slot")); +} + +#[tokio::test] +async fn session_cleanup_aborts_only_queries_owned_by_that_browser_session() { + let state = QueryCancellationState::default(); + let owner = Uuid::new_v4(); + let other = Uuid::new_v4(); + let owner_task = sleeper().await; + let other_task = sleeper().await; + let owner_slot = cancellation_slot( + QueryRequestScope { + session_id: Some(owner), + request_id: Some("request-owner"), + }, + "connection-1", + ); + let other_slot = cancellation_slot( + QueryRequestScope { + session_id: Some(other), + request_id: Some("request-other"), + }, + "connection-1", + ); + register_abort_handle( + &state.handles, + owner_slot, + Arc::new(owner_task.abort_handle()), + ); + register_abort_handle( + &state.handles, + other_slot.clone(), + Arc::new(other_task.abort_handle()), + ); + + cancel_session_queries(&state, owner); + + assert!(owner_task.await.unwrap_err().is_cancelled()); + assert!(!other_task.is_finished()); + assert!(state.handles.lock().unwrap().contains_key(&other_slot)); + other_task.abort(); +} + +#[tokio::test] +async fn cancellation_slots_are_isolated_by_session_and_request() { + let state = QueryCancellationState::default(); + let session_a = Uuid::new_v4(); + let session_b = Uuid::new_v4(); + let task_a = sleeper().await; + let task_b = sleeper().await; + let slot_a = cancellation_slot( + QueryRequestScope { + session_id: Some(session_a), + request_id: Some("request-a"), + }, + "connection-1", + ); + let slot_b = cancellation_slot( + QueryRequestScope { + session_id: Some(session_b), + request_id: Some("request-b"), + }, + "connection-1", + ); + register_abort_handle( + &state.handles, + slot_a.clone(), + Arc::new(task_a.abort_handle()), + ); + register_abort_handle( + &state.handles, + slot_b.clone(), + Arc::new(task_b.abort_handle()), + ); + + assert_eq!( + cancellation_slots_for_cancel(&state, Some(session_a), "connection-1", Some("request-a")), + vec![slot_a] + ); + cancel_registered_queries(&state, Some(session_a), "connection-1", Some("request-a")).unwrap(); + + assert!(task_a.await.unwrap_err().is_cancelled()); + assert!(!task_b.is_finished()); + assert!(state.handles.lock().unwrap().contains_key(&slot_b)); + task_b.abort(); + let _ = task_b.await; +} diff --git a/src-tauri/src/application/query_sessions.rs b/src-tauri/src/application/query_sessions.rs new file mode 100644 index 000000000..236cbcefb --- /dev/null +++ b/src-tauri/src/application/query_sessions.rs @@ -0,0 +1,134 @@ +//! Database tab sessions are namespaced independently of authenticated browser sessions. +use crate::drivers::driver_trait::DatabaseDriver; +use crate::runtime::RuntimeContext; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use uuid::Uuid; + +struct Session { + owner: Option, + connection_id: String, + tab_id: String, + driver: Arc, + active_runs: usize, + saw_transaction: bool, +} + +fn sessions() -> &'static Mutex> { + static SESSIONS: OnceLock>> = OnceLock::new(); + SESSIONS.get_or_init(Default::default) +} + +pub fn key(owner: Option, connection_id: &str, tab_id: &str) -> String { + serde_json::to_string(&(owner, connection_id, tab_id)).expect("session key is serializable") +} + +pub fn register( + owner: Option, + connection_id: &str, + tab_id: &str, + driver: Arc, +) -> String { + let key = key(owner, connection_id, tab_id); + let mut sessions = sessions().lock().unwrap_or_else(|e| e.into_inner()); + let session = sessions.entry(key.clone()).or_insert_with(|| Session { + owner, + connection_id: connection_id.to_string(), + tab_id: tab_id.to_string(), + driver, + active_runs: 0, + saw_transaction: false, + }); + session.active_runs += 1; + key +} + +pub fn report( + runtime: &RuntimeContext, + owner: Option, + connection_id: &str, + tab_id: Option<&str>, + in_transaction: bool, +) { + let Some(tab_id) = tab_id else { return }; + { + let key = key(owner, connection_id, tab_id); + let mut sessions = sessions().lock().unwrap_or_else(|e| e.into_inner()); + if let Some(session) = sessions.get_mut(&key) { + session.active_runs = session.active_runs.saturating_sub(1); + // Parent tasks may report out of order after the driver releases its lock. + // Retain tabs that used a transaction until explicit tab/session cleanup. + session.saw_transaction |= in_transaction; + if session.active_runs == 0 && !session.saw_transaction { + sessions.remove(&key); + } + } + } + emit_state(runtime, owner, tab_id, in_transaction); +} + +fn emit_state(runtime: &RuntimeContext, owner: Option, tab_id: &str, in_transaction: bool) { + let payload = serde_json::json!({"session_id": tab_id, "in_transaction": in_transaction}); + let _ = match owner { + Some(owner) => runtime + .events + .emit_to(owner, "session-transaction-state", payload), + None => runtime.events.emit("session-transaction-state", payload), + }; +} + +pub async fn release( + runtime: &RuntimeContext, + owner: Option, + connection_id: &str, + tab_id: &str, +) -> Result<(), String> { + let key = key(owner, connection_id, tab_id); + let session = sessions() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&key); + if let Some(session) = session { + session.driver.release_session(&key).await; + } + emit_state(runtime, owner, tab_id, false); + Ok(()) +} + +fn take_matching(owner: Option, connection_id: Option<&str>) -> Vec<(String, Session)> { + let mut sessions = sessions().lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<_> = sessions + .iter() + .filter(|(_, session)| { + session.owner == owner && connection_id.is_none_or(|id| session.connection_id == id) + }) + .map(|(key, _)| key.clone()) + .collect(); + keys.into_iter() + .filter_map(|key| sessions.remove(&key).map(|session| (key, session))) + .collect() +} + +pub async fn release_connection( + runtime: &RuntimeContext, + owner: Option, + connection_id: &str, +) { + for (key, session) in take_matching(owner, Some(connection_id)) { + emit_state(runtime, owner, &session.tab_id, false); + tokio::spawn(async move { + session.driver.release_session(&key).await; + }); + } +} + +pub fn clear_owner(owner: Uuid) { + for (key, session) in take_matching(Some(owner), None) { + tokio::spawn(async move { + session.driver.release_session(&key).await; + }); + } +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/application/query_sessions/tests.rs b/src-tauri/src/application/query_sessions/tests.rs new file mode 100644 index 000000000..22b1f3bd2 --- /dev/null +++ b/src-tauri/src/application/query_sessions/tests.rs @@ -0,0 +1,90 @@ +use super::*; + +#[test] +fn tab_keys_are_isolated_by_browser_and_connection() { + let first = Uuid::new_v4(); + let second = Uuid::new_v4(); + assert_ne!( + key(Some(first), "db", "tab"), + key(Some(second), "db", "tab") + ); + assert_ne!( + key(Some(first), "db", "tab"), + key(Some(first), "other", "tab") + ); + assert_ne!(key(None, "db", "tab"), key(Some(first), "db", "tab")); + assert_ne!(key(None, "a:b", "c"), key(None, "a", "b:c")); +} + +#[tokio::test] +async fn owner_cleanup_preserves_other_browsers_and_desktop() { + let first = Uuid::new_v4(); + let second = Uuid::new_v4(); + let driver: Arc = Arc::new(crate::drivers::sqlite::SqliteDriver::new()); + let own = register(Some(first), "db", "tab", driver.clone()); + let other = register(Some(second), "db", "tab", driver.clone()); + let desktop = register(None, "isolation-test-db", "tab", driver); + clear_owner(first); + { + let sessions = sessions().lock().unwrap(); + assert!(!sessions.contains_key(&own)); + assert!(sessions.contains_key(&other)); + assert!(sessions.contains_key(&desktop)); + } + take_matching(Some(second), None); + take_matching(None, Some("isolation-test-db")); +} + +#[test] +fn overlapping_read_completion_keeps_later_transaction_registered() { + let root = tempfile::tempdir().unwrap(); + let runtime = RuntimeContext::new( + Arc::new(crate::runtime::paths::FixedRuntimePaths::new( + root.path().into(), + root.path().into(), + )), + Arc::new(crate::runtime::events::NoopRuntimeEvents), + Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), + ); + let owner = Some(Uuid::new_v4()); + let driver: Arc = Arc::new(crate::drivers::sqlite::SqliteDriver::new()); + let key = register(owner, "db", "tab", driver.clone()); + register(owner, "db", "tab", driver); + report(&runtime, owner, "db", Some("tab"), false); + assert_eq!(sessions().lock().unwrap()[&key].active_runs, 1); + report(&runtime, owner, "db", Some("tab"), true); + let released = take_matching(owner, Some("db")); + assert_eq!( + released.len(), + 1, + "tab close must still find the pinned transaction" + ); + assert_eq!(released[0].0, key); +} + +#[test] +fn out_of_order_completions_keep_later_transaction_registered() { + let root = tempfile::tempdir().unwrap(); + let runtime = RuntimeContext::new( + Arc::new(crate::runtime::paths::FixedRuntimePaths::new( + root.path().into(), + root.path().into(), + )), + Arc::new(crate::runtime::events::NoopRuntimeEvents), + Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), + ); + let owner = Some(Uuid::new_v4()); + let driver: Arc = Arc::new(crate::drivers::sqlite::SqliteDriver::new()); + let key = register(owner, "db", "tab", driver.clone()); + register(owner, "db", "tab", driver); + report(&runtime, owner, "db", Some("tab"), true); + assert_eq!(sessions().lock().unwrap()[&key].active_runs, 1); + report(&runtime, owner, "db", Some("tab"), false); + let released = take_matching(owner, Some("db")); + assert_eq!( + released.len(), + 1, + "tab close must still find the pinned transaction" + ); + assert_eq!(released[0].0, key); +} diff --git a/src-tauri/src/application/records.rs b/src-tauri/src/application/records.rs new file mode 100644 index 000000000..ed4a6b544 --- /dev/null +++ b/src-tauri/src/application/records.rs @@ -0,0 +1,529 @@ +use super::file_transfers::{ClaimedUpload, FileTransferStore}; +use crate::drivers::driver_trait::DatabaseDriver; +use crate::models::DatabaseSelection; +use crate::runtime::RuntimeContext; +use base64::Engine; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashMap; +use std::fs; +use std::path::Path; +use uuid::Uuid; + +pub const MAX_WEB_BLOB_BYTES: u64 = crate::drivers::common::DEFAULT_MAX_BLOB_SIZE; +const UPLOAD_PREFIX: &str = "BLOB_UPLOAD_REF:"; +const BLOB_TRANSFER_PURPOSE: &str = "blob"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum BlobFetchPolicy { + Inline, + DownloadToken { session_id: Uuid }, +} + +#[derive(Debug)] +pub enum RecordCommand { + Delete { + connection_id: String, + table: String, + pk_map: HashMap, + schema: Option, + database: Option, + }, + Update { + connection_id: String, + table: String, + pk_map: HashMap, + col_name: String, + new_val: Value, + schema: Option, + database: Option, + }, + Insert { + connection_id: String, + table: String, + data: HashMap, + schema: Option, + database: Option, + }, + FetchBlob { + connection_id: String, + table: String, + col_name: String, + pk_map: HashMap, + schema: Option, + database: Option, + }, + DetectBlobMime { + base64_data: String, + }, + DetectMimeType { + header_base64: String, + }, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase" +)] +pub enum BlobFetchResponse { + Inline { + wire_value: String, + }, + Download { + token: String, + size: u64, + mime_type: String, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + session_id: Option, + command: RecordCommand, +) -> Result { + let result = match command { + RecordCommand::Delete { + connection_id, + table, + pk_map, + schema, + database, + } => serde_json::to_value( + delete_record( + runtime, + session_id, + &connection_id, + table, + pk_map, + schema, + database, + ) + .await?, + ), + RecordCommand::Update { + connection_id, + table, + pk_map, + col_name, + new_val, + schema, + database, + } => serde_json::to_value( + update_record( + runtime, + session_id, + &connection_id, + table, + pk_map, + col_name, + new_val, + schema, + database, + ) + .await?, + ), + RecordCommand::Insert { + connection_id, + table, + data, + schema, + database, + } => serde_json::to_value( + insert_record( + runtime, + session_id, + &connection_id, + table, + data, + schema, + database, + ) + .await?, + ), + RecordCommand::FetchBlob { + connection_id, + table, + col_name, + pk_map, + schema, + database, + } => { + let session_id = session_id.ok_or_else(|| { + "An authenticated browser session is required for tokenized BLOB downloads" + .to_string() + })?; + serde_json::to_value( + fetch_blob( + runtime, + Some(session_id), + &connection_id, + table, + col_name, + pk_map, + schema, + database, + BlobFetchPolicy::DownloadToken { session_id }, + ) + .await?, + ) + } + RecordCommand::DetectBlobMime { base64_data } => { + serde_json::to_value(detect_blob_mime(&base64_data)?) + } + RecordCommand::DetectMimeType { header_base64 } => { + serde_json::to_value(detect_mime_type(&header_base64)?) + } + }; + result.map_err(|error| error.to_string()) +} + +#[allow(clippy::too_many_arguments)] +pub async fn delete_record( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + pk_map: HashMap, + schema: Option, + database: Option, +) -> Result { + log::info!( + "Deleting a record on connection {} from table {}", + connection_id, + table + ); + reject_server_file_refs(session_id, pk_map.values())?; + let (_driver_id, mut params) = crate::application::connections::resolve_saved_connection_params( + runtime, + session_id, + connection_id, + )?; + apply_database(&mut params.database, database); + driver_for(¶ms) + .await? + .delete_record(¶ms, &table, &pk_map, schema.as_deref()) + .await +} + +#[allow(clippy::too_many_arguments)] +pub async fn update_record( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + pk_map: HashMap, + col_name: String, + mut new_val: Value, + schema: Option, + database: Option, +) -> Result { + log::info!( + "Updating column {} on connection {} in table {}", + col_name, + connection_id, + table + ); + let max_blob_size = max_blob_size(runtime); + reject_server_file_refs(session_id, pk_map.values())?; + let upload = resolve_upload_value( + runtime.paths.data_dir(), + session_id, + &mut new_val, + max_blob_size, + )?; + let (_driver_id, mut params) = crate::application::connections::resolve_saved_connection_params( + runtime, + session_id, + connection_id, + )?; + apply_database(&mut params.database, database); + let result = driver_for(¶ms) + .await? + .update_record( + ¶ms, + &table, + &pk_map, + &col_name, + new_val, + schema.as_deref(), + max_blob_size, + ) + .await; + drop(upload); + result +} + +#[allow(clippy::too_many_arguments)] +pub async fn insert_record( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + mut data: HashMap, + schema: Option, + database: Option, +) -> Result { + log::info!( + "Inserting a record on connection {} into table {}", + connection_id, + table + ); + let max_blob_size = max_blob_size(runtime); + let mut uploads = Vec::new(); + for value in data.values_mut() { + if let Some(upload) = + resolve_upload_value(runtime.paths.data_dir(), session_id, value, max_blob_size)? + { + uploads.push(upload); + } + } + let (_driver_id, mut params) = crate::application::connections::resolve_saved_connection_params( + runtime, + session_id, + connection_id, + )?; + apply_database(&mut params.database, database); + let result = driver_for(¶ms) + .await? + .insert_record(¶ms, &table, data, schema.as_deref(), max_blob_size) + .await; + drop(uploads); + result +} + +#[allow(clippy::too_many_arguments)] +pub async fn fetch_blob( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + col_name: String, + pk_map: HashMap, + schema: Option, + database: Option, + policy: BlobFetchPolicy, +) -> Result { + reject_server_file_refs(session_id, pk_map.values())?; + let (_driver_id, mut params) = crate::application::connections::resolve_saved_connection_params( + runtime, + session_id, + connection_id, + )?; + apply_database(&mut params.database, database); + let wire_value = driver_for(¶ms) + .await? + .fetch_blob_as_data_url(¶ms, &table, &col_name, &pk_map, schema.as_deref()) + .await?; + + match policy { + BlobFetchPolicy::Inline => Ok(BlobFetchResponse::Inline { wire_value }), + BlobFetchPolicy::DownloadToken { session_id } => { + let max_size = max_blob_size(runtime).min(MAX_WEB_BLOB_BYTES); + let bytes = crate::drivers::common::decode_blob_wire_format(&wire_value, max_size) + .ok_or_else(|| "Invalid BLOB wire format".to_string())?; + if bytes.len() as u64 > max_size { + return Err(format!( + "BLOB size {} exceeds the maximum web download size of {} bytes", + bytes.len(), + max_size + )); + } + let mime_type = + blob_wire_mime(&wire_value).unwrap_or_else(|| detect_mime(&bytes).to_string()); + let metadata = FileTransferStore::new(runtime.paths.data_dir()) + .store_download_bytes( + session_id, + BLOB_TRANSFER_PURPOSE, + "blob-download.bin", + Some(&mime_type), + bytes, + ) + .await?; + Ok(BlobFetchResponse::Download { + token: metadata.token, + size: metadata.size, + mime_type: metadata.mime_type, + }) + } + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn fetch_blob_as_data_url( + runtime: &RuntimeContext, + session_id: Option, + connection_id: &str, + table: String, + col_name: String, + pk_map: HashMap, + schema: Option, + database: Option, +) -> Result { + let BlobFetchResponse::Inline { wire_value } = fetch_blob( + runtime, + session_id, + connection_id, + table, + col_name, + pk_map, + schema, + database, + BlobFetchPolicy::Inline, + ) + .await? + else { + unreachable!("inline fetch policy always returns an inline value") + }; + let mime = blob_wire_mime(&wire_value).ok_or_else(|| "Invalid BLOB wire format".to_string())?; + if !mime.starts_with("image/") { + return Err(format!("Not an image: {mime}")); + } + let payload = wire_value + .rsplit_once(':') + .map(|(_, payload)| payload) + .ok_or_else(|| "Invalid BLOB wire format".to_string())?; + Ok(format!("data:{mime};base64,{payload}")) +} + +pub fn detect_blob_mime(base64_data: &str) -> Result { + let bytes = base64::engine::general_purpose::STANDARD + .decode(base64_data) + .map_err(|error| format!("Invalid base64: {error}"))?; + if bytes.len() as u64 > MAX_WEB_BLOB_BYTES { + return Err("BLOB payload exceeds the maximum allowed size".to_string()); + } + Ok(crate::drivers::common::encode_blob_full(&bytes)) +} + +pub fn detect_mime_type(header_base64: &str) -> Result { + let bytes = base64::engine::general_purpose::STANDARD + .decode(header_base64) + .map_err(|error| format!("Invalid base64: {error}"))?; + if bytes.len() > 8192 { + return Err("MIME detection headers cannot exceed 8192 bytes".to_string()); + } + Ok(detect_mime(&bytes).to_string()) +} + +/// Per-connection driver: plugins with connection metadata may specialise +/// themselves for the resolved connection. +async fn driver_for( + params: &crate::models::ConnectionParams, +) -> Result, String> { + crate::drivers::registry::get_connection_driver(params).await +} + +fn apply_database(selection: &mut DatabaseSelection, database: Option) { + if let Some(database) = database { + *selection = DatabaseSelection::Single(database); + } +} + +fn max_blob_size(runtime: &RuntimeContext) -> u64 { + fs::read_to_string(runtime.paths.config_dir().join("config.json")) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .and_then(|config| config.max_blob_size) + .unwrap_or(crate::drivers::common::DEFAULT_MAX_BLOB_SIZE) +} + +fn reject_server_file_refs<'a>( + session_id: Option, + values: impl Iterator, +) -> Result<(), String> { + if session_id.is_some() + && values + .filter_map(Value::as_str) + .any(|value| value.starts_with("BLOB_FILE_REF:")) + { + return Err("Browser record values cannot contain server file paths".to_string()); + } + Ok(()) +} + +fn resolve_upload_value( + data_dir: &Path, + session_id: Option, + value: &mut Value, + max_size: u64, +) -> Result, String> { + let Some(reference) = value.as_str() else { + return Ok(None); + }; + if session_id.is_some() && reference.starts_with("BLOB_FILE_REF:") { + return Err("Browser record values cannot contain server file paths".to_string()); + } + if !reference.starts_with(UPLOAD_PREFIX) { + return Ok(None); + } + let session_id = session_id.ok_or_else(|| { + "Browser BLOB upload references require an authenticated session".to_string() + })?; + let (claimed_size, _claimed_mime, token) = parse_upload_reference(reference)?; + let upload = + FileTransferStore::new(data_dir).claim_upload(session_id, token, BLOB_TRANSFER_PURPOSE)?; + if upload.metadata().size != claimed_size { + return Err("BLOB upload metadata does not match the uploaded file".to_string()); + } + if upload.metadata().size > max_size { + return Err(format!( + "BLOB size {} exceeds the configured maximum of {} bytes", + upload.metadata().size, + max_size + )); + } + *value = Value::String(format!( + "BLOB_FILE_REF:{}:{}:{}", + upload.metadata().size, + upload.metadata().mime_type, + upload.path().display() + )); + Ok(Some(upload)) +} + +fn parse_upload_reference(reference: &str) -> Result<(u64, &str, &str), String> { + let suffix = reference + .strip_prefix(UPLOAD_PREFIX) + .ok_or_else(|| "Invalid BLOB upload reference".to_string())?; + let mut fields = suffix.splitn(3, ':'); + let size = fields + .next() + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| "Invalid BLOB upload size".to_string())?; + let mime = fields + .next() + .filter(|value| !value.is_empty()) + .ok_or_else(|| "Invalid BLOB upload MIME type".to_string())?; + let token = fields + .next() + .filter(|value| !value.is_empty()) + .ok_or_else(|| "Invalid BLOB upload token".to_string())?; + validate_token(token)?; + Ok((size, mime, token)) +} + +fn blob_wire_mime(wire_value: &str) -> Option { + let suffix = wire_value.strip_prefix("BLOB:")?; + let (_, suffix) = suffix.split_once(':')?; + let (mime, _) = suffix.split_once(':')?; + (!mime.is_empty()).then(|| mime.to_string()) +} + +fn detect_mime(bytes: &[u8]) -> &str { + infer::get(bytes) + .map(|kind| kind.mime_type()) + .unwrap_or("application/octet-stream") +} + +fn validate_token(token: &str) -> Result<(), String> { + match Uuid::parse_str(token) { + Ok(parsed) if parsed.get_version_num() == 4 => Ok(()), + _ => Err("Invalid BLOB transfer token".to_string()), + } +} + +#[cfg(test)] +#[path = "records_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/records_tests.rs b/src-tauri/src/application/records_tests.rs new file mode 100644 index 000000000..340a03a52 --- /dev/null +++ b/src-tauri/src/application/records_tests.rs @@ -0,0 +1,100 @@ +use super::{ + detect_blob_mime, detect_mime_type, parse_upload_reference, resolve_upload_value, + BLOB_TRANSFER_PURPOSE, +}; +use crate::application::file_transfers::FileTransferStore; +use base64::Engine; +use bytes::Bytes; +use std::convert::Infallible; +use uuid::Uuid; + +async fn store_blob(data_dir: &std::path::Path, owner: Uuid, bytes: &'static [u8]) -> String { + let metadata = FileTransferStore::new(data_dir) + .store_upload( + owner, + BLOB_TRANSFER_PURPOSE, + "blob.bin", + Some("application/octet-stream"), + futures::stream::once( + async move { Ok::(Bytes::from_static(bytes)) }, + ), + ) + .await + .unwrap(); + format!( + "BLOB_UPLOAD_REF:{}:{}:{}", + metadata.size, metadata.mime_type, metadata.token + ) +} + +#[test] +fn mime_detection_is_bounded_and_uses_magic_bytes() { + let png = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + let encoded = base64::engine::general_purpose::STANDARD.encode(png); + + assert_eq!(detect_mime_type(&encoded).unwrap(), "image/png"); + assert_eq!( + detect_blob_mime(&encoded).unwrap(), + format!("BLOB:8:image/png:{encoded}") + ); + let oversized_header = base64::engine::general_purpose::STANDARD.encode(vec![0; 8193]); + assert!(detect_mime_type(&oversized_header).is_err()); +} + +#[tokio::test] +async fn resolving_an_upload_consumes_its_token_and_cleans_the_temporary_file() { + let temp = tempfile::tempdir().unwrap(); + let session = Uuid::new_v4(); + let reference = store_blob(temp.path(), session, b"blob").await; + let (_, _, token) = parse_upload_reference(&reference).unwrap(); + let token = token.to_string(); + let mut value = serde_json::Value::String(reference); + + let upload = resolve_upload_value(temp.path(), Some(session), &mut value, 1024) + .unwrap() + .unwrap(); + let consumed_path = value + .as_str() + .unwrap() + .strip_prefix("BLOB_FILE_REF:") + .unwrap() + .splitn(3, ':') + .nth(2) + .unwrap() + .to_string(); + + assert!(FileTransferStore::new(temp.path()) + .open_upload(session, &token, BLOB_TRANSFER_PURPOSE) + .await + .is_err()); + assert!(std::path::Path::new(&consumed_path).exists()); + drop(upload); + assert!(!std::path::Path::new(&consumed_path).exists()); +} + +#[test] +fn browser_values_reject_server_file_references() { + let temp = tempfile::tempdir().unwrap(); + let mut browser_value = serde_json::json!("BLOB_FILE_REF:4:text/plain:/etc/passwd"); + let mut desktop_value = browser_value.clone(); + + let error = + match resolve_upload_value(temp.path(), Some(Uuid::new_v4()), &mut browser_value, 1024) { + Err(error) => error, + Ok(_) => panic!("browser file reference should be rejected"), + }; + assert!(error.contains("cannot contain server file paths")); + assert!( + resolve_upload_value(temp.path(), None, &mut desktop_value, 1024) + .unwrap() + .is_none() + ); +} + +#[test] +fn blob_upload_references_reject_paths_and_non_v4_identifiers() { + assert!(parse_upload_reference("BLOB_UPLOAD_REF:4:text/plain:../../config.json").is_err()); + assert!( + parse_upload_reference(&format!("BLOB_UPLOAD_REF:4:text/plain:{}", Uuid::nil())).is_err() + ); +} diff --git a/src-tauri/src/application/themes.rs b/src-tauri/src/application/themes.rs new file mode 100644 index 000000000..75bab12c5 --- /dev/null +++ b/src-tauri/src/application/themes.rs @@ -0,0 +1,359 @@ +//! Theme catalog, personal themes and theme packages for every transport. +//! +//! Desktop commands and browser RPC both land here, so a theme change made in +//! one host is visible to the other and the `theme-catalog-changed` event +//! reaches every open window through [`RuntimeContext::events`]. + +use crate::application::file_transfers::FileTransferStore; +use crate::runtime::RuntimeContext; +use crate::theme_packages::{self, commands as packages}; +use serde::Serialize; +use serde_json::Value; +use std::path::PathBuf; +use tokio::io::AsyncReadExt; +use uuid::Uuid; + +/// Upload purpose used by the browser for local theme archives. +pub const THEME_PACKAGE_UPLOAD_PURPOSE: &str = "theme-package"; + +/// Where a local theme archive comes from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LocalThemeArchive { + /// A path on the host running Tabularis (desktop dialog or server file browser). + Path(PathBuf), + /// A file the browser uploaded for this session. + Upload { owner: Uuid, token: String }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ThemeCommand { + GetCatalog, + CreatePersonalTheme { + name: String, + source: String, + }, + CreatePersonalSnapshot { + name: String, + source: String, + }, + UpdatePersonalTheme { + theme_id: String, + name: String, + source: String, + expected_revision: String, + }, + UpdatePersonalSnapshot { + theme_id: String, + name: String, + source: String, + editor: Value, + expected_revision: String, + }, + DuplicatePersonalTheme { + theme_id: String, + name: String, + editor: Option, + }, + ImportTheme { + theme_json: String, + name: Option, + }, + ExportTheme { + theme_id: String, + }, + PreviewThemeDocument { + source: String, + name: String, + }, + PreviewLocalPackage { + archive: LocalThemeArchive, + }, + InstallLocalPackage { + archive: LocalThemeArchive, + package_name: String, + expected_digest: String, + }, + FetchRegistry { + package_name: Option, + expected_registry_key: Option, + }, + FetchPackageDetail { + package_name: String, + expected_registry_key: String, + requested_registry_url: Option, + }, + InstallRegistryTheme { + package_name: String, + expected_registry_key: String, + version: Option, + }, + CancelInstall { + registry_key: String, + package_name: String, + }, + SetPackageEnabled { + registry_key: String, + package_name: String, + enabled: bool, + }, + UninstallPackage { + registry_key: String, + package_name: String, + }, + RecoverPackages, +} + +pub async fn execute(runtime: &RuntimeContext, command: ThemeCommand) -> Result { + let config_dir = runtime.paths.config_dir().to_path_buf(); + match command { + ThemeCommand::GetCatalog => json(catalog(runtime)), + ThemeCommand::CreatePersonalTheme { name, source } => committed( + runtime, + theme_packages::create_personal_definition(&config_dir, &name, &source), + ), + ThemeCommand::CreatePersonalSnapshot { name, source } => committed( + runtime, + theme_packages::create_personal_snapshot(&config_dir, &name, &source), + ), + ThemeCommand::UpdatePersonalTheme { + theme_id, + name, + source, + expected_revision, + } => committed( + runtime, + theme_packages::update_personal_definition( + &config_dir, + &theme_id, + &name, + &source, + &expected_revision, + ), + ), + ThemeCommand::UpdatePersonalSnapshot { + theme_id, + name, + source, + editor, + expected_revision, + } => committed( + runtime, + theme_packages::update_personal_snapshot( + &config_dir, + &theme_id, + &name, + &source, + editor, + &expected_revision, + ), + ), + ThemeCommand::DuplicatePersonalTheme { + theme_id, + name, + editor, + } => committed( + runtime, + theme_packages::duplicate_personal_theme( + &config_dir, + &crate::paths::get_default_app_data_dir(), + env!("CARGO_PKG_VERSION"), + &theme_id, + &name, + editor, + ), + ), + ThemeCommand::ImportTheme { theme_json, name } => { + let result = match name { + Some(name) => { + theme_packages::import_legacy_theme_named(&config_dir, &theme_json, &name) + } + None => theme_packages::import_legacy_theme(&config_dir, &theme_json), + }; + committed(runtime, result) + } + ThemeCommand::ExportTheme { theme_id } => json(theme_packages::export_personal_theme( + &config_dir, + &theme_id, + )?), + ThemeCommand::PreviewThemeDocument { source, name } => { + json(packages::preview_theme_document(source, name)?) + } + ThemeCommand::PreviewLocalPackage { archive } => { + let bytes = read_archive_now(runtime, archive).await?; + json(packages::preview_local_package_bytes(bytes).await?) + } + ThemeCommand::InstallLocalPackage { + archive, + package_name, + expected_digest, + } => { + 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) + } + ThemeCommand::FetchRegistry { + package_name, + expected_registry_key, + } => json( + packages::fetch_registry(registry_base(runtime)?, package_name, expected_registry_key) + .await?, + ), + ThemeCommand::FetchPackageDetail { + package_name, + expected_registry_key, + requested_registry_url, + } => json( + packages::fetch_package_detail( + registry_base(runtime)?, + package_name, + expected_registry_key, + requested_registry_url, + ) + .await?, + ), + ThemeCommand::InstallRegistryTheme { + package_name, + expected_registry_key, + version, + } => { + let result = packages::install_registry( + registry_base(runtime)?, + expected_registry_key, + package_name, + version, + ) + .await?; + notify_catalog_changed(runtime); + json(result) + } + ThemeCommand::CancelInstall { + registry_key, + package_name, + } => json(packages::cancel_theme_install(registry_key, package_name)), + ThemeCommand::SetPackageEnabled { + registry_key, + package_name, + enabled, + } => { + packages::set_package_enabled(®istry_key, &package_name, enabled)?; + notify_catalog_changed(runtime); + Ok(Value::Null) + } + ThemeCommand::UninstallPackage { + registry_key, + package_name, + } => committed( + runtime, + packages::uninstall_package(®istry_key, &package_name), + ), + ThemeCommand::RecoverPackages => { + let failures = packages::recover_packages(); + if failures.is_empty() { + notify_catalog_changed(runtime); + } + json(failures) + } + } +} + +/// The complete catalog as the active storage location sees it. +pub fn catalog(runtime: &RuntimeContext) -> theme_packages::ThemeCatalog { + theme_packages::read_theme_catalog( + runtime.paths.config_dir(), + &crate::paths::get_default_app_data_dir(), + env!("CARGO_PKG_VERSION"), + ) +} + +/// Tells every window and browser session that the catalog changed. +pub fn notify_catalog_changed(runtime: &RuntimeContext) { + if let Err(error) = runtime.events.emit("theme-catalog-changed", Value::Null) { + log::warn!("Theme change committed but refresh delivery failed: {error}"); + } +} + +fn committed( + runtime: &RuntimeContext, + result: Result, +) -> Result { + let value = json(result?)?; + notify_catalog_changed(runtime); + Ok(value) +} + +fn registry_base(runtime: &RuntimeContext) -> Result { + let base = super::persistence::load_config(runtime) + .tabularium_registry_url + .unwrap_or_else(|| crate::plugins::registry::DEFAULT_TABULARIUM_URL.into()); + theme_packages::registry_key(&base)?; + Ok(base) +} + +async fn read_archive_now( + runtime: &RuntimeContext, + archive: LocalThemeArchive, +) -> Result, String> { + match archive { + LocalThemeArchive::Path(path) => { + tokio::task::spawn_blocking(move || packages::read_local_archive(&path)) + .await + .map_err(|error| error.to_string())? + } + LocalThemeArchive::Upload { owner, token } => { + read_uploaded_archive(runtime, owner, &token).await + } + } +} + +/// Reads an uploaded archive without consuming the token, so the preview and +/// the install step can both use the same upload. +pub async fn read_uploaded_archive( + runtime: &RuntimeContext, + owner: Uuid, + token: &str, +) -> Result, String> { + let reader = FileTransferStore::new(runtime.paths.data_dir()) + .open_upload(owner, token, THEME_PACKAGE_UPLOAD_PURPOSE) + .await?; + let limit = packages::MAX_LOCAL_ARCHIVE_BYTES as u64; + if reader.metadata().size > limit { + return Err("Local theme archive exceeds its byte limit".into()); + } + let mut bytes = Vec::new(); + reader + .take(limit + 1) + .read_to_end(&mut bytes) + .await + .map_err(|error| error.to_string())?; + if bytes.len() as u64 > limit { + return Err("Local theme archive exceeds its byte limit".into()); + } + Ok(bytes) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "themes_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/themes_tests.rs b/src-tauri/src/application/themes_tests.rs new file mode 100644 index 000000000..9fd37b2b8 --- /dev/null +++ b/src-tauri/src/application/themes_tests.rs @@ -0,0 +1,142 @@ +use super::*; +use crate::runtime::events::RuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use bytes::Bytes; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct RecordingEvents { + values: Mutex>, +} + +impl RuntimeEvents for RecordingEvents { + fn emit(&self, event: &str, _payload: Value) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(event.to_string()); + Ok(()) + } +} + +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(()) + } +} + +fn runtime(temp: &tempfile::TempDir) -> (RuntimeContext, Arc) { + let events = Arc::new(RecordingEvents::default()); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().join("config"), + temp.path().join("data"), + )), + events.clone(), + Arc::new(NoSecrets), + ); + (runtime, events) +} + +#[tokio::test] +async fn reads_the_catalog_from_the_runtime_config_folder() { + let temp = tempfile::tempdir().unwrap(); + let (runtime, events) = runtime(&temp); + let catalog = execute(&runtime, ThemeCommand::GetCatalog).await.unwrap(); + assert!(!catalog["themes"].as_array().unwrap().is_empty()); + assert!(events.values.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn announces_committed_personal_theme_changes() { + let temp = tempfile::tempdir().unwrap(); + let (runtime, events) = runtime(&temp); + let catalog = catalog(&runtime); + let builtin = catalog + .themes + .iter() + .find(|entry| entry.format == "legacy" && entry.editor.is_none()) + .expect("a builtin legacy theme"); + + let imported = execute( + &runtime, + ThemeCommand::ImportTheme { + theme_json: builtin.source.clone(), + name: Some("Imported copy".into()), + }, + ) + .await + .unwrap(); + assert!(imported.is_object()); + assert_eq!( + events.values.lock().unwrap().as_slice(), + ["theme-catalog-changed"] + ); + assert!(catalog_contains(&runtime, "Imported copy")); + + // A rejected document changes nothing and is not announced. + assert!(execute( + &runtime, + ThemeCommand::ImportTheme { + theme_json: "{".into(), + name: None, + }, + ) + .await + .is_err()); + assert_eq!(events.values.lock().unwrap().len(), 1); +} + +fn catalog_contains(runtime: &RuntimeContext, name: &str) -> bool { + catalog(runtime).themes.iter().any(|entry| entry.name == name) +} + +#[tokio::test] +async fn reads_uploaded_archives_without_consuming_the_token() { + let temp = tempfile::tempdir().unwrap(); + let (runtime, _events) = runtime(&temp); + let owner = Uuid::new_v4(); + let store = FileTransferStore::new(runtime.paths.data_dir()); + let metadata = store + .store_upload( + owner, + THEME_PACKAGE_UPLOAD_PURPOSE, + "nord.zip", + Some("application/zip"), + futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from_static(b"PK-bytes"))]), + ) + .await + .unwrap(); + + for _ in 0..2 { + let bytes = read_uploaded_archive(&runtime, owner, &metadata.token) + .await + .unwrap(); + assert_eq!(bytes, b"PK-bytes"); + } + // Another session, or another purpose, cannot use the token. + assert!(read_uploaded_archive(&runtime, Uuid::new_v4(), &metadata.token) + .await + .is_err()); + // Invalid archives surface the package validator's error. + assert!(execute( + &runtime, + ThemeCommand::PreviewLocalPackage { + archive: LocalThemeArchive::Upload { + owner, + token: metadata.token.clone(), + }, + }, + ) + .await + .is_err()); +} diff --git a/src-tauri/src/application/tunnels.rs b/src-tauri/src/application/tunnels.rs new file mode 100644 index 000000000..b25642e45 --- /dev/null +++ b/src-tauri/src/application/tunnels.rs @@ -0,0 +1,1039 @@ +use crate::models::{ + ConnectionParams, K8sConnection, K8sConnectionInput, SshConnection, SshConnectionInput, + SshTestParams, +}; +use crate::runtime::RuntimeContext; +use serde::Serialize; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use uuid::Uuid; + +const SSH_SECRET_SUFFIX: &str = "ssh"; +const SSH_PASSPHRASE_SUFFIX: &str = "ssh_passphrase"; +const WEB_ASKPASS_TIMEOUT: Duration = Duration::from_secs(120); +const DESKTOP_ASKPASS_TIMEOUT: Duration = Duration::from_secs(300); +/// Fallback remote port when a connection omits one (MySQL's default). +const DEFAULT_REMOTE_PORT: u16 = 3306; + +#[derive(Debug)] +pub enum TunnelCommand { + GetSshConnections, + SaveSshConnection { + name: String, + ssh: SshConnectionInput, + }, + UpdateSshConnection { + id: String, + name: String, + ssh: SshConnectionInput, + }, + DeleteSshConnection { + id: String, + }, + TestSshConnection { + ssh: SshTestParams, + }, + RespondSshAskpass { + id: u64, + response: Option, + }, + GetK8sConnections, + SaveK8sConnection { + k8s: K8sConnectionInput, + }, + UpdateK8sConnection { + id: String, + k8s: K8sConnectionInput, + }, + DeleteK8sConnection { + id: String, + }, + TestK8sConnection { + context: String, + namespace: String, + options: crate::k8s_tunnel::K8sCommandOptions, + }, + GetK8sContexts { + options: crate::k8s_tunnel::K8sCommandOptions, + }, + GetK8sNamespaces { + context: String, + options: crate::k8s_tunnel::K8sCommandOptions, + }, + GetK8sResources { + context: String, + namespace: String, + resource_type: String, + options: crate::k8s_tunnel::K8sCommandOptions, + }, + GetK8sResourcePorts { + context: String, + namespace: String, + resource_type: String, + resource_name: String, + options: crate::k8s_tunnel::K8sCommandOptions, + }, + ValidateK8sPath { + path: String, + kind: String, + }, + TestSsmConnection { + target: String, + profile: Option, + region: Option, + host: String, + port: u16, + }, +} + +pub async fn execute( + runtime: &RuntimeContext, + session_id: Option, + command: TunnelCommand, +) -> Result { + match command { + TunnelCommand::GetSshConnections => json(get_ssh_connections(runtime, false)?), + TunnelCommand::SaveSshConnection { name, ssh } => { + json(save_ssh_connection(runtime, name, ssh, false)?) + } + TunnelCommand::UpdateSshConnection { id, name, ssh } => { + json(update_ssh_connection(runtime, id, name, ssh, false)?) + } + TunnelCommand::DeleteSshConnection { id } => { + delete_ssh_connection(runtime, &id)?; + Ok(Value::Null) + } + TunnelCommand::TestSshConnection { ssh } => { + json(test_ssh_connection(runtime, ssh, session_id).await?) + } + TunnelCommand::RespondSshAskpass { id, response } => { + crate::askpass::respond_for_session(session_id, id, response)?; + Ok(Value::Null) + } + TunnelCommand::GetK8sConnections => json(get_k8s_connections(runtime)?), + TunnelCommand::SaveK8sConnection { k8s } => json(save_k8s_connection(runtime, k8s)?), + TunnelCommand::UpdateK8sConnection { id, k8s } => { + json(update_k8s_connection(runtime, id, k8s)?) + } + TunnelCommand::DeleteK8sConnection { id } => { + delete_k8s_connection(runtime, &id)?; + Ok(Value::Null) + } + TunnelCommand::TestK8sConnection { + context, + namespace, + options, + } => json( + run_blocking(move || { + crate::k8s_tunnel::test_k8s_connection(&context, &namespace, &options) + }) + .await?, + ), + TunnelCommand::GetK8sContexts { options } => { + json(run_blocking(move || crate::k8s_tunnel::get_k8s_contexts(&options)).await?) + } + TunnelCommand::GetK8sNamespaces { context, options } => json( + run_blocking(move || crate::k8s_tunnel::get_k8s_namespaces(&context, &options)).await?, + ), + TunnelCommand::GetK8sResources { + context, + namespace, + resource_type, + options, + } => json( + run_blocking(move || { + crate::k8s_tunnel::get_k8s_resources(&context, &namespace, &resource_type, &options) + }) + .await?, + ), + TunnelCommand::GetK8sResourcePorts { + context, + namespace, + resource_type, + resource_name, + options, + } => json( + run_blocking(move || { + crate::k8s_tunnel::get_k8s_resource_ports( + &context, + &namespace, + &resource_type, + &resource_name, + &options, + ) + }) + .await?, + ), + TunnelCommand::ValidateK8sPath { path, kind } => { + crate::k8s_tunnel::validate_k8s_path(&path, &kind)?; + Ok(Value::Null) + } + TunnelCommand::TestSsmConnection { + target, + profile, + region, + host, + port, + } => json( + run_blocking(move || { + crate::ssm_tunnel::test_ssm_connection( + &target, + profile.as_deref(), + region.as_deref(), + &host, + port, + ) + }) + .await?, + ), + } +} + +async fn run_blocking( + operation: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(operation) + .await + .map_err(|error| error.to_string())? +} + +pub fn get_ssh_connections( + runtime: &RuntimeContext, + reveal_secrets: bool, +) -> Result, String> { + let mut connections: Vec = load_json(&ssh_path(runtime))?; + for connection in &mut connections { + normalize_ssh_auth_type(connection); + if connection.save_in_keychain.unwrap_or(false) { + connection.password = runtime + .secrets + .get(&secret_account(&connection.id, SSH_SECRET_SUFFIX))?; + connection.key_passphrase = runtime + .secrets + .get(&secret_account(&connection.id, SSH_PASSPHRASE_SUFFIX))?; + } + if !reveal_secrets { + connection.password = None; + connection.key_passphrase = None; + } + } + Ok(connections) +} + +pub fn save_ssh_connection( + runtime: &RuntimeContext, + name: String, + ssh: SshConnectionInput, + reveal_secrets: bool, +) -> Result { + validate_ssh_input(&name, &ssh)?; + let path = ssh_path(runtime); + let mut connections: Vec = load_json(&path)?; + let id = Uuid::new_v4().to_string(); + let input_password = ssh.password.clone(); + let input_passphrase = ssh.key_passphrase.clone(); + let connection = persist_ssh_input(runtime, id, name, ssh, None)?; + connections.push(connection.clone()); + save_json(&path, &connections)?; + Ok(with_input_secrets( + redact_ssh(connection, reveal_secrets), + reveal_secrets, + input_password, + input_passphrase, + )) +} + +pub fn update_ssh_connection( + runtime: &RuntimeContext, + id: String, + name: String, + ssh: SshConnectionInput, + reveal_secrets: bool, +) -> Result { + validate_ssh_input(&name, &ssh)?; + let path = ssh_path(runtime); + let mut connections: Vec = load_json(&path)?; + let index = connections + .iter() + .position(|connection| connection.id == id) + .ok_or_else(|| "SSH connection not found".to_string())?; + let previous = connections[index].clone(); + let input_password = ssh.password.clone(); + let input_passphrase = ssh.key_passphrase.clone(); + let connection = persist_ssh_input(runtime, id, name, ssh, Some(&previous))?; + connections[index] = connection.clone(); + save_json(&path, &connections)?; + Ok(with_input_secrets( + redact_ssh(connection, reveal_secrets), + reveal_secrets, + input_password, + input_passphrase, + )) +} + +pub fn delete_ssh_connection(runtime: &RuntimeContext, id: &str) -> Result<(), String> { + let path = ssh_path(runtime); + if !path.exists() { + return Ok(()); + } + let mut connections: Vec = load_json(&path)?; + connections.retain(|connection| connection.id != id); + runtime + .secrets + .delete(&secret_account(id, SSH_SECRET_SUFFIX))?; + runtime + .secrets + .delete(&secret_account(id, SSH_PASSPHRASE_SUFFIX))?; + save_json(&path, &connections) +} + +pub async fn test_ssh_connection( + runtime: &RuntimeContext, + mut ssh: SshTestParams, + session_id: Option, +) -> Result { + restore_ssh_test_secrets(runtime, &mut ssh)?; + + emit_progress( + runtime, + session_id, + ssh.progress_id.as_deref(), + "sshTunnel", + "start", + Some(format!("{}@{}:{}", ssh.user, ssh.host, ssh.port)), + ); + + let allow_prompt = ssh.allow_passphrase_prompt.unwrap_or(false); + let askpass = if allow_prompt || ssh.password.is_some() || ssh.key_passphrase.is_some() { + Some(crate::askpass::start_scoped_server_with( + runtime.events.clone(), + session_id, + if session_id.is_some() { + WEB_ASKPASS_TIMEOUT + } else { + DESKTOP_ASKPASS_TIMEOUT + }, + crate::askpass::AskpassOptions { + password: ssh.password.clone(), + key_passphrase: ssh.key_passphrase.clone(), + key_path: ssh.key_file.clone(), + allow_ui: allow_prompt, + }, + )?) + } else { + None + }; + let result = tokio::task::spawn_blocking(move || { + crate::ssh_tunnel::test_ssh_connection_with_askpass( + &ssh.host, + ssh.port, + &ssh.user, + ssh.password.as_deref(), + ssh.key_file.as_deref(), + ssh.key_passphrase.as_deref(), + allow_prompt, + askpass, + ) + }) + .await + .map_err(|error| error.to_string())?; + + match &result { + Ok(_) => emit_progress( + runtime, + session_id, + ssh.progress_id.as_deref(), + "sshTunnel", + "ok", + None, + ), + Err(error) => emit_progress( + runtime, + session_id, + ssh.progress_id.as_deref(), + "sshTunnel", + "error", + Some(error.clone()), + ), + } + result +} + +fn restore_ssh_test_secrets( + runtime: &RuntimeContext, + ssh: &mut SshTestParams, +) -> Result<(), String> { + if let Some(connection_id) = ssh.connection_id.as_deref() { + let saved = get_ssh_connection(runtime, connection_id, true)?; + if ssh.password.as_deref().is_none_or(str::is_empty) { + ssh.password = saved.password; + } + if ssh.key_passphrase.as_deref().is_none_or(str::is_empty) { + ssh.key_passphrase = saved.key_passphrase; + } + } + if let Some(connection_id) = ssh.db_connection_id.as_deref() { + let saved_params = + crate::persistence::load_connections_file(&runtime.paths.connections_file()) + .ok() + .and_then(|file| { + file.connections + .into_iter() + .find(|connection| connection.id == connection_id) + .map(|connection| connection.params) + }); + if ssh.password.as_deref().is_none_or(str::is_empty) { + ssh.password = runtime + .secrets + .get(&secret_account(connection_id, SSH_SECRET_SUFFIX))? + .or_else(|| { + saved_params + .as_ref() + .and_then(|params| params.ssh_password.clone()) + }); + } + if ssh.key_passphrase.as_deref().is_none_or(str::is_empty) { + ssh.key_passphrase = runtime + .secrets + .get(&secret_account(connection_id, SSH_PASSPHRASE_SUFFIX))? + .or_else(|| { + saved_params + .as_ref() + .and_then(|params| params.ssh_key_passphrase.clone()) + }); + } + } + Ok(()) +} + +pub fn get_k8s_connections(runtime: &RuntimeContext) -> Result, String> { + load_json(&k8s_path(runtime)) +} + +pub fn save_k8s_connection( + runtime: &RuntimeContext, + k8s: K8sConnectionInput, +) -> Result { + validate_k8s_input(&k8s)?; + let path = k8s_path(runtime); + let mut connections: Vec = load_json(&path)?; + let connection = k8s_from_input(Uuid::new_v4().to_string(), k8s); + connections.push(connection.clone()); + save_json(&path, &connections)?; + Ok(connection) +} + +pub fn update_k8s_connection( + runtime: &RuntimeContext, + id: String, + k8s: K8sConnectionInput, +) -> Result { + validate_k8s_input(&k8s)?; + let path = k8s_path(runtime); + let mut connections: Vec = load_json(&path)?; + let index = connections + .iter() + .position(|connection| connection.id == id) + .ok_or_else(|| format!("K8s connection with ID {id} not found"))?; + let connection = k8s_from_input(id, k8s); + connections[index] = connection.clone(); + save_json(&path, &connections)?; + Ok(connection) +} + +pub fn delete_k8s_connection(runtime: &RuntimeContext, id: &str) -> Result<(), String> { + let path = k8s_path(runtime); + if !path.exists() { + return Ok(()); + } + let mut connections: Vec = load_json(&path)?; + connections.retain(|connection| connection.id != id); + save_json(&path, &connections) +} + +pub fn expand_connection_params( + runtime: &RuntimeContext, + params: &ConnectionParams, +) -> Result { + let mut expanded = params.clone(); + if expanded.ssh_enabled.unwrap_or(false) { + if let Some(id) = expanded.ssh_connection_id.as_deref() { + let ssh = get_ssh_connection(runtime, id, true)?; + expanded.ssh_host = Some(ssh.host); + expanded.ssh_port = Some(ssh.port); + expanded.ssh_user = Some(ssh.user); + expanded.ssh_password = ssh.password; + expanded.ssh_key_file = ssh.key_file; + expanded.ssh_key_passphrase = ssh.key_passphrase; + expanded.ssh_allow_passphrase_prompt = ssh.allow_passphrase_prompt; + } + } + if expanded.k8s_enabled.unwrap_or(false) { + if let Some(id) = expanded.k8s_connection_id.as_deref() { + let k8s = get_k8s_connections(runtime)? + .into_iter() + .find(|connection| connection.id == id) + .ok_or_else(|| format!("K8s connection with ID {id} not found"))?; + expanded.k8s_context = Some(k8s.context); + expanded.k8s_namespace = Some(k8s.namespace); + expanded.k8s_resource_type = Some(k8s.resource_type); + expanded.k8s_resource_name = Some(k8s.resource_name); + expanded.k8s_port = Some(k8s.port); + expanded.k8s_kubectl_path = k8s.kubectl_path; + expanded.k8s_kubeconfig_path = k8s.kubeconfig_path; + } + } + Ok(expanded) +} + +pub fn resolve_connection_params( + runtime: &RuntimeContext, + params: &ConnectionParams, + session_id: Option, +) -> Result { + let params = expand_connection_params(runtime, params)?; + let askpass = scoped_askpass(runtime, ¶ms, session_id)?; + resolve_expanded_connection_params(¶ms, askpass) +} + +pub fn resolve_expanded_connection_params( + params: &ConnectionParams, + askpass_server: Option, +) -> Result { + let mut resolved = resolve_connection_transport(params, askpass_server)?; + // Only file/folder drivers store a path in `database`; for network drivers + // it is a schema name and must be passed through untouched. + if crate::drivers::registry::is_local_path_driver(&resolved.driver) { + resolved.database = crate::fs_path::sanitize_database_selection(&resolved.database); + } + Ok(resolved) +} + +/// SSH, Kubernetes and AWS SSM each rewrite host/port to a local tunnel, so at +/// most one of them can be active for a connection. +pub(crate) fn ensure_single_tunnel(params: &ConnectionParams) -> Result<(), String> { + let enabled: Vec<&str> = [ + ("SSH", params.ssh_enabled), + ("Kubernetes", params.k8s_enabled), + ("AWS SSM", params.ssm_enabled), + ] + .into_iter() + .filter(|(_, on)| on.unwrap_or(false)) + .map(|(name, _)| name) + .collect(); + + if enabled.len() > 1 { + return Err(format!( + "{} tunnels cannot both be enabled for the same connection", + enabled.join(" and ") + )); + } + Ok(()) +} + +/// Resolve the tunnel / proxy transport for a connection (K8s, SSM, SSH or a +/// database-scope proxy) and return params pointing at the local endpoint. +fn resolve_connection_transport( + params: &ConnectionParams, + askpass_server: Option, +) -> Result { + ensure_single_tunnel(params)?; + + // K8s results are already on localhost; do not re-proxy. + if params.k8s_enabled.unwrap_or(false) { + return resolve_k8s_params(params); + } + if params.ssm_enabled.unwrap_or(false) { + return resolve_ssm_params(params); + } + if params.ssh_enabled.unwrap_or(false) { + return resolve_ssh_params(params, askpass_server); + } + + // Direct DB connection — apply database-scope proxy when configured. + let mut resolved = params.clone(); + if let Some(proxy) = crate::proxy::resolve_for_connection( + crate::proxy::SCOPE_DATABASE, + params.connection_id.as_deref(), + params.proxy.as_ref(), + ) { + let host = resolved.host.as_deref().unwrap_or("localhost").to_string(); + let port = resolved.port.unwrap_or(DEFAULT_REMOTE_PORT); + if !is_loopback_host(&host) { + let fwd_port = crate::proxy::ensure_forward(&proxy, &host, port)?; + log::info!( + "Database {}:{} reached via proxy forward on 127.0.0.1:{}", + host, + port, + fwd_port + ); + resolved.host = Some("127.0.0.1".to_string()); + resolved.port = Some(fwd_port); + } + } + Ok(resolved) +} + +fn is_loopback_host(host: &str) -> bool { + let h = host.trim().to_ascii_lowercase(); + h == "localhost" || h == "127.0.0.1" || h == "::1" || h == "[::1]" +} + +fn resolve_ssh_params( + params: &ConnectionParams, + askpass_server: Option, +) -> Result { + let ssh_host = params.ssh_host.as_deref().ok_or("Missing SSH Host")?; + let ssh_port = params.ssh_port.unwrap_or(22); + let ssh_user = params.ssh_user.as_deref().ok_or("Missing SSH User")?; + let remote_host = params.host.as_deref().unwrap_or("localhost"); + let remote_port = params.port.unwrap_or(DEFAULT_REMOTE_PORT); + + let proxy = crate::proxy::resolve_for_connection( + crate::proxy::SCOPE_SSH_TUNNEL, + params.connection_id.as_deref(), + params.proxy.as_ref(), + ); + let base_key = + crate::ssh_tunnel::build_tunnel_key(ssh_user, ssh_host, ssh_port, remote_host, remote_port); + let key = match &proxy { + Some(p) => { + let proto = match p.protocol { + crate::proxy::ProxyProtocol::Http => "http", + crate::proxy::ProxyProtocol::Socks5 => "socks5", + }; + let user = p.username.as_deref().unwrap_or(""); + format!("{base_key}|px:{proto}:{}:{}:{user}", p.host.trim(), p.port) + } + None => base_key, + }; + if let Some(tunnel) = crate::ssh_tunnel::get_tunnels().lock().unwrap().get(&key) { + log::debug!("Reusing existing SSH tunnel on port {}", tunnel.local_port); + let mut resolved = params.clone(); + resolved.host = Some("127.0.0.1".to_string()); + resolved.port = Some(tunnel.local_port); + return Ok(resolved); + } + + let (tcp_host, tcp_port) = if let Some(proxy) = proxy { + let fwd_port = crate::proxy::ensure_forward(&proxy, ssh_host, ssh_port)?; + log::info!( + "SSH bastion {}:{} reached via proxy forward on 127.0.0.1:{}", + ssh_host, + ssh_port, + fwd_port + ); + (Some("127.0.0.1".to_string()), Some(fwd_port)) + } else { + (None, None) + }; + + log::info!( + "Creating new SSH tunnel for {}@{}:{}", + ssh_user, + ssh_host, + ssh_port + ); + let allow_prompt = params.ssh_allow_passphrase_prompt.unwrap_or(false); + let tunnel = crate::ssh_tunnel::SshTunnel::new_with_askpass( + ssh_host, + ssh_port, + ssh_user, + params.ssh_password.as_deref(), + params.ssh_key_file.as_deref(), + params.ssh_key_passphrase.as_deref(), + allow_prompt, + remote_host, + remote_port, + askpass_server, + tcp_host.as_deref(), + tcp_port, + ) + .map_err(|e| { + eprintln!("[Connection Error] SSH Tunnel setup failed: {}", e); + e + })?; + let local_port = tunnel.local_port; + log::info!("SSH tunnel created successfully on port {}", local_port); + crate::ssh_tunnel::get_tunnels() + .lock() + .unwrap() + .insert(key, tunnel); + let mut resolved = params.clone(); + resolved.host = Some("127.0.0.1".to_string()); + resolved.port = Some(local_port); + Ok(resolved) +} + +/// Resolve AWS SSM tunnel params synchronously. Like SSH, the session forwards +/// to the connection's own host/port; unlike SSH there is no saved-connection +/// indirection, so every field is inline. +pub(crate) fn resolve_ssm_params(params: &ConnectionParams) -> Result { + let target = params + .ssm_target + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()) + .ok_or("Missing AWS SSM target")?; + let profile = params.ssm_profile.as_deref(); + let region = params.ssm_region.as_deref(); + let remote_host = params.host.as_deref().unwrap_or("localhost"); + let remote_port = params.port.unwrap_or(DEFAULT_REMOTE_PORT); + + let map_key = + crate::ssm_tunnel::build_tunnel_key(target, profile, region, remote_host, remote_port); + + { + let mut tunnels = crate::ssm_tunnel::get_tunnels().lock().unwrap(); + if let Some(tunnel) = tunnels.get(&map_key) { + if tunnel.is_alive() { + log::debug!("Reusing existing SSM tunnel on port {}", tunnel.local_port); + let mut new_params = params.clone(); + new_params.ssm_enabled = Some(false); + new_params.host = Some("127.0.0.1".to_string()); + new_params.port = Some(tunnel.local_port); + return Ok(new_params); + } + log::info!( + "Discarding dead SSM tunnel on port {}; the session ended", + tunnel.local_port + ); + tunnels.remove(&map_key); + } + } + + log::info!( + "Creating new SSM tunnel to {}:{} via {}", + remote_host, + remote_port, + target + ); + + let tunnel = + crate::ssm_tunnel::SsmTunnel::new(target, profile, region, remote_host, remote_port) + .map_err(|e| { + eprintln!("[Connection Error] SSM Tunnel setup failed: {}", e); + e + })?; + + let local_port = tunnel.local_port; + log::info!("SSM tunnel created successfully on port {}", local_port); + + crate::ssm_tunnel::get_tunnels() + .lock() + .unwrap() + .insert(map_key, tunnel); + + let mut new_params = params.clone(); + new_params.ssm_enabled = Some(false); + new_params.host = Some("127.0.0.1".to_string()); + new_params.port = Some(local_port); + Ok(new_params) +} + +fn scoped_askpass( + runtime: &RuntimeContext, + params: &ConnectionParams, + session_id: Option, +) -> Result, String> { + if !params.ssh_allow_passphrase_prompt.unwrap_or(false) + && params.ssh_password.is_none() + && params.ssh_key_passphrase.is_none() + { + return Ok(None); + } + crate::askpass::start_scoped_server_with( + runtime.events.clone(), + session_id, + if session_id.is_some() { + WEB_ASKPASS_TIMEOUT + } else { + DESKTOP_ASKPASS_TIMEOUT + }, + crate::askpass::AskpassOptions { + password: params.ssh_password.clone(), + key_passphrase: params.ssh_key_passphrase.clone(), + key_path: params.ssh_key_file.clone(), + allow_ui: params.ssh_allow_passphrase_prompt.unwrap_or(false), + }, + ) + .map(Some) +} + +pub(crate) fn resolve_k8s_params(params: &ConnectionParams) -> Result { + let context = params.k8s_context.as_deref().ok_or("Missing K8s context")?; + let namespace = params + .k8s_namespace + .as_deref() + .ok_or("Missing K8s namespace")?; + let resource_type = params + .k8s_resource_type + .as_deref() + .ok_or("Missing K8s resource type")?; + let resource_name = params + .k8s_resource_name + .as_deref() + .ok_or("Missing K8s resource name")?; + let port = params.k8s_port.ok_or("Missing K8s port")?; + let options = crate::k8s_tunnel::K8sCommandOptions::new( + params.k8s_kubectl_path.clone(), + params.k8s_kubeconfig_path.clone(), + ); + let key = crate::k8s_tunnel::build_tunnel_key( + context, + namespace, + resource_type, + resource_name, + port, + &options, + ); + let preferred_local_port = match crate::k8s_tunnel::reuse_or_discard_dead(&key) { + Ok(local_port) => { + let mut resolved = params.clone(); + resolved.k8s_enabled = Some(false); + resolved.host = Some("127.0.0.1".to_string()); + resolved.port = Some(local_port); + return Ok(resolved); + } + Err(previous) => previous, + }; + let tunnel = crate::k8s_tunnel::K8sTunnel::new( + context, + namespace, + resource_type, + resource_name, + port, + &options, + preferred_local_port, + )?; + let local_port = crate::k8s_tunnel::insert_tunnel(key, tunnel); + let mut resolved = params.clone(); + resolved.k8s_enabled = Some(false); + resolved.host = Some("127.0.0.1".to_string()); + resolved.port = Some(local_port); + Ok(resolved) +} + +fn persist_ssh_input( + runtime: &RuntimeContext, + id: String, + name: String, + ssh: SshConnectionInput, + previous: Option<&SshConnection>, +) -> Result { + let keychain = ssh.save_in_keychain.unwrap_or(false); + if keychain { + set_secret(runtime, &id, SSH_SECRET_SUFFIX, ssh.password.as_deref())?; + set_secret( + runtime, + &id, + SSH_PASSPHRASE_SUFFIX, + ssh.key_passphrase.as_deref(), + )?; + } else { + runtime + .secrets + .delete(&secret_account(&id, SSH_SECRET_SUFFIX))?; + runtime + .secrets + .delete(&secret_account(&id, SSH_PASSPHRASE_SUFFIX))?; + } + Ok(SshConnection { + id, + name, + host: ssh.host, + port: ssh.port, + user: ssh.user, + auth_type: Some(ssh.auth_type), + password: (!keychain) + .then(|| { + ssh.password + .or_else(|| previous.and_then(|value| value.password.clone())) + }) + .flatten(), + key_file: ssh.key_file, + key_passphrase: (!keychain) + .then(|| { + ssh.key_passphrase + .or_else(|| previous.and_then(|value| value.key_passphrase.clone())) + }) + .flatten(), + allow_passphrase_prompt: ssh.allow_passphrase_prompt, + save_in_keychain: ssh.save_in_keychain, + }) +} + +fn validate_ssh_input(name: &str, ssh: &SshConnectionInput) -> Result<(), String> { + if name.trim().is_empty() { + return Err("Connection name is required".to_string()); + } + if ssh.host.trim().is_empty() { + return Err("SSH host is required".to_string()); + } + if ssh.user.trim().is_empty() { + return Err("SSH user is required".to_string()); + } + if ssh.port == 0 { + return Err("SSH port must be between 1 and 65535".to_string()); + } + if !matches!(ssh.auth_type.as_str(), "password" | "ssh_key") { + return Err("Authentication type must be password or ssh_key".to_string()); + } + Ok(()) +} + +fn validate_k8s_input(k8s: &K8sConnectionInput) -> Result<(), String> { + if k8s.name.trim().is_empty() + || k8s.context.trim().is_empty() + || k8s.namespace.trim().is_empty() + || k8s.resource_name.trim().is_empty() + || !matches!(k8s.resource_type.as_str(), "service" | "pod") + || k8s.port == 0 + { + return Err("Invalid Kubernetes connection profile".to_string()); + } + crate::k8s_tunnel::validate_k8s_path( + k8s.kubectl_path.as_deref().unwrap_or_default(), + "kubectl", + )?; + crate::k8s_tunnel::validate_k8s_path( + k8s.kubeconfig_path.as_deref().unwrap_or_default(), + "kubeconfig", + ) +} + +fn k8s_from_input(id: String, input: K8sConnectionInput) -> K8sConnection { + K8sConnection { + id, + name: input.name, + context: input.context, + namespace: input.namespace, + resource_type: input.resource_type, + resource_name: input.resource_name, + port: input.port, + kubectl_path: input.kubectl_path, + kubeconfig_path: input.kubeconfig_path, + } +} + +fn get_ssh_connection( + runtime: &RuntimeContext, + id: &str, + reveal_secrets: bool, +) -> Result { + get_ssh_connections(runtime, reveal_secrets)? + .into_iter() + .find(|connection| connection.id == id) + .ok_or_else(|| format!("SSH connection with ID {id} not found")) +} + +fn normalize_ssh_auth_type(connection: &mut SshConnection) { + if connection.auth_type.is_none() { + connection.auth_type = Some( + if connection + .key_file + .as_deref() + .is_some_and(|key| !key.trim().is_empty()) + { + "ssh_key" + } else { + "password" + } + .to_string(), + ); + } +} + +fn redact_ssh(mut connection: SshConnection, reveal_secrets: bool) -> SshConnection { + if !reveal_secrets { + connection.password = None; + connection.key_passphrase = None; + } + connection +} + +fn with_input_secrets( + mut connection: SshConnection, + reveal_secrets: bool, + password: Option, + passphrase: Option, +) -> SshConnection { + if reveal_secrets { + connection.password = password; + connection.key_passphrase = passphrase; + } + connection +} + +fn set_secret( + runtime: &RuntimeContext, + id: &str, + suffix: &str, + value: Option<&str>, +) -> Result<(), String> { + if let Some(value) = value.filter(|value| !value.is_empty()) { + runtime.secrets.set(&secret_account(id, suffix), value)?; + } + Ok(()) +} + +fn emit_progress( + runtime: &RuntimeContext, + session_id: Option, + progress_id: Option<&str>, + step: &str, + status: &str, + detail: Option, +) { + let Some(id) = progress_id else { return }; + let payload = serde_json::json!({ + "id": id, + "step": step, + "status": status, + "detail": detail, + }); + let _ = match session_id { + Some(session_id) => runtime + .events + .emit_to(session_id, "connection-test-progress", payload), + None => runtime.events.emit("connection-test-progress", payload), + }; +} + +fn ssh_path(runtime: &RuntimeContext) -> PathBuf { + runtime.paths.config_dir().join("ssh_connections.json") +} + +fn k8s_path(runtime: &RuntimeContext) -> PathBuf { + runtime.paths.config_dir().join("k8s_connections.json") +} + +fn secret_account(id: &str, suffix: &str) -> String { + format!("{id}:{suffix}") +} + +fn load_json(path: &Path) -> Result, String> { + if !path.exists() { + return Ok(Vec::new()); + } + let content = fs::read_to_string(path).map_err(|error| error.to_string())?; + serde_json::from_str(&content).map_err(|error| error.to_string()) +} + +fn save_json(path: &Path, values: &[impl Serialize]) -> Result<(), String> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let content = serde_json::to_string_pretty(values).map_err(|error| error.to_string())?; + crate::persistence::write_private_file(path, content) +} + +fn json(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|error| error.to_string()) +} + +#[cfg(test)] +#[path = "tunnels_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/tunnels_tests.rs b/src-tauri/src/application/tunnels_tests.rs new file mode 100644 index 000000000..f46aff4f0 --- /dev/null +++ b/src-tauri/src/application/tunnels_tests.rs @@ -0,0 +1,240 @@ +use super::*; +use crate::models::DatabaseSelection; +use crate::runtime::events::NoopRuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct MemorySecrets { + values: Mutex>, +} + +impl RuntimeSecrets for MemorySecrets { + fn get(&self, account: &str) -> Result, String> { + Ok(self.values.lock().unwrap().get(account).cloned()) + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + self.values + .lock() + .unwrap() + .insert(account.to_string(), secret.to_string()); + Ok(()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + self.values.lock().unwrap().remove(account); + Ok(()) + } +} + +fn fixture() -> (tempfile::TempDir, RuntimeContext) { + let temp = tempfile::tempdir().unwrap(); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(MemorySecrets::default()), + ); + (temp, runtime) +} + +fn ssh_input() -> SshConnectionInput { + SshConnectionInput { + host: "bastion.example.com".to_string(), + port: 22, + user: "browser-user".to_string(), + auth_type: "password".to_string(), + password: Some("stored-password".to_string()), + key_file: None, + key_passphrase: Some("stored-passphrase".to_string()), + allow_passphrase_prompt: Some(true), + save_in_keychain: Some(true), + } +} + +#[test] +fn ssh_profile_secrets_are_write_only_for_web_responses() { + let (_temp, runtime) = fixture(); + let saved = save_ssh_connection( + &runtime, + "Production bastion".to_string(), + ssh_input(), + false, + ) + .unwrap(); + + assert!(saved.password.is_none()); + assert!(saved.key_passphrase.is_none()); + let persisted: Vec = load_json(&ssh_path(&runtime)).unwrap(); + assert!(persisted[0].password.is_none()); + assert!(persisted[0].key_passphrase.is_none()); + assert_eq!( + runtime + .secrets + .get(&secret_account(&saved.id, SSH_SECRET_SUFFIX)) + .unwrap() + .as_deref(), + Some("stored-password") + ); + + let desktop = get_ssh_connections(&runtime, true).unwrap(); + assert_eq!(desktop[0].password.as_deref(), Some("stored-password")); + let web = get_ssh_connections(&runtime, false).unwrap(); + assert!(web[0].password.is_none()); +} + +#[test] +fn saved_tunnel_profiles_expand_without_exposing_secrets() { + let (_temp, runtime) = fixture(); + let ssh = save_ssh_connection( + &runtime, + "Production bastion".to_string(), + ssh_input(), + false, + ) + .unwrap(); + let k8s = save_k8s_connection( + &runtime, + K8sConnectionInput { + name: "Production cluster".to_string(), + context: "prod".to_string(), + namespace: "database".to_string(), + resource_type: "service".to_string(), + resource_name: "postgres".to_string(), + port: 5432, + kubectl_path: None, + kubeconfig_path: None, + }, + ) + .unwrap(); + + let ssh_params = expand_connection_params( + &runtime, + &ConnectionParams { + driver: "postgres".to_string(), + database: DatabaseSelection::Single("app".to_string()), + ssh_enabled: Some(true), + ssh_connection_id: Some(ssh.id), + ..ConnectionParams::default() + }, + ) + .unwrap(); + assert_eq!(ssh_params.ssh_host.as_deref(), Some("bastion.example.com")); + assert_eq!(ssh_params.ssh_password.as_deref(), Some("stored-password")); + + let k8s_params = expand_connection_params( + &runtime, + &ConnectionParams { + driver: "postgres".to_string(), + database: DatabaseSelection::Single("app".to_string()), + k8s_enabled: Some(true), + k8s_connection_id: Some(k8s.id), + ..ConnectionParams::default() + }, + ) + .unwrap(); + assert_eq!(k8s_params.k8s_context.as_deref(), Some("prod")); + assert_eq!(k8s_params.k8s_resource_name.as_deref(), Some("postgres")); +} + +#[test] +fn ssh_tests_restore_inline_plaintext_secrets_from_saved_database_connections() { + let (_temp, runtime) = fixture(); + let file = crate::models::ConnectionsFile { + connections: vec![crate::models::SavedConnection { + id: "database-1".to_string(), + name: "Database".to_string(), + params: ConnectionParams { + driver: "postgres".to_string(), + database: DatabaseSelection::Single("app".to_string()), + ssh_password: Some("inline-password".to_string()), + ssh_key_passphrase: Some("inline-passphrase".to_string()), + save_in_keychain: Some(false), + ..ConnectionParams::default() + }, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + }], + ..crate::models::ConnectionsFile::default() + }; + crate::persistence::save_connections_file(&runtime.paths.connections_file(), &file).unwrap(); + let mut test = SshTestParams { + host: "bastion.example.com".to_string(), + port: 22, + user: "browser-user".to_string(), + password: None, + key_file: None, + key_passphrase: None, + allow_passphrase_prompt: None, + connection_id: None, + db_connection_id: Some("database-1".to_string()), + progress_id: None, + }; + + restore_ssh_test_secrets(&runtime, &mut test).unwrap(); + + assert_eq!(test.password.as_deref(), Some("inline-password")); + assert_eq!(test.key_passphrase.as_deref(), Some("inline-passphrase")); +} + +#[test] +fn profile_validation_rejects_invalid_inputs() { + let (_temp, runtime) = fixture(); + let mut ssh = ssh_input(); + ssh.auth_type = "agent".to_string(); + assert!( + save_ssh_connection(&runtime, "Invalid".to_string(), ssh, false) + .unwrap_err() + .contains("password or ssh_key") + ); + + let error = save_k8s_connection( + &runtime, + K8sConnectionInput { + name: "Invalid".to_string(), + context: "prod".to_string(), + namespace: "database".to_string(), + resource_type: "deployment".to_string(), + resource_name: "postgres".to_string(), + port: 5432, + kubectl_path: None, + kubeconfig_path: None, + }, + ) + .unwrap_err(); + assert_eq!(error, "Invalid Kubernetes connection profile"); +} + +#[cfg(unix)] +#[test] +fn ssh_profile_create_and_update_keep_plaintext_secrets_private() { + use std::os::unix::fs::PermissionsExt; + let (_temp, runtime) = fixture(); + let mut input = ssh_input(); + input.save_in_keychain = Some(false); + let saved = save_ssh_connection(&runtime, "Private".into(), input.clone(), true).unwrap(); + let path = ssh_path(&runtime); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + update_ssh_connection(&runtime, saved.id, "Updated".into(), input, true).unwrap(); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert!(fs::read_to_string(path) + .unwrap() + .contains("stored-password")); +} diff --git a/src-tauri/src/application/ui_state.rs b/src-tauri/src/application/ui_state.rs new file mode 100644 index 000000000..2fdfde5c4 --- /dev/null +++ b/src-tauri/src/application/ui_state.rs @@ -0,0 +1,48 @@ +//! Shared UI state commands (see [`crate::ui_state`]). + +use crate::runtime::RuntimeContext; +use serde_json::{json, Value}; + +/// Event emitted after a key changes so other windows and browser sessions +/// can apply the new value without reloading. +pub const UI_STATE_CHANGED_EVENT: &str = "ui-state://changed"; + +#[derive(Clone, Debug, PartialEq)] +pub enum UiStateCommand { + Get { keys: Option> }, + Set { key: String, value: Value }, + Delete { key: String }, +} + +pub async fn execute(runtime: &RuntimeContext, command: UiStateCommand) -> Result { + let database = crate::ui_state::database_path(runtime.paths.config_dir()); + match command { + UiStateCommand::Get { keys } => Ok(Value::Object( + crate::ui_state::get_entries(&database, keys.as_deref()).await?, + )), + UiStateCommand::Set { key, value } => { + crate::ui_state::set_entry(&database, &key, &value).await?; + notify(runtime, &key, value); + Ok(Value::Null) + } + UiStateCommand::Delete { key } => { + if crate::ui_state::delete_entry(&database, &key).await? { + notify(runtime, &key, Value::Null); + } + Ok(Value::Null) + } + } +} + +fn notify(runtime: &RuntimeContext, key: &str, value: Value) { + if let Err(error) = runtime.events.emit( + UI_STATE_CHANGED_EVENT, + json!({ "key": key, "value": value }), + ) { + log::warn!("UI state {key} saved but change delivery failed: {error}"); + } +} + +#[cfg(test)] +#[path = "ui_state_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/ui_state_tests.rs b/src-tauri/src/application/ui_state_tests.rs new file mode 100644 index 000000000..9881e67bc --- /dev/null +++ b/src-tauri/src/application/ui_state_tests.rs @@ -0,0 +1,97 @@ +use super::*; +use crate::runtime::events::RuntimeEvents; +use crate::runtime::paths::FixedRuntimePaths; +use crate::runtime::secrets::RuntimeSecrets; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct RecordingEvents { + values: Mutex>, +} + +impl RuntimeEvents for RecordingEvents { + fn emit(&self, event: &str, payload: Value) -> Result<(), String> { + self.values + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push((event.to_string(), payload)); + Ok(()) + } +} + +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 shares_state_through_the_config_folder_and_announces_changes() { + let temp = tempfile::tempdir().unwrap(); + let events = Arc::new(RecordingEvents::default()); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + temp.path().to_path_buf(), + temp.path().join("data"), + )), + events.clone(), + Arc::new(NoSecrets), + ); + + execute( + &runtime, + UiStateCommand::Set { + key: "tabularis_last_seen_version".into(), + value: json!("0.25.0"), + }, + ) + .await + .unwrap(); + let all = execute(&runtime, UiStateCommand::Get { keys: None }) + .await + .unwrap(); + assert_eq!(all, json!({ "tabularis_last_seen_version": "0.25.0" })); + assert!(temp.path().join(crate::ui_state::DATABASE_FILE).exists()); + + execute( + &runtime, + UiStateCommand::Delete { + key: "tabularis_last_seen_version".into(), + }, + ) + .await + .unwrap(); + // Deleting a missing key is not announced. + execute( + &runtime, + UiStateCommand::Delete { + key: "tabularis_last_seen_version".into(), + }, + ) + .await + .unwrap(); + + let emitted = events.values.lock().unwrap().clone(); + assert_eq!( + emitted, + vec![ + ( + UI_STATE_CHANGED_EVENT.to_string(), + json!({ "key": "tabularis_last_seen_version", "value": "0.25.0" }) + ), + ( + UI_STATE_CHANGED_EVENT.to_string(), + json!({ "key": "tabularis_last_seen_version", "value": null }) + ), + ] + ); + crate::ui_state::close(&crate::ui_state::database_path(temp.path())).await; +} diff --git a/src-tauri/src/askpass/mod.rs b/src-tauri/src/askpass/mod.rs index 800fc8d2d..046581404 100644 --- a/src-tauri/src/askpass/mod.rs +++ b/src-tauri/src/askpass/mod.rs @@ -24,6 +24,8 @@ pub use client::maybe_run_askpass_client; pub use protocol::PromptKind; pub use server::{AskpassOptions, AskpassServer, AskpassUi}; +use crate::runtime::events::RuntimeEvents; + use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{sync_channel, SyncSender}; @@ -31,7 +33,8 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use serde::Serialize; -use tauri::{AppHandle, Emitter}; + +use uuid::Uuid; /// Event emitted to the frontend when ssh needs user input. pub const REQUEST_EVENT: &str = "ssh-askpass://request"; @@ -42,20 +45,20 @@ 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); -fn pending_responses() -> &'static Mutex>>> { - static PENDING: OnceLock>>>> = OnceLock::new(); - PENDING.get_or_init(|| Mutex::new(HashMap::new())) +struct PendingResponse { + session_id: Option, + sender: SyncSender>, } -/// Store the app handle so SSH tunnel code can reach the frontend. -pub fn set_app_handle(app: AppHandle) { - let _ = APP_HANDLE.set(app); +fn pending_responses() -> &'static Mutex> { + static PENDING: OnceLock>> = OnceLock::new(); + PENDING.get_or_init(|| Mutex::new(HashMap::new())) } /// Start an askpass server bridged to the frontend. Fails when the app is not @@ -69,10 +72,36 @@ 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())?; - AskpassServer::start_with(Arc::new(FrontendUi { app: app.clone() }), options) + start_scoped_server_with( + 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, + response_timeout: Duration, + options: AskpassOptions, +) -> Result { + AskpassServer::start_with( + Arc::new(FrontendUi { + events, + session_id, + response_timeout, + }), + options, + ) } #[derive(Serialize, Clone)] @@ -82,36 +111,51 @@ struct AskpassRequestPayload { prompt: String, } -/// Bridges askpass exchanges to the webview via Tauri events. +/// Bridges askpass exchanges to the initiating frontend session. struct FrontendUi { - app: AppHandle, + events: Arc, + session_id: Option, + response_timeout: Duration, +} + +impl FrontendUi { + fn emit(&self, event: &str, payload: serde_json::Value) -> Result<(), String> { + match self.session_id { + Some(session_id) => self.events.emit_to(session_id, event, payload), + None => self.events.emit(event, payload), + } + } } impl AskpassUi for FrontendUi { fn request(&self, kind: PromptKind, prompt: &str) -> Option { let id = NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed); let (tx, rx) = sync_channel(1); - pending_responses().lock().unwrap().insert(id, tx); + pending_responses().lock().unwrap().insert( + id, + PendingResponse { + session_id: self.session_id, + sender: tx, + }, + ); let payload = AskpassRequestPayload { id, kind: kind.as_str(), prompt: prompt.to_string(), }; - if let Err(e) = self.app.emit(REQUEST_EVENT, payload) { - eprintln!("[Askpass] Failed to notify frontend: {}", e); + let payload = serde_json::to_value(payload).unwrap_or(serde_json::Value::Null); + if let Err(error) = self.emit(REQUEST_EVENT, payload) { + eprintln!("[Askpass] Failed to notify frontend: {error}"); pending_responses().lock().unwrap().remove(&id); return None; } - let response = rx - .recv_timeout(Duration::from_secs(RESPONSE_TIMEOUT_SECS)) - .ok() - .flatten(); + let response = rx.recv_timeout(self.response_timeout).ok().flatten(); // Entry is still present when the wait timed out (the command removes // it on a real answer); clean up and close the stale modal. if pending_responses().lock().unwrap().remove(&id).is_some() { - let _ = self.app.emit(DISMISS_EVENT, id); + let _ = self.emit(DISMISS_EVENT, serde_json::json!(id)); } response } @@ -123,22 +167,53 @@ impl AskpassUi for FrontendUi { kind: PromptKind::Notify.as_str(), prompt: prompt.to_string(), }; - if let Err(e) = self.app.emit(REQUEST_EVENT, payload) { - eprintln!("[Askpass] Failed to notify frontend: {}", e); + let payload = serde_json::to_value(payload).unwrap_or(serde_json::Value::Null); + if let Err(error) = self.emit(REQUEST_EVENT, payload) { + eprintln!("[Askpass] Failed to notify frontend: {error}"); } id } fn dismiss_notification(&self, id: u64) { - let _ = self.app.emit(DISMISS_EVENT, id); + let _ = self.emit(DISMISS_EVENT, serde_json::json!(id)); } } /// Frontend answer to an askpass prompt. `response = None` means the user /// cancelled. -#[tauri::command] pub fn respond_ssh_askpass(id: u64, response: Option) { - if let Some(tx) = pending_responses().lock().unwrap().remove(&id) { - let _ = tx.send(response); + let _ = respond_for_session(None, id, response); +} + +pub fn respond_for_session( + session_id: Option, + id: u64, + response: Option, +) -> Result<(), String> { + let mut pending = pending_responses().lock().unwrap(); + let Some(request) = pending.get(&id) else { + return Err("SSH askpass prompt is no longer pending".to_string()); + }; + if request.session_id != session_id { + return Err("SSH askpass prompt belongs to another session".to_string()); } + let request = pending.remove(&id).expect("pending response disappeared"); + drop(pending); + request + .sender + .send(response) + .map_err(|_| "SSH askpass prompt is no longer accepting responses".to_string()) +} + +pub fn start_scoped_server( + events: Arc, + session_id: Option, + response_timeout: Duration, +) -> Result { + start_scoped_server_with( + events, + session_id, + response_timeout, + AskpassOptions::interactive(), + ) } diff --git a/src-tauri/src/askpass/tests.rs b/src-tauri/src/askpass/tests.rs index 6b8aec54c..765605747 100644 --- a/src-tauri/src/askpass/tests.rs +++ b/src-tauri/src/askpass/tests.rs @@ -143,6 +143,91 @@ mod response_codec_tests { } } +#[cfg(unix)] +mod scoped_ui_tests { + use super::super::{respond_for_session, AskpassUi, FrontendUi, PromptKind}; + use crate::runtime::events::RuntimeEvents; + use serde_json::Value; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + use uuid::Uuid; + + #[derive(Default)] + struct RecordingEvents { + events: Mutex>, + } + + impl RuntimeEvents for RecordingEvents { + fn emit(&self, _event: &str, _payload: Value) -> Result<(), String> { + Err("unscoped event".to_string()) + } + + fn emit_to(&self, session_id: Uuid, event: &str, payload: Value) -> Result<(), String> { + self.events + .lock() + .unwrap() + .push((session_id, event.to_string(), payload)); + Ok(()) + } + } + + #[test] + fn prompt_responses_are_bound_to_the_initiating_session() { + let events = Arc::new(RecordingEvents::default()); + let owner = Uuid::new_v4(); + let ui = Arc::new(FrontendUi { + events: events.clone(), + session_id: Some(owner), + response_timeout: Duration::from_secs(1), + }); + let worker = std::thread::spawn(move || ui.request(PromptKind::Secret, "Enter PIN")); + + let id = wait_for_request(&events); + let other = Uuid::new_v4(); + assert!( + respond_for_session(Some(other), id, Some("wrong".to_string())) + .unwrap_err() + .contains("another session") + ); + respond_for_session(Some(owner), id, Some("1234".to_string())).unwrap(); + assert_eq!(worker.join().unwrap().as_deref(), Some("1234")); + } + + #[test] + fn unattended_prompts_time_out_and_emit_a_scoped_dismissal() { + let events = Arc::new(RecordingEvents::default()); + let owner = Uuid::new_v4(); + let ui = FrontendUi { + events: events.clone(), + session_id: Some(owner), + response_timeout: Duration::from_millis(10), + }; + + assert!(ui.request(PromptKind::Confirm, "Continue?").is_none()); + let recorded = events.events.lock().unwrap(); + assert_eq!(recorded[0].0, owner); + assert_eq!(recorded[0].1, "ssh-askpass://request"); + assert_eq!(recorded[1].0, owner); + assert_eq!(recorded[1].1, "ssh-askpass://dismiss"); + } + + fn wait_for_request(events: &RecordingEvents) -> u64 { + for _ in 0..100 { + if let Some(id) = events + .events + .lock() + .unwrap() + .first() + .and_then(|(_, _, payload)| payload["id"].as_u64()) + { + return id; + } + std::thread::sleep(Duration::from_millis(5)); + } + panic!("askpass request was not emitted"); + } +} + #[cfg(unix)] mod server_tests { use super::super::protocol::{decode_response, encode_request, PromptKind}; diff --git a/src-tauri/src/backup/mod.rs b/src-tauri/src/backup/mod.rs index 4c0346a90..12bf0ed87 100644 --- a/src-tauri/src/backup/mod.rs +++ b/src-tauri/src/backup/mod.rs @@ -11,7 +11,8 @@ use chrono::NaiveDateTime; use keyring::Entry; use std::fs; use std::path::PathBuf; -use tauri::{AppHandle, Runtime}; + +use crate::runtime::RuntimeContext; #[cfg(test)] mod tests; @@ -30,27 +31,17 @@ const MAX_TICK_SECS: u64 = 15 * 60; // ---------- Keychain ---------- -fn set_keychain(user: &str, password: &str) -> Result<(), String> { - Entry::new(SERVICE_NAME, user) - .and_then(|e| e.set_password(password)) - .map_err(|e| e.to_string()) -} - fn get_keychain(user: &str) -> Result, String> { - match Entry::new(SERVICE_NAME, user).map_err(|e| e.to_string())?.get_password() { + match Entry::new(SERVICE_NAME, user) + .map_err(|e| e.to_string())? + .get_password() + { Ok(pwd) => Ok(Some(pwd)), Err(keyring::Error::NoEntry) => Ok(None), Err(e) => Err(e.to_string()), } } -fn delete_keychain(user: &str) -> Result<(), String> { - match Entry::new(SERVICE_NAME, user).map_err(|e| e.to_string())?.delete_credential() { - Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), - Err(e) => Err(e.to_string()), - } -} - pub fn get_password() -> Result, String> { get_keychain(KEYCHAIN_USER) } @@ -153,11 +144,24 @@ trait BackupTarget: Send + Sync { /// Builds the configured backup target. `"local"` is the default; unknown /// ids fall back to local so a config written by a newer version degrades /// gracefully instead of failing. -fn target_from_config( +fn target_from_config(config: &crate::config::AppConfig) -> Result, String> { + let webdav_password = if backup_target(config) == "webdav" { + get_target_password("webdav")? + } else { + None + }; + target_from_config_with_password(config, webdav_password) +} + +fn target_from_config_with_password( config: &crate::config::AppConfig, + webdav_password: Option, ) -> Result, String> { match backup_target(config).as_str() { - "webdav" => Ok(Box::new(WebdavTarget::from_config(config)?)), + "webdav" => Ok(Box::new(WebdavTarget::from_config( + config, + webdav_password, + )?)), _ => { let dir = config .backup_directory @@ -233,7 +237,10 @@ struct WebdavTarget { } impl WebdavTarget { - fn from_config(config: &crate::config::AppConfig) -> Result { + fn from_config( + config: &crate::config::AppConfig, + password: Option, + ) -> Result { let base = config .backup_webdav_url .clone() @@ -247,7 +254,7 @@ impl WebdavTarget { .map_err(|e| format!("Failed to build HTTP client: {e}"))?, base, username: config.backup_webdav_username.clone().unwrap_or_default(), - password: get_target_password("webdav")?.ok_or("WebDAV password is not set")?, + password: password.ok_or("WebDAV password is not set")?, }) } } @@ -317,8 +324,27 @@ 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 { - let target = target_from_config(config).ok()?; +pub(crate) async fn newest_backup(config: &crate::config::AppConfig) -> Option { + newest_backup_on_target(target_from_config(config).ok()?).await +} + +async fn newest_backup_for_runtime( + runtime: &RuntimeContext, + config: &crate::config::AppConfig, +) -> Option { + let password = if backup_target(config) == "webdav" { + runtime + .secrets + .get(&target_keychain_user("webdav")) + .ok() + .flatten() + } else { + None + }; + newest_backup_on_target(target_from_config_with_password(config, password).ok()?).await +} + +async fn newest_backup_on_target(target: Box) -> Option { target .list() .await @@ -332,20 +358,43 @@ async fn newest_backup(config: &crate::config::AppConfig) -> Option(app: AppHandle, trigger: &str) -> Result { - let config = crate::config::load_config_internal(&app); - let password = get_password()?.ok_or("Backup password is not set")?; - - let payload = crate::commands::export_connections_payload(app.clone(), Some(true), None).await?; +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum BackupTargetKind { + ServerDirectory, + Webdav, +} + +pub struct BackupArtifact { + pub file_name: String, + pub content: String, + pub location: String, + pub target_kind: BackupTargetKind, +} + +pub async fn run_backup_for_runtime( + runtime: &RuntimeContext, + trigger: &str, +) -> Result { + let config = load_runtime_config(runtime); + let password = runtime + .secrets + .get(KEYCHAIN_USER)? + .ok_or("Backup password is not set")?; + let payload = crate::application::connection_files::export_payload(runtime, true, None).await?; let plaintext = serde_json::to_string(&payload).map_err(|e| e.to_string())?; let envelope = crate::export_crypto::encrypt(&plaintext, &password)?; let content = serde_json::to_string_pretty(&envelope).map_err(|e| e.to_string())?; - let name = backup_file_name(chrono::Local::now().naive_local()); let retention = config.backup_retention.unwrap_or(DEFAULT_RETENTION) as usize; - - let target = target_from_config(&config)?; - target.put(&name, content).await?; + let target_kind = target_kind(&config); + let target_password = if matches!(target_kind, BackupTargetKind::Webdav) { + runtime.secrets.get(&target_keychain_user("webdav"))? + } else { + None + }; + let target = target_from_config_with_password(&config, target_password)?; + target.put(&name, content.clone()).await?; match target.list().await { Ok(names) => { for old in select_backups_to_prune(&names, retention) { @@ -356,13 +405,17 @@ pub async fn run_backup(app: AppHandle, trigger: &str) -> Result< } Err(e) => log::warn!("Backup rotation: listing failed: {e}"), } - let location = target.location(&name); log::info!("Connections backup ({trigger}) written to {location}"); - Ok(location) + Ok(BackupArtifact { + file_name: name, + content, + location, + target_kind, + }) } -fn backup_mode(config: &crate::config::AppConfig) -> String { +pub(crate) fn backup_mode(config: &crate::config::AppConfig) -> String { config .backup_mode .clone() @@ -370,77 +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)] @@ -452,53 +434,72 @@ pub struct BackupStatus { pub target_password_set: bool, /// Timestamp of the newest backup on the configured target, local time. pub last_backup_at: Option, + pub target_kind: BackupTargetKind, + pub target_display: Option, } -#[tauri::command] -pub async fn get_connections_backup_status( - app: AppHandle, -) -> Result { - let config = crate::config::load_config_internal(&app); - let last_backup_at = newest_backup(&config) +pub async fn backup_status(runtime: &RuntimeContext) -> Result { + let config = load_runtime_config(runtime); + let last_backup_at = newest_backup_for_runtime(runtime, &config) .await .map(|ts| ts.format("%Y-%m-%dT%H:%M:%S").to_string()); let target_id = backup_target(&config); let target_password_set = match target_id.as_str() { "local" => true, - id => get_target_password(id)?.is_some(), + id => runtime.secrets.get(&target_keychain_user(id))?.is_some(), + }; + let target_display = if target_id == "webdav" { + config + .backup_webdav_url + .clone() + .filter(|value| !value.is_empty()) + } else { + config + .backup_directory + .clone() + .filter(|value| !value.is_empty()) }; Ok(BackupStatus { - password_set: get_password()?.is_some(), + password_set: runtime.secrets.get(KEYCHAIN_USER)?.is_some(), target_password_set, last_backup_at, + target_kind: target_kind(&config), + target_display, }) } -#[tauri::command] -pub async fn set_connections_backup_password(password: String) -> Result<(), String> { +pub fn set_backup_password(runtime: &RuntimeContext, password: &str) -> Result<(), String> { if password.is_empty() { - delete_keychain(KEYCHAIN_USER) + runtime.secrets.delete(KEYCHAIN_USER) } else { - set_keychain(KEYCHAIN_USER, &password) + runtime.secrets.set(KEYCHAIN_USER, 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( - target_id: String, - password: String, +pub fn set_backup_target_password( + runtime: &RuntimeContext, + target_id: &str, + password: &str, ) -> Result<(), String> { - let user = target_keychain_user(&target_id); + let user = target_keychain_user(target_id); if password.is_empty() { - delete_keychain(&user) + runtime.secrets.delete(&user) } else { - set_keychain(&user, &password) + runtime.secrets.set(&user, password) } } -#[tauri::command] -pub async fn run_connections_backup(app: AppHandle) -> Result { - run_backup(app, "manual").await +fn load_runtime_config(runtime: &RuntimeContext) -> crate::config::AppConfig { + fs::read_to_string(runtime.paths.config_dir().join("config.json")) + .ok() + .and_then(|content| serde_json::from_str(&content).ok()) + .unwrap_or_default() +} + +fn target_kind(config: &crate::config::AppConfig) -> BackupTargetKind { + if backup_target(config) == "webdav" { + BackupTargetKind::Webdav + } else { + BackupTargetKind::ServerDirectory + } } 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/cli.rs b/src-tauri/src/cli.rs index 88fdffed2..8fa59fe3d 100644 --- a/src-tauri/src/cli.rs +++ b/src-tauri/src/cli.rs @@ -1,20 +1,35 @@ //! Command-line argument parsing for the Tabularis binary. //! //! Keeping this in its own module means `lib.rs` does not have to know about -//! clap, and the flag surface (`--mcp`, `--debug`, `--explain`, `--help`, -//! `--version`) lives in one place. +//! clap, and the command surface (`--mcp`, `web`, `--debug`, `--explain`, +//! `--help`, `--version`) lives in one place. -use clap::Parser; +use clap::{Args as ClapArgs, Parser, Subcommand, ValueEnum}; +use std::path::PathBuf; + +#[cfg(test)] +mod tests; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +pub enum WebAuthMode { + /// Authenticate remote users with a password. + Password, + /// Trust authentication performed by a configured reverse proxy. + Proxy, +} #[derive(Parser, Debug)] -#[command(version, about, long_about = None)] +#[command(version, about, long_about = None, args_conflicts_with_subcommands = true)] pub struct Args { /// Start in MCP Server mode (Model Context Protocol) #[arg(long)] pub mcp: bool, - /// Enable debug logging (including sqlx queries and other dependencies) - #[arg(long)] + #[command(subcommand)] + pub command: Option, + + /// Enable debug logging (including sqlx queries) + #[arg(long, global = true)] pub debug: bool, /// Open a Visual Explain window for a previously-saved EXPLAIN file @@ -23,6 +38,69 @@ pub struct Args { pub explain: Option, } +#[derive(Debug, Subcommand)] +pub enum Command { + /// Start the browser-based Web UI + Web(WebArgs), +} + +#[derive(Debug, ClapArgs)] +pub struct WebArgs { + /// Address for the Web UI server to bind + #[arg(long, value_name = "HOST", default_value = "127.0.0.1")] + pub host: String, + + /// Port for the Web UI server to bind + #[arg(long, value_name = "PORT", default_value_t = 8080)] + pub port: u16, + + /// Do not open the Web UI in the default browser + #[arg(long)] + pub no_open: bool, + + /// Override the directory containing built Web UI assets + #[arg(long, value_name = "PATH")] + pub web_root: Option, + + /// Authentication mode for explicitly configured remote Web UI access + #[arg( + long, + value_name = "MODE", + value_enum, + requires_all = ["public_url", "allowed_origins"] + )] + pub auth: Option, + + /// Public HTTPS origin used by browsers through the trusted reverse proxy + #[arg(long, value_name = "URL", requires = "auth")] + pub public_url: Option, + + /// Browser origin allowed to access remote Web UI sessions; repeat as needed + #[arg( + long = "allowed-origin", + value_name = "ORIGIN", + action = clap::ArgAction::Append, + requires = "auth" + )] + pub allowed_origins: Vec, + + /// Trust X-Forwarded-For only from this proxy network; repeat as needed + #[arg(long = "trusted-proxy", value_name = "CIDR", requires = "auth")] + pub trusted_proxies: Vec, + + /// Grant remote sessions high-risk local-administrator capabilities + #[arg(long, requires = "auth")] + pub allow_high_risk: bool, + + /// Allow the Web UI to browse this server directory; repeat as needed + #[arg( + long = "server-file-browser-root", + value_name = "PATH", + action = clap::ArgAction::Append + )] + pub server_file_browser_roots: Vec, +} + impl Args { /// Log level for this run: `Debug` with `--debug` (which also lets sqlx's /// query logging through), otherwise whatever `RUST_LOG` names, and `Info` @@ -38,6 +116,7 @@ impl Args { fn defaults() -> Self { Self { mcp: false, + command: None, debug: false, explain: None, } @@ -46,22 +125,40 @@ impl Args { /// Parse the process arguments, with platform-friendly fallback behaviour. /// -/// - `--help` / `--version` surface as `Err(DisplayHelp|DisplayVersion)` with the -/// formatted message attached; let clap print them and exit cleanly. -/// - Any other parse failure falls back to defaults so that GUI launches (e.g. -/// macOS passing `-psn_*`) still reach the Tauri builder. +/// Platform launch metadata (for example macOS `-psn_*` arguments or a +/// registered `tabularis:` URL) falls back to desktop defaults. User-facing +/// parse failures, including mode conflicts, are printed by clap and exit. pub fn parse() -> Args { - Args::try_parse().unwrap_or_else(|err| { - if matches!( - err.kind(), - clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion - ) { - err.exit(); - } - Args::defaults() - }) + try_parse_from(std::env::args_os()).unwrap_or_else(|err| err.exit()) +} + +fn try_parse_from(arguments: I) -> Result +where + I: IntoIterator, + T: Into, +{ + let arguments: Vec = arguments.into_iter().map(Into::into).collect(); + match Args::try_parse_from(arguments.clone()) { + Err(_) if has_only_platform_launch_arguments(&arguments) => Ok(Args::defaults()), + result => result, + } +} + +fn has_only_platform_launch_arguments(arguments: &[std::ffi::OsString]) -> bool { + let mut launch_arguments = arguments.iter().skip(1); + let Some(first) = launch_arguments.next() else { + return false; + }; + + std::iter::once(first) + .chain(launch_arguments) + .all(|argument| { + argument + .to_str() + .is_some_and(|value| value.starts_with("-psn_") || value.starts_with("tabularis:")) + }) } #[cfg(test)] #[path = "cli_tests.rs"] -mod tests; +mod log_level_tests; diff --git a/src-tauri/src/cli/tests.rs b/src-tauri/src/cli/tests.rs new file mode 100644 index 000000000..b0b0b45fd --- /dev/null +++ b/src-tauri/src/cli/tests.rs @@ -0,0 +1,186 @@ +use super::{try_parse_from, Args, Command, WebArgs, WebAuthMode}; +use clap::{error::ErrorKind, Parser}; +use std::path::PathBuf; + +fn web_args(args: &Args) -> &WebArgs { + match args.command.as_ref() { + Some(Command::Web(web_args)) => web_args, + None => panic!("expected the web subcommand"), + } +} + +#[test] +fn parses_desktop_defaults() { + let args = Args::try_parse_from(["tabularis"]).expect("defaults should parse"); + + assert!(!args.mcp); + assert!(!args.debug); + assert!(args.explain.is_none()); + assert!(args.command.is_none()); +} + +#[test] +fn parses_all_web_options() { + let args = Args::try_parse_from([ + "tabularis", + "web", + "--host", + "localhost", + "--port", + "9090", + "--no-open", + "--web-root", + "/tmp/tabularis-web", + "--auth", + "password", + "--public-url", + "https://tabularis.example.com", + "--allowed-origin", + "https://tabularis.example.com", + "--allowed-origin", + "https://admin.example.com", + "--allow-high-risk", + "--server-file-browser-root", + "/srv/databases", + "--server-file-browser-root", + "/var/backups", + "--debug", + ]) + .expect("web options should parse"); + + let web_args = web_args(&args); + assert_eq!(web_args.host, "localhost"); + assert_eq!(web_args.port, 9090); + assert!(web_args.no_open); + assert_eq!(web_args.web_root, Some(PathBuf::from("/tmp/tabularis-web"))); + assert_eq!(web_args.auth, Some(WebAuthMode::Password)); + assert_eq!( + web_args.public_url.as_deref(), + Some("https://tabularis.example.com") + ); + assert_eq!( + web_args.allowed_origins, + [ + "https://tabularis.example.com".to_string(), + "https://admin.example.com".to_string() + ] + ); + assert!(web_args.allow_high_risk); + assert_eq!( + web_args.server_file_browser_roots, + [ + PathBuf::from("/srv/databases"), + PathBuf::from("/var/backups") + ] + ); + assert!(args.debug); +} + +#[test] +fn web_conflicts_with_mcp_mode() { + let error = Args::try_parse_from(["tabularis", "--mcp", "web"]) + .expect_err("web and MCP modes must conflict"); + + assert_eq!(error.kind(), ErrorKind::ArgumentConflict); +} + +#[test] +fn web_conflicts_with_explain_mode() { + let error = Args::try_parse_from(["tabularis", "--explain", "plan.json", "web"]) + .expect_err("web and explain modes must conflict"); + + assert_eq!(error.kind(), ErrorKind::ArgumentConflict); +} + +#[test] +fn web_options_require_web_subcommand() { + for option in [ + "--host", + "--port", + "--web-root", + "--auth", + "--public-url", + "--allowed-origin", + "--server-file-browser-root", + ] { + let value = match option { + "--host" => "localhost", + "--port" => "9090", + "--web-root" => "/tmp/tabularis-web", + "--auth" => "proxy", + "--public-url" | "--allowed-origin" => "https://tabularis.example.com", + "--server-file-browser-root" => "/srv/databases", + _ => unreachable!(), + }; + let error = Args::try_parse_from(["tabularis", option, value]) + .expect_err("web options must require the web subcommand"); + assert_eq!(error.kind(), ErrorKind::UnknownArgument); + } + + for option in ["--no-open", "--allow-high-risk"] { + let error = Args::try_parse_from(["tabularis", option]) + .expect_err("the Web option must require the web subcommand"); + assert_eq!(error.kind(), ErrorKind::UnknownArgument); + } +} + +#[test] +fn rejects_legacy_web_flag() { + let error = Args::try_parse_from(["tabularis", "--web"]) + .expect_err("web must be a subcommand, not a flag"); + + assert_eq!(error.kind(), ErrorKind::UnknownArgument); +} + +#[test] +fn help_lists_web_subcommand_and_options() { + let error = Args::try_parse_from(["tabularis", "--help"]) + .expect_err("help should be returned as a clap display error"); + + assert_eq!(error.kind(), ErrorKind::DisplayHelp); + assert!(error.to_string().contains("web")); + + let error = Args::try_parse_from(["tabularis", "web", "--help"]) + .expect_err("web help should be returned as a clap display error"); + assert_eq!(error.kind(), ErrorKind::DisplayHelp); + let help = error.to_string(); + for option in [ + "--host ", + "--port ", + "--no-open", + "--web-root ", + "--auth ", + "--public-url ", + "--allowed-origin ", + "--allow-high-risk", + "--server-file-browser-root ", + ] { + assert!( + help.contains(option), + "help did not contain {option}: {help}" + ); + } + assert!(help.contains("127.0.0.1")); + assert!(help.contains("8080")); +} + +#[test] +fn platform_launch_arguments_fall_back_to_desktop_defaults() { + for platform_argument in ["-psn_0_12345", "tabularis://plugins/example"] { + let args = try_parse_from(["tabularis", platform_argument]) + .expect("platform launch metadata should use desktop defaults"); + + assert!(args.command.is_none()); + assert!(!args.mcp); + assert!(!args.debug); + assert!(args.explain.is_none()); + } +} + +#[test] +fn user_parse_errors_do_not_fall_back_to_desktop_mode() { + let error = try_parse_from(["tabularis", "--mcp", "web"]) + .expect_err("a mode conflict must remain visible to the user"); + + assert_eq!(error.kind(), ErrorKind::ArgumentConflict); +} diff --git a/src-tauri/src/clipboard_import.rs b/src-tauri/src/clipboard_import.rs index dc39a444b..5f1ce2109 100644 --- a/src-tauri/src/clipboard_import.rs +++ b/src-tauri/src/clipboard_import.rs @@ -1,19 +1,8 @@ -use std::collections::HashSet; -use std::sync::Arc; -use crate::{ - commands::{ - expand_k8s_connection_params, expand_ssh_connection_params, find_connection_by_id, - resolve_connection_params_with_id, - }, - drivers::{ - driver_trait::DatabaseDriver, - registry::get_driver, - sql_syntax::{quote_string_literal, BooleanLiterals, LiteralStyle, SqlSyntax}, - }, - models::{ColumnDefinition, TableColumn}, -}; +use crate::drivers::sql_syntax::{quote_string_literal, BooleanLiterals, LiteralStyle, SqlSyntax}; +use crate::models::TableColumn; +use crate::{drivers::driver_trait::DatabaseDriver, models::ColumnDefinition}; use serde::{Deserialize, Serialize}; -use tauri::{AppHandle, Runtime}; +use std::collections::HashSet; #[derive(Deserialize, Debug)] pub struct ClipboardImportRequest { @@ -182,9 +171,9 @@ fn table_ref(table_name: &str, schema: Option<&str>, quote: &str) -> String { } } -#[tauri::command] -pub async fn execute_clipboard_import( - app: AppHandle, +pub async fn import_with_runtime( + runtime: &crate::runtime::RuntimeContext, + session_id: Option, req: ClipboardImportRequest, ) -> Result { log::info!( @@ -194,15 +183,18 @@ pub async fn execute_clipboard_import( req.create_table ); - let saved_conn = find_connection_by_id(&app, &req.connection_id)?; - let expanded = expand_ssh_connection_params(&app, &saved_conn.params).await?; - let expanded = expand_k8s_connection_params(&app, &expanded).await?; - let params = resolve_connection_params_with_id(&expanded, &req.connection_id)?; - let drv: Arc = get_driver(&saved_conn.params.driver) - .await - .ok_or_else(|| format!("Unsupported driver: {}", saved_conn.params.driver))?; - - let drv = drv.for_connection(¶ms).await?.unwrap_or(drv); + let runtime = runtime.clone(); + let connection_id = req.connection_id.clone(); + let (_, params) = tokio::task::spawn_blocking(move || { + crate::application::connections::resolve_saved_connection_params( + &runtime, + session_id, + &connection_id, + ) + }) + .await + .map_err(|e| e.to_string())??; + let drv = crate::drivers::registry::get_connection_driver(¶ms).await?; let quote = import_identifier_quote(drv.as_ref()); let schema_ref = req.schema.as_deref(); let tbl_ref = table_ref(&req.table_name, schema_ref, quote); @@ -293,7 +285,10 @@ async fn insert_rows( table_created: bool, ) -> Result { if req.rows.is_empty() { - return Ok(ClipboardImportResult { rows_inserted: 0, table_created }); + return Ok(ClipboardImportResult { + rows_inserted: 0, + table_created, + }); } let col_list = req @@ -330,13 +325,25 @@ async fn insert_rows( drv.execute_query(params, &insert_sql, None, 1, schema_ref) .await - .map_err(|e| format!("Failed to insert rows (batch starting at {}): {e}", rows_inserted))?; + .map_err(|e| { + format!( + "Failed to insert rows (batch starting at {}): {e}", + rows_inserted + ) + })?; rows_inserted += chunk.len(); } - log::info!("Clipboard import complete: {} rows inserted into {}", rows_inserted, tbl_ref); - Ok(ClipboardImportResult { rows_inserted, table_created }) + log::info!( + "Clipboard import complete: {} rows inserted into {}", + rows_inserted, + tbl_ref + ); + Ok(ClipboardImportResult { + rows_inserted, + table_created, + }) } #[cfg(test)] diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index c7ee0f15d..74e02917e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,22 +1,14 @@ use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; -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; -use crate::ssh_tunnel::{get_tunnels, SshTunnel}; // Constants /// Resolve the driver from the registry or return a descriptive error. @@ -28,50 +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 -} - -/// Pure SQL builders still need no credentials for static drivers. Only -/// discovery-enabled plugins resolve credentials and tunnels here. -async fn driver_for_saved( - app: &AppHandle, - saved: &SavedConnection, -) -> Result, String> { - let driver = driver_for(&saved.params.driver).await?; - if !driver.has_connection_metadata() { - return Ok(driver); - } - let expanded = expand_ssh_connection_params(app, &saved.params).await?; - let expanded = expand_k8s_connection_params(app, &expanded).await?; - let params = resolve_connection_params_with_id(&expanded, &saved.id)?; - driver_for_params(¶ms).await -} - -#[tauri::command] -pub async fn get_connection_metadata( - app: AppHandle, - connection_id: String, -) -> Result, String> { - let saved = find_connection_by_id(&app, &connection_id)?; - if !driver_for(&saved.params.driver) - .await? - .has_connection_metadata() - { - return Ok(None); - } - let driver = driver_for_saved(&app, &saved).await?; - Ok(Some( - crate::plugins::connection_metadata::ConnectionMetadata { - capabilities: driver.manifest().capabilities.clone(), - data_types: driver.get_data_types(), - type_mappings: driver.manifest().type_mappings.clone(), - }, - )) -} - const DEFAULT_MYSQL_PORT: u16 = 3306; const DEFAULT_POSTGRES_PORT: u16 = 5432; @@ -127,124 +75,8 @@ pub(crate) fn unregister_abort_handle( } } -/// Trims trailing semicolons and normalises Unicode smart quotes that some -/// editors insert when the user pastes a query. Called on every query the -/// UI hands off to a driver. -fn sanitize_user_query(query: &str) -> String { - query - .trim() - .trim_end_matches(';') - .replace('\u{2018}', "'") - .replace('\u{2019}', "'") - .replace('\u{201C}', "\"") - .replace('\u{201D}', "\"") -} - // --- Persistence Helpers --- -/// Load a single SSH connection by ID, fetching only its credentials from -/// keychain (via the in-memory cache). This is O(1) keychain calls versus the -/// O(N) behaviour of `get_ssh_connections`, which loads every saved SSH -/// connection and retrieves credentials for each one. -async fn get_ssh_connection_by_id( - app: &AppHandle, - ssh_id: &str, -) -> Result { - let path = get_ssh_config_path(app)?; - if !path.exists() { - return Err(format!("SSH connection with ID {} not found", ssh_id)); - } - - // File I/O off the Tokio executor thread - let content = tokio::task::spawn_blocking({ - let path = path.clone(); - move || std::fs::read_to_string(path).map_err(|e| e.to_string()) - }) - .await - .map_err(|e| e.to_string())??; - - let mut ssh = serde_json::from_str::>(&content) - .unwrap_or_default() - .into_iter() - .find(|s| s.id == ssh_id) - .ok_or_else(|| format!("SSH connection with ID {} not found", ssh_id))?; - - // Backward compat: determine auth_type if absent (mirrors get_ssh_connections logic) - if ssh.auth_type.is_none() { - ssh.auth_type = Some( - if ssh - .key_file - .as_ref() - .map_or(false, |k| !k.trim().is_empty()) - { - "ssh_key".to_string() - } else { - "password".to_string() - }, - ); - } - - // Fetch credentials only for this connection, via the in-memory cache. - // On a warm cache hit this is a HashMap lookup (nanoseconds); on a cold miss - // it calls keychain once per credential and then caches the result. - if ssh.save_in_keychain.unwrap_or(false) { - // Clone the Arc out of the Tauri State so the closure owns it ('static bound) - let cache = app - .state::>() - .inner() - .clone(); - let id = ssh.id.clone(); - let (pwd_r, pass_r) = tokio::task::spawn_blocking(move || { - let pwd = credential_cache::get_ssh_password_cached(&cache, &id); - let pass = credential_cache::get_ssh_key_passphrase_cached(&cache, &id); - (pwd, pass) - }) - .await - .map_err(|e| e.to_string())?; - - if let Ok(v) = pwd_r { - if !v.trim().is_empty() { - ssh.password = Some(v); - } - } - if let Ok(v) = pass_r { - if !v.trim().is_empty() { - ssh.key_passphrase = Some(v); - } - } - } - - Ok(ssh) -} - -pub async fn expand_ssh_connection_params( - app: &AppHandle, - params: &ConnectionParams, -) -> Result { - let mut expanded_params = params.clone(); - - // If ssh_connection_id is set and SSH is enabled, load the SSH connection and merge it - if params.ssh_enabled.unwrap_or(false) { - if let Some(ssh_id) = ¶ms.ssh_connection_id { - // Use targeted lookup instead of loading all SSH connections: - // this calls keychain only for this specific connection (O(1)), - // and results are backed by the in-memory credential cache. - let ssh_conn = get_ssh_connection_by_id(app, ssh_id).await?; - - // Populate legacy SSH fields from the SSH connection - expanded_params.ssh_host = Some(ssh_conn.host.clone()); - expanded_params.ssh_port = Some(ssh_conn.port); - expanded_params.ssh_user = Some(ssh_conn.user.clone()); - expanded_params.ssh_password = ssh_conn.password.clone(); - expanded_params.ssh_key_file = ssh_conn.key_file.clone(); - expanded_params.ssh_key_passphrase = ssh_conn.key_passphrase.clone(); - expanded_params.ssh_allow_passphrase_prompt = ssh_conn.allow_passphrase_prompt; - } - } - - Ok(expanded_params) -} - /// Check if a string option is empty or contains only whitespace. #[inline] #[cfg(test)] @@ -252,402 +84,18 @@ 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(()) +pub fn resolve_connection_params(params: &ConnectionParams) -> Result { + crate::application::tunnels::resolve_expanded_connection_params(params, None) } #[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(); - } -} - -/// Build the SSH tunnel map key for caching tunnels. -#[inline] -fn build_tunnel_map_key( - ssh_user: &str, - ssh_host: &str, - ssh_port: u16, - remote_host: &str, - remote_port: u16, -) -> String { - crate::ssh_tunnel::build_tunnel_key(ssh_user, ssh_host, ssh_port, remote_host, remote_port) -} - -/// Resolve K8s tunnel params synchronously (no saved-connection lookup; uses inline fields only). fn resolve_k8s_params(params: &ConnectionParams) -> Result { - let context = params.k8s_context.as_deref().ok_or("Missing K8s context")?; - let namespace = params - .k8s_namespace - .as_deref() - .ok_or("Missing K8s namespace")?; - let resource_type = params - .k8s_resource_type - .as_deref() - .ok_or("Missing K8s resource type")?; - let resource_name = params - .k8s_resource_name - .as_deref() - .ok_or("Missing K8s resource name")?; - let port = params.k8s_port.ok_or("Missing K8s port")?; - - let options = crate::k8s_tunnel::K8sCommandOptions::new( - params.k8s_kubectl_path.clone(), - params.k8s_kubeconfig_path.clone(), - ); - let map_key = crate::k8s_tunnel::build_tunnel_key( - context, - namespace, - resource_type, - resource_name, - port, - &options, - ); - - let preferred_local_port = match crate::k8s_tunnel::reuse_or_discard_dead(&map_key) { - Ok(local_port) => { - log::debug!("Reusing existing K8s tunnel on port {}", local_port); - let mut new_params = params.clone(); - new_params.k8s_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - return Ok(new_params); - } - Err(previous) => previous, - }; - - log::info!( - "Creating new K8s tunnel for {}/{} in {}:{} (context: {})", - resource_type, - resource_name, - namespace, - port, - context - ); - - let tunnel = crate::k8s_tunnel::K8sTunnel::new( - context, - namespace, - resource_type, - resource_name, - port, - &options, - preferred_local_port, - ) - .map_err(|e| { - eprintln!("[Connection Error] K8s Tunnel setup failed: {}", e); - e - })?; - - let local_port = crate::k8s_tunnel::insert_tunnel(map_key, tunnel); - log::info!("K8s tunnel created successfully on port {}", local_port); - - let mut new_params = params.clone(); - new_params.k8s_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - Ok(new_params) + crate::application::tunnels::resolve_k8s_params(params) } -/// Resolve AWS SSM tunnel params synchronously. Like SSH, the session forwards -/// to the connection's own host/port; unlike SSH there is no saved-connection -/// indirection, so every field is inline. +#[cfg(test)] fn resolve_ssm_params(params: &ConnectionParams) -> Result { - let target = params - .ssm_target - .as_deref() - .map(str::trim) - .filter(|t| !t.is_empty()) - .ok_or("Missing AWS SSM target")?; - let profile = params.ssm_profile.as_deref(); - let region = params.ssm_region.as_deref(); - let remote_host = params.host.as_deref().unwrap_or("localhost"); - let remote_port = params.port.unwrap_or(DEFAULT_MYSQL_PORT); - - let map_key = - crate::ssm_tunnel::build_tunnel_key(target, profile, region, remote_host, remote_port); - - { - let mut tunnels = crate::ssm_tunnel::get_tunnels().lock().unwrap(); - if let Some(tunnel) = tunnels.get(&map_key) { - if tunnel.is_alive() { - log::debug!("Reusing existing SSM tunnel on port {}", tunnel.local_port); - let mut new_params = params.clone(); - new_params.ssm_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(tunnel.local_port); - return Ok(new_params); - } - log::info!( - "Discarding dead SSM tunnel on port {}; the session ended", - tunnel.local_port - ); - tunnels.remove(&map_key); - } - } - - log::info!( - "Creating new SSM tunnel to {}:{} via {}", - remote_host, - remote_port, - target - ); - - let tunnel = - crate::ssm_tunnel::SsmTunnel::new(target, profile, region, remote_host, remote_port) - .map_err(|e| { - eprintln!("[Connection Error] SSM Tunnel setup failed: {}", e); - e - })?; - - let local_port = tunnel.local_port; - log::info!("SSM tunnel created successfully on port {}", local_port); - - { - let mut tunnels = crate::ssm_tunnel::get_tunnels().lock().unwrap(); - tunnels.insert(map_key, tunnel); - } - - let mut new_params = params.clone(); - new_params.ssm_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - Ok(new_params) -} - -/// SSH, Kubernetes and AWS SSM each rewrite host/port to a local tunnel, so at -/// most one of them can be active for a connection. -fn ensure_single_tunnel(params: &ConnectionParams) -> Result<(), String> { - let enabled: Vec<&str> = [ - ("SSH", params.ssh_enabled), - ("Kubernetes", params.k8s_enabled), - ("AWS SSM", params.ssm_enabled), - ] - .into_iter() - .filter(|(_, on)| on.unwrap_or(false)) - .map(|(name, _)| name) - .collect(); - - if enabled.len() > 1 { - return Err(format!( - "{} tunnels cannot both be enabled for the same connection", - enabled.join(" and ") - )); - } - Ok(()) -} - -pub fn resolve_connection_params(params: &ConnectionParams) -> Result { - let mut resolved = resolve_connection_transport(params)?; - // Only file/folder drivers store a path in `database`; for network drivers - // it is a schema name and must be passed through untouched. - if crate::drivers::registry::is_local_path_driver(&resolved.driver) { - resolved.database = crate::fs_path::sanitize_database_selection(&resolved.database); - } - Ok(resolved) -} - -/// Resolve the tunnel / proxy transport for a connection (K8s, SSM, SSH or a -/// database-scope proxy) and return params pointing at the local endpoint. -fn resolve_connection_transport(params: &ConnectionParams) -> Result { - ensure_single_tunnel(params)?; - - // Handle K8s tunnel - result is already on localhost; do not re-proxy. - if params.k8s_enabled.unwrap_or(false) { - return resolve_k8s_params(params); - } - - // Handle AWS SSM tunnel - if params.ssm_enabled.unwrap_or(false) { - return resolve_ssm_params(params); - } - - let connection_id = params.connection_id.as_deref(); - let proxy_override = params.proxy.as_ref(); - - // Handle SSH tunnel (existing logic), optionally via an SSH-scope proxy. - if params.ssh_enabled.unwrap_or(false) { - let ssh_host = params.ssh_host.as_deref().ok_or("Missing SSH Host")?; - let ssh_port = params.ssh_port.unwrap_or(22); - let ssh_user = params.ssh_user.as_deref().ok_or("Missing SSH User")?; - let remote_host = params.host.as_deref().unwrap_or("localhost"); - let remote_port = params.port.unwrap_or(DEFAULT_MYSQL_PORT); - - let proxy = crate::proxy::resolve_for_connection( - crate::proxy::SCOPE_SSH_TUNNEL, - connection_id, - proxy_override, - ); - let base_key = build_tunnel_map_key(ssh_user, ssh_host, ssh_port, remote_host, remote_port); - let map_key = match &proxy { - Some(p) => { - let proto = match p.protocol { - crate::proxy::ProxyProtocol::Http => "http", - crate::proxy::ProxyProtocol::Socks5 => "socks5", - }; - let user = p.username.as_deref().unwrap_or(""); - format!("{base_key}|px:{proto}:{}:{}:{user}", p.host.trim(), p.port) - } - None => base_key, - }; - - // Check for existing tunnel - { - let mut tunnels = get_tunnels().lock().unwrap(); - if let Some(tunnel) = tunnels.get(&map_key) { - if tunnel.is_alive() { - log::debug!("Reusing existing SSH tunnel on port {}", tunnel.local_port); - let mut new_params = params.clone(); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(tunnel.local_port); - return Ok(new_params); - } - log::info!( - "Discarding dead SSH tunnel on port {}; the session ended", - tunnel.local_port - ); - tunnels.remove(&map_key); - } - } - - let (tcp_host, tcp_port) = if let Some(proxy) = proxy { - let fwd_port = crate::proxy::ensure_forward(&proxy, ssh_host, ssh_port)?; - log::info!( - "SSH bastion {}:{} reached via proxy forward on 127.0.0.1:{}", - ssh_host, - ssh_port, - fwd_port - ); - (Some("127.0.0.1".to_string()), Some(fwd_port)) - } else { - (None, None) - }; - - log::info!( - "Creating new SSH tunnel for {}@{}:{}", - ssh_user, - ssh_host, - ssh_port - ); - let tunnel = SshTunnel::new_with_tcp_override( - ssh_host, - ssh_port, - ssh_user, - params.ssh_password.as_deref(), - params.ssh_key_file.as_deref(), - params.ssh_key_passphrase.as_deref(), - params.ssh_allow_passphrase_prompt.unwrap_or(false), - remote_host, - remote_port, - tcp_host.as_deref(), - tcp_port, - ) - .map_err(|e| { - eprintln!("[Connection Error] SSH Tunnel setup failed: {}", e); - e - })?; - - let local_port = tunnel.local_port; - log::info!("SSH tunnel created successfully on port {}", local_port); - - { - let mut tunnels = get_tunnels().lock().unwrap(); - tunnels.insert(map_key, tunnel); - } - - let mut new_params = params.clone(); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - return Ok(new_params); - } - - // Direct DB connection — apply database-scope proxy when configured. - let mut resolved = params.clone(); - if let Some(proxy) = crate::proxy::resolve_for_connection( - crate::proxy::SCOPE_DATABASE, - connection_id, - proxy_override, - ) { - let host = resolved.host.as_deref().unwrap_or("localhost").to_string(); - let port = resolved.port.unwrap_or(DEFAULT_MYSQL_PORT); - if !is_loopback_host(&host) { - let fwd_port = crate::proxy::ensure_forward(&proxy, &host, port)?; - log::info!( - "Database {}:{} reached via proxy forward on 127.0.0.1:{}", - host, - port, - fwd_port - ); - resolved.host = Some("127.0.0.1".to_string()); - resolved.port = Some(fwd_port); - } - } - - Ok(resolved) -} - -fn is_loopback_host(host: &str) -> bool { - let h = host.trim().to_ascii_lowercase(); - h == "localhost" || h == "127.0.0.1" || h == "::1" || h == "[::1]" + crate::application::tunnels::resolve_ssm_params(params) } /// Resolve params for closing a pool without respawning tunnels. @@ -677,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 @@ -700,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, @@ -910,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). @@ -1026,2199 +191,48 @@ 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) -} +// ==================== SSH Connection Management ==================== -#[tauri::command] -pub async fn get_schemas( - app: AppHandle, - connection_id: String, - database: Option, -) -> Result, String> { - log::info!("Fetching schemas for connection: {}", connection_id); +// ==================== 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. - 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); - } +// --------------------------------------------------------------------------- +// Kubernetes Connections +// --------------------------------------------------------------------------- - let drv = driver_for_params(¶ms).await?; - drv.get_schemas(¶ms).await -} +// --------------------------------------------------------------------------- +// AWS SSM +// --------------------------------------------------------------------------- -#[tauri::command] -pub async fn get_available_databases( - app: AppHandle, - connection_id: String, -) -> Result, String> { - log::info!( - "Fetching available databases for connection: {}", - connection_id - ); - - 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 params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - - let drv = driver_for_params(¶ms).await?; - drv.get_databases(¶ms).await -} +#[cfg(test)] +mod tests { + use super::*; + use crate::models::DatabaseSelection; -#[tauri::command] -pub async fn set_selected_databases( - app: AppHandle, - connection_id: String, - mut databases: Vec, -) -> Result<(), String> { - if databases.is_empty() { - return Err("Database selection cannot be empty".to_string()); - } - if databases.iter().any(|db| db.trim().is_empty()) { - return Err("Database names cannot be empty".to_string()); + 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() + } } - log::info!( - "Persisting database selection for connection {}: {} database(s)", - connection_id, - databases.len() - ); - - let path = get_config_path(&app)?; - let mut conn_file = persistence::load_connections_file(&path)?; - - let conn = conn_file - .connections - .iter_mut() - .find(|c| c.id == connection_id) - .ok_or("Connection not found")?; - - // Schema-based multi-db drivers (PostgreSQL) distinguish a one-element - // selection (array) from the traditional single-database mode (plain - // string) — the array shape is the opt-in signal - // (hasOptedIntoDatabaseSelection). Collapsing a singleton to Single here - // would lose that signal, so the next reconnect falls back to the flat - // schema-only layout. Flat multi-db drivers (MySQL) have no such - // ambiguity — a plain string is already an explicit one-element - // selection, so collapsing is correct there. - let is_schema_based = driver_for_saved(&app, conn) - .await - .ok() - .map(|drv| drv.manifest().capabilities.schemas) - .unwrap_or(false); - - conn.params.database = if databases.len() == 1 && !is_schema_based { - crate::models::DatabaseSelection::Single(databases.remove(0)) - } else { - crate::models::DatabaseSelection::Multiple(databases) - }; - - save_connections_and_invalidate(&app, &path, &conn_file) -} - -#[tauri::command] -pub async fn get_routines( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - log::info!("Fetching routines for connection: {}", connection_id); - - 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?; - let result = drv.get_routines(¶ms, schema.as_deref()).await; - let database = schema - .as_deref() - .unwrap_or_else(|| params.database.primary()); - - match &result { - Ok(routines) => log::info!("Retrieved {} routines from {}", routines.len(), database), - Err(error) => log::error!("Failed to get routines from {}: {}", database, error), - } - - result -} - -#[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> { - log::info!( - "Fetching routine parameters for: {} on connection: {}", - routine_name, - connection_id - ); - - 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.get_routine_parameters( - ¶ms, - &routine_name, - schema.as_deref(), - identity_args.as_deref(), - ) - .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 { - log::info!( - "Fetching routine definition for: {} ({}) on connection: {}", - routine_name, - routine_type, - connection_id - ); - - 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.get_routine_definition( - ¶ms, - &routine_name, - &routine_type, - schema.as_deref(), - identity_args.as_deref(), - ) - .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> { - 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.get_table_query_template(¶ms, &request).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> { - 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.get_column_stats(¶ms, &request).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 { - 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 params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - - let drv = driver_for_params(¶ms).await?; - drv.build_routine_call_sql( - ¶ms, - &routine_name, - &routine_type, - &args, - schema.as_deref(), - ) - .await -} - -#[tauri::command] -pub async fn get_routine_create_template( - app: AppHandle, - connection_id: String, - routine_type: String, - schema: Option, - database: Option, -) -> Result { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, _) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.routine_create_template(&routine_type, schema.as_deref()) - .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 { - 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.get_routine_edit_script( - ¶ms, - &routine_name, - &routine_type, - schema.as_deref(), - identity_args.as_deref(), - ) - .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> { - log::info!( - "Dropping routine: {} ({}) on connection: {}", - routine_name, - routine_type, - connection_id - ); - - 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.drop_routine( - ¶ms, - &routine_name, - &routine_type, - schema.as_deref(), - identity_args.as_deref(), - ) - .await -} - -#[tauri::command] -pub async fn get_schema_snapshot( - app: AppHandle, - connection_id: 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.get_schema_snapshot(¶ms, schema.as_deref()).await -} - -#[tauri::command] -pub async fn get_ai_schema_context( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result { - let saved_conn = find_connection_by_id(&app, &connection_id)?; - let expanded_params = expand_ssh_connection_params(&app, &saved_conn.params).await?; - let expanded_params = expand_k8s_connection_params(&app, &expanded_params).await?; - let mut params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let driver = driver_for_params(¶ms).await?; - let identifier_quote = driver.manifest().capabilities.identifier_quote.as_str(); - let context = driver - .get_ai_schema_context( - ¶ms, - schema.as_deref(), - crate::ai_schema_context::DEFAULT_MAX_TABLES, - ) - .await?; - - Ok(crate::ai_schema_context::format_for_prompt( - &context, - identifier_quote, - )) -} - -#[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)?; - // Use persistence function that handles both old and new formats - persistence::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> { - let path = get_ssh_config_path(&app)?; - if !path.exists() { - return Ok(Vec::new()); - } - - // File I/O off the Tokio executor thread - let content = tokio::task::spawn_blocking({ - let path = path.clone(); - move || std::fs::read_to_string(path).map_err(|e| e.to_string()) - }) - .await - .map_err(|e| e.to_string())??; - - let mut ssh_connections: Vec = - serde_json::from_str(&content).unwrap_or_default(); - - // Backward compatibility: determine auth_type if missing - for ssh in &mut ssh_connections { - if ssh.auth_type.is_none() { - ssh.auth_type = Some( - if ssh - .key_file - .as_ref() - .map_or(false, |k| !k.trim().is_empty()) - { - "ssh_key".to_string() - } else { - "password".to_string() - }, - ); - } - } - - // Fetch credentials for all connections that use keychain, in a single - // spawn_blocking call. The cache is checked first (HashMap lookup), so - // subsequent calls (e.g. from the UI refreshing the list) are near-instant. - let ids_needing_creds: Vec = ssh_connections - .iter() - .filter(|s| s.save_in_keychain.unwrap_or(false)) - .map(|s| s.id.clone()) - .collect(); - - if !ids_needing_creds.is_empty() { - // Clone the Arc out of the Tauri State so the closure owns it ('static bound) - let cache = app - .state::>() - .inner() - .clone(); - let credentials = tokio::task::spawn_blocking(move || { - ids_needing_creds - .into_iter() - .map(|id| { - let pwd = credential_cache::get_ssh_password_cached(&cache, &id); - let pass = credential_cache::get_ssh_key_passphrase_cached(&cache, &id); - (id, pwd, pass) - }) - .collect::>() - }) - .await - .map_err(|e| e.to_string())?; - - for (id, pwd_r, pass_r) in credentials { - if let Some(ssh) = ssh_connections.iter_mut().find(|s| s.id == id) { - if let Ok(pwd) = pwd_r { - if !pwd.trim().is_empty() { - ssh.password = Some(pwd); - } - } - if let Ok(pass) = pass_r { - if !pass.trim().is_empty() { - ssh.key_passphrase = Some(pass); - } - } - } - } - } - - Ok(ssh_connections) -} - -#[tauri::command] -pub async fn save_ssh_connection( - app: AppHandle, - name: String, - ssh: SshConnectionInput, -) -> Result { - let path = get_ssh_config_path(&app)?; - let mut ssh_connections: Vec = if path.exists() { - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).unwrap_or_default() - } else { - Vec::new() - }; - - let id = Uuid::new_v4().to_string(); - let ssh_to_save = SshConnection { - id: id.clone(), - name: name.clone(), - host: ssh.host, - port: ssh.port, - user: ssh.user, - auth_type: Some(ssh.auth_type.clone()), - password: if ssh.save_in_keychain.unwrap_or(false) { - let cache = app.state::>(); - if let Some(pwd) = &ssh.password { - keychain_utils::set_ssh_password(&id, pwd)?; - credential_cache::set_ssh_password_cached(&cache, &id, pwd); - } - None - } else { - ssh.password.clone() - }, - key_file: ssh.key_file.clone(), - key_passphrase: if ssh.save_in_keychain.unwrap_or(false) { - let cache = app.state::>(); - if let Some(passphrase) = &ssh.key_passphrase { - if !passphrase.trim().is_empty() { - keychain_utils::set_ssh_key_passphrase(&id, passphrase)?; - credential_cache::set_ssh_key_passphrase_cached(&cache, &id, passphrase); - } - } - None - } else { - ssh.key_passphrase.clone() - }, - allow_passphrase_prompt: ssh.allow_passphrase_prompt, - save_in_keychain: ssh.save_in_keychain, - }; - - ssh_connections.push(ssh_to_save.clone()); - let json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - - let mut returned_ssh = ssh_to_save; - returned_ssh.password = ssh.password; - returned_ssh.key_passphrase = ssh.key_passphrase; - Ok(returned_ssh) -} - -#[tauri::command] -pub async fn update_ssh_connection( - app: AppHandle, - id: String, - name: String, - ssh: SshConnectionInput, -) -> Result { - let path = get_ssh_config_path(&app)?; - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let mut ssh_connections: Vec = - serde_json::from_str(&content).unwrap_or_default(); - - let ssh_idx = ssh_connections - .iter() - .position(|s| s.id == id) - .ok_or("SSH connection not found")?; - - let cache = app.state::>(); - if ssh.save_in_keychain.unwrap_or(false) { - if let Some(pwd) = &ssh.password { - keychain_utils::set_ssh_password(&id, pwd)?; - credential_cache::set_ssh_password_cached(&cache, &id, pwd); - } - if let Some(passphrase) = &ssh.key_passphrase { - if !passphrase.trim().is_empty() { - keychain_utils::set_ssh_key_passphrase(&id, passphrase)?; - credential_cache::set_ssh_key_passphrase_cached(&cache, &id, passphrase); - } - } - } else { - 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); - } - - let ssh_to_save = SshConnection { - id: id.clone(), - name: name.clone(), - host: ssh.host, - port: ssh.port, - user: ssh.user, - auth_type: Some(ssh.auth_type.clone()), - password: if ssh.save_in_keychain.unwrap_or(false) { - None - } else { - ssh.password.clone() - }, - key_file: ssh.key_file.clone(), - key_passphrase: if ssh.save_in_keychain.unwrap_or(false) { - None - } else { - ssh.key_passphrase.clone() - }, - allow_passphrase_prompt: ssh.allow_passphrase_prompt, - save_in_keychain: ssh.save_in_keychain, - }; - - ssh_connections[ssh_idx] = ssh_to_save.clone(); - - let json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - - let mut returned_ssh = ssh_to_save; - returned_ssh.password = ssh.password; - returned_ssh.key_passphrase = ssh.key_passphrase; - Ok(returned_ssh) -} - -#[tauri::command] -pub async fn delete_ssh_connection( - app: AppHandle, - id: String, -) -> Result<(), String> { - let path = get_ssh_config_path(&app)?; - if !path.exists() { - return Ok(()); - } - - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let mut ssh_connections: Vec = - serde_json::from_str(&content).unwrap_or_default(); - - ssh_connections.retain(|s| s.id != id); - - // Remove credentials from keychain and invalidate cache - keychain_utils::delete_ssh_password(&id).ok(); - keychain_utils::delete_ssh_key_passphrase(&id).ok(); - let cache = app.state::>(); - credential_cache::invalidate_ssh_password(&cache, &id); - credential_cache::invalidate_ssh_key_passphrase(&cache, &id); - - let json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - Ok(()) -} - -#[tauri::command] -pub async fn test_ssh_connection( - app: AppHandle, - ssh: SshTestParams, -) -> Result { - use crate::ssh_tunnel; - - // Resolve password using same logic as database connections - let resolved_password = resolve_ssh_test_password( - ssh.password.as_deref(), - ssh.connection_id.as_deref(), - |conn_id| { - let path = get_ssh_config_path(&app).ok()?; - if !path.exists() { - return None; - } - let content = fs::read_to_string(path).ok()?; - let connections: Vec = - serde_json::from_str(&content).unwrap_or_default(); - connections.into_iter().find(|c| c.id == conn_id) - }, - |conn_id| keychain_utils::get_ssh_password(conn_id, ""), - ); - - // Resolve passphrase using same logic - let resolved_passphrase = resolve_ssh_test_credential( - ssh.key_passphrase.as_deref(), - ssh.connection_id.as_deref(), - |conn_id| { - let path = get_ssh_config_path(&app).ok()?; - if !path.exists() { - return None; - } - let content = fs::read_to_string(path).ok()?; - let connections: Vec = - serde_json::from_str(&content).unwrap_or_default(); - connections.into_iter().find(|c| c.id == conn_id) - }, - |conn_id| keychain_utils::get_ssh_key_passphrase(conn_id, ""), - |conn| { - conn.key_passphrase - .as_ref() - .filter(|p| !p.trim().is_empty()) - .cloned() - }, - ); - - // Inline SSH secrets of a saved DB connection live in the keychain under - // the DB connection id (not in the SSH connections file), so fall back - // there when the form did not re-enter them. - let (resolved_password, resolved_passphrase) = match ssh.db_connection_id.as_deref() { - Some(db_id) if resolved_password.is_none() || resolved_passphrase.is_none() => { - match find_connection_by_id(&app, db_id) { - Ok(saved) => apply_inline_ssh_secret_fallback( - resolved_password, - resolved_passphrase, - &saved.params, - ), - Err(_) => (resolved_password, resolved_passphrase), - } - } - _ => (resolved_password, resolved_passphrase), - }; - - let progress_id = ssh.progress_id.as_deref(); - emit_test_progress( - &app, - progress_id, - "sshTunnel", - "start", - Some(format!("{}@{}:{}", ssh.user, ssh.host, ssh.port)), - ); - - let result = ssh_tunnel::test_ssh_connection( - &ssh.host, - ssh.port, - &ssh.user, - resolved_password.as_deref(), - ssh.key_file.as_deref(), - resolved_passphrase.as_deref(), - ssh.allow_passphrase_prompt.unwrap_or(false), - ); - match &result { - Ok(_) => emit_test_progress(&app, progress_id, "sshTunnel", "ok", None), - Err(e) => emit_test_progress(&app, progress_id, "sshTunnel", "error", Some(e.clone())), - } - result -} - -// --------------------------------------------------------------------------- -// Kubernetes Connections -// --------------------------------------------------------------------------- - -fn validate_k8s_connection_paths(k8s: &K8sConnectionInput) -> Result<(), String> { - crate::k8s_tunnel::validate_k8s_path( - k8s.kubectl_path.as_deref().unwrap_or_default(), - "kubectl", - )?; - crate::k8s_tunnel::validate_k8s_path( - k8s.kubeconfig_path.as_deref().unwrap_or_default(), - "kubeconfig", - ) -} - -/// Load K8s connections synchronously from the config file. -fn load_k8s_connections_sync(app: &AppHandle) -> Result, String> { - let path = get_k8s_config_path(app)?; - if !path.exists() { - return Ok(vec![]); - } - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - Ok(serde_json::from_str(&content).unwrap_or_default()) -} - -/// Get the path to the k8s_connections.json file. -fn get_k8s_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("k8s_connections.json")) -} - -#[tauri::command] -pub async fn get_k8s_connections( - app: AppHandle, -) -> Result, String> { - let path = get_k8s_config_path(&app)?; - if !path.exists() { - return Ok(vec![]); - } - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let connections: Vec = serde_json::from_str(&content).unwrap_or_default(); - Ok(connections) -} - -#[tauri::command] -pub async fn save_k8s_connection( - app: AppHandle, - k8s: K8sConnectionInput, -) -> Result { - validate_k8s_connection_paths(&k8s)?; - let path = get_k8s_config_path(&app)?; - let mut connections: Vec = if path.exists() { - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).unwrap_or_default() - } else { - vec![] - }; - - let id = Uuid::new_v4().to_string(); - let connection = K8sConnection { - id: id.clone(), - name: k8s.name, - context: k8s.context, - namespace: k8s.namespace, - resource_type: k8s.resource_type, - resource_name: k8s.resource_name, - port: k8s.port, - kubectl_path: k8s.kubectl_path, - kubeconfig_path: k8s.kubeconfig_path, - }; - - connections.push(connection.clone()); - let json = - serde_json::to_string_pretty(&connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - - Ok(connection) -} - -#[tauri::command] -pub async fn update_k8s_connection( - app: AppHandle, - id: String, - k8s: K8sConnectionInput, -) -> Result { - validate_k8s_connection_paths(&k8s)?; - let path = get_k8s_config_path(&app)?; - let mut connections: Vec = if path.exists() { - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).unwrap_or_default() - } else { - return Err("No K8s connections file found".to_string()); - }; - - let idx = connections - .iter() - .position(|c| c.id == id) - .ok_or_else(|| format!("K8s connection with ID {} not found", id))?; - - let connection = K8sConnection { - id: id.clone(), - name: k8s.name, - context: k8s.context, - namespace: k8s.namespace, - resource_type: k8s.resource_type, - resource_name: k8s.resource_name, - port: k8s.port, - kubectl_path: k8s.kubectl_path, - kubeconfig_path: k8s.kubeconfig_path, - }; - - connections[idx] = connection.clone(); - let json = - serde_json::to_string_pretty(&connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - - Ok(connection) -} - -#[tauri::command] -pub async fn delete_k8s_connection( - app: AppHandle, - id: String, -) -> Result<(), String> { - let path = get_k8s_config_path(&app)?; - let mut connections: Vec = if path.exists() { - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).unwrap_or_default() - } else { - return Ok(()); - }; - - connections.retain(|c| c.id != id); - let json = - serde_json::to_string_pretty(&connections).map_err(|e| e.to_string())?; - persistence::write_private_file(&path, json)?; - - Ok(()) -} - -#[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 { - tokio::task::spawn_blocking(move || { - crate::ssm_tunnel::test_ssm_connection( - &target, - profile.as_deref(), - region.as_deref(), - &host, - port, - ) - }) - .await - .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 { - if !params.k8s_enabled.unwrap_or(false) { - return Ok(params.clone()); - } - - ensure_single_tunnel(params)?; - - // Resolve K8s params from saved connection if using connection_id - let (context, namespace, resource_type, resource_name, port, kubectl_path, kubeconfig_path) = - if let Some(k8s_id) = ¶ms.k8s_connection_id { - let k8s_conn = get_k8s_connection_by_id(app, k8s_id).await?; - ( - k8s_conn.context, - k8s_conn.namespace, - k8s_conn.resource_type, - k8s_conn.resource_name, - k8s_conn.port, - k8s_conn.kubectl_path, - k8s_conn.kubeconfig_path, - ) - } else { - let ctx = params - .k8s_context - .as_deref() - .ok_or("Missing K8s context")? - .to_string(); - let ns = params - .k8s_namespace - .as_deref() - .ok_or("Missing K8s namespace")? - .to_string(); - let rt = params - .k8s_resource_type - .as_deref() - .ok_or("Missing K8s resource type")? - .to_string(); - let rn = params - .k8s_resource_name - .as_deref() - .ok_or("Missing K8s resource name")? - .to_string(); - let p = params.k8s_port.ok_or("Missing K8s port")?; - ( - ctx, - ns, - rt, - rn, - p, - params.k8s_kubectl_path.clone(), - params.k8s_kubeconfig_path.clone(), - ) - }; - - let _remote_host = params.host.as_deref().unwrap_or("localhost"); - let _remote_port = params.port.unwrap_or(DEFAULT_MYSQL_PORT); - - let options = crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path); - let map_key = crate::k8s_tunnel::build_tunnel_key( - &context, - &namespace, - &resource_type, - &resource_name, - port, - &options, - ); - - let preferred_local_port = match crate::k8s_tunnel::reuse_or_discard_dead(&map_key) { - Ok(local_port) => { - log::debug!("Reusing existing K8s tunnel on port {}", local_port); - let mut new_params = params.clone(); - new_params.k8s_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - return Ok(new_params); - } - Err(previous) => previous, - }; - - // Create new tunnel - log::info!( - "Creating new K8s tunnel for {}/{} in {}:{} (context: {})", - resource_type, - resource_name, - namespace, - port, - context - ); - - let tunnel = crate::k8s_tunnel::K8sTunnel::new( - &context, - &namespace, - &resource_type, - &resource_name, - port, - &options, - preferred_local_port, - ) - .map_err(|e| { - eprintln!("[Connection Error] K8s Tunnel setup failed: {}", e); - e - })?; - - let local_port = crate::k8s_tunnel::insert_tunnel(map_key, tunnel); - log::info!("K8s tunnel created successfully on port {}", local_port); - - let mut new_params = params.clone(); - new_params.k8s_enabled = Some(false); - new_params.host = Some("127.0.0.1".to_string()); - new_params.port = Some(local_port); - Ok(new_params) -} - -/// Load a K8s connection by ID from the config file. -async fn get_k8s_connection_by_id( - app: &AppHandle, - k8s_id: &str, -) -> Result { - let path = get_k8s_config_path(app)?; - if !path.exists() { - return Err(format!("K8s connection with ID {} not found", k8s_id)); - } - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let connections: Vec = serde_json::from_str(&content).unwrap_or_default(); - connections - .into_iter() - .find(|c| c.id == k8s_id) - .ok_or_else(|| format!("K8s connection with ID {} not found", k8s_id)) -} - -#[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() - }; + #[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'"); @@ -3267,85 +281,6 @@ mod tests { ); } - #[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()) - ); - } - #[test] fn restores_the_exact_connection_uri_from_the_session_cache() { let cache = credential_cache::CredentialCache::default(); @@ -3389,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(), @@ -3483,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::*; @@ -4563,74 +1372,13 @@ mod tests { } #[test] - fn sql_builder_params_keep_saved_database_without_override() { - let built = sql_builder_params(&saved(base_params()), None); - assert_eq!( - built.database, - DatabaseSelection::Single("testdb".to_string()) - ); - assert_eq!(built.host.as_deref(), Some("localhost")); - } - - #[test] - fn sql_builder_params_carry_stored_plugin_secrets() { - let cache = credential_cache::CredentialCache::default(); - credential_cache::set_plugin_secret_cached( - &cache, - "conn-1", - "test-plugin", - "credential", - "stored-credential", - ); - let mut conn = saved(ConnectionParams { - driver: "test-plugin".to_string(), - host: Some("db.internal".to_string()), - ssh_enabled: Some(true), - ..base_params() - }); - conn.plugin_secret_keys = vec!["credential".to_string()]; - conn.params - .extra - .insert("project".to_string(), "analytics".to_string()); - - bind_sql_builder_secrets(&cache, &mut conn); - let built = sql_builder_params(&conn, None); - - assert_eq!( - built.extra.get("credential").map(String::as_str), - Some("stored-credential") - ); - assert_eq!( - built.extra.get("project").map(String::as_str), - Some("analytics") - ); - assert_eq!(built.host.as_deref(), Some("db.internal")); - } - - #[test] - fn sql_builder_params_build_without_a_missing_plugin_secret() { - let cache = credential_cache::CredentialCache::default(); - // A cached miss stands in for a keychain without the entry. - cache.plugin_secrets.lock().unwrap().insert( - credential_cache::plugin_secret_cache_key("conn-1", "test-plugin", "credential"), - credential_cache::CacheEntry::Absent, - ); - let mut conn = saved(ConnectionParams { - driver: "test-plugin".to_string(), - ..base_params() - }); - conn.plugin_secret_keys = vec!["credential".to_string()]; - - bind_sql_builder_secrets(&cache, &mut conn); - let built = sql_builder_params(&conn, Some("analytics".to_string())); - - assert!(!built.extra.contains_key("credential")); - assert_eq!(built.connection_id.as_deref(), Some("conn-1")); + fn sql_builder_params_keep_saved_database_without_override() { + let built = sql_builder_params(&saved(base_params()), None); assert_eq!( built.database, - DatabaseSelection::Single("analytics".to_string()) + DatabaseSelection::Single("testdb".to_string()) ); - assert_eq!(conn.plugin_secret_keys, vec!["credential"]); + assert_eq!(built.host.as_deref(), Some("localhost")); } #[test] @@ -4720,389 +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> { - log::info!("Fetching tables for connection: {}", connection_id); - - 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); - } - - log::debug!( - "Getting tables from {} database: {}", - saved_conn.params.driver, - params.database - ); - - let drv = driver_for_params(¶ms).await?; - let result = drv.get_tables(¶ms, schema.as_deref()).await; - - match &result { - Ok(tables) => log::info!("Retrieved {} tables from {}", tables.len(), params.database), - Err(e) => log::error!("Failed to get tables from {}: {}", params.database, e), - } - - result -} - -#[tauri::command] -pub async fn get_columns( - app: AppHandle, - connection_id: String, - table_name: 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.get_columns(¶ms, &table_name, schema.as_deref()) - .await -} - -#[tauri::command] -pub async fn get_foreign_keys( - app: AppHandle, - connection_id: String, - table_name: 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.get_foreign_keys(¶ms, &table_name, schema.as_deref()) - .await -} - -#[tauri::command] -pub async fn get_indexes( - app: AppHandle, - connection_id: String, - table_name: 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.get_indexes(¶ms, &table_name, schema.as_deref()) - .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 { - log::info!( - "Executing query on connection: {} | Query: DELETE FROM {} WHERE pk_map={:?}", - connection_id, - table, - pk_map - ); - 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.delete_record(¶ms, &table, &pk_map, schema.as_deref()) - .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 { - log::info!( - "Executing query on connection: {} | Query: UPDATE {} SET {} = {:?} WHERE pk_map={:?}", - connection_id, - table, - col_name, - new_val, - pk_map - ); - 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 max_blob_size = crate::config::get_max_blob_size(&app); - let drv = driver_for_params(¶ms).await?; - drv.update_record( - ¶ms, - &table, - &pk_map, - &col_name, - new_val, - schema.as_deref(), - max_blob_size, - ) - .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 -} - -/// 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 { - 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?; - let wire = drv - .fetch_blob_as_data_url(¶ms, &table, &col_name, &pk_map, schema.as_deref()) - .await?; - // Convert the BLOB wire format to a data: URL - // wire format: "BLOB:::" - if !wire.starts_with("BLOB:") { - return Err("Invalid BLOB wire format".into()); - } - let after_prefix = &wire[5..]; // skip "BLOB:" - let size_end = after_prefix.find(':').ok_or("Invalid BLOB wire format")?; - let after_size = &after_prefix[size_end + 1..]; - let mime_end = after_size.find(':').ok_or("Invalid BLOB wire format")?; - let mime = &after_size[..mime_end]; - if !mime.starts_with("image/") { - return Err(format!("Not an image: {}", mime)); - } - let base64_payload = &after_size[mime_end + 1..]; - Ok(format!("data:{};base64,{}", mime, base64_payload)) -} - /// 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 { - use base64::Engine; - let bytes = base64::engine::general_purpose::STANDARD - .decode(&base64_data) - .map_err(|e| format!("Invalid base64: {}", e))?; - Ok(crate::drivers::common::encode_blob_full(&bytes)) -} - -/// 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))? + 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 { - use base64::Engine; - let bytes = base64::engine::general_purpose::STANDARD - .decode(&header_base64) - .map_err(|e| format!("Invalid base64: {}", e))?; - let mime = infer::get(&bytes) - .map(|k| k.mime_type()) - .unwrap_or("application/octet-stream"); - Ok(mime.to_string()) + 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; @@ -5133,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; @@ -5168,563 +1548,16 @@ 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 { - let columns: Vec<&str> = data.keys().map(|k| k.as_str()).collect(); - log::info!( - "Executing query on connection: {} | Query: INSERT INTO {} ({}) VALUES (...)", - connection_id, - table, - columns.join(", ") - ); - 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 max_blob_size = crate::config::get_max_blob_size(&app); - let drv = driver_for_params(¶ms).await?; - drv.insert_record(¶ms, &table, data, schema.as_deref(), max_blob_size) - .await -} - +#[cfg(test)] pub(crate) fn cancel_query_impl( state: &QueryCancellationState, connection_id: &str, -) -> Result<(), String> { - let entries = { - let mut handles = state.handles.lock().unwrap(); - handles.remove(connection_id).unwrap_or_default() - }; - if entries.is_empty() { - return Err("No running query found".into()); - } - for handle in entries { - handle.abort(); - } - Ok(()) -} - -#[tauri::command] -pub async fn cancel_query( - state: State<'_, QueryCancellationState>, - connection_id: String, -) -> Result<(), String> { - cancel_query_impl(&state, &connection_id) -} - -/// Payload for the `database-dropped` event, emitted after a `DROP DATABASE` -/// statement succeeds so a listener can reconcile the connection's database -/// selection instead of leaving the dropped database in the sidebar until the -/// next reconnect (#525). -// `connectionId` rather than `connection_id`: the `connection-health-failed` -// event already carries this same field in camelCase, and matching the field -// name for the same concept matters more than matching the neighbouring -// `batch-statement-complete` payload, which happens to use snake_case. -#[derive(serde::Serialize, Clone)] -#[serde(rename_all = "camelCase")] -struct DatabaseDroppedEvent<'a> { - connection_id: &'a str, - database: &'a str, -} - -/// Announces that `database` no longer exists on the server behind -/// `connection_id`. Emitting is best-effort: a listener that missed the event -/// only means the sidebar stays stale until the next manual refresh, which is -/// the pre-#525 behaviour, so a failed emit must not fail the query. -fn emit_database_dropped(app: &AppHandle, connection_id: &str, database: &str) { - log::info!( - "DROP DATABASE detected on connection {}: '{}'", - connection_id, - database - ); - let _ = app.emit( - "database-dropped", - DatabaseDroppedEvent { - connection_id, - database, - }, - ); -} - -#[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 { - log::info!( - "Executing query on connection: {} | Query: {}", - connection_id, - query - ); - - let sanitized_query = sanitize_user_query(&query); - - 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); - } - - // Detected before the spawn, which takes ownership of `sanitized_query`. - // Cheap: only allocates when the statement really is a DROP DATABASE. - let dropped = crate::sql_database_statements::dropped_database(&sanitized_query); - - let drv = driver_for_params(¶ms).await?; - let session_driver = drv.clone(); - let session = session_id.clone(); - let task = tokio::spawn(async move { - drv.execute_query_in_session( - ¶ms, - &sanitized_query, - limit, - page.unwrap_or(1), - schema.as_deref(), - session.as_deref(), - ) - .await - }); - - let abort_handle = Arc::new(task.abort_handle()); - register_abort_handle(&state.handles, connection_id.clone(), abort_handle.clone()); - - let result = task.await; - - unregister_abort_handle(&state.handles, &connection_id, &abort_handle); - - match result { - Ok(Ok((query_result, in_transaction))) => { - log::info!( - "Query executed successfully, returned {} rows", - query_result.rows.len() - ); - // Driving a transaction one statement at a time is the whole - // point, so this path reports session state exactly as a batch - // does. - if let Some(id) = session_id.as_deref() { - emit_session_state(&app, &connection_id, id, in_transaction); - } - if let Some(database) = &dropped { - emit_database_dropped(&app, &connection_id, database); - } - Ok(query_result) - } - Ok(Err(e)) => { - log::error!("Query execution failed: {}", e); - emit_session_state_after_failure( - &app, - &connection_id, - session_driver.as_ref(), - session_id.as_deref(), - ) - .await; - Err(e) - } - Err(_) => { - log::warn!("Query was cancelled"); - emit_session_state_after_failure( - &app, - &connection_id, - session_driver.as_ref(), - session_id.as_deref(), - ) - .await; - Err("Query cancelled".into()) - } - } -} - -/// Payload for the `batch-statement-complete` event, emitted once per -/// statement the instant it finishes so the frontend can mark that result tab -/// done in real time instead of waiting for the whole batch. `batch_id` lets a -/// listener ignore events from other concurrent runs; `index` maps back to the -/// statement's slot. Borrows the result so no clone of the (potentially large) -/// row set is needed. -#[derive(serde::Serialize, Clone)] -struct BatchStatementEvent<'a> { - batch_id: &'a str, - index: usize, - statement: &'a BatchStatementResult, -} - -/// Payload for the `session-transaction-state` event, emitted after a batch -/// that carried a `session_id` so the owning tab can show whether it is -/// still inside an explicit transaction — and therefore still holding a -/// pooled connection. -#[derive(serde::Serialize, Clone)] -struct SessionTransactionStateEvent<'a> { - session_id: &'a str, - in_transaction: bool, -} - -/// Sessions last reported inside a transaction, per connection id, so a -/// disconnect can release them through the driver. -fn open_sessions() -> &'static Mutex>> { - static OPEN: std::sync::OnceLock>>> = - std::sync::OnceLock::new(); - OPEN.get_or_init(Default::default) -} - -fn note_session_state(connection_id: &str, session_id: &str, in_transaction: bool) { - let mut open = open_sessions().lock().unwrap_or_else(|e| e.into_inner()); - if in_transaction { - open.entry(connection_id.to_string()) - .or_default() - .insert(session_id.to_string()); - } else if let Some(ids) = open.get_mut(connection_id) { - ids.remove(session_id); - if ids.is_empty() { - open.remove(connection_id); - } - } -} - -fn take_open_sessions(connection_id: &str) -> Vec { - let mut open = open_sessions().lock().unwrap_or_else(|e| e.into_inner()); - open.remove(connection_id) - .map(|ids| ids.into_iter().collect()) - .unwrap_or_default() -} - -#[cfg(test)] -mod open_sessions_tests { - use super::{note_session_state, take_open_sessions}; - - #[test] - fn disconnect_takes_only_that_connections_open_sessions() { - note_session_state("os-conn-a", "tab-1", true); - note_session_state("os-conn-a", "tab-2", true); - note_session_state("os-conn-a", "tab-2", false); - note_session_state("os-conn-b", "tab-3", true); - - assert_eq!(take_open_sessions("os-conn-a"), vec!["tab-1".to_string()]); - assert!(take_open_sessions("os-conn-a").is_empty()); - assert_eq!(take_open_sessions("os-conn-b"), vec!["tab-3".to_string()]); - } -} - -/// Tell the UI whether a tab is inside a transaction, and remember it for disconnect. -fn emit_session_state( - app: &AppHandle, - connection_id: &str, - session_id: &str, - in_transaction: bool, -) { - note_session_state(connection_id, session_id, in_transaction); - let _ = app.emit( - "session-transaction-state", - SessionTransactionStateEvent { - session_id, - in_transaction, - }, - ); -} - -/// Roll back the transactions a connection's tabs left open, for every path -/// that closes it (disconnect, failed health check). The releases run in the -/// background, so closing a connection never waits on a tab's in-flight run. -/// Without `params` the bookkeeping is still cleared and the idle sweep -/// reclaims the connections. -pub(crate) async fn release_connection_sessions( - app: &AppHandle, - connection_id: &str, - params: Option<&ConnectionParams>, -) { - let open = take_open_sessions(connection_id); - if open.is_empty() { - return; - } - for id in &open { - let _ = app.emit( - "session-transaction-state", - SessionTransactionStateEvent { - session_id: id, - in_transaction: false, - }, - ); - } - let Some(params) = params else { - log::warn!("Could not resolve {connection_id} to release its open sessions"); - return; - }; - match driver_for_params(params).await { - Ok(drv) => { - tauri::async_runtime::spawn(async move { - for id in open { - drv.release_session(&id).await; - } - }); - } - Err(e) => log::warn!("Could not release open sessions of {connection_id}: {e}"), - } -} - -/// A failed or cancelled run returns no session flag, so ask the driver, or -/// the tab's TX badge would keep showing a transaction that already ended. -async fn emit_session_state_after_failure( - app: &AppHandle, - connection_id: &str, - drv: &dyn crate::drivers::driver_trait::DatabaseDriver, - session_id: Option<&str>, -) { - let Some(id) = session_id else { return }; - if let Some(in_transaction) = drv.session_in_transaction(id).await { - emit_session_state(app, connection_id, id, in_transaction); - } -} - -/// Roll back and release the connection pinned to `session_id`. -/// -/// Called when an editor tab closes, so an abandoned transaction cannot -/// hold its locks until the idle sweep reclaims it. -#[tauri::command] -pub async fn release_query_session( - app: AppHandle, - connection_id: String, - session_id: String, -) -> 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 params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - let drv = driver_for_params(¶ms).await?; - drv.release_session(&session_id).await; - note_session_state(&connection_id, &session_id, false); - Ok(()) -} - -/// 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> { - log::info!( - "Executing query batch on connection: {} | {} statement(s)", - connection_id, - queries.len() - ); - - let sanitized_queries: Vec = queries.iter().map(|q| sanitize_user_query(q)).collect(); - - // One entry per statement, computed before the spawn takes ownership of - // `sanitized_queries`. Index-aligned with the results returned below, the - // same assumption the `batch-statement-complete` event already relies on. - let dropped_per_statement: Vec> = sanitized_queries - .iter() - .map(|q| crate::sql_database_statements::dropped_database(q)) - .collect(); - - 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?; - - // Build a Tauri-agnostic progress sink the driver invokes per statement. - // Each invocation emits one event so result tabs resolve as they finish. - let progress: Option> = - batch_id.map(|bid| { - let app = app.clone(); - let cb: Arc = - Arc::new(move |index, statement: &BatchStatementResult| { - let _ = app.emit( - "batch-statement-complete", - BatchStatementEvent { - batch_id: &bid, - index, - statement, - }, - ); - }); - cb - }); - - let session_driver = drv.clone(); - let session = session_id.clone(); - let task = tokio::spawn(async move { - drv.execute_batch_in_session( - ¶ms, - &sanitized_queries, - limit, - page.unwrap_or(1), - schema.as_deref(), - session.as_deref(), - progress.as_deref(), - ) - .await - }); - - let abort_handle = Arc::new(task.abort_handle()); - register_abort_handle(&state.handles, connection_id.clone(), abort_handle.clone()); - - let result = task.await; - - unregister_abort_handle(&state.handles, &connection_id, &abort_handle); - - match result { - Ok(Ok((batch_results, in_transaction))) => { - // The tab holds a pooled connection for as long as its - // transaction is open, so the UI has to be able to show it and - // release it on close. - if let Some(id) = session_id.as_deref() { - emit_session_state(&app, &connection_id, id, in_transaction); - } - let success_count = batch_results.iter().filter(|r| r.result.is_some()).count(); - log::info!( - "Batch executed: {} succeeded, {} failed (of {} total)", - success_count, - batch_results.len() - success_count, - batch_results.len() - ); - // A batch reports per-statement outcomes, so only announce drops - // whose own statement succeeded; a failed DROP leaves the database - // in place. - for (dropped, statement) in dropped_per_statement.iter().zip(&batch_results) { - if let Some(database) = dropped { - if statement.result.is_some() { - emit_database_dropped(&app, &connection_id, database); - } - } - } - Ok(batch_results) - } - Ok(Err(e)) => { - log::error!("Batch execution failed at setup: {}", e); - emit_session_state_after_failure( - &app, - &connection_id, - session_driver.as_ref(), - session_id.as_deref(), - ) - .await; - Err(e) - } - Err(_) => { - log::warn!("Batch was cancelled"); - emit_session_state_after_failure( - &app, - &connection_id, - session_driver.as_ref(), - session_id.as_deref(), - ) - .await; - Err("Query cancelled".into()) - } - } -} - -// --- 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 { - log::info!( - "Explaining query on connection: {} | analyze: {} | Query: {}", - connection_id, - analyze, - query - ); - - let sanitized_query = sanitize_user_query(&query); - - 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?; - - // Leading comments are skipped with the driver's own comment rules, so a - // `# note` header on MySQL does not hide an explainable statement. - let hash_comments = - crate::drivers::sql_syntax::SqlSyntax::resolve(&drv.manifest().capabilities).hash_comments; - if !crate::drivers::common::is_explainable_query_for(&sanitized_query, hash_comments) { - return Err( - "EXPLAIN is only supported for DML statements (SELECT, INSERT, UPDATE, DELETE, REPLACE). DDL statements like CREATE, DROP, or ALTER cannot be explained." - .into(), - ); - } - - let task = tokio::spawn(async move { - drv.explain_query(¶ms, &sanitized_query, analyze, schema.as_deref()) - .await - }); - - let abort_handle = Arc::new(task.abort_handle()); - register_abort_handle(&state.handles, connection_id.clone(), abort_handle.clone()); - - let result = task.await; - - unregister_abort_handle(&state.handles, &connection_id, &abort_handle); - - match result { - Ok(Ok(plan)) => { - log::info!("Explain query completed successfully"); - Ok(plan) - } - Ok(Err(e)) => { - log::error!("Explain query failed: {}", e); - Err(e) - } - Err(_) => { - log::warn!("Explain query was cancelled"); - Err("Explain query cancelled".into()) - } - } +) -> Result<(), String> { + crate::application::queries::cancel_registered_queries(state, None, connection_id, None) } +// --- Explain Query Plan --- + /// 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. @@ -5759,197 +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 { - 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 sanitized = query.trim().trim_end_matches(';').to_string(); - - let count_q = format!("SELECT COUNT(*) FROM ({}) as count_wrapper", sanitized); - - let drv = driver_for_params(¶ms).await?; - // The editor sends a session only for a tab inside a transaction. - let result = match session_id.as_deref() { - Some(id) => { - read_in_open_transaction( - drv.as_ref(), - ¶ms, - &count_q, - None, - 1, - schema.as_deref(), - id, - ) - .await? - } - None => { - drv.execute_query(¶ms, &count_q, None, 1, schema.as_deref()) - .await? - } - }; - - let total: u64 = result - .rows - .first() - .and_then(|r| r.first()) - .and_then(|v| v.as_i64()) - .map(|n| n as u64) - .unwrap_or(0); - - Ok(total) -} - // --- 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()); @@ -5981,35 +1625,14 @@ pub async fn build_connection_url(params: &ConnectionParams) -> Result, - get_keychain_password: impl Fn(&str) -> Result, -) -> Option { - if let Some(pwd) = ¶ms.password { - return Some(pwd.clone()); - } - - let saved = saved_conn?; - - if saved.params.save_in_keychain.unwrap_or(false) { - if let Ok(pwd) = get_keychain_password(&saved.id) { - if !pwd.trim().is_empty() { - return Some(pwd); - } - } - } - - match &saved.params.password { - Some(pwd) if !pwd.trim().is_empty() => Some(pwd.clone()), - _ => None, - } -} - /// Resolves SSH credential (password or passphrase) for testing /// 1. Credential from request params (if provided, even if empty) /// 2. Credential from keychain (if save_in_keychain is enabled) /// 3. Credential from saved connection (as fallback) +#[cfg(test)] +use crate::models::SshConnection; + +#[cfg(test)] fn resolve_ssh_test_credential( request_credential: Option<&str>, connection_id: Option<&str>, @@ -6045,6 +1668,7 @@ fn resolve_ssh_test_credential( /// 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, @@ -6060,754 +1684,39 @@ fn apply_inline_ssh_secret_fallback( } /// 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> { - log::info!("Fetching views for connection: {}", connection_id); - - 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); - } - - log::debug!( - "Getting views from {} database: {}", - saved_conn.params.driver, - params.database - ); - - let drv = driver_for_params(¶ms).await?; - let result = drv.get_views(¶ms, schema.as_deref()).await; - - match &result { - Ok(views) => log::info!("Retrieved {} views from {}", views.len(), params.database), - Err(e) => log::error!("Failed to get views from {}: {}", params.database, e), - } - - result -} - -#[tauri::command] -pub async fn get_view_definition( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result { - log::info!( - "Fetching view definition for: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .get_view_definition(¶ms, &view_name, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully retrieved view definition for {}", view_name), - Err(e) => log::error!("Failed to get view definition for {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn create_view( - app: AppHandle, - connection_id: String, - view_name: String, - definition: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!( - "Creating view: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .create_view(¶ms, &view_name, &definition, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully created view: {}", view_name), - Err(e) => log::error!("Failed to create view {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn alter_view( - app: AppHandle, - connection_id: String, - view_name: String, - definition: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!( - "Altering view: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .alter_view(¶ms, &view_name, &definition, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully altered view: {}", view_name), - Err(e) => log::error!("Failed to alter view {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn drop_view( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!( - "Dropping view: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv.drop_view(¶ms, &view_name, schema.as_deref()).await; - - match &result { - Ok(_) => log::info!("Successfully dropped view: {}", view_name), - Err(e) => log::error!("Failed to drop view {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn get_view_columns( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result, String> { - log::info!( - "Fetching view columns for: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .get_view_columns(¶ms, &view_name, schema.as_deref()) - .await; - - match &result { - Ok(columns) => log::info!("Retrieved {} columns for view {}", columns.len(), view_name), - Err(e) => log::error!("Failed to get view columns for {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn get_materialized_views( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - log::info!( - "Fetching materialized views for connection: {}", - connection_id - ); - - 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?; - let result = drv.get_materialized_views(¶ms, schema.as_deref()).await; - - match &result { - Ok(views) => log::info!( - "Retrieved {} materialized views from {}", - views.len(), - params.database - ), - Err(e) => log::error!( - "Failed to get materialized views from {}: {}", - params.database, - e - ), - } - - result -} - -#[tauri::command] -pub async fn get_materialized_view_columns( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result, String> { - log::info!( - "Fetching materialized view columns for: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .get_materialized_view_columns(¶ms, &view_name, schema.as_deref()) - .await; - - match &result { - Ok(columns) => log::info!( - "Retrieved {} columns for materialized view {}", - columns.len(), - view_name - ), - Err(e) => log::error!( - "Failed to get materialized view columns for {}: {}", - view_name, - e - ), - } - - result -} - -#[tauri::command] -pub async fn get_materialized_view_definition( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result { - log::info!( - "Fetching materialized view definition for: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .get_materialized_view_definition(¶ms, &view_name, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!( - "Successfully retrieved materialized view definition for {}", - view_name - ), - Err(e) => log::error!( - "Failed to get materialized view definition for {}: {}", - view_name, - e - ), - } - - result -} - -#[tauri::command] -pub async fn refresh_materialized_view( - app: AppHandle, - connection_id: String, - view_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!( - "Refreshing materialized view: {} on connection: {}", - view_name, - connection_id - ); - - 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?; - let result = drv - .refresh_materialized_view(¶ms, &view_name, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully refreshed materialized view: {}", view_name), - Err(e) => log::error!("Failed to refresh materialized view {}: {}", view_name, e), - } - - result -} - -#[tauri::command] -pub async fn get_triggers( - app: AppHandle, - connection_id: String, - schema: Option, - database: Option, -) -> Result, String> { - log::info!("Fetching triggers for connection: {}", connection_id); - - 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?; - let result = drv.get_triggers(¶ms, schema.as_deref()).await; - - match &result { - Ok(triggers) => log::info!("Retrieved {} triggers", triggers.len()), - Err(e) => log::error!("Failed to get triggers: {}", e), - } - - result -} - -#[tauri::command] -pub async fn get_trigger_definition( - app: AppHandle, - connection_id: String, - trigger_name: String, - table_name: String, - schema: Option, - database: Option, -) -> Result { - log::info!( - "Fetching trigger definition for: {} on connection: {}", - trigger_name, - connection_id - ); - - 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.get_trigger_definition(¶ms, &trigger_name, &table_name, schema.as_deref()) - .await -} - -#[tauri::command] -pub async fn create_trigger( - app: AppHandle, - connection_id: String, - trigger_sql: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!("Creating trigger on connection: {}", connection_id); - - 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?; - let result = drv - .create_trigger(¶ms, &trigger_sql, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully created trigger"), - Err(e) => log::error!("Failed to create trigger: {}", e), - } - - result -} - -#[tauri::command] -pub async fn drop_trigger( - app: AppHandle, - connection_id: String, - trigger_name: String, - table_name: String, - schema: Option, - database: Option, -) -> Result<(), String> { - log::info!( - "Dropping trigger: {} on connection: {}", - trigger_name, - connection_id - ); - - 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?; - let result = drv - .drop_trigger(¶ms, &trigger_name, &table_name, schema.as_deref()) - .await; - - match &result { - Ok(_) => log::info!("Successfully dropped trigger: {}", trigger_name), - Err(e) => log::error!("Failed to drop trigger {}: {}", trigger_name, e), - } - - result -} - -// --- User management (gated by `DriverCapabilities::user_management`) ------- - -/// Resolves the connection and driver shared by every user-management command. -async fn user_mgmt_context( - app: &AppHandle, - connection_id: &str, -) -> Result< - ( - std::sync::Arc, - ConnectionParams, - ), - 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 params = resolve_connection_params_with_id(&expanded_params, connection_id)?; - let drv = driver_for_params(¶ms).await?; - Ok((drv, params)) -} - -#[tauri::command] -pub async fn get_db_privilege_catalog( - app: AppHandle, - connection_id: String, -) -> Result { - let saved_conn = find_connection_by_id(&app, &connection_id)?; - let drv = driver_for_saved(&app, &saved_conn).await?; - drv.get_db_privilege_catalog().await -} - -#[tauri::command] -pub async fn get_db_users( - app: AppHandle, - connection_id: String, -) -> Result, String> { - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - drv.get_db_users(¶ms).await -} - -#[tauri::command] -pub async fn get_db_user_grants( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result, String> { - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - drv.get_db_user_grants(¶ms, &user, &host).await -} - -#[tauri::command] -pub async fn create_db_user( - app: AppHandle, - connection_id: String, - user: String, - host: String, - password: String, -) -> Result<(), String> { - log::info!("Creating database user '{user}'@'{host}'"); - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - let result = drv.create_db_user(¶ms, &user, &host, &password).await; - if let Err(e) = &result { - log::error!("Failed to create user '{user}'@'{host}': {e}"); - } - result -} - -#[tauri::command] -pub async fn drop_db_user( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result<(), String> { - log::info!("Dropping database user '{user}'@'{host}'"); - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - let result = drv.drop_db_user(¶ms, &user, &host).await; - if let Err(e) = &result { - log::error!("Failed to drop user '{user}'@'{host}': {e}"); - } - result -} - -#[tauri::command] -pub async fn set_db_user_password( - app: AppHandle, - connection_id: String, - user: String, - host: String, - password: String, -) -> Result<(), String> { - log::info!("Changing password for database user '{user}'@'{host}'"); - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - let result = drv - .set_db_user_password(¶ms, &user, &host, &password) - .await; - if let Err(e) = &result { - log::error!("Failed to change password for '{user}'@'{host}': {e}"); - } - result -} - -#[tauri::command] -pub async fn get_db_user_privileges( - app: AppHandle, - connection_id: String, - user: String, - host: String, -) -> Result, String> { - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - drv.get_db_user_privileges(¶ms, &user, &host).await +) -> 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() + }, + ) } -#[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> { - let scope = match (database.as_deref(), table.as_deref()) { - (Some(db), Some(tbl)) => format!("{db}.{tbl}"), - (Some(db), None) => format!("{db}.*"), - _ => "*.*".to_string(), - }; - log::info!( - "{} privileges for '{user}'@'{host}' on {scope}", - if grant { "Granting" } else { "Revoking" }, - ); - let (drv, params) = user_mgmt_context(&app, &connection_id).await?; - let result = drv - .apply_db_user_privileges( - ¶ms, - &user, - &host, - database.as_deref(), - table.as_deref(), - &privileges, - grant, - ) - .await; - if let Err(e) = &result { - log::error!("Failed to apply privileges for '{user}'@'{host}': {e}"); - } - result -} +// ==================== 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::health_check::register_connection(connection_id).await; - // Broadcast so every window learns this connection is now open. - crate::health_check::emit_active_changed(&app).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> { - log::info!("Disconnecting from connection: {}", connection_id); - - // Unregister from health check before closing the pool. - crate::health_check::unregister_connection(&connection_id).await; - - // A plugin secret that can no longer be read must not prevent closing the - // pools: fall back to the connection without plugin secrets. - let saved_conn = match find_connection_by_id(&app, &connection_id) { - Ok(conn) => conn, - Err(e) => { - log::warn!("Disconnecting {connection_id} without plugin secrets: {e}"); - find_connection_metadata_by_id(&app, &connection_id)? - } - }; - if let Some(driver) = crate::drivers::registry::get_driver(&saved_conn.params.driver).await { - driver - .invalidate_connection_metadata(Some(&connection_id)) - .await; - } - - // Close pools before resolving SSH/K8s params. Pool keys depend only on - // connection_id (plus driver/database/TLS), not the tunnel's local port. - // `close_pools_for_connection_id` matches by connection_id prefix, so it - // subsumes the single-key close on single-database connections and closes - // per-database override pools too (#1063). A dead bastion / unreachable - // cluster must not prevent pool cleanup (#1065). - 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 params_for_pool_close(&saved_conn.params, &connection_id) { - Ok(p) => p, - Err(e) => { - log::warn!( - "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.clone()); - fallback - } - }; - release_connection_sessions(&app, &connection_id, Some(&close_params)).await; - - // Broadcast so every window learns this connection is now closed. - crate::health_check::emit_active_changed(&app).await; - - log::info!( - "Successfully disconnected from connection: {}", - connection_id - ); - Ok(()) -} - // --- Type Registry --- -#[tauri::command] pub async fn get_data_types(driver: String) -> Result { log::debug!("Fetching data types for driver: {}", driver); @@ -6817,27 +1726,6 @@ pub async fn get_data_types(driver: String) -> Result( - app: AppHandle, - driver: String, - kinds: Vec, - connection_id: Option, -) -> Result, String> { - let drv = if let Some(id) = connection_id { - let saved = find_connection_by_id(&app, &id)?; - if saved.params.driver != driver { - return Err("Connection driver does not match the requested driver".into()); - } - driver_for_saved(&app, &saved).await? - } else { - driver_for(&driver).await? - }; - Ok(kinds.iter().map(|k| drv.map_inferred_type(k)).collect()) -} - // --- DDL generation commands --- /// Point `params` at the database the user is browsing (multi-database @@ -6853,7 +1741,7 @@ pub(crate) fn apply_ddl_database_override(params: &mut ConnectionParams, databas /// builder only renders SQL, so a keychain error leaves the secret unset and /// the params are bound without it. SSH secrets are not loaded because the /// builders never open tunnels. -fn apply_sql_builder_secrets( +pub(crate) fn apply_sql_builder_secrets( params: &mut ConnectionParams, connection_id: &str, connection_uri: impl FnOnce(bool) -> Result, String>, @@ -6882,36 +1770,6 @@ fn apply_sql_builder_secrets( } } -/// Bind every secret a plugin SQL builder may need: the keychain connection -/// URI and password (see `apply_sql_builder_secrets`) and the plugin-owned -/// secrets, resolved into `params.extra` like for any other driver call. A -/// builder may call the plugin's backend (for example to look up a table's -/// type before rendering its DROP statement), so it needs the same -/// credentials. Never fails: a missing or unreadable secret is logged and left -/// unset. SSH secrets are not loaded because the builders never open tunnels. -fn bind_sql_builder_secrets(cache: &credential_cache::CredentialCache, conn: &mut SavedConnection) { - let conn_id = conn.id.clone(); - apply_sql_builder_secrets( - &mut conn.params, - &conn_id, - |stored| credential_cache::get_connection_uri_cached(cache, &conn_id, stored), - || credential_cache::get_db_password_cached(cache, &conn_id), - ); - crate::plugin_secrets::hydrate_connection(cache, conn); -} - -/// Saved connection for the SQL-builder commands: secrets are read leniently -/// (see `bind_sql_builder_secrets`) and no tunnel is touched. -fn find_connection_for_sql_builders( - app: &AppHandle, - id: &str, -) -> Result { - let mut conn = lookup_saved_connection(app, id)?; - let cache = app.state::>(); - bind_sql_builder_secrets(&cache, &mut conn); - Ok(conn) -} - /// Params forwarded to the plugin SQL builders: the saved params with the /// connection id and the browsed `database` applied. SSH/SSM/K8s tunnels and /// proxies are never resolved here, so host and port stay as saved: a @@ -6930,218 +1788,10 @@ pub(crate) fn sql_builder_params( params } -/// Driver and params for the SQL-preview builders. Built-in drivers build SQL -/// without credentials, so they keep the registered instance and the saved -/// params, exactly as before. Plugin drivers get `sql_builder_params` bound -/// to a driver snapshot, so every builder RPC carries the connection context -/// (additive `params` field). No tunnel, metadata discovery or other RPC -/// happens here. -async fn ddl_driver_for_saved( - saved: &SavedConnection, - database: Option, -) -> Result< - ( - Arc, - ConnectionParams, - ), - String, -> { - let driver = driver_for(&saved.params.driver).await?; - if driver.manifest().is_builtin { - return Ok((driver, saved.params.clone())); - } - let params = sql_builder_params(saved, database); - let driver = driver.bind_connection_params(¶ms).unwrap_or(driver); - Ok((driver, 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> { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, _) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_create_table_sql(&table_name, columns, schema.as_deref()) - .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> { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, _) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_add_column_sql(&table, column, schema.as_deref()) - .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> { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, _) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_alter_column_sql(&table, old_column, new_column, schema.as_deref()) - .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> { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, _) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_create_index_sql(&table, &index_name, columns, is_unique, schema.as_deref()) - .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> { - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, params) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_create_foreign_key_sql( - ¶ms, - &table, - &fk_name, - &column, - &ref_table, - &ref_column, - on_delete.as_deref(), - on_update.as_deref(), - schema.as_deref(), - ) - .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> { - let stored = lookup_saved_connection(&app, &connection_id)?; - let driver = driver_for(&stored.params.driver).await?; - if driver.manifest().is_builtin || !driver.manifest().capabilities.drop_table_sql { - return Ok(None); - } - let saved_conn = find_connection_for_sql_builders(&app, &connection_id)?; - let (drv, params) = ddl_driver_for_saved(&saved_conn, database).await?; - drv.get_drop_table_sql(¶ms, &table, schema.as_deref()) - .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> { - 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.drop_index(¶ms, &table, &index_name, schema.as_deref()) - .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> { - 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.drop_foreign_key(¶ms, &table, &fk_name, schema.as_deref()) - .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 { - let config_dir = crate::paths::get_app_config_dir(); - let path = config_dir.join("keybindings.json"); - if !path.exists() { - return Ok(serde_json::Value::Object(serde_json::Map::new())); - } - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).map_err(|e| e.to_string()) -} - -#[tauri::command] -pub async fn save_keybindings( - _app: AppHandle, - keybindings: serde_json::Value, -) -> Result<(), String> { - let config_dir = crate::paths::get_app_config_dir(); - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - let path = config_dir.join("keybindings.json"); - let content = serde_json::to_string_pretty(&keybindings).map_err(|e| e.to_string())?; - fs::write(&path, content).map_err(|e| e.to_string()) -} - -#[tauri::command] pub async fn get_driver_manifest( driver_id: String, ) -> Option { @@ -7157,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> { @@ -7241,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. @@ -7410,487 +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 { - 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 params = resolve_connection_params_with_id(&expanded_params, &connection_id)?; - - let query = match saved_conn.params.driver.as_str() { - "sqlite" => "SELECT datetime('now', 'localtime')", - _ => "SELECT NOW()", - }; - - let drv = driver_for_params(¶ms).await?; - let result = drv.execute_query(¶ms, query, Some(1), 1, None).await?; - - result - .rows - .first() - .and_then(|row| row.first()) - .map(|v| match v { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), - }) - .ok_or_else(|| "No timestamp returned from server".to_string()) -} - -#[tauri::command] -pub async fn export_connections_payload( - app: AppHandle, - include_secrets: Option, - connection_ids: Option>, -) -> Result { - let include_secrets = include_secrets.unwrap_or(true); - let conn_path = get_config_path(&app)?; - let ssh_path = get_ssh_config_path(&app)?; - - let mut conn_file = persistence::load_connections_file(&conn_path)?; - let mut ssh_connections = if ssh_path.exists() { - let content = fs::read_to_string(&ssh_path).map_err(|e| e.to_string())?; - serde_json::from_str::>(&content).unwrap_or_default() - } else { - Vec::new() - }; - let mut k8s_connections = load_k8s_connections_sync(&app)?; - - // When a selection is provided, keep only the selected connections (of any - // kind) plus the group chains needed to preserve their hierarchy. Done - // before password resolution so unselected credentials never leave the - // keychain. - if let Some(ids) = &connection_ids { - let selected: std::collections::HashSet<&str> = ids.iter().map(String::as_str).collect(); - conn_file - .connections - .retain(|c| selected.contains(c.id.as_str())); - ssh_connections.retain(|s| selected.contains(s.id.as_str())); - k8s_connections.retain(|k| selected.contains(k.id.as_str())); - let kept_groups = crate::models::collect_group_ancestors( - &conn_file.groups, - conn_file - .connections - .iter() - .filter_map(|c| c.group_id.as_deref()), - ); - conn_file.groups.retain(|g| kept_groups.contains(&g.id)); - // Same for tags: only export the ones the selection actually uses. - let kept_tags: std::collections::HashSet = conn_file - .connections - .iter() - .flat_map(|c| c.tag_ids.iter().flatten()) - .cloned() - .collect(); - conn_file.tags.retain(|t| kept_tags.contains(&t.id)); - } - - let cache = app - .state::>() - .inner() - .clone(); - let mut plugin_secrets = HashMap::new(); - - // Resolve passwords for database connections - for conn in &mut conn_file.connections { - if !include_secrets { - // Strip any secrets that may already live in the connections file - conn.params.password = None; - conn.params.ssh_password = None; - conn.params.ssh_key_passphrase = None; - conn.params.connection_uri = None; - conn.plugin_secret_keys.clear(); - continue; - } - // A missing keychain entry must not abort the whole export (or a - // scheduled backup): the connection is exported without that value. - let resolved_plugin_secrets = crate::plugin_secrets::load_secret_values( - &cache, - &conn.id, - &conn.params.driver, - &conn.plugin_secret_keys, - ); - if !resolved_plugin_secrets.is_empty() { - plugin_secrets.insert(conn.id.clone(), resolved_plugin_secrets); - } - if conn.params.save_in_keychain.unwrap_or(false) { - // Without this the export carries the marker but not the URI, and - // restoring elsewhere yields a connection that cannot resolve it. - if let Ok(Some(uri)) = - credential_cache::get_connection_uri_cached(&cache, &conn.id, true) - { - conn.params.connection_uri = Some(uri); - } - if let Ok(pwd) = credential_cache::get_db_password_cached(&cache, &conn.id) { - conn.params.password = Some(pwd); - } - if conn.params.ssh_enabled.unwrap_or(false) { - if let Ok(ssh_pwd) = credential_cache::get_ssh_password_cached(&cache, &conn.id) { - conn.params.ssh_password = Some(ssh_pwd); - } - if let Ok(ssh_passphrase) = - credential_cache::get_ssh_key_passphrase_cached(&cache, &conn.id) - { - conn.params.ssh_key_passphrase = Some(ssh_passphrase); - } - } - } - } - - // Resolve passwords for SSH connections - for ssh in &mut ssh_connections { - if !include_secrets { - ssh.password = None; - ssh.key_passphrase = None; - continue; - } - if ssh.save_in_keychain.unwrap_or(false) { - if let Ok(pwd) = credential_cache::get_ssh_password_cached(&cache, &ssh.id) { - ssh.password = Some(pwd); - } - if let Ok(passphrase) = credential_cache::get_ssh_key_passphrase_cached(&cache, &ssh.id) - { - ssh.key_passphrase = Some(passphrase); - } - } - } - - Ok(ExportPayload { - version: 1, - groups: conn_file.groups, - connections: conn_file.connections, - ssh_connections, - k8s_connections, - tags: conn_file.tags, - plugin_secrets, - }) -} - -#[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, - mut payload: ExportPayload, -) -> Result<(), String> { - let conn_path = get_config_path(&app)?; - let ssh_path = get_ssh_config_path(&app)?; - - let mut current_file = persistence::load_connections_file(&conn_path).unwrap_or_default(); - let mut current_ssh = if ssh_path.exists() { - let content = fs::read_to_string(&ssh_path).map_err(|e| e.to_string())?; - serde_json::from_str::>(&content).unwrap_or_default() - } else { - Vec::new() - }; - - let cache = app - .state::>() - .inner() - .clone(); - let mut imported_plugin_secrets = std::mem::take(&mut payload.plugin_secrets); - let mut plugin_secret_writes = Vec::new(); - - // Merge groups (preserves hierarchy; demotes orphaned parent_ids to root) - merge_groups(&mut current_file.groups, payload.groups); - - // Merge tags (import wins on id collision, name matches are unified onto - // the existing tag) and remap the imported connections' tag_ids so - // name-merged tags keep resolving. - let tag_remap = - crate::connection_tags::merge_imported_tags(&mut current_file.tags, payload.tags); - let mut payload_connections = payload.connections; - if !tag_remap.is_empty() { - // Existing connections may reference a tag id that the merge unified - // onto another tag, so the remap applies to both sides. - for conn in payload_connections - .iter_mut() - .chain(current_file.connections.iter_mut()) - { - if let Some(tag_ids) = &mut conn.tag_ids { - let mut seen = std::collections::HashSet::new(); - *tag_ids = tag_ids - .iter() - .map(|id| tag_remap.get(id).unwrap_or(id).clone()) - .filter(|id| seen.insert(id.clone())) - .collect(); - } - } - } - - // Environments come from an external file: normalize instead of failing - // the whole import — an unknown tier just becomes "unclassified". - for conn in &mut payload_connections { - conn.environment = validate_environment(conn.environment.take()).unwrap_or(None); - } - - // Merge connections and handle passwords - for mut new_conn in payload_connections { - // An imported payload is untrusted input and may carry an inline URI. - // Hold it to the same rule as a save: keychain or nothing. - validate_connection_uri_persistence(&new_conn.params)?; - let declared_plugin_secret_keys = std::mem::take(&mut new_conn.plugin_secret_keys); - let secrets_for_connection = imported_plugin_secrets - .remove(&new_conn.id) - .unwrap_or_default(); - let previous_plugin_metadata = current_file - .connections - .iter() - .find(|connection| connection.id == new_conn.id) - .map(|connection| { - ( - connection.params.driver.clone(), - connection.plugin_secret_keys.clone(), - ) - }); - // Keychain writes are deferred until the connections file is saved, - // so a failed import never leaves orphaned plugin secrets behind. - plugin_secret_writes.extend(crate::plugin_secrets::plan_imported_secrets( - &mut new_conn, - &declared_plugin_secret_keys, - secrets_for_connection, - previous_plugin_metadata - .as_ref() - .map(|(driver, keys)| (driver.as_str(), keys.as_slice())), - )); - - // Handle passwords in keychain - if new_conn.params.save_in_keychain.unwrap_or(false) { - if let Some(uri) = runtime_connection_uri(&new_conn.params) { - let uri = uri.to_string(); - keychain_utils::set_connection_uri(&new_conn.id, &uri)?; - credential_cache::set_connection_uri_cached(&cache, &new_conn.id, &uri); - } - if let Some(pwd) = &new_conn.params.password { - keychain_utils::set_db_password(&new_conn.id, pwd)?; - credential_cache::set_db_password_cached(&cache, &new_conn.id, pwd); - } - if new_conn.params.ssh_enabled.unwrap_or(false) { - if let Some(ssh_pwd) = &new_conn.params.ssh_password { - keychain_utils::set_ssh_password(&new_conn.id, ssh_pwd)?; - credential_cache::set_ssh_password_cached(&cache, &new_conn.id, ssh_pwd); - } - if let Some(ssh_passphrase) = &new_conn.params.ssh_key_passphrase { - keychain_utils::set_ssh_key_passphrase(&new_conn.id, ssh_passphrase)?; - credential_cache::set_ssh_key_passphrase_cached( - &cache, - &new_conn.id, - ssh_passphrase, - ); - } - } - // Clear passwords from struct before saving to disk - new_conn.params.password = None; - new_conn.params.ssh_password = None; - new_conn.params.ssh_key_passphrase = None; - } - - // The URI never reaches disk: it is either in the keychain by now, or - // `validate_connection_uri_persistence` rejected the payload above. - let imported_uri_in_keychain = runtime_connection_uri(&new_conn.params).is_some(); - new_conn.params = params_for_persistence(&new_conn.params, imported_uri_in_keychain); - - if let Some(existing) = current_file - .connections - .iter_mut() - .find(|c| c.id == new_conn.id) - { - *existing = new_conn; - } else { - current_file.connections.push(new_conn); - } - } - - // Merge SSH connections and handle passwords - for mut new_ssh in payload.ssh_connections { - if new_ssh.save_in_keychain.unwrap_or(false) { - if let Some(pwd) = &new_ssh.password { - keychain_utils::set_ssh_password(&new_ssh.id, pwd)?; - credential_cache::set_ssh_password_cached(&cache, &new_ssh.id, pwd); - } - if let Some(passphrase) = &new_ssh.key_passphrase { - keychain_utils::set_ssh_key_passphrase(&new_ssh.id, passphrase)?; - credential_cache::set_ssh_key_passphrase_cached(&cache, &new_ssh.id, passphrase); - } - // Clear passwords from struct before saving to disk - new_ssh.password = None; - new_ssh.key_passphrase = None; - } - - if let Some(existing) = current_ssh.iter_mut().find(|s| s.id == new_ssh.id) { - *existing = new_ssh; - } else { - current_ssh.push(new_ssh); - } - } - - // Save files. Plugin secrets reach the keychain only once the connections - // file that lists them has landed. - crate::plugin_secrets::commit_secret_writes( - &crate::plugin_secrets::KeychainSecretStore, - &cache, - plugin_secret_writes, - || save_connections_and_invalidate(&app, &conn_path, ¤t_file), - )?; - let ssh_json = serde_json::to_string_pretty(¤t_ssh).map_err(|e| e.to_string())?; - persistence::write_private_file(&ssh_path, ssh_json)?; - - // Merge K8s connections - let k8s_path = get_k8s_config_path(&app)?; - let mut current_k8s = load_k8s_connections_sync(&app)?; - for new_k8s in payload.k8s_connections { - if let Some(existing) = current_k8s.iter_mut().find(|k| k.id == new_k8s.id) { - *existing = new_k8s; - } else { - current_k8s.push(new_k8s); - } - } - let k8s_json = serde_json::to_string_pretty(¤t_k8s).map_err(|e| e.to_string())?; - persistence::write_private_file(&k8s_path, k8s_json)?; - - Ok(()) -} diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 3f504fe96..ca4c2e89a 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -1,49 +1,10 @@ -use crate::keychain_utils; 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; -#[derive(Serialize, Deserialize, Debug, Clone, Default)] -#[serde(rename_all = "camelCase")] -pub struct PluginConfig { - pub interpreter: Option, - #[serde(default)] - pub settings: HashMap, - /// Per-plugin override of `AppConfig::plugin_call_timeout_seconds`. - /// `None` inherits the global value; `0` disables the timeout. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub call_timeout_seconds: Option, - /// Per-plugin override of `AppConfig::plugin_shutdown_grace_seconds`. - /// `None` inherits the global value; values below 1 are clamped at runtime. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub shutdown_grace_seconds: Option, -} - -/// Per-connection column masking overrides (`table.column` entries). -#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct ColumnMaskingOverride { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub include: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub exclude: Option>, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub enum WindowDecorationsMode { - #[default] - Automatic, - AlwaysShow, - AlwaysHide, -} - fn default_true() -> bool { true } @@ -85,6 +46,41 @@ pub struct DatabaseBackupPlan { pub tables: Option>, } +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +#[serde(rename_all = "camelCase")] +pub struct PluginConfig { + pub interpreter: Option, + #[serde(default)] + pub settings: HashMap, + /// Per-plugin override of `AppConfig::plugin_call_timeout_seconds`. + /// `None` inherits the global value; `0` disables the timeout. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub call_timeout_seconds: Option, + /// Per-plugin override of `AppConfig::plugin_shutdown_grace_seconds`. + /// `None` inherits the global value; values below 1 are clamped at runtime. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shutdown_grace_seconds: Option, +} + +/// Per-connection column masking overrides (`table.column` entries). +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ColumnMaskingOverride { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub include: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exclude: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum WindowDecorationsMode { + #[default] + Automatic, + AlwaysShow, + AlwaysHide, +} + #[derive(Serialize, Deserialize, Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct AppConfig { @@ -263,7 +259,6 @@ pub struct AppConfig { pub backup_webdav_url: Option, /// WebDAV username; the password lives in the OS keychain. pub backup_webdav_username: Option, - // Scheduled database content backup (Milestone 1) pub database_backup_plan: Option, // ----- Privacy ----- @@ -350,11 +345,7 @@ 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()) -} - -fn cache_config(config: &AppConfig) { +pub(crate) fn cache_config(config: &AppConfig) { crate::plugins::call_timeout::apply_config(config); crate::plugins::shutdown_grace::apply_config(config); if let Ok(mut cached) = CONFIG_CACHE.write() { @@ -434,370 +425,12 @@ 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 { - load_config_internal(&app) -} - -#[tauri::command] -pub fn save_config(app: AppHandle, config: AppConfig) -> Result<(), String> { - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - - // Load existing config and merge with new values - let mut existing_config = load_config_internal(&app); - - // Merge: only update fields that are Some in the new config - if config.theme.is_some() { - existing_config.theme = config.theme; - } - if config.follow_system_theme.is_some() { - existing_config.follow_system_theme = config.follow_system_theme; - } - if config.light_theme_id.is_some() { - existing_config.light_theme_id = config.light_theme_id; - } - if config.dark_theme_id.is_some() { - existing_config.dark_theme_id = config.dark_theme_id; - } - if config.language.is_some() { - existing_config.language = config.language; - } - if config.result_page_size.is_some() { - existing_config.result_page_size = config.result_page_size; - } - if config.font_family.is_some() { - existing_config.font_family = config.font_family; - } - if config.font_size.is_some() { - existing_config.font_size = config.font_size; - } - if config.result_color_by_type.is_some() { - existing_config.result_color_by_type = config.result_color_by_type; - } - if config.result_type_colors.is_some() { - existing_config.result_type_colors = config.result_type_colors; - } - if config.sticky_column_headers.is_some() { - existing_config.sticky_column_headers = config.sticky_column_headers; - } - if config.result_zebra_stripes.is_some() { - existing_config.result_zebra_stripes = config.result_zebra_stripes; - } - if config.default_sort_direction.is_some() { - existing_config.default_sort_direction = config.default_sort_direction; - } - if config.row_editor_follow_selection.is_some() { - existing_config.row_editor_follow_selection = config.row_editor_follow_selection; - } - if config.group_sidebar_connections_by_folder.is_some() { - existing_config.group_sidebar_connections_by_folder = - config.group_sidebar_connections_by_folder; - } - if config.cell_double_click_action.is_some() { - existing_config.cell_double_click_action = config.cell_double_click_action; - } - if config.ai_enabled.is_some() { - existing_config.ai_enabled = config.ai_enabled; - } - if config.ai_provider.is_some() { - existing_config.ai_provider = config.ai_provider; - } - if config.ai_model.is_some() { - existing_config.ai_model = config.ai_model; - } - if config.ai_custom_models.is_some() { - existing_config.ai_custom_models = config.ai_custom_models; - } - if config.ai_ollama_port.is_some() { - existing_config.ai_ollama_port = config.ai_ollama_port; - } - if config.ai_custom_openai_url.is_some() { - existing_config.ai_custom_openai_url = config.ai_custom_openai_url; - } - if config.ai_custom_openai_model.is_some() { - existing_config.ai_custom_openai_model = config.ai_custom_openai_model; - } - if config.check_for_updates.is_some() { - existing_config.check_for_updates = config.check_for_updates; - } - if config.auto_check_updates_on_startup.is_some() { - existing_config.auto_check_updates_on_startup = config.auto_check_updates_on_startup; - } - if config.last_dismissed_version.is_some() { - existing_config.last_dismissed_version = config.last_dismissed_version; - } - if config.notified_plugin_versions.is_some() { - existing_config.notified_plugin_versions = config.notified_plugin_versions; - } - if config.er_diagram_default_layout.is_some() { - existing_config.er_diagram_default_layout = config.er_diagram_default_layout; - } - if config.schema_preferences.is_some() { - existing_config.schema_preferences = config.schema_preferences; - } - if config.selected_schemas.is_some() { - existing_config.selected_schemas = config.selected_schemas; - } - if config.max_blob_size.is_some() { - existing_config.max_blob_size = config.max_blob_size; - } - if config.copy_format.is_some() { - existing_config.copy_format = config.copy_format; - } - if config.csv_delimiter.is_some() { - existing_config.csv_delimiter = config.csv_delimiter; - } - if config.csv_include_headers.is_some() { - existing_config.csv_include_headers = config.csv_include_headers; - } - if config.active_external_drivers.is_some() { - existing_config.active_external_drivers = config.active_external_drivers; - } - if config.tabularium_registry_url.is_some() { - existing_config.tabularium_registry_url = config.tabularium_registry_url; - } - if config.release_channel.is_some() { - existing_config.release_channel = config.release_channel; - } - if config.plugins.is_some() { - existing_config.plugins = config.plugins; - } - if config.plugin_call_timeout_seconds.is_some() { - existing_config.plugin_call_timeout_seconds = config.plugin_call_timeout_seconds; - } - if config.plugin_shutdown_grace_seconds.is_some() { - existing_config.plugin_shutdown_grace_seconds = config.plugin_shutdown_grace_seconds; - } - if config.editor_theme.is_some() { - existing_config.editor_theme = config.editor_theme; - } - if config.result_font_family.is_some() { - existing_config.result_font_family = config.result_font_family; - } - if config.editor_font_family.is_some() { - existing_config.editor_font_family = config.editor_font_family; - } - if config.editor_font_size.is_some() { - existing_config.editor_font_size = config.editor_font_size; - } - if config.editor_line_height.is_some() { - existing_config.editor_line_height = config.editor_line_height; - } - if config.editor_tab_size.is_some() { - existing_config.editor_tab_size = config.editor_tab_size; - } - if config.editor_word_wrap.is_some() { - existing_config.editor_word_wrap = config.editor_word_wrap; - } - if config.editor_highlight_invisible_characters.is_some() { - existing_config.editor_highlight_invisible_characters = - config.editor_highlight_invisible_characters; - } - if config.editor_show_line_numbers.is_some() { - existing_config.editor_show_line_numbers = config.editor_show_line_numbers; - } - if config.editor_accept_suggestion_on_enter.is_some() { - existing_config.editor_accept_suggestion_on_enter = - config.editor_accept_suggestion_on_enter; - } - if config.run_statement_under_cursor.is_some() { - existing_config.run_statement_under_cursor = config.run_statement_under_cursor; - } - if config.safety_confirmation_delay_enabled.is_some() { - existing_config.safety_confirmation_delay_enabled = - config.safety_confirmation_delay_enabled; - } - if config.notify_long_queries.is_some() { - existing_config.notify_long_queries = config.notify_long_queries; - } - if config.notify_long_queries_threshold_sec.is_some() { - existing_config.notify_long_queries_threshold_sec = - config.notify_long_queries_threshold_sec; - } - if config.autocomplete_keyword_case.is_some() { - existing_config.autocomplete_keyword_case = config.autocomplete_keyword_case; - } - if config.ping_interval.is_some() { - let old_interval = existing_config.ping_interval; - existing_config.ping_interval = config.ping_interval; - // Restart the ping loop if the interval changed. - if existing_config.ping_interval != old_interval { - let interval = existing_config - .ping_interval - .unwrap_or(crate::health_check::DEFAULT_PING_INTERVAL); - tauri::async_runtime::spawn(crate::health_check::restart_ping_loop( - app.clone(), - interval as u64, - )); - } - } - if config.query_history_max_entries.is_some() { - existing_config.query_history_max_entries = config.query_history_max_entries; - } - if config.show_welcome.is_some() { - existing_config.show_welcome = config.show_welcome; - } - if config.start_maximized.is_some() { - existing_config.start_maximized = config.start_maximized; - } - let window_decorations_changed = config.window_decorations.is_some() - && config.window_decorations != existing_config.window_decorations; - if config.window_decorations.is_some() { - existing_config.window_decorations = config.window_decorations; - } - if config.display_timezone.is_some() { - existing_config.display_timezone = config.display_timezone; - } - if config.ai_audit_enabled.is_some() { - existing_config.ai_audit_enabled = config.ai_audit_enabled; - } - if config.ai_audit_max_entries.is_some() { - existing_config.ai_audit_max_entries = config.ai_audit_max_entries; - } - if config.ai_session_gap_minutes.is_some() { - existing_config.ai_session_gap_minutes = config.ai_session_gap_minutes; - } - if config.mcp_output_format.is_some() { - existing_config.mcp_output_format = config.mcp_output_format; - } - if config.mcp_readonly_default.is_some() { - existing_config.mcp_readonly_default = config.mcp_readonly_default; - } - if config.mcp_readonly_connections.is_some() { - existing_config.mcp_readonly_connections = config.mcp_readonly_connections; - } - if config.mcp_approval_mode.is_some() { - existing_config.mcp_approval_mode = config.mcp_approval_mode; - } - if config.mcp_approval_timeout_seconds.is_some() { - existing_config.mcp_approval_timeout_seconds = config.mcp_approval_timeout_seconds; - } - if config.mcp_preflight_explain.is_some() { - existing_config.mcp_preflight_explain = config.mcp_preflight_explain; - } - if config.mcp_approval_always_on_top.is_some() { - existing_config.mcp_approval_always_on_top = config.mcp_approval_always_on_top; - } - if config.mcp_approval_notify_sound.is_some() { - existing_config.mcp_approval_notify_sound = config.mcp_approval_notify_sound; - } - if config.backup_mode.is_some() { - existing_config.backup_mode = config.backup_mode; - } - if config.backup_directory.is_some() { - existing_config.backup_directory = config.backup_directory; - } - if config.backup_interval_minutes.is_some() { - existing_config.backup_interval_minutes = config.backup_interval_minutes; - } - if config.backup_retention.is_some() { - existing_config.backup_retention = config.backup_retention; - } - if config.backup_target.is_some() { - existing_config.backup_target = config.backup_target; - } - if config.backup_webdav_url.is_some() { - existing_config.backup_webdav_url = config.backup_webdav_url; - } - if config.backup_webdav_username.is_some() { - existing_config.backup_webdav_username = config.backup_webdav_username; - } - if config.database_backup_plan.is_some() { - existing_config.database_backup_plan = config.database_backup_plan; - } - if config.column_masking_enabled.is_some() { - existing_config.column_masking_enabled = config.column_masking_enabled; - } - if config.column_masking_patterns.is_some() { - existing_config.column_masking_patterns = config.column_masking_patterns; - } - if config.column_masking_overrides.is_some() { - existing_config.column_masking_overrides = config.column_masking_overrides; - } - if config.auto_connect_last_connection.is_some() { - existing_config.auto_connect_last_connection = config.auto_connect_last_connection; - } - if config.last_active_connection_id.is_some() { - existing_config.last_active_connection_id = config.last_active_connection_id; - } - if config.last_open_connection_ids.is_some() { - existing_config.last_open_connection_ids = config.last_open_connection_ids; - } - if config.postgres_plugin_migration_banner_dismissed.is_some() { - existing_config.postgres_plugin_migration_banner_dismissed = - config.postgres_plugin_migration_banner_dismissed; - } - if config - .postgres_plugin_migration_banner_dismissed_for - .is_some() - { - existing_config.postgres_plugin_migration_banner_dismissed_for = - config.postgres_plugin_migration_banner_dismissed_for; - } - if config.driver_migration_history.is_some() { - existing_config.driver_migration_history = config.driver_migration_history; - } - if config.known_capability_gaps.is_some() { - existing_config.known_capability_gaps = config.known_capability_gaps; - } - if config.migration_mode_by_driver.is_some() { - existing_config.migration_mode_by_driver = config.migration_mode_by_driver; - } - if config.proxy.is_some() { - existing_config.proxy = config.proxy; - // Drop cached TCP forwards / SSH tunnels that may have been built - // with the previous proxy (password rotation, protocol switch, …). - crate::proxy::stop_all_forwards(); - crate::ssh_tunnel::stop_all_tunnels(); - } - if config.ai_provider_proxies.is_some() { - existing_config.ai_provider_proxies = config.ai_provider_proxies; - } - - let content = serde_json::to_string_pretty(&existing_config).map_err(|e| e.to_string())?; - fs::write(config_path, content).map_err(|e| e.to_string())?; - cache_config(&existing_config); - if window_decorations_changed { - crate::window_decorations::apply_to_all_windows( - &app, - existing_config.window_decorations.as_ref(), - ); - } - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - /// 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 /// on one connection) keeps each database's schema selection independent /// instead of every database sharing one flat per-connection entry. -fn schema_storage_key(connection_id: &str, database: Option<&str>) -> String { +pub(crate) fn schema_storage_key(connection_id: &str, database: Option<&str>) -> String { match database { Some(db) if !db.is_empty() => format!("{connection_id}::{db}"), _ => connection_id.to_string(), @@ -813,7 +446,7 @@ fn schema_storage_key(connection_id: &str, database: Option<&str>) -> String { /// `connection_id::database` instead — without this fallback, that old /// preference is orphaned and silently lost the first time each database is /// looked up under its new per-database key. -fn resolve_schema_preference( +pub(crate) fn resolve_schema_preference( prefs: &HashMap, connection_id: &str, database: Option<&str>, @@ -828,199 +461,6 @@ fn resolve_schema_preference( None } -#[tauri::command] -pub fn get_schema_preference( - app: AppHandle, - connection_id: String, - database: Option, -) -> Option { - let config = load_config_internal(&app); - let prefs = config.schema_preferences.unwrap_or_default(); - resolve_schema_preference(&prefs, &connection_id, database.as_deref()) -} - -#[tauri::command] -pub fn set_schema_preference( - app: AppHandle, - connection_id: String, - schema: String, - database: Option, -) -> Result<(), String> { - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - let mut config = load_config_internal(&app); - let key = schema_storage_key(&connection_id, database.as_deref()); - let prefs = config.schema_preferences.get_or_insert_with(HashMap::new); - prefs.insert(key, schema); - let content = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?; - fs::write(config_path, content).map_err(|e| e.to_string())?; - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - -#[tauri::command] -pub fn get_last_active_connection(app: AppHandle) -> Option { - load_config_internal(&app).last_active_connection_id -} - -#[tauri::command] -pub fn set_last_active_connection( - app: AppHandle, - connection_id: Option, -) -> Result<(), String> { - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - let mut config = load_config_internal(&app); - config.last_active_connection_id = connection_id; - let content = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?; - fs::write(config_path, content).map_err(|e| e.to_string())?; - cache_config(&config); - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - -#[tauri::command] -pub fn get_last_open_connections(app: AppHandle) -> Vec { - load_config_internal(&app) - .last_open_connection_ids - .unwrap_or_default() -} - -#[tauri::command] -pub fn set_last_open_connections( - app: AppHandle, - connection_ids: Vec, -) -> Result<(), String> { - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - let mut config = load_config_internal(&app); - config.last_open_connection_ids = Some(connection_ids); - let content = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?; - fs::write(config_path, content).map_err(|e| e.to_string())?; - cache_config(&config); - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - -#[tauri::command] -pub fn get_selected_schemas( - app: AppHandle, - connection_id: String, - database: Option, -) -> Vec { - let config = load_config_internal(&app); - let key = schema_storage_key(&connection_id, database.as_deref()); - config - .selected_schemas - .and_then(|map| map.get(&key).cloned()) - .unwrap_or_default() -} - -#[tauri::command] -pub fn set_selected_schemas( - app: AppHandle, - connection_id: String, - schemas: Vec, - database: Option, -) -> Result<(), String> { - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - let mut config = load_config_internal(&app); - let key = schema_storage_key(&connection_id, database.as_deref()); - let map = config.selected_schemas.get_or_insert_with(HashMap::new); - if schemas.is_empty() { - map.remove(&key); - } else { - map.insert(key, schemas); - } - let content = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?; - fs::write(config_path, content).map_err(|e| e.to_string())?; - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - -#[tauri::command] -pub fn set_ai_key(app: AppHandle, provider: String, key: String) -> Result<(), String> { - keychain_utils::set_ai_key(&provider, &key)?; - // Write-through so subsequent reads avoid hitting the keychain (and its prompt). - let cache = app.state::>(); - crate::credential_cache::set_ai_key_cached(&cache, &provider, &key); - Ok(()) -} - -#[tauri::command] -pub fn delete_ai_key(app: AppHandle, provider: String) -> Result<(), String> { - keychain_utils::delete_ai_key(&provider)?; - // Drop the cached value so the next read reflects the deletion. - let cache = app.state::>(); - crate::credential_cache::invalidate_ai_key(&cache, &provider); - Ok(()) -} - -/// 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 { @@ -1028,202 +468,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 { - get_ai_api_key(&app, &provider).is_ok() -} - -#[tauri::command] -pub fn check_ai_key_status(app: AppHandle, provider: String) -> AiKeyStatus { - get_ai_api_key_status(&app, &provider) -} - -const DEFAULT_SYSTEM_PROMPT: &str = "You are an expert SQL assistant. Your task is to generate a SQL query based on the user's request and the provided database schema.\nReturn ONLY the SQL query, without any markdown formatting, explanations, or code blocks.\n\nSchema:\n{{SCHEMA}}"; -const DEFAULT_EXPLAIN_PROMPT: &str = - "You are a helpful SQL assistant. Explain SQL queries in {{LANGUAGE}}."; -const DEFAULT_EXPLAINPLAN_PROMPT: &str = - "You are a database performance expert. Analyze the following SQL query and its EXPLAIN plan output. Identify performance bottlenecks, suggest index improvements, and explain the execution strategy. Respond in {{LANGUAGE}}."; -const DEFAULT_CELLNAME_PROMPT: &str = "You are an assistant that generates concise, descriptive names for notebook cells.\nGiven a SQL query or Markdown content, return ONLY a short name (3-6 words max) that describes what the cell does or what it is about.\nDo not include quotes, punctuation, or explanations. Just the name."; -const DEFAULT_TABRENAME_PROMPT: &str = "You are an assistant that generates concise, descriptive names for SQL query result tabs.\nGiven a SQL query, return ONLY a short name (3-6 words max) that describes what the query does.\nDo not include quotes, punctuation, or explanations. Just the name."; - -fn get_prompt(app: &AppHandle, filename: &str, default: &str) -> String { - if let Some(config_dir) = get_config_dir(app) { - let path = config_dir.join(filename); - if let Ok(content) = fs::read_to_string(path) { - return content; - } - } - default.to_string() -} - -fn save_prompt(app: &AppHandle, filename: &str, prompt: &str) -> Result<(), String> { - let config_dir = get_config_dir(app).ok_or("Could not resolve config directory")?; - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - fs::write(config_dir.join(filename), prompt).map_err(|e| e.to_string()) -} - -fn reset_prompt(app: &AppHandle, filename: &str, default: &str) -> Result { - if let Some(config_dir) = get_config_dir(app) { - let path = config_dir.join(filename); - if path.exists() { - fs::remove_file(path).map_err(|e| e.to_string())?; - } - } - Ok(default.to_string()) -} - -#[tauri::command] -pub fn get_system_prompt(app: AppHandle) -> String { - get_prompt(&app, "prompt_query.txt", DEFAULT_SYSTEM_PROMPT) -} -#[tauri::command] -pub fn save_system_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt(&app, "prompt_query.txt", &prompt) -} -#[tauri::command] -pub fn reset_system_prompt(app: AppHandle) -> Result { - reset_prompt(&app, "prompt_query.txt", DEFAULT_SYSTEM_PROMPT) -} - -#[tauri::command] -pub fn get_explain_prompt(app: AppHandle) -> String { - get_prompt(&app, "prompt_explain.txt", DEFAULT_EXPLAIN_PROMPT) -} -#[tauri::command] -pub fn save_explain_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt(&app, "prompt_explain.txt", &prompt) -} -#[tauri::command] -pub fn reset_explain_prompt(app: AppHandle) -> Result { - reset_prompt(&app, "prompt_explain.txt", DEFAULT_EXPLAIN_PROMPT) -} - -#[tauri::command] -pub fn get_explainplan_prompt(app: AppHandle) -> String { - get_prompt(&app, "prompt_explainplan.txt", DEFAULT_EXPLAINPLAN_PROMPT) -} -#[tauri::command] -pub fn save_explainplan_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt(&app, "prompt_explainplan.txt", &prompt) -} -#[tauri::command] -pub fn reset_explainplan_prompt(app: AppHandle) -> Result { - reset_prompt(&app, "prompt_explainplan.txt", DEFAULT_EXPLAINPLAN_PROMPT) -} - -#[tauri::command] -pub fn get_cellname_prompt(app: AppHandle) -> String { - get_prompt(&app, "prompt_cellname.txt", DEFAULT_CELLNAME_PROMPT) -} -#[tauri::command] -pub fn save_cellname_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt(&app, "prompt_cellname.txt", &prompt) -} -#[tauri::command] -pub fn reset_cellname_prompt(app: AppHandle) -> Result { - reset_prompt(&app, "prompt_cellname.txt", DEFAULT_CELLNAME_PROMPT) -} - -#[tauri::command] -pub fn get_tabrename_prompt(app: AppHandle) -> String { - get_prompt(&app, "prompt_tabrename.txt", DEFAULT_TABRENAME_PROMPT) -} -#[tauri::command] -pub fn save_tabrename_prompt(app: AppHandle, prompt: String) -> Result<(), String> { - save_prompt(&app, "prompt_tabrename.txt", &prompt) -} -#[tauri::command] -pub fn reset_tabrename_prompt(app: AppHandle) -> Result { - reset_prompt(&app, "prompt_tabrename.txt", DEFAULT_TABRENAME_PROMPT) -} - -#[tauri::command] -pub fn get_config_json(app: AppHandle) -> Result { - if let Some(config_dir) = get_config_dir(&app) { - let config_path = config_dir.join("config.json"); - if config_path.exists() { - return fs::read_to_string(config_path).map_err(|e| e.to_string()); - } - } - // Return empty JSON object if no config file exists yet - Ok("{}".to_string()) -} - -#[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> { - // Validate the JSON parses as a valid AppConfig - serde_json::from_str::(&json) - .map_err(|e| format!("Invalid configuration JSON: {}", e))?; - - if let Some(config_dir) = get_config_dir(&app) { - if !config_dir.exists() { - fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?; - } - let config_path = config_dir.join("config.json"); - // Re-serialize with pretty-printing for consistency - let value: serde_json::Value = serde_json::from_str(&json).map_err(|e| e.to_string())?; - let pretty = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?; - fs::write(config_path, pretty).map_err(|e| e.to_string())?; - Ok(()) - } else { - Err("Could not resolve config directory".to_string()) - } -} - #[cfg(test)] #[path = "config/plugin_notification_tests.rs"] mod plugin_notification_tests; @@ -1308,13 +552,13 @@ mod tests { } #[test] - fn schema_storage_key_plain_connection_without_database() { + pub(crate) fn schema_storage_key_plain_connection_without_database() { assert_eq!(schema_storage_key("conn-1", None), "conn-1"); assert_eq!(schema_storage_key("conn-1", Some("")), "conn-1"); } #[test] - fn schema_storage_key_scopes_to_database_when_given() { + pub(crate) fn schema_storage_key_scopes_to_database_when_given() { assert_eq!( schema_storage_key("conn-1", Some("analytics")), "conn-1::analytics" @@ -1322,14 +566,14 @@ mod tests { } #[test] - fn schema_storage_key_keeps_two_databases_on_the_same_connection_independent() { + pub(crate) fn schema_storage_key_keeps_two_databases_on_the_same_connection_independent() { let a = schema_storage_key("conn-1", Some("db_a")); let b = schema_storage_key("conn-1", Some("db_b")); assert_ne!(a, b); } #[test] - fn resolve_schema_preference_prefers_the_scoped_key_when_it_exists() { + pub(crate) fn resolve_schema_preference_prefers_the_scoped_key_when_it_exists() { let mut prefs = HashMap::new(); prefs.insert("conn-1".to_string(), "legacy_public".to_string()); prefs.insert( @@ -1344,7 +588,7 @@ mod tests { } #[test] - fn resolve_schema_preference_falls_back_to_the_flat_key_after_a_multi_db_opt_in() { + pub(crate) fn resolve_schema_preference_falls_back_to_the_flat_key_after_a_multi_db_opt_in() { // Regression: a connection's schema preference saved before it opted // into multi-database browsing lives under the flat "conn-1" key. // Once opted in, every lookup passes a database and would otherwise @@ -1359,7 +603,7 @@ mod tests { } #[test] - fn resolve_schema_preference_returns_none_when_neither_key_exists() { + pub(crate) fn resolve_schema_preference_returns_none_when_neither_key_exists() { let prefs = HashMap::new(); assert_eq!( resolve_schema_preference(&prefs, "conn-1", Some("analytics")), @@ -1368,7 +612,7 @@ mod tests { } #[test] - fn resolve_schema_preference_plain_connection_reads_only_the_flat_key() { + pub(crate) fn resolve_schema_preference_plain_connection_reads_only_the_flat_key() { let mut prefs = HashMap::new(); prefs.insert("conn-1".to_string(), "public".to_string()); 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_import/driver_map.rs b/src-tauri/src/connection_import/driver_map.rs index 8e64de59a..85aff2aff 100644 --- a/src-tauri/src/connection_import/driver_map.rs +++ b/src-tauri/src/connection_import/driver_map.rs @@ -1,7 +1,7 @@ //! Maps a foreign app's database label to a Tabularis driver id. //! //! Built-in drivers are `postgres`, `mysql`, `sqlite` (see -//! `src/utils/connections.ts`). MariaDB rides the MySQL driver. Anything else +//! `packages/web-ui/src/utils/connections.ts`). MariaDB rides the MySQL driver. Anything else //! is only importable when a plugin driver with the same id is registered; the //! analyzer flags the rest with a "driver not installed" warning but still lets //! the user import the metadata. diff --git a/src-tauri/src/connection_import_commands.rs b/src-tauri/src/connection_import_commands.rs deleted file mode 100644 index 49c1b7774..000000000 --- a/src-tauri/src/connection_import_commands.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! Tauri commands for importing connections from other installed SQL clients. -//! -//! Flow: `list_connection_import_sources` populates the picker; -//! `preview_connection_import` runs the chosen importer, caches the full -//! envelope (with secrets) in app state and returns a passwordless preview; -//! `apply_connection_import` converts the cached envelope per the user's -//! resolutions and merges it through `apply_export_payload`. - -use std::collections::HashMap; -use std::path::PathBuf; -use std::sync::Mutex; - -use serde::Serialize; -use tauri::{AppHandle, Runtime}; - -use crate::commands::{apply_export_payload, get_config_path}; -use crate::connection_import::{ - all_importers, analyzer, convert, expand_home, importer_by_id, tabularis, ImportEnvelope, -}; -use crate::models::ExportPayload; -use crate::persistence; - -/// Caches the most recent envelope per source so `apply` doesn't re-read the -/// keychain (and re-prompt) after `preview`. -#[derive(Default)] -pub struct ImportEnvelopeCache(pub Mutex>); - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ImportSourceInfo { - pub id: String, - pub display_name: String, - pub available: bool, - pub connection_count: usize, - pub reads_passwords_from_keychain: bool, - /// True when the importer reads a user-picked export file (none today). - pub needs_file: bool, - /// True when auto-discovery can be replaced by a user-selected config path. - pub manual_path_supported: bool, -} - -/// List every known source app with availability and connection counts. -#[tauri::command] -pub async fn list_connection_import_sources() -> Result, String> { - let mut sources = Vec::new(); - for importer in all_importers() { - let available = importer.is_available().await; - let connection_count = if available { - importer.connection_count().await - } else { - 0 - }; - sources.push(ImportSourceInfo { - id: importer.id().to_string(), - display_name: importer.display_name().to_string(), - available, - connection_count, - reads_passwords_from_keychain: importer.reads_passwords_from_keychain(), - needs_file: importer.import_file_types().is_some(), - manual_path_supported: importer.supports_manual_path(), - }); - } - Ok(sources) -} - -/// Run the importer and return a preview annotated against existing connections -/// and installed drivers. The full envelope (with secrets) is cached in state. -#[tauri::command] -pub async fn preview_connection_import( - app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, - source_id: String, - include_passwords: bool, - file_path: Option, -) -> Result { - let importer = importer_by_id(&source_id) - .ok_or_else(|| format!("Unknown import source: {source_id}"))?; - - let file = file_path.map(PathBuf::from); - let envelope = importer - .import(include_passwords, file.as_deref()) - .await - .map_err(|e| e.to_string())?; - - let existing = load_existing_connections(&app)?; - let registered_ids = registered_driver_ids().await; - let file_exists = |p: &str| PathBuf::from(expand_home(p)).exists(); - let preview = analyzer::analyze(&envelope, &existing, ®istered_ids, &file_exists); - - cache - .0 - .lock() - .map_err(|_| "Import cache poisoned".to_string())? - .insert(source_id, envelope); - - Ok(preview) -} - -/// Apply the cached envelope for `source_id` using the user's resolutions. -#[tauri::command] -pub async fn apply_connection_import( - app: AppHandle, - cache: tauri::State<'_, ImportEnvelopeCache>, - source_id: String, - resolutions: Vec, -) -> Result<(), String> { - let envelope = cache - .0 - .lock() - .map_err(|_| "Import cache poisoned".to_string())? - .remove(&source_id) - .ok_or_else(|| "No import preview found; run preview first".to_string())?; - - let registered_ids = registered_driver_ids().await; - let existing_groups = load_existing_groups(&app)?; - let payload = convert::build_payload(&envelope, &resolutions, ®istered_ids, &existing_groups); - - apply_export_payload(app, payload).await -} - -/// Preview a parsed Tabularis JSON export (already decrypted by the caller) -/// against existing connections, so the frontend can render the same per-item -/// group picker used for foreign-app imports. -#[tauri::command] -pub async fn preview_tabularis_import( - app: AppHandle, - payload: ExportPayload, -) -> Result { - let existing = load_existing_connections(&app)?; - let registered_ids = registered_driver_ids().await; - Ok(tabularis::preview(&payload, &existing, ®istered_ids)) -} - -/// Apply a Tabularis JSON export using the user's per-item resolutions, -/// preserving native fields and honouring group overrides. -#[tauri::command] -pub async fn apply_tabularis_import( - app: AppHandle, - payload: ExportPayload, - resolutions: Vec, -) -> Result<(), String> { - let existing_groups = load_existing_groups(&app)?; - let built = tabularis::apply(&payload, &resolutions, &existing_groups); - apply_export_payload(app, built).await -} - -// MARK: - Helpers - -async fn registered_driver_ids() -> Vec { - crate::drivers::registry::list_drivers() - .await - .into_iter() - .map(|m| m.id) - .collect() -} - -fn load_existing_connections( - app: &AppHandle, -) -> Result, String> { - let path = get_config_path(app)?; - Ok(persistence::load_connections_file(&path) - .unwrap_or_default() - .connections) -} - -fn load_existing_groups( - app: &AppHandle, -) -> Result, String> { - let path = get_config_path(app)?; - Ok(persistence::load_connections_file(&path) - .unwrap_or_default() - .groups) -} 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/database_backup/mod.rs b/src-tauri/src/database_backup/mod.rs index 1493d4d63..6b6418cbb 100644 --- a/src-tauri/src/database_backup/mod.rs +++ b/src-tauri/src/database_backup/mod.rs @@ -22,8 +22,8 @@ use std::fs; use std::future::Future; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Mutex; -use tauri::{AppHandle, Manager, Runtime}; +use std::sync::{Arc, Mutex}; +use crate::runtime::RuntimeContext; use crate::config::DatabaseBackupPlan; use crate::dump_commands::{ @@ -223,7 +223,7 @@ pub(crate) struct BackupRunReport { } /// One backup attempt into `dest_dir`: runs `dump` with the target file path, -/// then prunes old backups on success, or deletes the partial file on failure +/// then atomically publishes and prunes on success, or drops the temporary file on failure /// so previous backups are never touched. A failure counts as a cancellation /// when the dump reports [`DUMP_CANCELLED`] or `cancel_requested` was set. pub(crate) async fn execute_backup( @@ -258,8 +258,17 @@ where let target_path = dest_dir.join(&file_name); let target = target_path.display().to_string(); - match dump(target.clone()).await { + let staging = match tempfile::Builder::new().prefix(".pending-backup-").tempfile_in(dest_dir) { + Ok(file) => file, + Err(error) => return failed(BackupOutcome::Error, format!("Failed to create backup file: {error}")), + }; + let result = dump(staging.path().display().to_string()).await; + let result = if cancel_requested.load(Ordering::SeqCst) { Err(DUMP_CANCELLED.to_string()) } else { result }; + match result { Ok(()) => { + if let Err(error) = staging.persist(&target_path) { + return failed(BackupOutcome::Error, format!("Failed to publish database backup: {error}")); + } let retention = if plan.retention > 0 { plan.retention as usize } else { @@ -289,9 +298,6 @@ where } } Err(err) => { - if target_path.exists() { - let _ = fs::remove_file(&target_path); - } let outcome = if err == DUMP_CANCELLED || cancel_requested.load(Ordering::SeqCst) { BackupOutcome::Cancelled } else { @@ -327,12 +333,13 @@ fn record_report(key: &str, report: &BackupRunReport, finished_at: DateTime } } -pub async fn run_database_backup( - app: AppHandle, +pub async fn run_database_backup( + runtime: &RuntimeContext, + cancellation_state: &DumpCancellationState, trigger: &str, ) -> Result { run_exclusive(&RUNTIME_STATE.is_running, || async { - let result = run_plan_once(&app, trigger).await; + let result = run_plan_once(runtime, cancellation_state, trigger).await; // Reset on every way out, so a cancel never leaks into the next run. *RUNTIME_STATE.active_slot.lock().unwrap() = None; RUNTIME_STATE.was_cancelled.store(false, Ordering::SeqCst); @@ -341,8 +348,8 @@ pub async fn run_database_backup( .await } -async fn run_plan_once(app: &AppHandle, trigger: &str) -> Result { - let config = crate::config::load_config_internal(app); +async fn run_plan_once(runtime: &RuntimeContext, cancellation_state: &DumpCancellationState, trigger: &str) -> Result { + let config = crate::application::persistence::load_config(runtime); let plan = config .database_backup_plan .clone() @@ -356,7 +363,6 @@ async fn run_plan_once(app: &AppHandle, trigger: &str) -> Result< } let dest_dir = PathBuf::from(&plan.destination_directory); - let cancellation_state = app.state::(); let slot_key = db_backup_slot_key(&plan.connection_id); *RUNTIME_STATE.active_slot.lock().unwrap() = Some(slot_key.clone()); let options = DumpOptions { @@ -378,7 +384,7 @@ async fn run_plan_once(app: &AppHandle, trigger: &str) -> Result< &RUNTIME_STATE.was_cancelled, |target| { dump_database_with_handles( - app, + runtime, &cancellation_state.handles, DumpRequest { slot_key, @@ -414,13 +420,13 @@ async fn run_plan_once(app: &AppHandle, trigger: &str) -> Result< // ---------- Background scheduler ---------- -pub fn spawn_database_backup_scheduler(app: AppHandle) { - tauri::async_runtime::spawn(async move { +pub fn spawn_database_backup_scheduler(runtime: RuntimeContext, cancellation_state: Arc) -> crate::async_rt::JoinHandle<()> { + crate::async_rt::spawn(async move { // App-open boundary: scheduler runs every 30 seconds while Tabularis is open loop { tokio::time::sleep(std::time::Duration::from_secs(30)).await; - let config = crate::config::load_config_internal(&app); + let config = crate::application::persistence::load_config(&runtime); let Some(plan) = config.database_backup_plan else { continue; }; @@ -442,22 +448,22 @@ pub fn spawn_database_backup_scheduler(app: AppHandle) { && !recently_failed && !RUNTIME_STATE.is_running.load(Ordering::SeqCst) { - let app_clone = app.clone(); - tauri::async_runtime::spawn(async move { - let _ = run_database_backup(app_clone, "scheduled").await; + let runtime = runtime.clone(); + let cancellation_state = cancellation_state.clone(); + crate::async_rt::spawn(async move { + let _ = run_database_backup(&runtime, &cancellation_state, "scheduled").await; }); } } - }); + }) } -// ---------- Tauri commands ---------- +// ---------- Application commands ---------- -#[tauri::command] -pub async fn get_database_backup_status( - app: AppHandle, +pub async fn get_database_backup_status( + runtime: &RuntimeContext, ) -> Result { - let config = crate::config::load_config_internal(&app); + let config = crate::application::persistence::load_config(&runtime); let now_utc = Utc::now(); // The last success and the next run always describe the current plan. @@ -492,17 +498,15 @@ pub async fn get_database_backup_status( }) } -#[tauri::command] -pub async fn run_database_backup_now(app: AppHandle) -> Result { - run_database_backup(app, "manual").await +pub async fn run_database_backup_now(runtime: &RuntimeContext, cancellation_state: &DumpCancellationState) -> Result { + run_database_backup(runtime, cancellation_state, "manual").await } /// Cancels the run in progress, whatever the plan says now. Before the dump /// task exists (e.g. during the SSH/K8s setup) the flag alone stops it: the /// dump checks it once the setup is done and again right after registering. -#[tauri::command] pub async fn cancel_database_backup( - state: tauri::State<'_, DumpCancellationState>, + state: &DumpCancellationState, ) -> Result<(), String> { if !RUNTIME_STATE.is_running.load(Ordering::SeqCst) { return Err("No database backup is running".into()); diff --git a/src-tauri/src/database_backup/tests.rs b/src-tauri/src/database_backup/tests.rs index b726a73c6..7e9abd8a1 100644 --- a/src-tauri/src/database_backup/tests.rs +++ b/src-tauri/src/database_backup/tests.rs @@ -669,3 +669,19 @@ async fn a_cancel_before_the_dump_is_registered_still_stops_it() { assert_eq!(result, Err(DUMP_CANCELLED.to_string())); assert!(handles.lock().unwrap().is_empty(), "slot unregistered"); } + +#[tokio::test] +async fn unfinished_backups_are_never_discovered_and_are_removed_on_future_drop() { + let dir = tempfile::tempdir().unwrap(); + let plan = plan_for(dir.path(), 7); + let cancel = AtomicBool::new(false); + let now = Utc.with_ymd_and_hms(2026, 10, 22, 3, 0, 0).unwrap(); + let mut attempt = Box::pin(execute_backup(dir.path(), &plan, now, &cancel, |target| async move { + std::fs::write(target, "-- incomplete dump").unwrap(); + std::future::pending::>().await + })); + assert!(futures::poll!(&mut attempt).is_pending()); + assert!(last_success_for(&plan, None).is_none()); + drop(attempt); + assert!(list_directory_files(dir.path()).is_empty()); +} diff --git a/src-tauri/src/drivers/common/query.rs b/src-tauri/src/drivers/common/query.rs index efb597658..d44e55ad0 100644 --- a/src-tauri/src/drivers/common/query.rs +++ b/src-tauri/src/drivers/common/query.rs @@ -99,7 +99,7 @@ pub fn returns_result_set_for(query: &str, hash_comments: bool) -> bool { /// Leading SQL comments are stripped before checking. /// /// Kept in sync with the TypeScript classifier in -/// `src/utils/sqlSplitter/classify.ts` (EXPLAINABLE_KEYWORDS) so the +/// `packages/web-ui/src/utils/sqlSplitter/classify.ts` (EXPLAINABLE_KEYWORDS) so the /// editor's Explain UI cannot offer a statement the backend will refuse. pub fn is_explainable_query(query: &str) -> bool { is_explainable_query_for(query, false) diff --git a/src-tauri/src/drivers/driver_trait.rs b/src-tauri/src/drivers/driver_trait.rs index d8574ae75..08c564e7a 100644 --- a/src-tauri/src/drivers/driver_trait.rs +++ b/src-tauri/src/drivers/driver_trait.rs @@ -22,7 +22,7 @@ use crate::models::{ pub type BatchProgressFn = dyn Fn(usize, &BatchStatementResult) + Send + Sync; /// SQL dialect declaration used by the frontend statement splitter -/// (`src/utils/sqlSplitter/`) to pick per-dialect tokenizer rules: +/// (`packages/web-ui/src/utils/sqlSplitter/`) to pick per-dialect tokenizer rules: /// string-literal quoting, identifier quoting (backticks vs brackets), /// dollar-quoted strings, `DELIMITER` / `GO` directives, etc. /// @@ -192,7 +192,7 @@ pub struct DriverCapabilities { /// that needs to tell "explicitly postgres" apart from "unspecified." /// The frontend's own splitter still applies the historical /// postgres-default at its point of use (`?? "postgres"` in - /// `src/utils/identifiers.ts`/`sqlSplitter`); this Rust-side field + /// `packages/web-ui/src/utils/identifiers.ts`/`sqlSplitter`); this Rust-side field /// stays a strict `Option` so security-relevant Rust consumers (the SSL /// mode migration, the MCP schema default) can't inherit that default /// by accident. @@ -241,6 +241,10 @@ pub struct UIExtensionEntry { /// matches this identifier (e.g. `"wordpress"`). #[serde(skip_serializing_if = "Option::is_none")] pub driver: Option, + /// `@tabularis/plugin-api` version used to build the UI bundle. + /// Absent for legacy bundles, which remain supported. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_version: Option, } /// An EXPLAIN parser bundle declared in a plugin's manifest. diff --git a/src-tauri/src/drivers/registry.rs b/src-tauri/src/drivers/registry.rs index d1383aea4..49baf1e03 100644 --- a/src-tauri/src/drivers/registry.rs +++ b/src-tauri/src/drivers/registry.rs @@ -96,6 +96,22 @@ pub async fn unregister_driver(id: &str) -> bool { } } +/// Shut down and remove every external driver process. +pub async fn shutdown_external_drivers() { + let external_ids = { + let registry = REGISTRY.read().await; + registry + .iter() + .filter(|(_, driver)| !driver.manifest().is_builtin) + .map(|(id, _)| id.clone()) + .collect::>() + }; + + for id in external_ids { + unregister_driver(&id).await; + } +} + /// Register the manifest of a UI-only plugin (no driver process). pub async fn register_manifest(manifest: PluginManifest) { let id = manifest.id.clone(); @@ -136,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 eaaa39267..1828ef149 100644 --- a/src-tauri/src/dump_commands.rs +++ b/src-tauri/src/dump_commands.rs @@ -1,1038 +1,6 @@ -use crate::commands::{ - expand_k8s_connection_params, expand_ssh_connection_params, find_connection_by_id, - register_abort_handle, resolve_connection_params_with_id, unregister_abort_handle, - AbortHandleMap, +pub use crate::application::database_transfers::{ + db_backup_slot_key, dump_database_with_handles, DumpCancellationState, DumpOptions, DumpRequest, DUMP_CANCELLED, }; -use crate::drivers::driver_trait::DatabaseDriver; -use crate::dump_utils::DumpDialect; -use crate::models::{ConnectionParams, Pagination, TableColumn}; -use crate::pool_manager::{get_mysql_pool, get_postgres_pool, get_sqlite_pool}; -use futures::TryStreamExt; -use serde::{Deserialize, Serialize}; -use sqlx::Row; -use std::collections::HashSet; -use std::fs::File; -use std::io::{BufRead, BufReader, BufWriter, Read, Write}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use tauri::{AppHandle, Emitter, Runtime, State}; -use zip::ZipArchive; - -#[derive(Debug, Serialize, Deserialize)] -pub struct DumpOptions { - pub structure: bool, - pub data: bool, - pub tables: Option>, // None = All -} - -#[derive(Default)] -pub struct DumpCancellationState { - pub handles: Arc>, -} - -/// Slot key for the cancellation registry. Imports share the dump state -/// but need a distinct slot so `cancel_dump` and `cancel_import` don't -/// alias each other. -fn import_slot_key(connection_id: &str) -> String { - format!("{}_import", connection_id) -} - -pub fn db_backup_slot_key(connection_id: &str) -> String { - format!("{}_db_backup", connection_id) -} - -/// Error returned by a dump whose task was aborted through its slot. -pub const DUMP_CANCELLED: &str = "Dump cancelled"; - -/// Aborts every task registered under `slot_key`. Returns `false` when -/// nothing was running there. -pub(crate) fn abort_slot(handles: &Mutex, slot_key: &str) -> bool { - let entries = { - let mut handles = handles.lock().unwrap(); - handles.remove(slot_key).unwrap_or_default() - }; - for handle in &entries { - handle.abort(); - } - !entries.is_empty() -} - -/// Registers `task` under `slot_key` so `abort_slot` can stop it, then waits -/// for it. An aborted task yields [`DUMP_CANCELLED`]. -/// -/// `cancel_requested` covers a cancel that arrives before the task is -/// registered, when `abort_slot` finds nothing to stop: the flag is checked -/// again right after registering, so either the canceller sees the handle or -/// this sees the flag. -pub(crate) async fn await_cancellable_dump( - handles: &Mutex, - slot_key: String, - task: tokio::task::JoinHandle>, - cancel_requested: Option<&AtomicBool>, -) -> Result<(), String> { - let abort_handle = Arc::new(task.abort_handle()); - register_abort_handle(handles, slot_key.clone(), abort_handle.clone()); - if cancel_requested.is_some_and(|flag| flag.load(Ordering::SeqCst)) { - abort_handle.abort(); - } - - let result = task.await; - - unregister_abort_handle(handles, &slot_key, &abort_handle); - - match result { - Ok(res) => res, - Err(e) if e.is_cancelled() => Err(DUMP_CANCELLED.into()), - Err(e) => Err(format!("Dump task failed: {e}")), - } -} - -#[tauri::command] -pub async fn cancel_dump( - state: State<'_, DumpCancellationState>, - connection_id: String, -) -> Result<(), String> { - if !abort_slot(&state.handles, &connection_id) { - return Err("No active dump process found".into()); - } - Ok(()) -} - -/// One dump: what to write, where, and the cancellation slot it runs under. -pub struct DumpRequest { - pub slot_key: String, - pub connection_id: String, - pub file_path: String, - pub options: DumpOptions, - pub schema: Option, - pub database: Option, -} - -/// Runs `request`. When `cancel_requested` is set before the dump starts -/// (e.g. during the SSH/K8s setup), it returns [`DUMP_CANCELLED`] without -/// writing anything. -pub async fn dump_database_with_handles( - app: &AppHandle, - handles: &Arc>, - request: DumpRequest, - cancel_requested: Option<&AtomicBool>, -) -> Result<(), String> { - let DumpRequest { - slot_key, - connection_id, - file_path, - options, - schema, - database, - } = request; - 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 cancel_requested.is_some_and(|flag| flag.load(Ordering::SeqCst)) { - return Err(DUMP_CANCELLED.into()); - } - // Scope the dump to the selected database on connections that expose multiple - // databases (e.g. MySQL/MariaDB). Without this the connection pool stays bound - // to the primary database, so unqualified statements such as `SHOW CREATE TABLE` - // and `SELECT * FROM table` run against the wrong database. - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let driver = saved_conn.params.driver.clone(); - - // Spawn the dump process - let task = tokio::spawn(async move { - let file = File::create(&file_path).map_err(|e| e.to_string())?; - let mut writer = BufWriter::new(file); - - // Write header - writeln!(writer, "-- Tabularis Dump").map_err(|e| e.to_string())?; - writeln!(writer, "-- Database: {}", params.database).map_err(|e| e.to_string())?; - writeln!(writer, "-- Date: {}\n", chrono::Local::now().to_rfc3339()) - .map_err(|e| e.to_string())?; - - // Get tables - let drv = crate::drivers::registry::get_connection_driver(¶ms).await?; - // Quoting, schema qualification and literal syntax follow the - // driver's capabilities, so plugin drivers (backtick quoting, - // datasets as schemas, ...) get statements their engine accepts. - let dialect = DumpDialect::from_capabilities(&driver, &drv.manifest().capabilities); - let schema = dialect.resolve_schema(schema.as_deref()); - // Schema-based drivers use `schema` to scope the listing to a - // specific schema within the database. Flat multi-db drivers (MySQL, - // SQLite) pass None — they ignore the schema arg and use - // params.database to determine which tables to list, avoiding a - // confusing `WHERE table_schema = 'public'` on a MySQL connection. - let scoped_schema = dialect.scoped_schema(schema.as_deref()); - let all_tables = drv.get_tables(¶ms, scoped_schema).await?; - - let tables_to_process: Vec = if let Some(selection) = &options.tables { - selection.clone() - } else { - all_tables.into_iter().map(|t| t.name).collect() - }; - - for table in tables_to_process { - if options.structure { - writeln!( - writer, - "-- Structure for table {}", - dialect.table_ref(scoped_schema, &table) - ) - .map_err(|e| e.to_string())?; - // A plugin that doesn't implement get_table_ddl must not - // abort the whole dump over one table's missing structure — - // the data step below still runs for it, and every other - // table's structure/data is unaffected. Composing an - // approximate CREATE TABLE from generic column/FK/index - // metadata was considered and rejected: a dump file is meant - // to be restored, and a plausible-looking but subtly wrong - // DDL statement (missed default, generated column, check - // constraint) is worse than a visible, honest gap. - // - // The DROP TABLE IF EXISTS is written only when DDL is - // available, not unconditionally before the DDL fetch: writing - // the DROP first then failing to emit a CREATE TABLE produces a - // dump file whose import deletes the restore target with no way - // to recreate it (the builtin drivers wrap import in a - // transaction that rolls back, but plugin drivers execute each - // statement independently — the DROP commits and the table is - // gone). Skipping both when DDL fails leaves the existing table - // intact. - match drv.get_table_ddl(¶ms, &table, scoped_schema).await { - Ok(ddl) => { - writeln!( - writer, - "{}", - dialect.drop_table_if_exists(scoped_schema, &table) - ) - .map_err(|e| e.to_string())?; - writeln!(writer, "{}\n", ddl).map_err(|e| e.to_string())?; - } - Err(e) => { - writeln!( - writer, - "-- WARNING: could not generate DDL for {}: {} (table left unchanged)\n", - dialect.table_ref(scoped_schema, &table), - e - ) - .map_err(|e| e.to_string())?; - } - } - } - - if options.data { - writeln!( - writer, - "-- Data for table {}", - dialect.table_ref(scoped_schema, &table) - ) - .map_err(|e| e.to_string())?; - export_table_data( - &mut writer, - &drv, - ¶ms, - &driver, - &dialect, - &table, - scoped_schema, - ) - .await?; - writeln!(writer, "\n").map_err(|e| e.to_string())?; - } - } - - writer.flush().map_err(|e| e.to_string())?; - Ok::<(), String>(()) - }); - - await_cancellable_dump(handles, slot_key, task, cancel_requested).await -} - -#[tauri::command] -pub async fn dump_database( - app: AppHandle, - state: State<'_, DumpCancellationState>, - connection_id: String, - file_path: String, - options: DumpOptions, - schema: Option, - database: Option, -) -> Result<(), String> { - dump_database_with_handles( - &app, - &state.handles, - DumpRequest { - slot_key: connection_id.clone(), - connection_id, - file_path, - options, - schema, - database, - }, - None, - ) - .await -} - -async fn export_table_data( - writer: &mut BufWriter, - drv: &Arc, - params: &ConnectionParams, - driver: &str, - dialect: &DumpDialect, - table: &str, - schema: Option<&str>, -) -> Result<(), String> { - // We need to implement streaming fetch manually here because we need raw values, not JSON strings if possible, - // or we parse JSON strings back to SQL literals. - // The current drivers return JSON-like values via `extract_value`. - // Let's reuse `extract_value` logic but format for SQL. - - // Ideally we should use specific batch size - let query = format!("SELECT * FROM {}", dialect.table_ref(schema, table)); - - match driver { - "mysql" => { - use crate::drivers::mysql::extract::extract_value; - use crate::pool_manager::get_mysql_pool; // Returns String (JSON value or "NULL") - use sqlx::{Column, TypeInfo}; - - let pool = get_mysql_pool(params).await?; - let mut rows = sqlx::query(&query).fetch(&pool); - - let mut batch = Vec::new(); - while let Some(row) = rows.try_next().await.map_err(|e| e.to_string())? { - let mut values = Vec::new(); - for i in 0..row.columns().len() { - let val = extract_value(&row, i, None); - // JSON columns are extracted as parsed values and must be - // written back as JSON literals, not as their string content. - let is_json_column = row.column(i).type_info().name() == "JSON"; - values.push(if is_json_column { - dialect.escape_json_value(val) - } else { - dialect.escape_value(val) - }); - } - batch.push(format!("({})", values.join(", "))); - - if batch.len() >= 100 { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - batch.clear(); - } - } - if !batch.is_empty() { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - } - } - "postgres" => { - use crate::drivers::postgres::extract::extract_value; - use crate::pool_manager::get_postgres_pool; - - let pool = get_postgres_pool(params).await?; - let client = pool.get().await.map_err(|e| e.to_string())?; - let params: Vec = vec![]; - let mut rows = std::pin::pin!(client - .query_raw(&query, ¶ms) - .await - .map_err(|e| e.to_string())?); - - let mut batch = Vec::new(); - - while let Some(row) = rows.try_next().await.map_err(|e| e.to_string())? { - let mut values = Vec::new(); - for i in 0..row.columns().len() { - let val = extract_value(&row, i, None); - let column_type = row.columns()[i].type_(); - let is_json_column = *column_type == tokio_postgres::types::Type::JSON - || *column_type == tokio_postgres::types::Type::JSONB; - values.push(if is_json_column { - dialect.escape_json_value(val) - } else { - dialect.escape_value(val) - }); - } - batch.push(format!("({})", values.join(", "))); - - if batch.len() >= 100 { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - batch.clear(); - } - } - if !batch.is_empty() { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - } - } - "sqlite" => { - use crate::drivers::sqlite::extract::extract_value; - use crate::pool_manager::get_sqlite_pool; - - let pool = get_sqlite_pool(params).await?; - let mut rows = sqlx::query(&query).fetch(&pool); - - let mut batch = Vec::new(); - while let Some(row) = rows.try_next().await.map_err(|e| e.to_string())? { - let mut values = Vec::new(); - for i in 0..row.columns().len() { - let val = extract_value(&row, i, None); - values.push(dialect.escape_value(val)); - } - batch.push(format!("({})", values.join(", "))); - - if batch.len() >= 100 { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - batch.clear(); - } - } - if !batch.is_empty() { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - } - } - // Any plugin-backed driver: no local pool to stream from (the plugin - // owns its own pool inside its subprocess), so fall back to the - // generic RPC surface every driver implements — paginate through - // `execute_query` instead of a raw `sqlx`/`tokio-postgres` client. - _ => { - // `schema` is already scoped by `DumpDialect::scoped_schema`: it - // is `None` for a plugin without schemas, whose "schema" RPC - // parameter may mean something else entirely (e.g. a database - // selector), so the plugin's own default is left alone. - let fallback_schema = schema; - let json_columns = - json_column_names(&drv.get_columns(params, table, fallback_schema).await?); - - let mut batch = Vec::new(); - let mut page = 1u32; - loop { - let result = drv - .execute_query(params, &query, Some(1000), page, fallback_schema) - .await?; - let fetched = result.rows.len() as u32; - - for row in result.rows { - batch.push(format_row_values( - row, - &result.columns, - &json_columns, - dialect, - )); - - if batch.len() >= 100 { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - batch.clear(); - } - } - - let has_more = plugin_dump_has_more(result.pagination, fetched, 1000); - if fetched == 0 || !has_more { - break; - } - page += 1; - } - if !batch.is_empty() { - writeln!( - writer, - "{}", - dialect.insert_into_statement(schema, table, &batch.join(", ")) - ) - .map_err(|e| e.to_string())?; - } - } - } - - Ok(()) -} - -/// Whether the plugin-driver fallback's paginated fetch loop (in -/// `export_table_data`) should request another page. -/// -/// A plugin's `execute_query` RPC may not populate `pagination` at all — -/// defaulting the "no pagination info" case to `false` (as if the table -/// were exhausted) would silently truncate a dump the moment a table has -/// more rows than one page, with no error raised. Falling back to whether -/// the page came back full instead matches `export.rs`'s established -/// pattern for the same "driver doesn't report pagination" gap: it may -/// cost one extra empty-page fetch when a table's row count is an exact -/// multiple of the page size, but it never drops rows. -fn plugin_dump_has_more(pagination: Option, fetched: u32, page_size: u32) -> bool { - pagination - .map(|p| p.has_more) - .unwrap_or(fetched >= page_size) -} - -/// Column names whose PostgreSQL type is `json`/`jsonb`. Used to decide -/// which cells in a row fetched through the generic (plugin-driver) -/// `execute_query` RPC need `escape_json_column_value` rather than -/// `escape_sql_value` — see `export_table_data`'s fallback arm. Unlike the -/// builtin drivers' own extraction (which sees the source column type -/// directly), `QueryResult` only carries column *names*, so a JSON column -/// can't be told apart from a plain text column by inspecting a cell's -/// value alone — both arrive as a `serde_json::Value::String`. -fn json_column_names(columns: &[TableColumn]) -> HashSet { - columns - .iter() - .filter(|c| { - let t = c.data_type.to_ascii_lowercase(); - t == "json" || t == "jsonb" - }) - .map(|c| c.name.clone()) - .collect() -} - -/// Formats one row from the generic `execute_query` RPC into a parenthesized -/// SQL value list, e.g. `(1, 'Alice', NULL)`. `columns` must be the same -/// `QueryResult.columns` the row's values came from, in the same order. -fn format_row_values( - row: Vec, - columns: &[String], - json_columns: &HashSet, - dialect: &DumpDialect, -) -> String { - let values: Vec = row - .into_iter() - .zip(columns.iter()) - .map(|(val, col_name)| { - if json_columns.contains(col_name) { - dialect.escape_json_value(val) - } else { - dialect.escape_value(val) - } - }) - .collect(); - format!("({})", values.join(", ")) -} - -#[derive(Debug, Serialize, Clone)] -pub struct ImportProgress { - pub statements_executed: usize, - pub total_statements: usize, - pub percentage: f32, - pub current_operation: String, -} - -// Stream-based statement parser that yields statements as they are read -struct SqlStatementStream { - reader: R, - current_statement: String, - line_buffer: String, -} - -impl SqlStatementStream { - fn new(reader: R) -> Self { - Self { - reader, - current_statement: String::new(), - line_buffer: String::new(), - } - } - - fn next_statement(&mut self) -> Result, String> { - loop { - self.line_buffer.clear(); - let bytes_read = self - .reader - .read_line(&mut self.line_buffer) - .map_err(|e| e.to_string())?; - - if bytes_read == 0 { - // EOF - return last statement if any - if self.current_statement.trim().is_empty() { - return Ok(None); - } else { - let stmt = self.current_statement.trim().to_string(); - self.current_statement.clear(); - return Ok(Some(stmt)); - } - } - - let trimmed = self.line_buffer.trim(); - - // Skip comments and empty lines - if trimmed.starts_with("--") || trimmed.is_empty() { - continue; - } - - self.current_statement.push_str(&self.line_buffer); - - // Check if statement is complete - if trimmed.ends_with(';') { - let stmt = self.current_statement.trim().to_string(); - self.current_statement.clear(); - if !stmt.is_empty() { - return Ok(Some(stmt)); - } - } - } - } -} - -// Helper macro for streaming execution with progress -macro_rules! execute_statements_streaming { - ($executor_macro:ident, $stream:expr, $app:expr) => {{ - // Larger batch for better performance - execute and emit progress every 500 statements - const PROGRESS_EMIT_INTERVAL: usize = 500; - let mut executed = 0; - let mut since_last_progress = 0; - - while let Some(stmt) = $stream.next_statement()? { - // Execute statement immediately without batching in memory - $executor_macro!(&stmt).await.map_err(|e| { - format!( - "Error at statement {}: {}\nQuery: {}", - executed + 1, - e, - stmt - ) - })?; - - executed += 1; - since_last_progress += 1; - - // Emit progress only every PROGRESS_EMIT_INTERVAL statements to reduce overhead - if since_last_progress >= PROGRESS_EMIT_INTERVAL { - let _ = $app.emit( - "import_progress", - ImportProgress { - statements_executed: executed, - total_statements: 0, // 0 indicates unknown total - percentage: 0.0, - current_operation: format!("Imported {} statements", executed), - }, - ); - since_last_progress = 0; - } - } - - // Final progress update - let _ = $app.emit( - "import_progress", - ImportProgress { - statements_executed: executed, - total_statements: executed, - percentage: 100.0, - current_operation: "Import completed".to_string(), - }, - ); - - Ok::(executed) - }}; -} - -#[tauri::command] -pub async fn cancel_import( - state: State<'_, DumpCancellationState>, - connection_id: String, -) -> Result<(), String> { - let key = import_slot_key(&connection_id); - let entries = { - let mut handles = state.handles.lock().unwrap(); - handles.remove(&key).unwrap_or_default() - }; - if entries.is_empty() { - return Err("No active import process found".into()); - } - for handle in entries { - handle.abort(); - } - Ok(()) -} - -#[tauri::command] -pub async fn import_database( - app: AppHandle, - state: State<'_, DumpCancellationState>, - connection_id: String, - 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)?; - // Scope the import to the selected database on connections that expose multiple - // databases (e.g. MySQL/MariaDB). Without this the connection pool stays bound - // to the primary database, so every statement in the dump file is executed - // against the wrong database. Mirrors the same fix already applied to - // `dump_database`. - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let driver = saved_conn.params.driver.clone(); - // Postgres dump files reference unqualified table names expecting the - // default `public` schema, so only Postgres(-flavored plugin) statements - // need that default. A non-Postgres plugin driver's `schema` parameter - // may mean something else entirely (a database selector, for a - // MySQL-like plugin with no real schema concept) - defaulting it to - // "public" there could silently retarget the connection to a database - // that doesn't exist instead of leaving the plugin's own default alone. - let pg_schema = schema.clone().unwrap_or_else(|| "public".to_string()); - let app_handle = app.clone(); - let conn_id = connection_id.clone(); - let drv = crate::drivers::registry::get_connection_driver(¶ms).await?; - let is_postgres = - DumpDialect::from_capabilities(&driver, &drv.manifest().capabilities).postgres; - - // Spawn the import process - let task = tokio::spawn(async move { - // Open file and create streaming reader - let file = File::open(&file_path).map_err(|e| e.to_string())?; - let reader = create_sql_reader(file, &file_path)?; - let mut stream = SqlStatementStream::new(reader); - - // Emit initial progress - let _ = app_handle.emit( - "import_progress", - ImportProgress { - statements_executed: 0, - total_statements: 0, - percentage: 0.0, - current_operation: "Starting import...".to_string(), - }, - ); - - // Execute with transaction and optimizations for speed - match driver.as_str() { - "mysql" => { - let pool = get_mysql_pool(¶ms).await?; - let mut tx = pool.begin().await.map_err(|e| e.to_string())?; - - // Performance optimizations for MySQL - sqlx::query("SET FOREIGN_KEY_CHECKS=0") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("SET UNIQUE_CHECKS=0") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("SET AUTOCOMMIT=0") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - - macro_rules! execute_statement { - ($stmt:expr) => { - sqlx::query($stmt).execute(&mut *tx) - }; - } - - execute_statements_streaming!(execute_statement, stream, app_handle)?; - - // Restore settings - sqlx::query("SET FOREIGN_KEY_CHECKS=1") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("SET UNIQUE_CHECKS=1") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("SET AUTOCOMMIT=1") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - - tx.commit().await.map_err(|e| e.to_string())?; - } - "postgres" => { - let pool = get_postgres_pool(¶ms).await?; - let mut client = pool.get().await.map_err(|e| e.to_string())?; - let tx = client.transaction().await.map_err(|e| e.to_string())?; - - // Set schema search path so unqualified table names resolve correctly - tx.execute(&format!("SET search_path TO \"{}\"", pg_schema), &[]) - .await - .map_err(|e| e.to_string())?; - - // Performance optimizations for PostgreSQL - tx.execute("SET CONSTRAINTS ALL DEFERRED", &[]) - .await - .map_err(|e| e.to_string())?; - // Temporarily disable synchronous commit for speed (data at risk until commit) - tx.execute("SET LOCAL synchronous_commit=OFF", &[]) - .await - .map_err(|e| e.to_string())?; - - macro_rules! execute_statement { - ($stmt:expr) => { - tx.execute($stmt, &[]) - }; - } - - execute_statements_streaming!(execute_statement, stream, app_handle)?; - - tx.commit().await.map_err(|e| e.to_string())?; - } - "sqlite" => { - let pool = get_sqlite_pool(¶ms).await?; - let mut tx = pool.begin().await.map_err(|e| e.to_string())?; - - // Performance optimizations for SQLite - sqlx::query("PRAGMA foreign_keys=OFF") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("PRAGMA synchronous=OFF") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("PRAGMA journal_mode=MEMORY") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - - macro_rules! execute_statement { - ($stmt:expr) => { - sqlx::query($stmt).execute(&mut *tx) - }; - } - - execute_statements_streaming!(execute_statement, stream, app_handle)?; - - // Restore settings - sqlx::query("PRAGMA foreign_keys=ON") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - sqlx::query("PRAGMA synchronous=FULL") - .execute(&mut *tx) - .await - .map_err(|e| e.to_string())?; - - tx.commit().await.map_err(|e| e.to_string())?; - } - // Any plugin-backed driver: no local pool to open a transaction - // on (the plugin owns its own pool inside its subprocess), and no - // cross-process RPC for transaction begin/commit/rollback exists - // yet. Execute each statement independently through the generic - // RPC surface instead — correct (each call passes a schema so - // schema-scoping doesn't depend on session state persisting - // across pooled connections, unlike the builtin arms' `SET - // search_path`), but NOT atomic: unlike the builtin drivers - // above, a failure partway through leaves whatever ran so far - // committed rather than rolling the whole import back. A - // transactional bulk-execute RPC would need to be added to the - // plugin protocol to close that gap (followed up separately). - _ => { - // Only default to "public" for a Postgres-flavored plugin - // (see `pg_schema` above). - let fallback_schema = if is_postgres { - Some(pg_schema.as_str()) - } else { - schema.as_deref() - }; - macro_rules! execute_statement { - ($stmt:expr) => { - drv.execute_query(¶ms, $stmt, None, 1, fallback_schema) - }; - } - - execute_statements_streaming!(execute_statement, stream, app_handle)?; - } - } - - Ok::<(), String>(()) - }); - - let abort_handle = Arc::new(task.abort_handle()); - let import_key = import_slot_key(&conn_id); - register_abort_handle(&state.handles, import_key.clone(), abort_handle.clone()); - - let result = task.await; - - unregister_abort_handle(&state.handles, &import_key, &abort_handle); - - match result { - Ok(res) => res, - Err(_) => Err("Import cancelled".into()), - } -} - -// Creates a BufReader from the file without loading entire content into memory -// For ZIP files, extracts to a string in memory (limitation of zip crate) -// For regular SQL files, uses streaming with a large buffer -fn create_sql_reader(file: File, file_path: &str) -> Result, String> { - if file_path.ends_with(".zip") { - // For ZIP files, we need to extract the SQL content to memory - // The zip crate doesn't support true streaming because by_index requires ownership - let mut archive = - ZipArchive::new(file).map_err(|e| format!("Failed to open zip: {}", e))?; - - // Find first .sql file and extract content - for i in 0..archive.len() { - let mut zipped_file = archive.by_index(i).map_err(|e| e.to_string())?; - if zipped_file.name().ends_with(".sql") { - let mut content = String::new(); - zipped_file - .read_to_string(&mut content) - .map_err(|e| e.to_string())?; - - // Create a BufReader from the extracted string - let cursor = std::io::Cursor::new(content.into_bytes()); - return Ok(Box::new(BufReader::new(cursor))); - } - } - Err("No .sql file found in zip archive".into()) - } else { - // For regular files, use a buffered reader with larger buffer for efficient streaming - let reader = BufReader::with_capacity(8192 * 16, file); // 128KB buffer - Ok(Box::new(reader)) - } -} - +pub(crate) use crate::application::database_transfers::abort_slot; #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn postgres_dialect() -> DumpDialect { - let pg = crate::drivers::postgres::PostgresDriver::new(); - DumpDialect::from_capabilities("postgres", &pg.manifest().capabilities) - } - - fn column(name: &str, data_type: &str) -> TableColumn { - TableColumn { - name: name.to_string(), - data_type: data_type.to_string(), - is_pk: false, - is_nullable: true, - is_auto_increment: false, - is_generated: false, - default_value: None, - character_maximum_length: None, - comment: None, - numeric_precision: None, - numeric_scale: None, - } - } - - #[test] - fn test_json_column_names_matches_json_and_jsonb_case_insensitively() { - let columns = vec![ - column("id", "integer"), - column("payload", "jsonb"), - column("meta", "JSON"), - column("name", "text"), - ]; - let json_cols = json_column_names(&columns); - assert_eq!(json_cols.len(), 2); - assert!(json_cols.contains("payload")); - assert!(json_cols.contains("meta")); - assert!(!json_cols.contains("id")); - assert!(!json_cols.contains("name")); - } - - #[test] - fn test_json_column_names_empty_for_no_json_columns() { - let columns = vec![column("id", "integer"), column("name", "text")]; - assert!(json_column_names(&columns).is_empty()); - } - - #[test] - fn test_format_row_values_escapes_json_column_differently_from_plain_text() { - // Same underlying serde_json::Value::String("hi") in two columns: - // the plain text column keeps it literal, the JSON column re-encodes - // it as a JSON string literal (surrounding quotes preserved) -- - // this is the whole reason json_column_names exists (#822 dump fix - // for plugin-backed drivers: QueryResult only carries column names, - // not types, so this can't be inferred from the value alone). - let columns = vec!["name".to_string(), "payload".to_string()]; - let mut json_cols = HashSet::new(); - json_cols.insert("payload".to_string()); - - let row = vec![json!("hi"), json!("hi")]; - assert_eq!( - format_row_values(row, &columns, &json_cols, &postgres_dialect()), - r#"('hi', '"hi"')"# - ); - } - - #[test] - fn test_format_row_values_regression_json_object_and_null_round_trip() { - let columns = vec!["id".to_string(), "payload".to_string(), "note".to_string()]; - let mut json_cols = HashSet::new(); - json_cols.insert("payload".to_string()); - - let row = vec![json!(1), json!({"a": 1}), serde_json::Value::Null]; - assert_eq!( - format_row_values(row, &columns, &json_cols, &postgres_dialect()), - r#"(1, '{"a":1}', NULL)"# - ); - } - - fn pagination(has_more: bool) -> Pagination { - Pagination { - page: 1, - page_size: 1000, - total_rows: None, - has_more, - } - } - - #[test] - fn test_plugin_dump_has_more_trusts_real_pagination_over_the_fallback() { - // A full page that the driver explicitly says is the last one must - // not be reinterpreted as "more rows" just because it's full. - assert!(!plugin_dump_has_more(Some(pagination(false)), 1000, 1000)); - // A short page the driver explicitly says has more must still be - // honored, even though the fallback heuristic alone would say no. - assert!(plugin_dump_has_more(Some(pagination(true)), 10, 1000)); - } - - #[test] - fn test_plugin_dump_has_more_regression_a_full_page_without_pagination_is_not_treated_as_the_end( - ) { - // Regression: a plugin's execute_query RPC that never populates - // `pagination` used to default this to `false`, silently truncating - // any table with more rows than one page. - assert!(plugin_dump_has_more(None, 1000, 1000)); - } - - #[test] - fn test_plugin_dump_has_more_a_short_page_without_pagination_ends_the_fetch() { - assert!(!plugin_dump_has_more(None, 10, 1000)); - } - - #[test] - fn test_plugin_dump_has_more_an_empty_page_without_pagination_ends_the_fetch() { - assert!(!plugin_dump_has_more(None, 0, 1000)); - } -} +pub(crate) use crate::application::database_transfers::await_cancellable_dump; 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 24db1cf2c..1225e5b05 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -10,19 +10,12 @@ pub use progress::{ProgressEmitter, DEFAULT_INTERVAL as DEFAULT_PROGRESS_INTERVA pub use sink::{CsvSink, JsonSink, MarkdownSink, RowSink}; use std::collections::HashMap; -use std::fs::File; -use std::io::BufWriter; +use std::io::Write; use std::sync::{Arc, Mutex}; -use serde::Serialize; use serde_json::Value; -use tauri::{AppHandle, Emitter, Runtime, State}; -use crate::commands::{ - expand_k8s_connection_params, expand_ssh_connection_params, find_connection_by_id, - register_abort_handle, resolve_connection_params_with_id, unregister_abort_handle, - AbortHandleMap, -}; +use crate::commands::AbortHandleMap; use crate::drivers::{mysql, postgres, sqlite}; use crate::models::ConnectionParams; @@ -38,118 +31,22 @@ impl Default for ExportCancellationState { } } -#[derive(Clone, Serialize)] -struct ExportProgressPayload { - rows_processed: u64, -} - -const EXPORT_PROGRESS_EVENT: &str = "export_progress"; - -fn sanitize_query(query: &str) -> String { - query.trim().trim_end_matches(';').to_string() -} - -#[tauri::command] -pub async fn cancel_export( - state: State<'_, ExportCancellationState>, - connection_id: String, -) -> Result<(), String> { - let entries = { - let mut handles = state.handles.lock().unwrap(); - handles.remove(&connection_id).unwrap_or_default() - }; - for handle in entries { - handle.abort(); - } - Ok(()) -} - -#[tauri::command] -pub async fn export_query_to_file( - app: AppHandle, - state: State<'_, ExportCancellationState>, - connection_id: String, - query: String, - file_path: String, - format: String, - csv_delimiter: Option, - database: Option, - session_id: Option, -) -> Result<(), String> { - let sanitized_query = sanitize_query(&query); - 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)?; - // Scope the export to the selected database on connections that expose multiple - // databases (e.g. MySQL/MariaDB), so the query runs against the database the - // user is viewing rather than the connection's primary database. - if let Some(db) = database.filter(|d| !d.is_empty()) { - params.database = crate::models::DatabaseSelection::Single(db); - } - let driver = saved_conn.params.driver.clone(); - - let export_format = ExportFormat::parse(&format)?; - let delimiter = parse_csv_delimiter(csv_delimiter.as_deref()); - - let app_for_task = app.clone(); - let task_connection_id = connection_id.clone(); - - let task = tokio::spawn(async move { - let file = File::create(&file_path).map_err(|e| e.to_string())?; - let writer = BufWriter::new(file); - run_export( - app_for_task, - &driver, - ¶ms, - &sanitized_query, - writer, - export_format, - delimiter, - session_id.as_deref(), - ) - .await - }); - - let abort_handle = Arc::new(task.abort_handle()); - register_abort_handle( - &state.handles, - task_connection_id.clone(), - abort_handle.clone(), - ); - - let result = task.await; - - unregister_abort_handle(&state.handles, &task_connection_id, &abort_handle); - - match result { - Ok(res) => res, - Err(_) => Err("Export cancelled".into()), - } -} - /// Wires the driver stream, the row sink, and the progress emitter together. -/// Kept as a free function so the spawned task body stays linear and the -/// pieces remain individually unit-testable. -async fn run_export( - app: AppHandle, +pub async fn run_export( driver: &str, params: &ConnectionParams, query: &str, - writer: BufWriter, + writer: W, format: ExportFormat, delimiter: u8, session_id: Option<&str>, -) -> Result<(), String> { - let app_for_progress = app.clone(); - let mut progress = ProgressEmitter::new(DEFAULT_PROGRESS_INTERVAL, move |count| { - let _ = app_for_progress.emit( - EXPORT_PROGRESS_EVENT, - ExportProgressPayload { - rows_processed: count, - }, - ); - }); + on_progress: F, +) -> Result<(), String> +where + W: Write + Send, + F: FnMut(u64) + Send, +{ + let mut progress = ProgressEmitter::new(DEFAULT_PROGRESS_INTERVAL, on_progress); match format { ExportFormat::Csv => { @@ -196,16 +93,12 @@ where "mysql" => mysql::export::stream_query(params, query, &mut on_row).await, "postgres" => postgres::export::stream_query(params, query, session_id, &mut on_row).await, "sqlite" => sqlite::export::stream_query(params, query, &mut on_row).await, - // External plugin drivers: page through the driver's own paginated - // `execute_query` and forward every row to the sink. other => stream_query_via_plugin(other, params, query, session_id, &mut on_row).await, } } /// Streams a query for an external plugin driver by repeatedly calling its -/// `execute_query` with the driver's pagination, forwarding each row to -/// `on_row`. Built-in drivers stream directly from the database; plugins only -/// expose paged query execution over JSON-RPC, so we drive that here. +/// paginated execution API and forwarding each row to the export sink. async fn stream_query_via_plugin( driver_id: &str, params: &ConnectionParams, @@ -253,7 +146,7 @@ where let has_more = result .pagination .as_ref() - .map(|p| p.has_more) + .map(|pagination| pagination.has_more) .unwrap_or(fetched >= PAGE_SIZE); if fetched == 0 || !has_more { diff --git a/src-tauri/src/export/format.rs b/src-tauri/src/export/format.rs index d43f194da..7ea21fb5b 100644 --- a/src-tauri/src/export/format.rs +++ b/src-tauri/src/export/format.rs @@ -16,6 +16,22 @@ impl ExportFormat { other => Err(format!("Unsupported export format: {}", other)), } } + + pub fn extension(self) -> &'static str { + match self { + Self::Csv => "csv", + Self::Json => "json", + Self::Markdown => "md", + } + } + + pub fn mime_type(self) -> &'static str { + match self { + Self::Csv => "text/csv", + Self::Json => "application/json", + Self::Markdown => "text/markdown", + } + } } pub const DEFAULT_CSV_DELIMITER: u8 = b','; 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 1315ac117..5a8aa7a03 100644 --- a/src-tauri/src/heartbeat.rs +++ b/src-tauri/src/heartbeat.rs @@ -1,14 +1,14 @@ -//! GUI heartbeat used by the MCP subprocess to detect whether the Tabularis -//! desktop app is currently running. +//! Approval-host heartbeat used by the MCP subprocess to detect whether a +//! Tabularis desktop or web runtime is currently running. //! -//! The GUI refreshes `/tabularis.alive` every `TICK_INTERVAL`. +//! The approval host refreshes `/tabularis.alive` every `TICK_INTERVAL`. //! The MCP subprocess calls `is_alive()` before queueing approval requests -//! so that — when the GUI is closed — write/DDL queries fail fast with a +//! so that — when the approval host is closed — write/DDL queries fail fast with a //! clear error instead of hanging until `mcp_approval_timeout_seconds` //! (default 120s) elapses. //! -//! The file is intentionally not removed on shutdown: stale-by-mtime is -//! enough and survives crashes/SIGKILL transparently. +//! Hosts share this file, so shutdown stops refreshing without deleting it. +//! Stale-by-mtime detection handles the last host exiting or crashing. use serde::{Deserialize, Serialize}; use std::fs; @@ -19,7 +19,7 @@ use crate::paths::get_app_config_dir; const FILE_NAME: &str = "tabularis.alive"; -/// How often the GUI refreshes the heartbeat file. +/// How often the approval host refreshes the heartbeat file. pub const TICK_INTERVAL: Duration = Duration::from_secs(5); /// Heartbeats older than this are considered stale (3 missed ticks). @@ -95,22 +95,41 @@ pub fn is_alive() -> bool { is_alive_in(&get_app_config_dir()) } -/// Spawn the periodic heartbeat ticker. Writes the initial file synchronously -/// so `is_alive()` is true the moment the GUI finishes booting, then refreshes -/// every `TICK_INTERVAL` from a tokio task. -pub fn spawn() { - if let Err(e) = write_now() { - log::warn!("Failed to write initial heartbeat: {}", e); +/// 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(crate::async_rt::JoinHandle<()>); + +impl HeartbeatTask { + pub fn stop(&self) { + // Another host may still be running, even when this process wrote last. + self.0.abort(); } - tauri::async_runtime::spawn(async move { +} + +impl Drop for HeartbeatTask { + fn drop(&mut self) { + self.stop(); + } +} + +/// Writes immediately, then refreshes until the owning runtime stops the task. +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 = crate::async_rt::spawn(async move { let mut ticker = tokio::time::interval(TICK_INTERVAL); - // The first tick fires immediately; we already wrote synchronously. ticker.tick().await; loop { ticker.tick().await; - if let Err(e) = write_now() { - log::warn!("Heartbeat refresh failed: {}", e); + if let Err(error) = write_now_in(&base) { + log::warn!("Heartbeat refresh failed: {}", error); } } }); + HeartbeatTask(task) +} + +pub fn spawn() -> HeartbeatTask { + spawn_in(get_app_config_dir()) } 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/k8s_tunnel.rs b/src-tauri/src/k8s_tunnel.rs index d25403c40..8135e4be8 100644 --- a/src-tauri/src/k8s_tunnel.rs +++ b/src-tauri/src/k8s_tunnel.rs @@ -38,6 +38,22 @@ pub fn get_tunnels() -> &'static Mutex> { TUNNELS.get_or_init(|| Mutex::new(HashMap::new())) } +pub fn stop_all_tunnels() { + let tunnels = { + let mut tunnels = get_tunnels() + .lock() + .unwrap_or_else(|error| error.into_inner()); + tunnels + .drain() + .map(|(_, tunnel)| tunnel) + .collect::>() + }; + + for tunnel in tunnels { + tunnel.stop(); + } +} + /// Allocate a local TCP port for kubectl port-forward. /// /// When `preferred` is set (replacing a dead tunnel), require that port so @@ -290,16 +306,6 @@ impl K8sTunnel { } } -pub fn stop_all_tunnels() { - if let Some(tunnels) = TUNNELS.get() { - if let Ok(mut guard) = tunnels.lock() { - for (_, tunnel) in guard.drain() { - tunnel.stop(); - } - } - } -} - /// Build a deterministic, collision-safe tunnel map key from K8s parameters /// and the effective command selections. #[inline] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d4516b47b..037c58a29 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,5 +1,9 @@ +// 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 chatgpt; pub mod ai_activity; #[cfg(test)] pub mod ai_activity_tests; @@ -9,35 +13,35 @@ 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; pub mod ai_schema_context; #[cfg(test)] pub mod ai_schema_context_tests; +pub mod application; pub mod askpass; pub mod backup; +pub mod database_backup; +pub mod chatgpt; pub mod cli; pub mod clipboard_import; pub mod commands; +pub mod config; pub mod connection_appearance; -pub mod connection_import; -pub mod connection_import_commands; #[cfg(test)] pub mod connection_appearance_tests; -pub mod config; pub mod connection_cache; #[cfg(test)] pub mod connection_cache_tests; +pub mod connection_import; + pub mod connection_migrations; #[cfg(test)] pub mod connection_migrations_tests; -pub mod database_backup; 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)] @@ -53,34 +57,26 @@ pub mod export_import_tests; pub mod fs_path; #[cfg(test)] pub mod fs_path_tests; -pub mod health_check; #[cfg(test)] pub mod group_tree_tests; +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)] pub mod keychain_utils_tests; -pub mod results_window; -pub mod sandbox; -#[cfg(test)] -pub mod sandbox_tests; -pub mod k8s_tunnel; pub mod log_commands; pub mod logger; 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; -pub mod storage_location; -#[cfg(test)] -pub mod storage_location_tests; pub mod persistence; #[cfg(test)] pub mod persistence_tests; @@ -94,34 +90,49 @@ pub mod proxy; pub mod query_history; #[cfg(test)] pub mod query_history_tests; -pub mod sql_database_statements; -pub mod sql_file; +pub mod runtime; +pub mod sandbox; #[cfg(test)] -pub mod sql_file_tests; +pub mod sandbox_tests; pub mod saved_queries; #[cfg(test)] pub mod saved_queries_tests; +pub mod sql_database_statements; +pub mod sql_file; +#[cfg(test)] +pub mod sql_file_tests; pub mod saved_query_folders; #[cfg(test)] pub mod saved_query_folders_tests; -pub mod ssh_tunnel; -pub mod ssm_tunnel; +pub mod secret_store; pub mod sqlite_database; #[cfg(test)] pub mod sqlite_database_tests; -mod system_theme; -pub mod task_manager; +pub mod ssh_tunnel; +pub mod ssm_tunnel; +pub mod storage_location; +#[cfg(test)] +pub mod storage_location_tests; + pub mod team_share; -pub mod theme_commands; + pub mod theme_models; pub mod theme_packages; -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; +pub mod transport; +pub mod ui_state; + +#[cfg(test)] +pub mod ui_state_tests; + + +/// 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; @@ -139,37 +150,10 @@ pub mod drivers { pub mod sqlite; } -use logger::{create_log_buffer, init_logger, SharedLogBuffer}; -use std::sync::atomic::{AtomicBool, Ordering}; -use tauri::Manager; - -static DEBUG_MODE: AtomicBool = AtomicBool::new(false); - -// Global log buffer for capturing logs -static LOG_BUFFER: std::sync::OnceLock = std::sync::OnceLock::new(); - -pub fn get_log_buffer() -> SharedLogBuffer { - LOG_BUFFER - .get() - .expect("Log buffer not initialized") - .clone() -} - -#[tauri::command] -fn is_debug_mode() -> bool { - DEBUG_MODE.load(Ordering::Relaxed) -} +pub use runtime::bootstrap::get_log_buffer; -#[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(crate) fn is_debug_mode() -> bool { + runtime::bootstrap::is_debug_mode() } #[cfg_attr(mobile, tauri::mobile_entry_point)] @@ -178,21 +162,7 @@ pub fn run() { // `askpass` module), serve the prompt and exit without booting the app. askpass::maybe_run_askpass_client(); - // Install the rustls `ring` crypto provider as the process-wide default. - // - // Both `sqlx` (via the `tls-rustls-ring-native-roots` feature) and the - // workspace's direct `rustls` usage link against the same `rustls 0.23` - // crate, but `rustls 0.23` enables both the `ring` and the `aws-lc-rs` - // crypto providers when their respective feature flags are active in - // the dependency graph. With two providers linked, rustls refuses to - // pick one automatically and panics the first time someone tries a TLS - // handshake ("Could not automatically determine the process-level - // CryptoProvider"). We pin `ring` here because: - // * `sqlx` is configured to use the `ring` provider. - // * `ring` is pure-Rust and works on all our target platforms - // (macOS, Linux, Windows) without a C toolchain at runtime. - // This must run before any sqlx pool is built. - let _ = rustls::crypto::ring::default_provider().install_default(); + runtime::bootstrap::install_process_prerequisites(); // On Linux + Wayland, disable the DMA-BUF renderer in WebKitGTK to prevent // "Protocol error dispatching to Wayland display" crashes. @@ -209,670 +179,91 @@ pub fn run() { let args = cli::parse(); - if args.mcp { - // Initialize the logger so plugin-loading and driver RPC errors (which - // use the `log` crate) are visible. The custom logger writes to stderr - // only, leaving the stdout JSON-RPC stream clean. - init_logger(create_log_buffer(1000), args.log_level()); - let rt = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime"); - rt.block_on(mcp::run_mcp_server()); - return; - } - - // Info by default so users can see application logs; --debug raises it - // to Debug, which includes sqlx queries, and RUST_LOG is honoured when the - // flag is absent. - let log_level = args.log_level(); - - // Store debug flag in global state - DEBUG_MODE.store(args.debug, Ordering::Relaxed); + // The capturing logger writes to stderr, keeping MCP's stdout JSON-RPC + // stream clean while providing the same diagnostics in every launch mode. + let log_buffer = runtime::bootstrap::initialize_logging(args.debug); - // Create and initialize log buffer - MUST be before sqlx to capture all logs - let log_buffer = create_log_buffer(1000); - LOG_BUFFER - .set(log_buffer.clone()) - .expect("Failed to initialize log buffer"); - - // Initialize custom logger that captures logs to buffer and prints to stderr - init_logger(log_buffer.clone(), log_level); - - // 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"); - } - - // Install default drivers for sqlx::Any - sqlx::any::install_default_drivers(); - - #[cfg_attr(not(feature = "e2e-testing"), allow(unused_mut))] - let mut builder = tauri::Builder::default() - // Singleton: a second launch (typically a `tabularis://...` URL - // clicked while the app is already running) hands its argv to the - // first instance and exits. With `features = ["deep-link"]` the plugin - // usually auto-routes those URLs through `on_open_url`, but on - // Linux/Windows the URL arrives as a plain argv entry on warm launch. - // We scan argv for it defensively and dispatch ourselves so the - // install modal fires even when auto-routing doesn't. - // - // Order matters: must be the FIRST plugin in the chain so it can - // intercept duplicate launches before any heavy initialisation. - .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| { - log::info!("Duplicate launch detected — forwarded to existing instance"); - if let Some(url) = argv.iter().find(|a| a.starts_with("tabularis:")) { - crate::plugins::deep_link::handle_url(app, url); - } - if let Some(win) = tauri::Manager::get_webview_window(app, "main") { - let _ = win.unminimize(); - let _ = win.set_focus(); - } - })) - .plugin(tauri_plugin_clipboard_manager::init()) - .plugin(tauri_plugin_opener::init()) - .plugin(tauri_plugin_fs::init()) - .plugin(tauri_plugin_notification::init()) - .plugin(tauri_plugin_updater::Builder::new().build()) - .plugin(tauri_plugin_deep_link::init()); - - // Dialog plugin: real in production, mocked under e2e-testing (the mock - // auto-accepts ask()/confirm() so native Tauri confirm dialogs — which - // WebDriverIO can't click — don't block the trigger-save flow). Registered - // as a same-named "dialog" plugin so it replaces the real one at Tauri's - // IPC dispatch layer (PluginStore::register retains only the last). - #[cfg(not(feature = "e2e-testing"))] - { - builder = builder.plugin(tauri_plugin_dialog::init()); - } - #[cfg(feature = "e2e-testing")] - { - builder = builder.plugin(crate::e2e_dialog_mock::init()); - // In-app WebDriver server. tauri-wd connects to drive the real WKWebView - // via the W3C WebDriver protocol on macOS, exercising real Tauri IPC. - builder = builder.plugin(tauri_plugin_webdriver_automation::init()); + if let Err(error) = secret_store::install_from_env() { + eprintln!("Error: {error}"); + std::process::exit(1); } - builder - .manage(crate::plugins::deep_link::PendingInstall::default()) - .manage(commands::QueryCancellationState::default()) - .manage(export::ExportCancellationState::default()) - .manage(dump_commands::DumpCancellationState::default()) - .manage(log_buffer) - .manage(std::sync::Arc::new( - credential_cache::CredentialCache::default(), - )) - .manage(std::sync::Arc::new( - connection_cache::ConnectionCache::default(), - )) - .manage(connection_import_commands::ImportEnvelopeCache::default()) - .manage(explain_import::PendingExplainFile::default()) - .manage(json_viewer::JsonViewerStore::default()) - .manage(results_window::ResultsWindowStore::default()) - .manage(window_placement::WindowPlacementCache::default()) - .manage(query_history::QueryHistoryState::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(), + if let Some(cli::Command::Web(web_args)) = &args.command { + let rt = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime"); + rt.block_on(async { + let web_root = + transport::web::static_assets::resolve_web_root(web_args.web_root.as_deref()) + .expect("Failed to locate Tabularis Web assets"); + let web_events = transport::web::events::WebEventBus::default(); + let runtime_context = runtime::RuntimeContext::new( + std::sync::Arc::new(runtime::paths::FixedRuntimePaths::system()), + std::sync::Arc::new(web_events.clone()), + std::sync::Arc::new(runtime::secrets::KeyringRuntimeSecrets), ); - // 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()); - - // Read persisted config to know which external plugins are enabled. - // `None` means no preference has been saved yet → load all installed plugins. - let active_ext_drivers = startup_config.active_external_drivers.as_deref(); - - // Register built-in drivers - tauri::async_runtime::block_on(async { - drivers::registry::register_driver(drivers::mysql::MysqlDriver::new()).await; - drivers::registry::register_driver(drivers::postgres::PostgresDriver::new()).await; - drivers::registry::register_driver(drivers::sqlite::SqliteDriver::new()).await; - - // Load only enabled external plugins (or all if no preference saved). - crate::plugins::manager::load_plugins_with_configs( - startup_config.plugins.clone().unwrap_or_default(), - active_ext_drivers, - ) + let application = runtime::bootstrap::bootstrap_application( + runtime_context, + runtime::bootstrap::BootstrapOptions::default(), + ) + .await + .expect("Failed to bootstrap Tabularis Web services"); + let application_state = + std::sync::Arc::new(runtime::state::ApplicationState::default()); + let web_data_dir = application.context.paths.data_dir().to_path_buf(); + let web_plugins_dir = application.context.paths.plugins_dir(); + let database_backup_scheduler = database_backup::spawn_database_backup_scheduler( + application.context.clone(), application_state.dump_cancellation.clone(), + ); + let approval_heartbeat = runtime::lifecycle::start_approval_heartbeat(&application.context); + let approval_watcher = ai_approval_watcher::spawn_headless( + application.context.clone(), + application_state.clone(), + ); + let application_api = std::sync::Arc::new(application::RuntimeApplicationApi::new( + application.context, + application_state.clone(), + )); + + let server_result = + transport::web::server::run(transport::web::server::WebServerOptions { + trusted_proxies: web_args.trusted_proxies.clone(), + host: web_args.host.clone(), + port: web_args.port, + web_root, + data_dir: web_data_dir, + plugins_dir: web_plugins_dir, + open_browser: !web_args.no_open, + auth: web_args.auth, + public_url: web_args.public_url.clone(), + allowed_origins: web_args.allowed_origins.clone(), + allow_high_risk: web_args.allow_high_risk, + server_file_browser_roots: web_args.server_file_browser_roots.clone(), + application: application_api, + events: web_events, + }) .await; - }); - - // 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; - }); - } - - // Start connection health-check ping loop. - { - let interval = startup_config - .ping_interval - .unwrap_or(health_check::DEFAULT_PING_INTERVAL); - let handle = app.handle().clone(); - tauri::async_runtime::spawn(async move { - health_check::start_ping_loop(handle, interval as u64).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()); - } - } - } - - // Watch for pending MCP approval requests and run periodic cleanup. - ai_approval_watcher::spawn(app.handle().clone()); - - // Periodic encrypted backup of the connections, when enabled. - backup::spawn_scheduler(app.handle().clone()); - - // Scheduled daily database content backups, when enabled (app-open boundary). - database_backup::spawn_database_backup_scheduler(app.handle().clone()); - - // Refresh the GUI heartbeat so the MCP subprocess can detect - // when Tabularis is closed and fail fast on approval-gated - // queries instead of waiting for the full approval timeout. - heartbeat::spawn(); - // 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}"); - } - } - } + database_backup_scheduler.abort(); + approval_watcher.abort(); + drop(approval_heartbeat); + runtime::lifecycle::shutdown_headless_runtime(&application_state).await; + server_result.expect("Failed to run Tabularis Web server"); + }); + return; + } - // 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 args.mcp { + let rt = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime"); + rt.block_on(mcp::run_mcp_server()); + return; + } - // 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, - backup::get_connections_backup_status, - backup::set_connections_backup_password, - backup::set_connections_backup_target_password, - backup::run_connections_backup, - database_backup::get_database_backup_status, - database_backup::run_database_backup_now, - database_backup::cancel_database_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, - 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_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, - 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, - dump_commands::cancel_dump, - // 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(|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 { - // Back up the freshest state before the process ends (no-op - // unless backups are enabled and due). - backup::run_exit_backup(app_handle); - // Roll back pinned transactions while the tunnels they run through are still up. - // Only the built-in PostgreSQL driver pins; plugins release in their own shutdown. - tauri::async_runtime::block_on(async { - let release = crate::drivers::postgres::session::release_all(); - if tokio::time::timeout(std::time::Duration::from_secs(3), release) - .await - .is_err() - { - log::warn!("Releasing pinned PostgreSQL sessions timed out on exit"); - } - }); - 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(); - } - }); + #[cfg(feature = "desktop")] + transport::desktop::run(args, log_buffer); + #[cfg(not(feature = "desktop"))] + { + drop(log_buffer); + eprintln!("This build has no desktop app. Run `tabularis web` or `tabularis --mcp`."); + std::process::exit(2); + } } + diff --git a/src-tauri/src/log_commands.rs b/src-tauri/src/log_commands.rs index c319dda6f..045b699ec 100644 --- a/src-tauri/src/log_commands.rs +++ b/src-tauri/src/log_commands.rs @@ -1,117 +1,9 @@ -use crate::logger::{LogEntry, SharedLogBuffer}; -use serde::Deserialize; -use std::path::PathBuf; -use tauri::State; +use crate::application::operations; -#[derive(Debug, Deserialize)] -pub struct GetLogsRequest { - limit: Option, - level_filter: Option, -} - -#[tauri::command] -pub fn get_logs(log_buffer: State, request: GetLogsRequest) -> Vec { - read_logs(&log_buffer, request) -} - -fn read_logs(log_buffer: &SharedLogBuffer, request: GetLogsRequest) -> Vec { - // The Logs tab polls this every few seconds, so keep it out of Debug. - log::trace!( - "Getting logs with limit: {:?}, filter: {:?}", - request.limit, - request.level_filter - ); - // Release the lock before logging: the capturing logger locks the same - // buffer, so logging while holding it would deadlock. - let entries = { - let buffer = log_buffer.lock().unwrap(); - buffer.get_entries(request.limit, request.level_filter) - }; - log::trace!("Returning {} log entries", entries.len()); - entries -} - -#[tauri::command] -pub fn clear_logs(log_buffer: State) -> Result<(), String> { - let mut buffer = log_buffer.lock().unwrap(); - buffer.clear(); - Ok(()) -} - -#[tauri::command] -pub fn get_log_settings(log_buffer: State) -> LogSettings { - let buffer = log_buffer.lock().unwrap(); - LogSettings { - enabled: buffer.is_enabled(), - max_size: buffer.get_max_size(), - current_count: buffer.get_entries(None, None).len(), - } -} - -#[tauri::command] -pub fn set_log_enabled(log_buffer: State, enabled: bool) -> Result<(), String> { - let mut buffer = log_buffer.lock().unwrap(); - buffer.set_enabled(enabled); - Ok(()) -} - -#[tauri::command] -pub fn set_log_max_size(log_buffer: State, max_size: usize) -> Result<(), String> { - if max_size == 0 || max_size > 10000 { - return Err("Max size must be between 1 and 10000".to_string()); - } - let mut buffer = log_buffer.lock().unwrap(); - buffer.set_max_size(max_size); - Ok(()) -} - -#[derive(Debug, serde::Serialize)] -pub struct LogSettings { - pub enabled: bool, - pub max_size: usize, - pub current_count: usize, -} - -#[tauri::command] -pub fn export_logs(log_buffer: State, file_path: String) -> Result<(), String> { - let buffer = log_buffer.lock().unwrap(); - let entries = buffer.get_entries(None, None); - - if entries.is_empty() { - return Err("No logs to export".to_string()); - } - - let mut content = String::new(); - content.push_str("Tabularis Application Logs\n"); - content.push_str("==========================\n\n"); - - for entry in entries { - content.push_str(&format!( - "[{}] [{}] {}", - entry.timestamp, - entry.level.to_uppercase(), - entry.message - )); - if let Some(target) = &entry.target { - content.push_str(&format!(" (target: {})", target)); - } - content.push('\n'); - } - - // Release the lock before writing - drop(buffer); - - // Write to file synchronously - let path = PathBuf::from(file_path); - std::fs::write(&path, content).map_err(|e| format!("Failed to write log file: {}", e))?; - - log::info!("Logs exported to: {:?}", path); - Ok(()) -} +pub use operations::{GetLogsRequest, LogSettings}; /// 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), @@ -122,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/log_commands_tests.rs b/src-tauri/src/log_commands_tests.rs index 6cac316f8..364224964 100644 --- a/src-tauri/src/log_commands_tests.rs +++ b/src-tauri/src/log_commands_tests.rs @@ -9,6 +9,25 @@ use std::time::Duration; /// the call never returned and every other logging thread blocked behind it. #[test] fn get_logs_does_not_deadlock_when_its_own_logs_are_captured() { + // The global logger cannot be replaced; isolate it from runtime audit tests. + const CHILD: &str = "TABULARIS_LOG_DEADLOCK_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "log_commands::tests::get_logs_does_not_deadlock_when_its_own_logs_are_captured", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + return; + } let buffer = create_log_buffer(100); // Trace is the most verbose level, so this keeps covering `get_logs` // whatever level its own log lines use. @@ -21,7 +40,7 @@ fn get_logs_does_not_deadlock_when_its_own_logs_are_captured() { limit: None, level_filter: None, }; - tx.send(read_logs(&reader, request)).ok(); + tx.send(operations::get_logs(&reader, request)).ok(); }); rx.recv_timeout(Duration::from_secs(5)) diff --git a/src-tauri/src/logger/tests.rs b/src-tauri/src/logger/tests.rs index e732c1bd2..2b4d25314 100644 --- a/src-tauri/src/logger/tests.rs +++ b/src-tauri/src/logger/tests.rs @@ -127,6 +127,7 @@ fn cli_log_level_prefers_the_flag_over_the_environment() { // it, so the two cannot fight. let args = crate::cli::Args { mcp: false, + command: None, debug: true, explain: None, }; @@ -139,6 +140,7 @@ fn cli_log_level_prefers_the_flag_over_the_environment() { fn cli_log_level_falls_back_to_the_environment_without_the_flag() { let args = crate::cli::Args { mcp: false, + command: None, debug: false, explain: None, }; diff --git a/src-tauri/src/mcp/install.rs b/src-tauri/src/mcp/install.rs index 3a2e7c06a..139597f9c 100644 --- a/src-tauri/src/mcp/install.rs +++ b/src-tauri/src/mcp/install.rs @@ -1,362 +1,2 @@ -use directories::BaseDirs; -use serde_json::json; -use std::fs; -use std::path::{Path, PathBuf}; -use tauri::{AppHandle, Runtime}; -/// "file" → standard mcpServers JSON config file -/// "command" → installed via CLI (e.g. `claude mcp add`) -#[derive(serde::Serialize, Clone)] -pub struct McpClientStatus { - pub client_id: String, - pub client_name: String, - pub installed: bool, - pub config_path: Option, - pub executable_path: String, - pub client_type: String, - pub manual_command: Option, -} - -struct McpClient { - id: &'static str, - name: &'static str, - config_path: Option, - client_type: &'static str, -} - -/// Claude Desktop keeps its config in a `Claude` folder directly under the OS -/// config dir (`BaseDirs::config_dir()`): `~/Library/Application Support` on -/// macOS, `%APPDATA%` (Roaming) on Windows, `$XDG_CONFIG_HOME` on Linux. -fn claude_desktop_config_path(config_dir: &Path) -> PathBuf { - config_dir.join("Claude").join("claude_desktop_config.json") -} - -fn get_all_clients() -> Vec { - let base = BaseDirs::new(); - - let claude_path = base - .as_ref() - .map(|b| claude_desktop_config_path(b.config_dir())); - - // Claude Code stores user-scope MCP in ~/.claude.json - let claude_code_path = base.as_ref().map(|b| b.home_dir().join(".claude.json")); - - let codex_path = base - .as_ref() - .map(|b| b.home_dir().join(".codex/config.toml")); - - let cursor_path = base.as_ref().map(|b| b.home_dir().join(".cursor/mcp.json")); - - let windsurf_path = base - .as_ref() - .map(|b| b.home_dir().join(".codeium/windsurf/mcp_config.json")); - - let antigravity_path = base - .as_ref() - .map(|b| b.home_dir().join(".gemini/antigravity/mcp_config.json")); - - vec![ - McpClient { - id: "claude", - name: "Claude Desktop", - config_path: claude_path, - client_type: "file", - }, - McpClient { - id: "claude_code", - name: "Claude Code", - config_path: claude_code_path, - client_type: "command", - }, - McpClient { - id: "codex", - name: "Codex", - config_path: codex_path, - client_type: "command", - }, - McpClient { - id: "cursor", - name: "Cursor", - config_path: cursor_path, - client_type: "file", - }, - McpClient { - id: "windsurf", - name: "Windsurf", - config_path: windsurf_path, - client_type: "file", - }, - McpClient { - id: "antigravity", - name: "Antigravity", - config_path: antigravity_path, - client_type: "file", - }, - ] -} - -fn is_tabularis_in_mcp_servers(path: &PathBuf) -> bool { - if !path.exists() { - return false; - } - fs::read_to_string(path) - .ok() - .and_then(|c| serde_json::from_str::(&c).ok()) - .and_then(|j| j.get("mcpServers").cloned()) - .map(|s| s.get("tabularis").is_some()) - .unwrap_or(false) -} - -/// Command-driven clients store MCP config in different formats; for status -/// purposes, consider Tabularis installed when their config references it. -fn is_command_client_installed(path: &PathBuf) -> bool { - if !path.exists() { - return false; - } - fs::read_to_string(path) - .map(|c| { - c.contains("\"tabularis\"") - || c.contains("[mcp_servers.tabularis]") - || c.contains("[mcp_servers.\"tabularis\"]") - }) - .unwrap_or(false) -} - -fn build_command_client_invocation( - client_id: &str, - exe_str: &str, -) -> Option<(String, Vec)> { - match client_id { - "claude_code" => Some(( - "claude".to_string(), - vec![ - "mcp".to_string(), - "add".to_string(), - "--scope".to_string(), - "user".to_string(), - "tabularis".to_string(), - exe_str.to_string(), - "--".to_string(), - "--mcp".to_string(), - ], - )), - "codex" => Some(( - "codex".to_string(), - vec![ - "mcp".to_string(), - "add".to_string(), - "tabularis".to_string(), - "--".to_string(), - exe_str.to_string(), - "--mcp".to_string(), - ], - )), - _ => None, - } -} - -fn build_manual_command(client_id: &str, exe_str: &str) -> Option { - let (program, args) = build_command_client_invocation(client_id, exe_str)?; - Some(format!("{} {}", program, args.join(" "))) -} - -#[tauri::command] -pub async fn get_mcp_status( - _app: AppHandle, -) -> Result, String> { - let exe_path = std::env::current_exe() - .map_err(|e| format!("Failed to get executable path: {}", e))? - .to_string_lossy() - .to_string(); - - let clients = get_all_clients(); - let statuses = clients - .into_iter() - .map(|c| { - let installed = match c.client_type { - "command" => c - .config_path - .as_ref() - .map(|p| is_command_client_installed(p)) - .unwrap_or(false), - _ => c - .config_path - .as_ref() - .map(|p| is_tabularis_in_mcp_servers(p)) - .unwrap_or(false), - }; - McpClientStatus { - client_id: c.id.to_string(), - client_name: c.name.to_string(), - installed, - config_path: c.config_path.map(|p| p.to_string_lossy().to_string()), - executable_path: exe_path.clone(), - client_type: c.client_type.to_string(), - manual_command: build_manual_command(c.id, &exe_path), - } - }) - .collect(); - - Ok(statuses) -} - -#[tauri::command] -pub async fn install_mcp_config( - _app: AppHandle, - client_id: String, -) -> Result { - let exe_path = - std::env::current_exe().map_err(|e| format!("Failed to get executable path: {}", e))?; - let exe_str = exe_path.to_string_lossy().to_string(); - - let clients = get_all_clients(); - let client = clients - .iter() - .find(|c| c.id == client_id) - .ok_or_else(|| format!("Unknown client: {}", client_id))?; - - if client.client_type == "command" { - let (program, args) = build_command_client_invocation(client.id, &exe_str) - .ok_or_else(|| format!("Unsupported command client: {}", client.id))?; - let manual_command = build_manual_command(client.id, &exe_str) - .unwrap_or_else(|| format!("{} {}", program, args.join(" "))); - let output = std::process::Command::new(&program) - .args(&args) - .output() - .map_err(|e| { - format!( - "{} CLI not found. Run manually:\n{}\n(Error: {})", - client.name, manual_command, e - ) - })?; - - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - return Err(format!("{} mcp add failed: {}", program, stderr)); - } - - return Ok(client.name.to_string()); - } - - // File-based clients - let config_path = client - .config_path - .as_ref() - .ok_or("Could not determine config path for this OS")?; - - if let Some(parent) = config_path.parent() { - fs::create_dir_all(parent).map_err(|e| e.to_string())?; - } - - let mut config: serde_json::Value = if config_path.exists() { - let content = fs::read_to_string(config_path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).unwrap_or(json!({})) - } else { - json!({}) - }; - - if config.get("mcpServers").is_none() { - config["mcpServers"] = json!({}); - } - - config["mcpServers"]["tabularis"] = json!({ - "command": exe_str, - "args": ["--mcp"] - }); - - let new_content = serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?; - fs::write(config_path, new_content).map_err(|e| e.to_string())?; - - Ok(client.name.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn claude_desktop_config_sits_directly_in_the_claude_folder() { - // Roaming AppData on Windows: Claude Desktop reads - // %APPDATA%\Claude\claude_desktop_config.json, with no `config` subfolder. - let roaming = PathBuf::from("C:/Users/alice/AppData/Roaming"); - assert_eq!( - claude_desktop_config_path(&roaming), - roaming.join("Claude").join("claude_desktop_config.json") - ); - } - - #[test] - fn lists_claude_desktop_under_the_os_config_dir() { - let clients = get_all_clients(); - let claude = clients - .iter() - .find(|client| client.id == "claude") - .expect("Claude Desktop should be listed as an MCP client"); - let config_dir = BaseDirs::new() - .expect("home directory") - .config_dir() - .to_path_buf(); - - assert_eq!(claude.client_type, "file"); - assert_eq!( - claude.config_path, - Some(config_dir.join("Claude").join("claude_desktop_config.json")) - ); - } - - #[test] - fn lists_codex_as_command_client() { - let clients = get_all_clients(); - let codex = clients - .iter() - .find(|client| client.id == "codex") - .expect("Codex should be listed as an MCP client"); - - assert_eq!(codex.name, "Codex"); - assert_eq!(codex.client_type, "command"); - assert!( - codex - .config_path - .as_ref() - .is_some_and(|path| path.ends_with(".codex/config.toml")), - "Codex config path should point to ~/.codex/config.toml" - ); - } - - #[test] - fn builds_codex_manual_command() { - assert_eq!( - build_manual_command("codex", "/Applications/Tabularis.app/tabularis").as_deref(), - Some("codex mcp add tabularis -- /Applications/Tabularis.app/tabularis --mcp") - ); - } - - #[test] - fn builds_claude_code_manual_command() { - assert_eq!( - build_manual_command("claude_code", "/Applications/Tabularis.app/tabularis") - .as_deref(), - Some( - "claude mcp add --scope user tabularis /Applications/Tabularis.app/tabularis -- --mcp" - ) - ); - } - - #[test] - fn detects_codex_toml_config() { - let temp_dir = tempfile::tempdir().unwrap(); - let config_path = temp_dir.path().join("config.toml"); - fs::write( - &config_path, - r#" -[mcp_servers.tabularis] -command = "/Applications/Tabularis.app/tabularis" -args = ["--mcp"] -"#, - ) - .unwrap(); - - assert!(is_command_client_installed(&config_path)); - } -} diff --git a/src-tauri/src/mcp/mod.rs b/src-tauri/src/mcp/mod.rs index deb61488a..c08ffec2f 100644 --- a/src-tauri/src/mcp/mod.rs +++ b/src-tauri/src/mcp/mod.rs @@ -9,6 +9,7 @@ use crate::config::{ use crate::credential_cache; use crate::drivers::driver_trait::{DatabaseDriver, SqlDialect}; use crate::drivers::registry as driver_registry; +#[cfg(test)] use crate::drivers::{mysql, postgres, sqlite}; use crate::heartbeat; use crate::models::{ConnectionParams, DatabaseSelection, K8sConnection, SshConnection}; @@ -338,21 +339,14 @@ async fn resolve_db_params( /// mysql/postgres/sqlite connections — every other driver fails with /// "Unsupported driver". async fn register_drivers_for_mcp() { - driver_registry::register_driver(mysql::MysqlDriver::new()).await; - driver_registry::register_driver(postgres::PostgresDriver::new()).await; - driver_registry::register_driver(sqlite::SqliteDriver::new()).await; - - plugins::manager::reload_plugins_from_disk_config().await; - - // Must run after driver registration above — the migration resolves each - // connection's driver dialect via the same registry, so it needs plugin - // drivers already loaded. This is the standalone MCP process's own entry - // point for a migration that previously only ran from the GUI process's - // Tauri commands (issue #639) — never blocks server startup on failure. - let conn_path = paths::resolve_connections_path(&paths::get_app_config_dir()); - crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path(&conn_path) - .await - .ok(); + if let Err(error) = crate::runtime::bootstrap::bootstrap_application( + crate::runtime::RuntimeContext::system(), + crate::runtime::bootstrap::BootstrapOptions::default(), + ) + .await + { + log::error!("Failed to bootstrap MCP application services: {error}"); + } } /// Resolve the driver for an MCP-known connection. Returns the connection, diff --git a/src-tauri/src/notebooks.rs b/src-tauri/src/notebooks.rs deleted file mode 100644 index 13b57f42f..000000000 --- a/src-tauri/src/notebooks.rs +++ /dev/null @@ -1,243 +0,0 @@ -use std::fs; -use std::path::{Path, PathBuf}; -use std::time::SystemTime; - -use serde::Serialize; - -use crate::paths::get_app_config_dir; - -#[cfg(test)] -mod tests; - -/// Metadata describing a saved notebook, used to populate the -/// "saved notebooks" list without loading full cell contents. -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct NotebookMetadata { - pub id: String, - pub title: String, - pub created_at: Option, - pub updated_at: Option, -} - -/// Reject ids that could escape the notebooks directory. Notebook and -/// connection ids are generated internally and never contain separators, -/// so anything that does is treated as malformed input. -fn validate_id(id: &str) -> Result<(), String> { - if id.is_empty() || id.contains('/') || id.contains('\\') || id.contains("..") { - return Err(format!("Invalid id: {}", id)); - } - Ok(()) -} - -/// Root notebooks directory: `/notebooks`. -fn get_notebooks_dir() -> PathBuf { - let mut config_dir = get_app_config_dir(); - config_dir.push("notebooks"); - config_dir -} - -/// Per-connection notebooks directory: `/`. -fn connection_dir(root: &Path, connection_id: &str) -> Result { - validate_id(connection_id)?; - Ok(root.join(connection_id)) -} - -/// Path to a notebook file: `//.tabularis-notebook`. -fn notebook_path(root: &Path, connection_id: &str, notebook_id: &str) -> Result { - validate_id(notebook_id)?; - let dir = connection_dir(root, connection_id)?; - Ok(dir.join(format!("{}.tabularis-notebook", notebook_id))) -} - -/// Legacy flat path (pre per-connection layout): `/.tabularis-notebook`. -fn legacy_notebook_path(root: &Path, notebook_id: &str) -> Result { - validate_id(notebook_id)?; - Ok(root.join(format!("{}.tabularis-notebook", notebook_id))) -} - -// --- Core implementation (directory-injectable for testing) --- - -fn write_in(root: &Path, connection_id: &str, notebook_id: &str, content: &str) -> Result<(), String> { - let dir = connection_dir(root, connection_id)?; - fs::create_dir_all(&dir).map_err(|e| format!("Failed to create notebooks directory: {}", e))?; - let path = notebook_path(root, connection_id, notebook_id)?; - fs::write(&path, content).map_err(|e| format!("Failed to write notebook: {}", e))?; - Ok(()) -} - -fn load_in(root: &Path, connection_id: &str, notebook_id: &str) -> Result, String> { - let path = notebook_path(root, connection_id, notebook_id)?; - if path.exists() { - let content = - fs::read_to_string(&path).map_err(|e| format!("Failed to read notebook: {}", e))?; - return Ok(Some(content)); - } - - // Lazily migrate a legacy flat notebook into the per-connection layout the - // first time it is opened. The owning connection is the one whose tab - // references it, which is exactly the caller here. - let legacy = legacy_notebook_path(root, notebook_id)?; - if legacy.exists() { - let content = - fs::read_to_string(&legacy).map_err(|e| format!("Failed to read notebook: {}", e))?; - let dir = connection_dir(root, connection_id)?; - fs::create_dir_all(&dir) - .map_err(|e| format!("Failed to create notebooks directory: {}", e))?; - // Move rather than copy so the flat file does not linger as a duplicate. - if fs::rename(&legacy, &path).is_err() { - // Cross-device or other rename failure — fall back to copy + delete. - fs::write(&path, &content) - .map_err(|e| format!("Failed to migrate notebook: {}", e))?; - let _ = fs::remove_file(&legacy); - } - return Ok(Some(content)); - } - - Ok(None) -} - -fn delete_in(root: &Path, connection_id: &str, notebook_id: &str) -> Result<(), String> { - let path = notebook_path(root, connection_id, notebook_id)?; - if path.exists() { - fs::remove_file(&path).map_err(|e| format!("Failed to delete notebook: {}", e))?; - } - // Also clear any leftover legacy flat file. - if let Ok(legacy) = legacy_notebook_path(root, notebook_id) { - if legacy.exists() { - let _ = fs::remove_file(&legacy); - } - } - Ok(()) -} - -fn rename_in(root: &Path, connection_id: &str, notebook_id: &str, title: &str) -> Result<(), String> { - let path = notebook_path(root, connection_id, notebook_id)?; - if !path.exists() { - return Err(format!("Notebook not found: {}", notebook_id)); - } - let content = - fs::read_to_string(&path).map_err(|e| format!("Failed to read notebook: {}", e))?; - let mut value: serde_json::Value = - serde_json::from_str(&content).map_err(|e| format!("Invalid notebook file: {}", e))?; - match value.as_object_mut() { - Some(obj) => { - obj.insert("title".to_string(), serde_json::Value::String(title.to_string())); - } - None => return Err("Notebook file is not a JSON object".to_string()), - } - let serialized = serde_json::to_string_pretty(&value) - .map_err(|e| format!("Failed to serialize notebook: {}", e))?; - fs::write(&path, serialized).map_err(|e| format!("Failed to save notebook: {}", e))?; - Ok(()) -} - -fn list_in(root: &Path, connection_id: &str) -> Result, String> { - let dir = connection_dir(root, connection_id)?; - if !dir.exists() { - return Ok(Vec::new()); - } - - let entries = - fs::read_dir(&dir).map_err(|e| format!("Failed to read notebooks directory: {}", e))?; - - let mut notebooks = Vec::new(); - for entry in entries.flatten() { - let path = entry.path(); - let id = match path.file_name().and_then(|n| n.to_str()) { - Some(name) if name.ends_with(".tabularis-notebook") => { - name.trim_end_matches(".tabularis-notebook").to_string() - } - _ => continue, - }; - - let content = match fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - let value: serde_json::Value = match serde_json::from_str(&content) { - Ok(v) => v, - Err(_) => continue, - }; - - let title = value - .get("title") - .and_then(|t| t.as_str()) - .unwrap_or("Notebook") - .to_string(); - let created_at = value - .get("createdAt") - .and_then(|t| t.as_str()) - .map(|s| s.to_string()); - let updated_at = entry - .metadata() - .ok() - .and_then(|m| m.modified().ok()) - .map(system_time_to_rfc3339); - - notebooks.push(NotebookMetadata { - id, - title, - created_at, - updated_at, - }); - } - - Ok(notebooks) -} - -fn system_time_to_rfc3339(time: SystemTime) -> String { - let datetime: chrono::DateTime = time.into(); - datetime.to_rfc3339() -} - -// --- Tauri command wrappers --- - -#[tauri::command] -pub async fn create_notebook( - connection_id: String, - notebook_id: String, - content: String, -) -> Result<(), String> { - write_in(&get_notebooks_dir(), &connection_id, ¬ebook_id, &content) -} - -#[tauri::command] -pub async fn save_notebook( - connection_id: String, - notebook_id: String, - content: String, -) -> Result<(), String> { - write_in(&get_notebooks_dir(), &connection_id, ¬ebook_id, &content) -} - -#[tauri::command] -pub async fn load_notebook( - connection_id: String, - notebook_id: String, -) -> Result, String> { - load_in(&get_notebooks_dir(), &connection_id, ¬ebook_id) -} - -#[tauri::command] -pub async fn delete_notebook(connection_id: String, notebook_id: String) -> Result<(), String> { - delete_in(&get_notebooks_dir(), &connection_id, ¬ebook_id) -} - -/// Rename a saved notebook by patching the `title` field in place, without -/// touching cell contents. Works on notebooks that are not currently open. -#[tauri::command] -pub async fn rename_notebook( - connection_id: String, - notebook_id: String, - title: String, -) -> Result<(), String> { - rename_in(&get_notebooks_dir(), &connection_id, ¬ebook_id, &title) -} - -/// List all saved notebooks for a connection. Reads each file's `title` and -/// `createdAt`; uses the filesystem modification time as `updatedAt`. -#[tauri::command] -pub async fn list_notebooks(connection_id: String) -> Result, String> { - list_in(&get_notebooks_dir(), &connection_id) -} diff --git a/src-tauri/src/notebooks/tests.rs b/src-tauri/src/notebooks/tests.rs deleted file mode 100644 index 7fda62be8..000000000 --- a/src-tauri/src/notebooks/tests.rs +++ /dev/null @@ -1,152 +0,0 @@ -use super::*; -use std::fs; -use tempfile::TempDir; - -const CONN: &str = "conn_1"; - -fn sample(title: &str) -> String { - format!( - r#"{{"version":2,"title":"{}","createdAt":"2026-01-01T00:00:00Z","cells":[{{"type":"sql","content":"SELECT 1"}}]}}"#, - title - ) -} - -#[test] -fn write_then_load_round_trips() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - write_in(root, CONN, "nb_a", &sample("Hello")).unwrap(); - let loaded = load_in(root, CONN, "nb_a").unwrap(); - assert_eq!(loaded.as_deref(), Some(sample("Hello").as_str())); -} - -#[test] -fn write_creates_per_connection_directory() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - write_in(root, CONN, "nb_a", &sample("Hello")).unwrap(); - assert!(root.join(CONN).join("nb_a.tabularis-notebook").exists()); -} - -#[test] -fn load_missing_returns_none() { - let tmp = TempDir::new().unwrap(); - assert!(load_in(tmp.path(), CONN, "nope").unwrap().is_none()); -} - -#[test] -fn list_returns_metadata() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - write_in(root, CONN, "nb_a", &sample("First")).unwrap(); - write_in(root, CONN, "nb_b", &sample("Second")).unwrap(); - - let mut list = list_in(root, CONN).unwrap(); - list.sort_by(|a, b| a.id.cmp(&b.id)); - - assert_eq!(list.len(), 2); - assert_eq!(list[0].id, "nb_a"); - assert_eq!(list[0].title, "First"); - assert_eq!(list[0].created_at.as_deref(), Some("2026-01-01T00:00:00Z")); - assert!(list[0].updated_at.is_some()); - assert_eq!(list[1].id, "nb_b"); - assert_eq!(list[1].title, "Second"); -} - -#[test] -fn list_missing_connection_is_empty() { - let tmp = TempDir::new().unwrap(); - assert!(list_in(tmp.path(), "ghost").unwrap().is_empty()); -} - -#[test] -fn list_ignores_unrelated_and_malformed_files() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - let dir = root.join(CONN); - fs::create_dir_all(&dir).unwrap(); - - write_in(root, CONN, "nb_a", &sample("Valid")).unwrap(); - fs::write(dir.join("notes.txt"), "ignore me").unwrap(); - fs::write(dir.join("broken.tabularis-notebook"), "{not json").unwrap(); - - let list = list_in(root, CONN).unwrap(); - assert_eq!(list.len(), 1); - assert_eq!(list[0].id, "nb_a"); -} - -#[test] -fn rename_updates_title_and_preserves_cells() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - write_in(root, CONN, "nb_a", &sample("Old")).unwrap(); - rename_in(root, CONN, "nb_a", "New Name").unwrap(); - - let loaded = load_in(root, CONN, "nb_a").unwrap().unwrap(); - let value: serde_json::Value = serde_json::from_str(&loaded).unwrap(); - assert_eq!(value["title"], "New Name"); - // Cells (and other fields) survive the rename. - assert_eq!(value["cells"][0]["content"], "SELECT 1"); - assert_eq!(value["version"], 2); -} - -#[test] -fn rename_missing_notebook_errors() { - let tmp = TempDir::new().unwrap(); - assert!(rename_in(tmp.path(), CONN, "nope", "x").is_err()); -} - -#[test] -fn delete_removes_file() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - write_in(root, CONN, "nb_a", &sample("Bye")).unwrap(); - delete_in(root, CONN, "nb_a").unwrap(); - - assert!(load_in(root, CONN, "nb_a").unwrap().is_none()); -} - -#[test] -fn delete_missing_is_ok() { - let tmp = TempDir::new().unwrap(); - assert!(delete_in(tmp.path(), CONN, "nope").is_ok()); -} - -#[test] -fn legacy_flat_notebook_is_migrated_on_load() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - fs::create_dir_all(root).unwrap(); - - // Simulate a pre-existing flat notebook from the old layout. - let legacy = root.join("nb_legacy.tabularis-notebook"); - fs::write(&legacy, sample("Legacy")).unwrap(); - - let loaded = load_in(root, CONN, "nb_legacy").unwrap(); - assert_eq!(loaded.as_deref(), Some(sample("Legacy").as_str())); - - // It moved into the per-connection folder and the flat file is gone. - assert!(root.join(CONN).join("nb_legacy.tabularis-notebook").exists()); - assert!(!legacy.exists()); - - // And it now shows up in the connection's list. - let list = list_in(root, CONN).unwrap(); - assert_eq!(list.len(), 1); - assert_eq!(list[0].id, "nb_legacy"); -} - -#[test] -fn ids_with_path_traversal_are_rejected() { - let tmp = TempDir::new().unwrap(); - let root = tmp.path(); - - assert!(load_in(root, CONN, "../escape").is_err()); - assert!(load_in(root, "../escape", "nb_a").is_err()); - assert!(write_in(root, CONN, "a/b", "{}").is_err()); - assert!(rename_in(root, "..", "nb_a", "x").is_err()); -} diff --git a/src-tauri/src/plugins/commands.rs b/src-tauri/src/plugins/commands.rs index 66d993b7f..1f048c6ef 100644 --- a/src-tauri/src/plugins/commands.rs +++ b/src-tauri/src/plugins/commands.rs @@ -1,477 +1,20 @@ -use std::fs; +use crate::plugins::installer::{self}; -use crate::drivers::driver_trait::PluginManifest; -use crate::plugins::installer::{self, InstalledPluginInfo}; -use crate::plugins::manager::ConfigManifest; -use crate::plugins::registry::{self, RegistryPlugin, RegistryPluginWithStatus, RegistryReleaseWithStatus}; -use tauri::AppHandle; - -/// Resolves which Tabularium registry to talk to. Operators pin a -/// URL via `tabularium_registry_url` in `config.json`; otherwise the -/// built-in default applies. -fn registry_base_url(config: &crate::config::AppConfig) -> &str { - config - .tabularium_registry_url - .as_deref() - .unwrap_or(registry::DEFAULT_TABULARIUM_URL) -} - -#[tauri::command] -pub async fn fetch_plugin_registry( - app: AppHandle, -) -> Result, String> { - let config = crate::config::load_config_internal(&app); - let base_url = registry_base_url(&config).trim_end_matches('/').to_string(); - // COMPAT(registry-ga): merge the API with the legacy static registry.json so - // not-yet-migrated plugins stay visible during the transition. - let legacy_url = crate::plugins::compat::legacy_registry_url(&config); - let installed = installer::list_installed()?; - let installed_ids: Vec = installed.iter().map(|i| i.id.clone()).collect(); - let remote = - crate::plugins::compat::resolve_registry(&base_url, &legacy_url, &installed_ids).await?; - let platform = registry::get_current_platform(); - // Themes are declarative packages tracked by the theme catalog, never by - // the executable plugin installer. Read the catalog once for the whole list. - let themes = InstalledThemes::load(&base_url); - - let result: Vec = remote - .plugins - .into_iter() - // Unknown or ambiguous kinds have no install path; keep them out of the - // Plugin Center so the kind filter only ever offers drivers and themes. - .filter(|plugin| matches!(plugin.kind.as_deref(), None | Some("driver") | Some("theme"))) - .map(|plugin| { - let (installed_version, platform) = if plugin.kind.as_deref() == Some("theme") { - (themes.version_of(&plugin.id), "universal") - } else { - ( - installed - .iter() - .find(|i| i.id == plugin.id) - .map(|i| i.version.clone()), - platform.as_str(), - ) - }; - // `registry_base_url` is stamped in resolve_registry, which still - // knows whether a plugin came from the API or the legacy registry. - to_plugin_with_status(plugin, installed_version, platform) - }) - .collect(); - - Ok(result) -} - -/// Installed declarative theme packages, resolved from the -/// host-owned theme catalog so theme status never touches driver discovery. -struct InstalledThemes { - catalog: crate::theme_packages::ThemeCatalog, -} - -impl InstalledThemes { - fn load(_base_url: &str) -> Self { - Self { - catalog: crate::theme_packages::read_theme_catalog( - &crate::paths::get_app_config_dir(), - &crate::paths::get_default_app_data_dir(), - env!("CARGO_PKG_VERSION"), - ), - } - } - - fn version_of(&self, package_name: &str) -> Option { - self.catalog - .themes - .iter() - .find(|entry| { - entry.origin["kind"] == "installed" - && entry.origin["identity"]["packageName"] == package_name - }) - .and_then(|entry| entry.origin["packageVersion"].as_str()) - .map(str::to_string) - } -} - -/// Builds a `RegistryPluginWithStatus` from a registry plugin + the installed -/// version (if any), computing per-release platform support and a SemVer-aware -/// `update_available`. `install_action` is left `None` here; the deeplink -/// preview path sets it explicitly. -fn to_plugin_with_status( - plugin: RegistryPlugin, - installed_version: Option, - platform: &str, -) -> RegistryPluginWithStatus { - let releases: Vec = plugin - .releases - .iter() - .map(|r| { - let platform_supported = - r.assets.contains_key(platform) || r.assets.contains_key("universal"); - RegistryReleaseWithStatus { - version: r.version.clone(), - min_tabularis_version: r.min_tabularis_version.clone(), - platform_supported, - } - }) - .collect(); - - let platform_supported = releases - .iter() - .any(|r| r.version == plugin.latest_version && r.platform_supported); - - // SemVer-aware: "update" classification doubles as `update_available`. - let action = registry::classify_install(installed_version.as_deref(), &plugin.latest_version); - let update_available = matches!(action, registry::InstallAction::Update); - - RegistryPluginWithStatus { - id: plugin.id, - name: plugin.name, - description: plugin.description, - author: plugin.author, - homepage: plugin.homepage, - latest_version: plugin.latest_version, - releases, - installed_version, - update_available, - platform_supported, - icon: plugin.icon, - repo_url: plugin.repo_url, - kind: plugin.kind, - tags: plugin.tags, - category: plugin.category, - downloads: plugin.downloads, - registry_base_url: plugin.registry_base_url, - engine: plugin.engine, - paradigms: plugin.paradigms, - verified: plugin.verified, - install_action: None, - signature: None, - } -} - -/// API-path install resolution: resolves the concrete target version, confirms -/// the platform is supported (+ sha256), and returns the registry's TRACKED -/// download URL. Returns `(download_url, expected_sha256, target_version)`. -async fn resolve_api_install_asset( - base: &str, - plugin_id: &str, - version: Option<&str>, - platform: &str, -) -> Result<(String, Option, String), String> { - let detail = crate::plugins::tabularium::fetch_plugin_detail(base, plugin_id).await?; - if !matches!(detail.kind.as_deref(), None | Some("driver")) { - return Err(super::package_kind::KIND_ERROR.into()); - } - let target_version = match version { - Some(v) => v.to_string(), - None => { - if !detail.latest_version.is_empty() { - detail.latest_version - } else { - detail - .releases - .first() - .map(|r| r.version.clone()) - .ok_or_else(|| { - format!("Plugin '{}' has no releases on the registry", plugin_id) - })? - } - } - }; - // Resolve the asset for its sha256 + to confirm the platform is supported, - // but download via the registry's TRACKED redirect so the download counter - // increments. Use the dedicated `/latest` endpoint when no version was - // pinned, otherwise the versioned `/releases/{version}` endpoint. - let asset = - registry::resolve_tabularium_asset(base, plugin_id, &target_version, platform).await?; - let download_url = match version { - Some(_) => crate::plugins::tabularium::tracked_download_url( - base, - plugin_id, - &target_version, - platform, - ), - None => crate::plugins::tabularium::tracked_latest_download_url(base, plugin_id, platform), - }; - Ok((download_url, asset.expected_sha256, target_version)) -} - -#[tauri::command] -pub async fn install_plugin( - app: AppHandle, - plugin_id: String, - version: Option, -) -> Result<(), String> { - let install_guard = crate::plugins::install_cancellation::begin(&plugin_id)?; - let cancellation = install_guard.cancellation(); - cancellation.check()?; - - let config = crate::config::load_config_internal(&app); - let platform = registry::get_current_platform(); - let base = registry_base_url(&config); - - // Resolve the download URL + expected SHA-256 + concrete target version. - // Resolution order: - // 1. COMPAT(registry-ga): if the configured registry URL is a static - // `.json` file, resolve directly from it (direct download, no sha256). - // 2. Otherwise use the Tabularium API + the TRACKED redirect download. - // 3. COMPAT(registry-ga): if the API doesn't know the plugin (it lives - // only in the legacy registry, not yet migrated), fall back to the - // configured legacy `registry.json`'s direct asset. - let (download_url, expected_sha256, target_version) = if let Some(res) = - crate::plugins::compat::resolve_static_asset( - base, - &plugin_id, - version.as_deref(), - &platform, - ) - .await - { - let asset = res?; - (asset.download_url, asset.expected_sha256, asset.version) - } else { - match resolve_api_install_asset(base, &plugin_id, version.as_deref(), &platform).await { - Ok(resolved) => resolved, - Err(api_err) => { - if api_err == super::package_kind::KIND_ERROR { - return Err(api_err); - } - // COMPAT(registry-ga): legacy-registry install fallback. - let legacy_url = crate::plugins::compat::legacy_registry_url(&config); - match crate::plugins::compat::fetch_static_asset( - &legacy_url, - &plugin_id, - version.as_deref(), - &platform, - ) - .await - { - Ok(asset) => (asset.download_url, asset.expected_sha256, asset.version), - Err(_) => return Err(api_err), - } - } - } - }; - // Identity/version verification against what the registry advertised - // happens inside download_and_install, while the bundle is still in its - // temp dir — a mismatching archive is discarded without ever touching an - // existing installation. - cancellation.check()?; - installer::download_and_install( - &plugin_id, - &download_url, - expected_sha256.as_deref(), - Some(&target_version), - cancellation, - ) - .await?; - - // Hot-register the new driver (no restart needed) - let plugin_cfg = config.plugins.as_ref().and_then(|m| m.get(&plugin_id)); - let interpreter_override = plugin_cfg.and_then(|c| c.interpreter.clone()); - let settings = plugin_cfg.map(|c| c.settings.clone()).unwrap_or_default(); - let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; - crate::plugins::manager::load_plugin_from_dir(&plugin_dir, interpreter_override, settings) - .await - .map_err(|e| format!("Plugin installed but failed to load: {}", e))?; - - crate::plugins::connection_metadata::notify_plugin_reload(&app, &plugin_id).await; - - Ok(()) -} - -#[tauri::command] pub fn cancel_plugin_install(plugin_id: String) -> bool { - crate::plugins::install_cancellation::cancel(&plugin_id) + crate::application::plugins::cancel_plugin_install(plugin_id).unwrap_or(false) } -#[tauri::command] -pub async fn uninstall_plugin(plugin_id: String) -> Result<(), String> { - // Unregister from in-memory driver registry first - crate::drivers::registry::unregister_driver(&plugin_id).await; - crate::drivers::registry::unregister_manifest(&plugin_id).await; - - // Remove from filesystem - installer::uninstall(&plugin_id)?; - - Ok(()) -} - -#[tauri::command] -pub async fn get_installed_plugins() -> Result, String> { - installer::list_installed() -} - -/// Stops the plugin process and removes the driver from the registry. -/// The plugin files remain on disk and can be re-enabled with `enable_plugin`. -#[tauri::command] pub async fn disable_plugin(plugin_id: String) -> Result<(), String> { - crate::drivers::registry::unregister_driver(&plugin_id).await; - crate::drivers::registry::unregister_manifest(&plugin_id).await; - Ok(()) -} - -/// Loads the plugin from disk and registers its driver, starting the plugin process. -#[tauri::command] -pub async fn enable_plugin(app: AppHandle, plugin_id: String) -> Result<(), String> { - let config = crate::config::load_config_internal(&app); - let plugin_cfg = config.plugins.as_ref().and_then(|m| m.get(&plugin_id)); - let interpreter_override = plugin_cfg.and_then(|c| c.interpreter.clone()); - let settings = plugin_cfg.map(|c| c.settings.clone()).unwrap_or_default(); - let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; - crate::plugins::manager::load_plugin_from_dir(&plugin_dir, interpreter_override, settings) - .await?; - crate::plugins::connection_metadata::notify_plugin_reload(&app, &plugin_id).await; - Ok(()) -} - -/// Reads a plugin's `.tabularium` manifest from disk and returns a PluginManifest. -/// Useful for retrieving setting definitions for disabled plugins. -#[tauri::command] -pub async fn get_plugin_manifest(plugin_id: String) -> Result { - let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; - - let config: ConfigManifest = installer::read_manifest(&plugin_dir) - .map_err(|e| format!("Failed to read manifest for '{}': {}", plugin_id, e))?; - - Ok(PluginManifest { - id: config.id.unwrap_or_else(|| config.name.clone()), - name: config.name, - version: config.version, - description: config.description, - default_port: config.default_port, - capabilities: config.capabilities, - is_builtin: false, - engine: config.engine, - paradigms: config.paradigms, - default_username: config.default_username.unwrap_or_default(), - color: config.color, - icon: config.icon, - settings: config.settings, - ui_extensions: config.ui_extensions, - explain_parsers: config.explain_parsers, - connection_fields: config.connection_fields, - type_mappings: config.type_mappings, - // `deprecated` is a built-in-only concept stamped at registration; - // external plugins read from disk are never deprecated by the app. - deprecated: None, - }) + crate::application::plugins::disable_plugin(plugin_id).await } /// Returns the absolute filesystem path of an installed plugin's directory. -#[tauri::command] +/// Desktop-only: browser RPC deliberately does not expose server filesystem paths. pub fn get_plugin_dir(plugin_id: String) -> Result { let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; plugin_dir .to_str() .ok_or_else(|| "Plugin path contains invalid UTF-8".to_string()) - .map(|s| s.to_string()) -} - -/// Opens the plugins directory in the OS file manager so the user can manage -/// plugin bundles manually (e.g. when an uninstall fails because the folder -/// on disk no longer matches what the app expects). -#[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(|e| format!("Failed to open plugins directory: {}", e)) -} - -/// Fetches a rich plugin preview from a Tabularium registry, used by the -/// `tabularis://` deep-link confirmation modal. When `registry_url` is -/// omitted the user's configured registry (or the built-in default) is -/// queried instead. Returns `RegistryPluginWithStatus` populated with the -/// installed version and a resolved `install_action` so the modal can show -/// Install / Update / "already installed". -/// -/// NB: the deeplink *preview* talks to the Tabularium API directly (no static -/// `registry.json` support). This is intentional — `tabularis://` links target -/// the new registry — so there is deliberately no `COMPAT(registry-ga)` marker -/// here. (`install_plugin` itself DOES support static registries, so the -/// catalogue install path stays fully backwards-compatible.) -#[tauri::command] -pub async fn fetch_tabularium_plugin_preview( - app: AppHandle, - slug: String, - registry_url: Option, - version: Option, -) -> Result { - let config = crate::config::load_config_internal(&app); - let base = registry_url - .as_deref() .map(str::to_string) - .unwrap_or_else(|| registry_base_url(&config).to_string()); - let mut plugin = crate::plugins::tabularium::fetch_plugin_detail(&base, &slug).await?; - plugin.registry_base_url = Some(base.trim_end_matches('/').to_string()); - - // Declarative previews must not traverse driver discovery/startup paths. - let (installed_version, platform) = if plugin.kind.as_deref() == Some("theme") { - crate::theme_packages::registry_key(&base)?; - (InstalledThemes::load(&base).version_of(&slug), "universal".to_string()) - } else { - ( - installer::list_installed()? - .into_iter() - .find(|i| i.id == slug) - .map(|i| i.version), - registry::get_current_platform(), - ) - }; - - // Target = the version the deeplink will install: the pinned version if the - // link specified one, otherwise the registry's latest. - let target = version - .as_deref() - .filter(|v| !v.is_empty()) - .map(str::to_string) - .unwrap_or_else(|| plugin.latest_version.clone()); - let action = registry::classify_install(installed_version.as_deref(), &target); - - let mut with_status = to_plugin_with_status(plugin, installed_version, &platform); - with_status.install_action = Some(action); - // Probe the target release's signature so the confirm modal can badge it - // (verified / unsigned / invalid) before the user commits to installing. - with_status.signature = - Some(crate::plugins::tabularium::check_release_signature(&base, &slug, &target).await); - Ok(with_status) -} - -/// Fetches a plugin's README from the Tabularium registry, locale-aware. -/// `locale` is the app UI language mapped to a registry locale; the registry -/// falls back on its own (usually to English) and reports the locale it -/// actually served. Legacy static registries have no README endpoint, so this -/// simply errors there and the frontend degrades to its no-README state. -#[tauri::command] -pub async fn fetch_plugin_readme( - app: AppHandle, - slug: String, - locale: Option, - registry_url: Option, -) -> Result { - let config = crate::config::load_config_internal(&app); - let base = registry_url - .as_deref() - .map(str::to_string) - .unwrap_or_else(|| registry_base_url(&config).to_string()); - crate::plugins::tabularium::fetch_plugin_readme(&base, &slug, locale.as_deref()).await } -/// Reads a file from an installed plugin's directory. -/// The `file_path` must be a relative path with no `..` components. -#[tauri::command] -pub fn read_plugin_file(plugin_id: String, file_path: String) -> Result { - if file_path.contains("..") || file_path.starts_with('/') || file_path.starts_with('\\') { - return Err( - "Invalid file path: must be relative and contain no '..' components".to_string(), - ); - } - let full_path = installer::resolve_plugin_dir(&plugin_id)?.join(&file_path); - fs::read_to_string(&full_path).map_err(|e| { - format!( - "Failed to read '{}' from plugin '{}': {}", - file_path, plugin_id, e - ) - }) -} 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/driver.rs b/src-tauri/src/plugins/driver.rs index 67be6b496..0496f99f0 100644 --- a/src-tauri/src/plugins/driver.rs +++ b/src-tauri/src/plugins/driver.rs @@ -2084,6 +2084,10 @@ pub(crate) fn test_manifest() -> PluginManifest { } } +#[cfg(test)] +#[path = "driver_resilience_tests.rs"] +mod resilience_tests; + /// Builds a fake, in-memory `RpcDriver` backed by `handle_request` instead of /// a real subprocess, with `connection_metadata` disabled. `pub(crate)` so /// other modules' tests (e.g. `mcp::tests`) can build one too; enable diff --git a/src-tauri/src/plugins/driver_resilience_tests.rs b/src-tauri/src/plugins/driver_resilience_tests.rs new file mode 100644 index 000000000..8b229da87 --- /dev/null +++ b/src-tauri/src/plugins/driver_resilience_tests.rs @@ -0,0 +1,29 @@ +use super::*; + +#[tokio::test] +async fn crashed_plugin_process_fails_pending_calls_without_hanging() { + let (sender, mut receiver) = mpsc::channel::(1); + tokio::spawn(async move { + let _pending_call = receiver.recv().await; + }); + let (shutdown_tx, _shutdown_rx) = oneshot::channel(); + let process = PluginProcess { + plugin_id: "crashed-plugin-test".to_string(), + route_selected_database: false, + accepting_calls: std::sync::atomic::AtomicBool::new(true), + manager_task: tokio::sync::Mutex::new(None), + sender, + next_id: AtomicU64::new(1), + shutdown_tx: tokio::sync::Mutex::new(Some(shutdown_tx)), + pid: None, + initialization_settings: None, + initialized: OnceCell::new(), + }; + + let result = tokio::time::timeout(Duration::from_millis(100), process.call("ping", json!({}))) + .await + .expect("a crashed plugin must release pending callers") + .unwrap_err(); + + assert_eq!(result, "Plugin process did not respond"); +} diff --git a/src-tauri/src/plugins/force_install.rs b/src-tauri/src/plugins/force_install.rs index 3a50b1769..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::{commands, 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,105 +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; - } - if let Err(e) = commands::install_plugin(app.clone(), plugin_id.to_string(), 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 @@ -181,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 @@ -260,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/installer.rs b/src-tauri/src/plugins/installer.rs index 4790c9d8f..d4c17feab 100644 --- a/src-tauri/src/plugins/installer.rs +++ b/src-tauri/src/plugins/installer.rs @@ -177,9 +177,28 @@ pub async fn download_and_install( expected_version: Option<&str>, cancellation: &InstallCancellation, ) -> Result<(), String> { - cancellation.check()?; let plugins_dir = get_plugins_dir()?; - let final_dir = super::layout::driver_destination(&plugins_dir, plugin_id)?; + download_and_install_into( + &plugins_dir, + plugin_id, + download_url, + expected_sha256, + expected_version, + cancellation, + ) + .await +} + +pub async fn download_and_install_into( + plugins_dir: &Path, + plugin_id: &str, + download_url: &str, + expected_sha256: Option<&str>, + expected_version: Option<&str>, + cancellation: &InstallCancellation, +) -> Result<(), String> { + cancellation.check()?; + let final_dir = super::layout::driver_destination(plugins_dir, plugin_id)?; let kind_dir = final_dir.parent().ok_or("Missing driver directory")?; fs::create_dir_all(kind_dir).map_err(|e| e.to_string())?; let tmp_dir = kind_dir.join(format!(".tmp-{}", plugin_id)); @@ -414,7 +433,7 @@ pub async fn download_and_install( // replacing files, otherwise the OS may keep them locked. Once this short // commit phase starts, installation is completed atomically rather than // leaving the existing plugin disabled. - let previous = super::layout::driver_candidates(&plugins_dir)? + let previous = super::layout::driver_candidates(plugins_dir)? .into_iter() .filter(|path| super::layout::driver_identity(path).as_deref() == Some(plugin_id)) .collect::>(); @@ -444,9 +463,13 @@ pub async fn download_and_install( pub fn uninstall(plugin_id: &str) -> Result<(), String> { let plugins_dir = get_plugins_dir()?; - super::layout::resolve_driver(&plugins_dir, plugin_id)?; + uninstall_from(&plugins_dir, plugin_id) +} + +pub fn uninstall_from(plugins_dir: &Path, plugin_id: &str) -> Result<(), String> { + super::layout::resolve_driver(plugins_dir, plugin_id)?; // Remove fallback copies first so uninstall cannot resurrect an older bundle. - for path in super::layout::driver_candidates(&plugins_dir)?.into_iter().rev() { + for path in super::layout::driver_candidates(plugins_dir)?.into_iter().rev() { if super::layout::driver_identity(&path).as_deref() == Some(plugin_id) { fs::remove_dir_all(&path) .map_err(|e| format!("Failed to remove plugin '{}': {}", plugin_id, e))?; @@ -464,13 +487,20 @@ pub fn resolve_plugin_dir(plugin_id: &str) -> Result { pub fn list_installed() -> Result, String> { let plugins_dir = get_plugins_dir()?; + Ok(list_installed_from(&plugins_dir)) +} + +pub fn list_installed_from(plugins_dir: &Path) -> Vec { let mut plugins = Vec::new(); - for path in super::layout::driver_directories(&plugins_dir)? { + let Ok(paths) = super::layout::driver_directories(plugins_dir) else { + return plugins; + }; + for path in paths { if let Ok(plugin) = read_plugin_info_from_dir(&path) { plugins.push(plugin); } } - Ok(plugins) + plugins } diff --git a/src-tauri/src/plugins/manager.rs b/src-tauri/src/plugins/manager.rs index 9fc2a39c7..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,8 +40,11 @@ pub struct PluginLoadError { pub error: String, } -#[tauri::command] pub fn get_plugin_startup_errors() -> Vec { + crate::application::plugins::get_plugin_startup_errors() +} + +pub fn take_plugin_startup_errors() -> Vec { let mut guard = STARTUP_ERRORS.lock().unwrap_or_else(|e| e.into_inner()); std::mem::take(&mut *guard) } @@ -106,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 @@ -154,7 +144,19 @@ pub async fn load_plugins_with_configs( } }; - let entries = match super::layout::driver_directories(&plugins_dir) { + load_plugins_from_dir(&plugins_dir, plugin_configs, enabled_ids).await; +} + +/// Load external drivers from a runtime-provided directory. +/// +/// Startup adapters resolve paths; plugin discovery and registration remain +/// platform-neutral and can therefore run without a Tauri `AppHandle`. +pub async fn load_plugins_from_dir( + plugins_dir: &Path, + plugin_configs: HashMap, + enabled_ids: Option<&[String]>, +) { + let entries = match super::layout::driver_directories(plugins_dir) { Ok(e) => e, Err(e) => { log::error!("Failed to read plugins directory: {}", e); 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/plugins/tests.rs b/src-tauri/src/plugins/tests.rs index fdbf88f8a..29ced8d3f 100644 --- a/src-tauri/src/plugins/tests.rs +++ b/src-tauri/src/plugins/tests.rs @@ -118,7 +118,8 @@ fn preserves_ui_extension_driver_filter_from_manifest() { { "slot": "connection-modal.connection_content", "module": "ui/dist/index.js", - "driver": "wordpress" + "driver": "wordpress", + "api_version": "0.1.1" }, { "slot": "data-grid.toolbar.actions", @@ -132,6 +133,7 @@ fn preserves_ui_extension_driver_filter_from_manifest() { let entries = manifest.ui_extensions.expect("ui_extensions present"); assert_eq!(entries[0].driver.as_deref(), Some("wordpress")); + assert_eq!(entries[0].api_version.as_deref(), Some("0.1.1")); assert_eq!(entries[1].driver, None); assert_eq!(entries[1].order, Some(10)); } diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs index 44a2265f0..faf636c5c 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -1,124 +1,8 @@ use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; -use crate::paths::get_app_config_dir; - -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EditorPreferences { pub tabs: Vec, pub active_tab_id: Option, } -/// Get the preferences directory path -fn get_preferences_dir() -> PathBuf { - let mut config_dir = get_app_config_dir(); - config_dir.push("preferences"); - config_dir -} - -/// Get the preferences file path for a specific connection -fn get_connection_preferences_path(connection_id: &str) -> PathBuf { - let mut prefs_dir = get_preferences_dir(); - prefs_dir.push(connection_id); - prefs_dir.push("preferences.json"); - prefs_dir -} - -/// Ensure the preferences directory exists for a connection -fn ensure_preferences_dir(connection_id: &str) -> Result<(), String> { - let mut prefs_dir = get_preferences_dir(); - prefs_dir.push(connection_id); - - fs::create_dir_all(&prefs_dir) - .map_err(|e| format!("Failed to create preferences directory: {}", e))?; - - Ok(()) -} - -#[tauri::command] -pub async fn save_editor_preferences( - connection_id: String, - preferences: EditorPreferences, -) -> Result<(), String> { - ensure_preferences_dir(&connection_id)?; - - let path = get_connection_preferences_path(&connection_id); - let json = serde_json::to_string_pretty(&preferences) - .map_err(|e| format!("Failed to serialize preferences: {}", e))?; - - fs::write(&path, json).map_err(|e| format!("Failed to write preferences file: {}", e))?; - - Ok(()) -} - -#[tauri::command] -pub async fn load_editor_preferences( - connection_id: String, -) -> Result, String> { - let path = get_connection_preferences_path(&connection_id); - - if !path.exists() { - return Ok(None); - } - - let content = - fs::read_to_string(&path).map_err(|e| format!("Failed to read preferences file: {}", e))?; - - let preferences: EditorPreferences = serde_json::from_str(&content) - .map_err(|e| format!("Failed to parse preferences file: {}", e))?; - - Ok(Some(preferences)) -} - -#[tauri::command] -pub async fn delete_editor_preferences(connection_id: String) -> Result<(), String> { - let path = get_connection_preferences_path(&connection_id); - - if path.exists() { - fs::remove_file(&path).map_err(|e| format!("Failed to delete preferences file: {}", e))?; - } - - Ok(()) -} - -#[tauri::command] -pub async fn list_all_preferences() -> Result, String> { - let prefs_dir = get_preferences_dir(); - - if !prefs_dir.exists() { - return Ok(HashMap::new()); - } - - let mut all_prefs = HashMap::new(); - - let entries = fs::read_dir(&prefs_dir) - .map_err(|e| format!("Failed to read preferences directory: {}", e))?; - - for entry in entries { - let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; - let path = entry.path(); - - if path.is_dir() { - if let Some(connection_id) = path.file_name().and_then(|n| n.to_str()) { - let pref_file = path.join("preferences.json"); - - if pref_file.exists() { - let content = fs::read_to_string(&pref_file).map_err(|e| { - format!("Failed to read preferences for {}: {}", connection_id, e) - })?; - - let preferences: EditorPreferences = - serde_json::from_str(&content).map_err(|e| { - format!("Failed to parse preferences for {}: {}", connection_id, e) - })?; - - all_prefs.insert(connection_id.to_string(), preferences); - } - } - } - } - - Ok(all_prefs) -} 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 e10a34db5..d6ebb6216 100644 --- a/src-tauri/src/query_history.rs +++ b/src-tauri/src/query_history.rs @@ -1,331 +1,6 @@ -use crate::config::load_config_internal; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use tauri::{AppHandle, Manager, Runtime, State}; -use tokio::sync::Mutex; -use uuid::Uuid; -const DEFAULT_MAX_HISTORY_ENTRIES: u32 = 500; - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct QueryHistoryEntry { - pub id: String, - pub sql: String, - pub executed_at: String, - pub execution_time_ms: Option, - pub status: String, - pub rows_affected: Option, - pub error: Option, - #[serde(default)] - pub database: Option, -} - -/// Response shape for `get_query_history`. `recovered_backup_path` is set -/// when the on-disk JSON could not be parsed and was renamed aside so the -/// app could start fresh; the UI surfaces a banner with the backup location -/// so the user can recover entries manually if needed. -#[derive(Debug, Serialize, Deserialize, Clone, Default)] -#[serde(rename_all = "camelCase")] -pub struct QueryHistoryResponse { - pub entries: Vec, - pub recovered_backup_path: Option, -} - -/// Serializes read-modify-write sequences against each connection's history -/// file so concurrent `addEntry` calls (e.g. one per statement in a -/// multi-statement batch) can't interleave and overwrite each other. -#[derive(Default)] -pub struct QueryHistoryState { - locks: Mutex>>>, -} - -async fn acquire_lock(state: &QueryHistoryState, connection_id: &str) -> Arc> { - let mut map = state.locks.lock().await; - map.entry(connection_id.to_string()) - .or_insert_with(|| Arc::new(Mutex::new(()))) - .clone() -} - -fn get_history_dir(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - let history_dir = config_dir.join("query_history"); - if !history_dir.exists() { - fs::create_dir_all(&history_dir).map_err(|e| e.to_string())?; - } - Ok(history_dir) -} - -fn get_history_path( - app: &AppHandle, - connection_id: &str, -) -> Result { - let dir = get_history_dir(app)?; - Ok(dir.join(format!("{}.json", connection_id))) -} - -/// Read history, recovering from corruption by renaming the bad file aside. -/// -/// Returns the parsed entries and, when recovery happened, the path of the -/// backup file. Callers that don't need to surface recovery info can use -/// the [`read_history`] wrapper. -fn read_history_with_recovery( - app: &AppHandle, - connection_id: &str, -) -> Result<(Vec, Option), String> { - let path = get_history_path(app, connection_id)?; - if !path.exists() { - return Ok((Vec::new(), None)); - } - let content = fs::read_to_string(&path).map_err(|e| e.to_string())?; - match serde_json::from_str::>(&content) { - Ok(entries) => Ok((entries, None)), - Err(parse_err) => { - let backup = backup_corrupt_file(&path).map_err(|e| { - format!( - "Query history JSON parse failed and backup also failed: {} (parse error: {})", - e, parse_err - ) - })?; - log::warn!( - "Query history file for connection '{}' was corrupt ({}); moved to {}", - connection_id, - parse_err, - backup.display() - ); - Ok((Vec::new(), Some(backup))) - } - } -} - -fn read_history( - app: &AppHandle, - connection_id: &str, -) -> Result, String> { - read_history_with_recovery(app, connection_id).map(|(entries, _)| entries) -} - -/// Rename a corrupt history file aside using a UTC timestamp suffix. If a -/// file already exists at the target backup path (unlikely but possible on -/// the same-millisecond retry) a short uuid suffix is appended. -pub(crate) fn backup_corrupt_file(path: &Path) -> Result { - let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%S%3f"); - let base = path.file_name().and_then(|n| n.to_str()).unwrap_or("history.json"); - let mut backup = path.with_file_name(format!("{}.corrupt-{}", base, timestamp)); - if backup.exists() { - backup = path.with_file_name(format!( - "{}.corrupt-{}-{}", - base, - timestamp, - Uuid::new_v4().simple() - )); - } - fs::rename(path, &backup).map_err(|e| e.to_string())?; - Ok(backup) -} - -/// Atomic write: serialise to a per-write temp file in the same directory, -/// then `rename` onto the target. `rename` within a filesystem is atomic on -/// POSIX/APFS, so a concurrent or crashed write can never leave the target -/// file half-written (which is the failure mode that produced the original -/// "extra data after array" corruption). -fn write_history( - app: &AppHandle, - connection_id: &str, - entries: &[QueryHistoryEntry], -) -> Result<(), String> { - let path = get_history_path(app, connection_id)?; - let content = serde_json::to_string_pretty(entries).map_err(|e| e.to_string())?; - atomic_write(&path, content.as_bytes()) -} - -pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> { - let dir = path.parent().ok_or_else(|| "history path has no parent".to_string())?; - let file_name = path - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("history.json"); - let tmp = dir.join(format!(".{}.tmp.{}", file_name, Uuid::new_v4().simple())); - if let Err(e) = fs::write(&tmp, bytes) { - let _ = fs::remove_file(&tmp); - return Err(e.to_string()); - } - if let Err(e) = fs::rename(&tmp, path) { - let _ = fs::remove_file(&tmp); - return Err(e.to_string()); - } - Ok(()) -} - -#[tauri::command] -pub async fn get_query_history( - app: AppHandle, - state: State<'_, QueryHistoryState>, - connection_id: String, -) -> Result { - let lock = acquire_lock(&state, &connection_id).await; - let _guard = lock.lock().await; - let (entries, backup) = read_history_with_recovery(&app, &connection_id)?; - Ok(QueryHistoryResponse { - entries, - recovered_backup_path: backup.map(|p| p.to_string_lossy().into_owned()), - }) -} - -#[tauri::command] -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 lock = acquire_lock(&state, &connection_id).await; - let _guard = lock.lock().await; - - let mut entries = read_history(&app, &connection_id)?; - - let config = load_config_internal(&app); - let max_entries = config - .query_history_max_entries - .unwrap_or(DEFAULT_MAX_HISTORY_ENTRIES) as usize; - - // Deduplicate: if the most recent entry has the same SQL and database, update it instead - if let Some(first) = entries.first_mut() { - if first.sql == sql && first.database == database { - first.executed_at = executed_at.clone(); - first.execution_time_ms = execution_time_ms; - first.status = status.clone(); - first.rows_affected = rows_affected; - first.error = error.clone(); - let updated = first.clone(); - write_history(&app, &connection_id, &entries)?; - return Ok(updated); - } - } - - let entry = QueryHistoryEntry { - id: Uuid::new_v4().to_string(), - sql, - executed_at, - execution_time_ms, - status, - rows_affected, - error, - database, - }; - - // Insert at the beginning (newest first) - entries.insert(0, entry.clone()); - - // Evict oldest entries if over the limit - if entries.len() > max_entries { - entries.truncate(max_entries); - } - - write_history(&app, &connection_id, &entries)?; - Ok(entry) -} - -#[tauri::command] -pub async fn delete_query_history_entry( - app: AppHandle, - state: State<'_, QueryHistoryState>, - connection_id: String, - id: String, -) -> Result<(), String> { - let lock = acquire_lock(&state, &connection_id).await; - let _guard = lock.lock().await; - - let mut entries = read_history(&app, &connection_id)?; - let original_len = entries.len(); - entries.retain(|e| e.id != id); - - if entries.len() == original_len { - return Err("History entry not found".to_string()); - } - - write_history(&app, &connection_id, &entries) -} - -#[tauri::command] -pub async fn clear_query_history( - app: AppHandle, - state: State<'_, QueryHistoryState>, - connection_id: String, -) -> Result<(), String> { - let lock = acquire_lock(&state, &connection_id).await; - let _guard = lock.lock().await; - - let path = get_history_path(&app, &connection_id)?; - if path.exists() { - fs::remove_file(path).map_err(|e| e.to_string())?; - } - Ok(()) -} - -/// Set `database = Some(database)` on any history entry whose `database` is currently -/// `None`. Returns the count of entries updated. -pub fn backfill_missing_database(entries: &mut [QueryHistoryEntry], database: &str) -> usize { - let mut updated = 0usize; - for entry in entries.iter_mut() { - if entry.database.is_none() { - entry.database = Some(database.to_string()); - updated += 1; - } - } - updated -} - -/// Backfill `database` on history entries for a connection where it is currently `None`. -/// Used when a connection transitions from single-db to multi-db: existing entries -/// without an explicit database get associated with the original single database. -/// -/// Acquires the per-connection [`QueryHistoryState`] lock so concurrent -/// `add_query_history_entry` calls can't race the read-modify-write sequence -/// and lose entries. -pub async fn backfill_missing_database_for_connection( - app: &AppHandle, - connection_id: &str, - database: &str, -) -> Result { - let state = app.state::(); - let lock = acquire_lock(&state, connection_id).await; - let _guard = lock.lock().await; - - let mut entries = read_history(app, connection_id)?; - let updated = backfill_missing_database(&mut entries, database); - if updated > 0 { - write_history(app, connection_id, &entries)?; - } - Ok(updated) -} - -/// Remove history file for a connection (called during connection deletion). -/// -/// Acquires the per-connection [`QueryHistoryState`] lock so an in-flight -/// `add_query_history_entry` (started before the connection was deleted) can't -/// recreate the file after we remove it. -pub async fn remove_history_for_connection( - app: &AppHandle, - connection_id: &str, -) -> Result<(), String> { - let state = app.state::(); - let lock = acquire_lock(&state, connection_id).await; - let _guard = lock.lock().await; - - let path = get_history_path(app, connection_id)?; - if path.exists() { - fs::remove_file(path).map_err(|e| e.to_string())?; - } - Ok(()) -} +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}; 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/bootstrap.rs b/src-tauri/src/runtime/bootstrap.rs new file mode 100644 index 000000000..ebdd0d74c --- /dev/null +++ b/src-tauri/src/runtime/bootstrap.rs @@ -0,0 +1,128 @@ +use super::RuntimeContext; +use crate::config::AppConfig; +use crate::drivers::{mysql, postgres, registry, sqlite}; +use crate::logger::{create_log_buffer, init_logger, SharedLogBuffer}; +use std::fs; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; + +const LOG_BUFFER_CAPACITY: usize = 1000; + +static DEBUG_MODE: AtomicBool = AtomicBool::new(false); +static LOG_BUFFER: OnceLock = OnceLock::new(); + +#[derive(Clone, Copy, Debug)] +pub struct BootstrapOptions { + pub load_external_plugins: bool, + pub run_connection_migrations: bool, +} + +impl Default for BootstrapOptions { + fn default() -> Self { + Self { + load_external_plugins: true, + run_connection_migrations: true, + } + } +} + +pub struct BootstrappedApplication { + pub context: RuntimeContext, + pub config: AppConfig, +} + +pub fn install_process_prerequisites() { + // rustls can have multiple providers linked through transitive dependencies; + // pin ring before sqlx or a plugin attempts its first TLS handshake. + let _ = rustls::crypto::ring::default_provider().install_default(); + sqlx::any::install_default_drivers(); +} + +pub fn initialize_logging(debug: bool) -> SharedLogBuffer { + DEBUG_MODE.store(debug, Ordering::Relaxed); + let buffer = create_log_buffer(LOG_BUFFER_CAPACITY); + let shared = LOG_BUFFER.get_or_init(|| buffer.clone()).clone(); + let level = if debug { + log::LevelFilter::Debug + } else { + crate::logger::resolve_log_level_from_env() + }; + init_logger(shared.clone(), level); + shared +} + +pub fn is_debug_mode() -> bool { + DEBUG_MODE.load(Ordering::Relaxed) +} + +pub fn get_log_buffer() -> SharedLogBuffer { + LOG_BUFFER + .get() + .expect("Log buffer not initialized") + .clone() +} + +pub async fn bootstrap_application( + context: RuntimeContext, + options: BootstrapOptions, +) -> Result { + fs::create_dir_all(context.paths.config_dir()).map_err(|error| { + format!( + "Failed to create application config directory {}: {error}", + context.paths.config_dir().display() + ) + })?; + fs::create_dir_all(context.paths.data_dir()).map_err(|error| { + format!( + "Failed to create application data directory {}: {error}", + context.paths.data_dir().display() + ) + })?; + + let config = load_config(context.paths.config_dir()); + register_builtin_drivers().await; + + if options.load_external_plugins { + crate::plugins::installer::migrate_legacy_plugins_dir(); + let plugins_dir = context.paths.plugins_dir(); + fs::create_dir_all(&plugins_dir).map_err(|error| { + format!( + "Failed to create plugins directory {}: {error}", + plugins_dir.display() + ) + })?; + crate::plugins::manager::load_plugins_from_dir( + &plugins_dir, + config.plugins.clone().unwrap_or_default(), + config.active_external_drivers.as_deref(), + ) + .await; + } + + if options.run_connection_migrations { + crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path( + &context.paths.connections_file(), + ) + .await + .ok(); + } + + Ok(BootstrappedApplication { context, config }) +} + +fn load_config(config_dir: &std::path::Path) -> AppConfig { + let path = config_dir.join("config.json"); + let mut config = fs::read_to_string(path) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .unwrap_or_default(); + crate::plugins::compat::migrate_legacy_config(&mut config); + crate::config::cache_config(&config); + config +} + +async fn register_builtin_drivers() { + registry::register_driver(mysql::MysqlDriver::new()).await; + registry::register_driver(postgres::PostgresDriver::new()).await; + registry::register_driver(sqlite::SqliteDriver::new()).await; +} diff --git a/src-tauri/src/runtime/events.rs b/src-tauri/src/runtime/events.rs new file mode 100644 index 000000000..bf8d9965f --- /dev/null +++ b/src-tauri/src/runtime/events.rs @@ -0,0 +1,19 @@ +use serde_json::Value; + +pub trait RuntimeEvents: Send + Sync { + fn emit(&self, event: &str, payload: Value) -> Result<(), String>; + + fn emit_to(&self, _session_id: uuid::Uuid, event: &str, payload: Value) -> Result<(), String> { + self.emit(event, payload) + } +} + +#[derive(Default)] +pub struct NoopRuntimeEvents; + +impl RuntimeEvents for NoopRuntimeEvents { + fn emit(&self, _event: &str, _payload: Value) -> Result<(), String> { + Ok(()) + } +} + diff --git a/src-tauri/src/runtime/lifecycle.rs b/src-tauri/src/runtime/lifecycle.rs new file mode 100644 index 000000000..f2a953203 --- /dev/null +++ b/src-tauri/src/runtime/lifecycle.rs @@ -0,0 +1,57 @@ +use std::sync::{Arc, Mutex}; + +type ShutdownHook = Box; + +#[derive(Clone, Default)] +pub struct ShutdownHooks { + hooks: Arc>>, +} + +impl ShutdownHooks { + pub fn register(&self, hook: impl Fn() + Send + Sync + 'static) { + self.hooks + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(Box::new(hook)); + } + + pub fn run(&self) { + for hook in self + .hooks + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + { + hook(); + } + } +} + +pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { + state.abort_background_jobs(); + release_pinned_sessions().await; + crate::pool_manager::close_all_pools().await; + crate::ssh_tunnel::stop_all_tunnels(); + crate::k8s_tunnel::stop_all_tunnels(); + crate::ssm_tunnel::stop_all_tunnels(); + crate::proxy::stop_all_forwards(); + crate::drivers::registry::shutdown_external_drivers().await; +} + +pub async fn release_pinned_sessions() { + if tokio::time::timeout( + std::time::Duration::from_secs(3), + crate::drivers::postgres::session::release_all(), + ) + .await + .is_err() + { + log::warn!("Releasing pinned PostgreSQL sessions timed out on exit"); + } +} + +pub fn start_approval_heartbeat( + context: &super::RuntimeContext, +) -> crate::heartbeat::HeartbeatTask { + crate::heartbeat::spawn_in(context.paths.config_dir().to_path_buf()) +} diff --git a/src-tauri/src/runtime/mod.rs b/src-tauri/src/runtime/mod.rs new file mode 100644 index 000000000..337dd74e8 --- /dev/null +++ b/src-tauri/src/runtime/mod.rs @@ -0,0 +1,43 @@ +pub mod bootstrap; +pub mod events; +pub mod lifecycle; +pub mod paths; +pub mod secrets; +pub mod state; + +use events::RuntimeEvents; +use paths::RuntimePaths; +use secrets::RuntimeSecrets; +use std::sync::Arc; + +#[derive(Clone)] +pub struct RuntimeContext { + pub paths: Arc, + pub events: Arc, + pub secrets: Arc, +} + +impl RuntimeContext { + pub fn new( + paths: Arc, + events: Arc, + secrets: Arc, + ) -> Self { + Self { + paths, + events, + secrets, + } + } + + pub fn system() -> Self { + Self::new( + Arc::new(paths::FixedRuntimePaths::system()), + Arc::new(events::NoopRuntimeEvents), + Arc::new(secrets::KeyringRuntimeSecrets), + ) + } +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/runtime/paths.rs b/src-tauri/src/runtime/paths.rs new file mode 100644 index 000000000..7dc73ba8f --- /dev/null +++ b/src-tauri/src/runtime/paths.rs @@ -0,0 +1,57 @@ +use std::path::{Path, PathBuf}; + +pub trait RuntimePaths: Send + Sync { + fn config_dir(&self) -> &Path; + fn data_dir(&self) -> &Path; + + fn plugins_dir(&self) -> PathBuf { + self.data_dir().join("plugins") + } + + fn connections_file(&self) -> PathBuf { + crate::paths::resolve_connections_path(self.config_dir()) + } +} + +#[derive(Clone, Debug)] +pub struct FixedRuntimePaths { + config_dir: PathBuf, + data_dir: PathBuf, + plugins_dir: PathBuf, +} + +impl FixedRuntimePaths { + pub fn new(config_dir: PathBuf, data_dir: PathBuf) -> Self { + Self { + config_dir, + plugins_dir: data_dir.join("plugins"), + data_dir, + } + } + + pub fn system() -> Self { + Self { + config_dir: crate::paths::get_app_config_dir(), + data_dir: crate::paths::get_app_data_dir(), + plugins_dir: crate::paths::get_plugins_dir(), + } + } +} + +impl RuntimePaths for FixedRuntimePaths { + fn plugins_dir(&self) -> PathBuf { + self.plugins_dir.clone() + } + + fn config_dir(&self) -> &Path { + &self.config_dir + } + + fn data_dir(&self) -> &Path { + &self.data_dir + } +} + +#[cfg(test)] +#[path = "paths_tests.rs"] +mod tests; diff --git a/src-tauri/src/runtime/paths_tests.rs b/src-tauri/src/runtime/paths_tests.rs new file mode 100644 index 000000000..c39e5f91e --- /dev/null +++ b/src-tauri/src/runtime/paths_tests.rs @@ -0,0 +1,14 @@ +use super::*; + +#[test] +fn system_plugins_stay_local_when_data_storage_is_redirected() { + let mut paths = FixedRuntimePaths::system(); + paths.data_dir = PathBuf::from("/custom/synced/storage"); + assert_eq!(paths.plugins_dir(), crate::paths::get_plugins_dir()); +} + +#[test] +fn explicit_fixture_paths_keep_plugins_inside_the_fixture() { + let paths = FixedRuntimePaths::new(PathBuf::from("config"), PathBuf::from("fixture-data")); + assert_eq!(paths.plugins_dir(), PathBuf::from("fixture-data/plugins")); +} diff --git a/src-tauri/src/runtime/secrets.rs b/src-tauri/src/runtime/secrets.rs new file mode 100644 index 000000000..336780645 --- /dev/null +++ b/src-tauri/src/runtime/secrets.rs @@ -0,0 +1,41 @@ +use keyring::Entry; + +const SERVICE_NAME: &str = "tabularis"; + +pub trait RuntimeSecrets: Send + Sync { + fn get(&self, account: &str) -> Result, String>; + fn set(&self, account: &str, secret: &str) -> Result<(), String>; + fn delete(&self, account: &str) -> Result<(), String>; +} + +#[derive(Default)] +pub struct KeyringRuntimeSecrets; + +impl RuntimeSecrets for KeyringRuntimeSecrets { + fn get(&self, account: &str) -> Result, String> { + match Entry::new(SERVICE_NAME, account) + .map_err(|error| error.to_string())? + .get_password() + { + Ok(secret) => Ok(Some(secret)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(error) => Err(error.to_string()), + } + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + Entry::new(SERVICE_NAME, account) + .and_then(|entry| entry.set_password(secret)) + .map_err(|error| error.to_string()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + match Entry::new(SERVICE_NAME, account) + .map_err(|error| error.to_string())? + .delete_credential() + { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(error) => Err(error.to_string()), + } + } +} diff --git a/src-tauri/src/runtime/state.rs b/src-tauri/src/runtime/state.rs new file mode 100644 index 000000000..b5104505d --- /dev/null +++ b/src-tauri/src/runtime/state.rs @@ -0,0 +1,60 @@ +use crate::application::connection_files::ImportEnvelopeCache; +use crate::commands::AbortHandleMap; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +pub struct ApplicationState { + 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: Arc, + pub pending_explain_file: Arc, + pub web_active_connections: Mutex>>, + pub web_approval_owners: Mutex>, + pub web_preferences: + Mutex>, +} + +impl ApplicationState { + pub fn abort_background_jobs(&self) { + abort_all(&self.query_cancellation.handles); + abort_all(&self.export_cancellation.handles); + abort_all(&self.dump_cancellation.handles); + } +} + +fn abort_all(handles: &Arc>) { + let pending = { + let mut handles = handles.lock().unwrap_or_else(|error| error.into_inner()); + handles + .drain() + .flat_map(|(_, handles)| handles) + .collect::>() + }; + + for handle in pending { + handle.abort(); + } +} + +impl Default for ApplicationState { + fn default() -> Self { + Self { + 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: 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 new file mode 100644 index 000000000..a9eca7c00 --- /dev/null +++ b/src-tauri/src/runtime/tests.rs @@ -0,0 +1,220 @@ +use super::bootstrap::{bootstrap_application, BootstrapOptions}; +use super::events::RuntimeEvents; +use super::lifecycle::ShutdownHooks; +use super::paths::RuntimePaths; +use super::secrets::RuntimeSecrets; +use super::state::ApplicationState; +use super::RuntimeContext; +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +struct TestPaths { + config_dir: PathBuf, + data_dir: PathBuf, +} + +impl RuntimePaths for TestPaths { + fn config_dir(&self) -> &Path { + &self.config_dir + } + + fn data_dir(&self) -> &Path { + &self.data_dir + } +} + +#[derive(Default)] +struct TestEvents { + emitted: Mutex>, +} + +impl RuntimeEvents for TestEvents { + fn emit(&self, event: &str, payload: Value) -> Result<(), String> { + self.emitted + .lock() + .map_err(|error| error.to_string())? + .push((event.to_string(), payload)); + Ok(()) + } +} + +#[derive(Default)] +struct TestSecrets; + +impl RuntimeSecrets for TestSecrets { + 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 bootstraps_application_services_without_a_webview() { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path().join("config"); + let data_dir = temp.path().join("data"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::write( + config_dir.join("config.json"), + r#"{"language":"en","activeExternalDrivers":[]}"#, + ) + .unwrap(); + + let context = RuntimeContext::new( + Arc::new(TestPaths { + config_dir, + data_dir, + }), + Arc::new(TestEvents::default()), + Arc::new(TestSecrets), + ); + + let bootstrapped = bootstrap_application( + context, + BootstrapOptions { + load_external_plugins: false, + run_connection_migrations: false, + }, + ) + .await + .unwrap(); + + assert_eq!(bootstrapped.config.language.as_deref(), Some("en")); + let driver_ids: Vec = crate::drivers::registry::list_drivers() + .await + .into_iter() + .filter(|manifest| manifest.is_builtin) + .map(|manifest| manifest.id) + .collect(); + assert_eq!(driver_ids, vec!["mysql", "postgres", "sqlite"]); + assert!(bootstrapped.context.paths.data_dir().ends_with("data")); +} + +#[test] +fn application_state_can_be_created_without_tauri() { + let _state = ApplicationState::default(); +} + +#[tokio::test] +async fn aborts_all_background_jobs_during_headless_shutdown() { + let state = ApplicationState::default(); + let query = tokio::spawn(std::future::pending::<()>()); + let export = tokio::spawn(std::future::pending::<()>()); + let dump = tokio::spawn(std::future::pending::<()>()); + + state + .query_cancellation + .handles + .lock() + .unwrap() + .insert("query".to_string(), vec![Arc::new(query.abort_handle())]); + state + .export_cancellation + .handles + .lock() + .unwrap() + .insert("export".to_string(), vec![Arc::new(export.abort_handle())]); + state + .dump_cancellation + .handles + .lock() + .unwrap() + .insert("dump".to_string(), vec![Arc::new(dump.abort_handle())]); + + state.abort_background_jobs(); + + assert!(query.await.unwrap_err().is_cancelled()); + assert!(export.await.unwrap_err().is_cancelled()); + assert!(dump.await.unwrap_err().is_cancelled()); + assert!(state.query_cancellation.handles.lock().unwrap().is_empty()); + assert!(state.export_cancellation.handles.lock().unwrap().is_empty()); + assert!(state.dump_cancellation.handles.lock().unwrap().is_empty()); +} + +#[test] +fn shutdown_hooks_run_without_a_tauri_runtime() { + let calls = Arc::new(AtomicUsize::new(0)); + let hooks = ShutdownHooks::default(); + let hook_calls = calls.clone(); + hooks.register(move || { + hook_calls.fetch_add(1, Ordering::Relaxed); + }); + + hooks.run(); + + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + + +#[tokio::test] +async fn approval_heartbeat_lives_only_for_its_runtime_lifecycle() { + let root = tempfile::tempdir().unwrap(); + let context = RuntimeContext::new( + Arc::new(super::paths::FixedRuntimePaths::new( + root.path().into(), + root.path().into(), + )), + Arc::new(TestEvents::default()), + Arc::new(TestSecrets), + ); + let heartbeat = super::lifecycle::start_approval_heartbeat(&context); + assert!(crate::heartbeat::is_alive_in(root.path())); + heartbeat.stop(); + assert!(crate::heartbeat::is_alive_in(root.path())); + heartbeat.stop(); + let heartbeat = super::lifecycle::start_approval_heartbeat(&context); + assert!(crate::heartbeat::is_alive_in(root.path())); + drop(heartbeat); + assert!(crate::heartbeat::is_alive_in(root.path())); + let expired = std::time::SystemTime::now() + - crate::heartbeat::STALE_AFTER + - std::time::Duration::from_secs(1); + filetime::set_file_mtime( + crate::heartbeat::heartbeat_path_in(root.path()), + filetime::FileTime::from_system_time(expired), + ).unwrap(); + assert!(!crate::heartbeat::is_alive_in(root.path())); +} + +#[tokio::test] +async fn stopping_approval_heartbeat_preserves_another_process_heartbeat() { + let root = tempfile::tempdir().unwrap(); + let context = RuntimeContext::new( + Arc::new(super::paths::FixedRuntimePaths::new( + root.path().into(), + root.path().into(), + )), + Arc::new(TestEvents::default()), + Arc::new(TestSecrets), + ); + let heartbeat = super::lifecycle::start_approval_heartbeat(&context); + let replacement = crate::heartbeat::Heartbeat { + pid: std::process::id().wrapping_add(1), + updated_at: "2026-10-15T00:00:00Z".into(), + }; + let path = crate::heartbeat::heartbeat_path_in(root.path()); + std::fs::write(&path, serde_json::to_vec(&replacement).unwrap()).unwrap(); + heartbeat.stop(); + let saved: crate::heartbeat::Heartbeat = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved, replacement); +} + +#[tokio::test] +async fn stopping_one_approval_host_preserves_liveness_for_another() { + let root = tempfile::tempdir().unwrap(); + let desktop = crate::heartbeat::spawn_in(root.path().to_path_buf()); + let web = crate::heartbeat::spawn_in(root.path().to_path_buf()); + web.stop(); + assert!(crate::heartbeat::is_alive_in(root.path())); + drop(desktop); +} diff --git a/src-tauri/src/saved_queries.rs b/src-tauri/src/saved_queries.rs index 78f79a7bc..80132e1ed 100644 --- a/src-tauri/src/saved_queries.rs +++ b/src-tauri/src/saved_queries.rs @@ -1,340 +1,5 @@ -use chrono::Utc; -use serde::{Deserialize, Serialize}; -use std::fs; -use std::path::PathBuf; -use tauri::{AppHandle, Runtime}; -use uuid::Uuid; -use crate::query_history::atomic_write; -use crate::saved_query_folders::{self, SavedQueryFolder}; +pub use crate::application::productivity::{SavedQuery, SavedQueryMeta}; -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct SavedQueryMeta { - pub id: String, - pub name: String, - pub filename: String, - pub connection_id: String, - #[serde(default)] - pub database: Option, - #[serde(default)] - pub created_at: Option, - #[serde(default)] - pub updated_at: Option, - /// `None` means Unfiled. Omitted from meta.json when unset so files from - /// before folders existed keep their exact shape. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub folder_id: Option, -} +pub use crate::application::productivity::backfill_saved_query_metadata as backfill_missing_database; -#[derive(Debug, Serialize, Deserialize)] -pub struct SavedQuery { - pub id: String, - pub name: String, - pub sql: String, - pub connection_id: String, - #[serde(default)] - pub database: Option, - #[serde(default)] - pub created_at: Option, - #[serde(default)] - pub updated_at: Option, - #[serde(default)] - pub folder_id: Option, -} - -fn get_queries_dir(_app: &AppHandle) -> Result { - let config_dir = crate::paths::get_app_config_dir(); - let queries_dir = config_dir.join("saved_queries"); - if !queries_dir.exists() { - fs::create_dir_all(&queries_dir).map_err(|e| e.to_string())?; - } - Ok(queries_dir) -} - -fn get_meta_path(app: &AppHandle) -> Result { - let dir = get_queries_dir(app)?; - Ok(dir.join("meta.json")) -} - -fn read_meta(app: &AppHandle) -> Result, String> { - let path = get_meta_path(app)?; - if !path.exists() { - return Ok(Vec::new()); - } - let content = fs::read_to_string(path).map_err(|e| e.to_string())?; - serde_json::from_str(&content).map_err(|e| e.to_string()) -} - -fn write_meta(app: &AppHandle, meta: &Vec) -> Result<(), String> { - let path = get_meta_path(app)?; - let content = serde_json::to_string_pretty(meta).map_err(|e| e.to_string())?; - atomic_write(&path, content.as_bytes()) -} - -fn get_folders_path(app: &AppHandle) -> Result { - Ok(get_queries_dir(app)?.join("folders.json")) -} - -/// Strict read, for commands that change folders: a corrupt file must not be -/// silently overwritten. -fn read_folders(app: &AppHandle) -> Result, String> { - saved_query_folders::read_folders_file(&get_folders_path(app)?) -} - -/// Lenient read, for commands that only display or return folders: a corrupt -/// file degrades to no folders (queries show as Unfiled) instead of failing. -fn read_folders_or_empty(app: &AppHandle) -> Vec { - match get_folders_path(app) { - Ok(path) => saved_query_folders::read_folders_file_lenient(&path), - Err(_) => Vec::new(), - } -} - -fn write_folders( - app: &AppHandle, - folders: &[SavedQueryFolder], -) -> Result<(), String> { - saved_query_folders::write_folders_file(&get_folders_path(app)?, folders) -} - -#[tauri::command] -pub async fn get_saved_queries( - app: AppHandle, - connection_id: String, -) -> Result, String> { - let meta_list = read_meta(&app)?; - let folders = read_folders_or_empty(&app); - let dir = get_queries_dir(&app)?; - - let mut results = Vec::new(); - - for meta in meta_list { - if meta.connection_id == connection_id { - let folder_id = saved_query_folders::resolve_folder_id(&meta, &folders); - let file_path = dir.join(&meta.filename); - let sql = if file_path.exists() { - fs::read_to_string(file_path).unwrap_or_default() - } else { - String::new() - }; - - results.push(SavedQuery { - id: meta.id, - name: meta.name, - sql, - connection_id: meta.connection_id, - database: meta.database, - created_at: meta.created_at, - updated_at: meta.updated_at, - folder_id, - }); - } - } - - Ok(results) -} - -#[tauri::command] -pub async fn save_query( - app: AppHandle, - connection_id: String, - name: String, - sql: String, - database: Option, -) -> Result { - let mut meta_list = read_meta(&app)?; - let dir = get_queries_dir(&app)?; - - let id = Uuid::new_v4().to_string(); - let filename = format!("{}.sql", id); - let file_path = dir.join(&filename); - - fs::write(file_path, &sql).map_err(|e| e.to_string())?; - - let now = Utc::now().to_rfc3339(); - - let new_meta = SavedQueryMeta { - id: id.clone(), - name: name.clone(), - filename, - connection_id: connection_id.clone(), - database: database.clone(), - created_at: Some(now.clone()), - updated_at: Some(now.clone()), - folder_id: None, - }; - - meta_list.push(new_meta); - write_meta(&app, &meta_list)?; - - Ok(SavedQuery { - id, - name, - sql, - connection_id, - database, - created_at: Some(now.clone()), - updated_at: Some(now), - folder_id: None, - }) -} - -#[tauri::command] -pub async fn update_saved_query( - app: AppHandle, - id: String, - name: String, - sql: String, - database: Option, -) -> Result { - let mut meta_list = read_meta(&app)?; - let folders = read_folders_or_empty(&app); - let dir = get_queries_dir(&app)?; - - let idx = meta_list - .iter() - .position(|m| m.id == id) - .ok_or("Query not found")?; - - let now = Utc::now().to_rfc3339(); - - // Update metadata - meta_list[idx].name = name.clone(); - meta_list[idx].database = database.clone(); - meta_list[idx].updated_at = Some(now.clone()); - write_meta(&app, &meta_list)?; - - // Update SQL file - let file_path = dir.join(&meta_list[idx].filename); - fs::write(file_path, &sql).map_err(|e| e.to_string())?; - - Ok(SavedQuery { - id: meta_list[idx].id.clone(), - name, - sql, - connection_id: meta_list[idx].connection_id.clone(), - database, - created_at: meta_list[idx].created_at.clone(), - updated_at: Some(now), - folder_id: saved_query_folders::resolve_folder_id(&meta_list[idx], &folders), - }) -} - -/// Set `database = Some(database)` on entries matching `connection_id` whose -/// `database` is currently `None`. Returns the count of entries updated. -pub fn backfill_missing_database( - meta_list: &mut [SavedQueryMeta], - connection_id: &str, - database: &str, -) -> usize { - let mut updated = 0usize; - for meta in meta_list.iter_mut() { - if meta.connection_id == connection_id && meta.database.is_none() { - meta.database = Some(database.to_string()); - updated += 1; - } - } - updated -} - -/// Backfill `database` on saved queries for a connection where it is currently `None`. -/// Used when a connection transitions from single-db to multi-db: existing favorites -/// without an explicit database get associated with the original single database. -pub fn backfill_missing_database_for_connection( - app: &AppHandle, - connection_id: &str, - database: &str, -) -> Result { - let mut meta_list = read_meta(app)?; - let updated = backfill_missing_database(&mut meta_list, connection_id, database); - if updated > 0 { - write_meta(app, &meta_list)?; - } - Ok(updated) -} - -#[tauri::command] -pub async fn delete_saved_query(app: AppHandle, id: String) -> Result<(), String> { - let mut meta_list = read_meta(&app)?; - let dir = get_queries_dir(&app)?; - - let idx = meta_list - .iter() - .position(|m| m.id == id) - .ok_or("Query not found")?; - let meta = meta_list.remove(idx); - - write_meta(&app, &meta_list)?; - - let file_path = dir.join(&meta.filename); - if file_path.exists() { - let _ = fs::remove_file(file_path); - } - - Ok(()) -} - -#[tauri::command] -pub async fn get_saved_query_folders( - app: AppHandle, - connection_id: String, -) -> Result, String> { - Ok(saved_query_folders::list_folders_for_connection( - &get_folders_path(&app)?, - &connection_id, - )) -} - -#[tauri::command] -pub async fn create_saved_query_folder( - app: AppHandle, - connection_id: String, - name: String, -) -> Result { - let mut folders = read_folders(&app)?; - let folder = saved_query_folders::create_folder( - &mut folders, - &connection_id, - &name, - &Utc::now().to_rfc3339(), - )?; - write_folders(&app, &folders)?; - Ok(folder) -} - -#[tauri::command] -pub async fn rename_saved_query_folder( - app: AppHandle, - id: String, - name: String, -) -> Result { - let mut folders = read_folders(&app)?; - let folder = saved_query_folders::rename_folder(&mut folders, &id, &name)?; - write_folders(&app, &folders)?; - Ok(folder) -} - -/// Only empty folders can be deleted; see `saved_query_folders::delete_folder`. -#[tauri::command] -pub async fn delete_saved_query_folder( - app: AppHandle, - id: String, -) -> Result<(), String> { - let mut folders = read_folders(&app)?; - let metas = read_meta(&app)?; - saved_query_folders::delete_folder(&mut folders, &metas, &id)?; - write_folders(&app, &folders) -} - -/// 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, - id: String, - folder_id: Option, -) -> Result<(), String> { - let mut metas = read_meta(&app)?; - let folders = read_folders(&app)?; - saved_query_folders::move_query(&mut metas, &folders, &id, folder_id.as_deref())?; - write_meta(&app, &metas) -} diff --git a/src-tauri/src/saved_query_folders.rs b/src-tauri/src/saved_query_folders.rs index c48e7133e..fd6418f07 100644 --- a/src-tauri/src/saved_query_folders.rs +++ b/src-tauri/src/saved_query_folders.rs @@ -9,7 +9,7 @@ use std::fs; use std::path::Path; use uuid::Uuid; -use crate::query_history::atomic_write; +use crate::application::productivity::atomic_write; use crate::saved_queries::SavedQueryMeta; /// Maximum folder name length in characters, mirrored by `maxLength` on the diff --git a/src-tauri/src/secret_store.rs b/src-tauri/src/secret_store.rs new file mode 100644 index 000000000..4e80fc2e9 --- /dev/null +++ b/src-tauri/src/secret_store.rs @@ -0,0 +1,341 @@ +//! Encrypted file store for the OS-keyring entries, for hosts without a +//! Secret Service (containers, headless servers). `TABULARIS_SECRET_STORE=file` +//! installs it as the process-wide `keyring` backend, so every `Entry::new` +//! (runtime secrets, keychain helpers, backups) lands here unchanged. +//! +//! The key comes from `TABULARIS_SECRET_KEY` or `TABULARIS_SECRET_KEY_FILE`. +//! Without either, a random key is generated next to the store: secrets then +//! survive restarts but are only as protected as the volume holding both. + +use std::any::Any; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use base64::engine::general_purpose::STANDARD as BASE64; +use base64::Engine; +use keyring::credential::{Credential, CredentialApi, CredentialBuilderApi}; +use serde::{Deserialize, Serialize}; + +use crate::export_crypto::{self, Sealed}; + +const STORE_ENV: &str = "TABULARIS_SECRET_STORE"; +const KEY_ENV: &str = "TABULARIS_SECRET_KEY"; +const KEY_FILE_ENV: &str = "TABULARIS_SECRET_KEY_FILE"; +const PATH_ENV: &str = "TABULARIS_SECRET_STORE_PATH"; +const STORE_FILE: &str = "secrets.enc.json"; +const GENERATED_KEY_FILE: &str = "secrets.key"; +const MIN_KEY_CHARS: usize = 16; +/// Encrypted with the derived key so a wrong key fails at startup instead of +/// on the first secret read. +const KEY_CHECK: &str = "tabularis-secret-store"; + +#[derive(Serialize, Deserialize)] +struct StoreFile { + version: u32, + salt: String, + m_cost: u32, + t_cost: u32, + p_cost: u32, + check: Sealed, + #[serde(default)] + entries: BTreeMap, +} + +pub struct FileSecretStore { + path: PathBuf, + key: [u8; 32], + file: Mutex, +} + +impl FileSecretStore { + /// Opens the store at `path`, creating it on first use. Fails when the + /// file exists but was written with another key. + pub fn open(path: PathBuf, passphrase: &str) -> Result { + if passphrase.chars().count() < MIN_KEY_CHARS { + return Err(format!( + "{KEY_ENV} must contain at least {MIN_KEY_CHARS} characters" + )); + } + if path.exists() { + let content = fs::read_to_string(&path) + .map_err(|error| format!("Cannot read {}: {error}", path.display()))?; + let file: StoreFile = serde_json::from_str(&content) + .map_err(|error| format!("Cannot parse {}: {error}", path.display()))?; + let salt = BASE64 + .decode(&file.salt) + .map_err(|error| format!("Invalid secret store salt: {error}"))?; + let key = export_crypto::derive_key( + passphrase, + &salt, + file.m_cost, + file.t_cost, + file.p_cost, + )?; + if export_crypto::open_with_key(&key, &file.check).as_deref() != Ok(KEY_CHECK) { + return Err(format!( + "The secret key does not match the secret store at {}", + path.display() + )); + } + return Ok(Self { + path, + key, + file: Mutex::new(file), + }); + } + + let salt = export_crypto::random_salt(); + let (m_cost, t_cost, p_cost) = ( + export_crypto::ARGON2_M_COST, + export_crypto::ARGON2_T_COST, + export_crypto::ARGON2_P_COST, + ); + let key = export_crypto::derive_key(passphrase, &salt, m_cost, t_cost, p_cost)?; + let store = Self { + path, + key, + file: Mutex::new(StoreFile { + version: 1, + salt: BASE64.encode(salt), + m_cost, + t_cost, + p_cost, + check: export_crypto::seal_with_key(&key, KEY_CHECK)?, + entries: BTreeMap::new(), + }), + }; + store.persist(&store.lock())?; + Ok(store) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, StoreFile> { + self.file.lock().unwrap_or_else(|error| error.into_inner()) + } + + fn get(&self, id: &str) -> Result>, String> { + let file = self.lock(); + let Some(sealed) = file.entries.get(id) else { + return Ok(None); + }; + let encoded = export_crypto::open_with_key(&self.key, sealed)?; + BASE64 + .decode(encoded) + .map(Some) + .map_err(|error| format!("Corrupt secret store entry: {error}")) + } + + fn set(&self, id: &str, secret: &[u8]) -> Result<(), String> { + let sealed = export_crypto::seal_with_key(&self.key, &BASE64.encode(secret))?; + let mut file = self.lock(); + let previous = file.entries.insert(id.to_string(), sealed); + self.persist(&file).inspect_err(|_| { + match previous { + Some(previous) => file.entries.insert(id.to_string(), previous), + None => file.entries.remove(id), + }; + }) + } + + /// `Ok(false)` when there was nothing to delete. + fn delete(&self, id: &str) -> Result { + let mut file = self.lock(); + let Some(previous) = file.entries.remove(id) else { + return Ok(false); + }; + self.persist(&file).inspect_err(|_| { + file.entries.insert(id.to_string(), previous); + })?; + Ok(true) + } + + /// Writes through a private temp file and a rename, so a crash never + /// leaves a truncated store. + fn persist(&self, file: &StoreFile) -> Result<(), String> { + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let content = serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?; + let temporary = self.path.with_extension("tmp"); + crate::persistence::write_private_file(&temporary, content)?; + fs::rename(&temporary, &self.path).map_err(|error| { + let _ = fs::remove_file(&temporary); + format!("Cannot write {}: {error}", self.path.display()) + }) + } +} + +/// Installs the file store as the `keyring` backend when +/// `TABULARIS_SECRET_STORE=file`. Must run before the first `keyring::Entry`. +pub fn install_from_env() -> Result<(), String> { + match std::env::var(STORE_ENV).as_deref() { + Err(_) | Ok("") | Ok("keyring") => return Ok(()), + Ok("file") => {} + Ok(other) => { + return Err(format!( + "Unknown {STORE_ENV} '{other}' (expected 'keyring' or 'file')" + )) + } + } + let directory = crate::paths::get_app_data_dir(); + let path = std::env::var_os(PATH_ENV) + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| directory.join(STORE_FILE)); + let passphrase = resolve_passphrase(&directory, &path)?; + let store = FileSecretStore::open(path.clone(), &passphrase)?; + log::info!("Storing secrets in the encrypted file {}", path.display()); + keyring::set_default_credential_builder(Box::new(FileCredentialBuilder(Arc::new(store)))); + Ok(()) +} + +fn resolve_passphrase(directory: &Path, store_path: &Path) -> Result { + // Compose and Helm pass unset values as empty strings. + if let Some(key) = std::env::var(KEY_ENV).ok().filter(|key| !key.is_empty()) { + return Ok(key); + } + if let Some(path) = std::env::var_os(KEY_FILE_ENV).filter(|path| !path.is_empty()) { + let path = PathBuf::from(path); + return fs::read_to_string(&path) + .map(|key| key.trim_end_matches(['\r', '\n']).to_string()) + .map_err(|error| format!("Cannot read {KEY_FILE_ENV} {}: {error}", path.display())); + } + generated_key(directory, store_path) +} + +/// The key generated on first start, reused afterwards. +fn generated_key(directory: &Path, store_path: &Path) -> Result { + use std::io::Write; + fs::create_dir_all(directory).map_err(|error| error.to_string())?; + // Keep the lock file: replacing its inode would let concurrent starts take different locks. + let mut options = fs::OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let lock = options + .open(directory.join(".secrets-key.lock")) + .map_err(|error| error.to_string())?; + fs2::FileExt::lock_exclusive(&lock).map_err(|error| error.to_string())?; + let path = directory.join(GENERATED_KEY_FILE); + match fs::read_to_string(&path) { + Ok(key) + if BASE64 + .decode(key.trim()) + .is_ok_and(|bytes| bytes.len() == 32) => + { + return Ok(key.trim().to_string()) + } + Ok(_) => { + if store_path.try_exists().map_err(|error| { + format!( + "Cannot inspect encrypted secret store {}: {error}", + store_path.display() + ) + })? { + return Err(format!("Generated key {} is incomplete. Restore the original key from backup; the existing secret store was not changed", path.display())); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if store_path.try_exists().map_err(|error| { + format!( + "Cannot inspect encrypted secret store {}: {error}", + store_path.display() + ) + })? { + return Err(format!("Generated key {} is missing. Restore the original key from backup; the existing secret store was not changed", path.display())); + } + } + Err(error) => { + return Err(format!( + "Cannot read generated key {}: {error}", + path.display() + )) + } + } + let mut bytes = [0u8; 32]; + use aes_gcm::aead::rand_core::RngCore; + aes_gcm::aead::OsRng.fill_bytes(&mut bytes); + let key = BASE64.encode(bytes); + let mut pending = + tempfile::NamedTempFile::new_in(directory).map_err(|error| error.to_string())?; + pending + .write_all(key.as_bytes()) + .map_err(|error| error.to_string())?; + pending + .as_file() + .sync_all() + .map_err(|error| error.to_string())?; + pending.persist(&path).map_err(|error| error.to_string())?; + log::warn!( + "No {KEY_ENV} set; generated {}. Anyone who can read the data volume can read the stored secrets", + path.display() + ); + Ok(key) +} + +struct FileCredentialBuilder(Arc); + +impl CredentialBuilderApi for FileCredentialBuilder { + fn build( + &self, + target: Option<&str>, + service: &str, + user: &str, + ) -> keyring::Result> { + Ok(Box::new(FileCredential { + store: self.0.clone(), + id: format!("{}\u{0}{}\u{0}{user}", target.unwrap_or_default(), service), + })) + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +struct FileCredential { + store: Arc, + id: String, +} + +impl std::fmt::Debug for FileCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FileCredential").finish_non_exhaustive() + } +} + +fn platform_error(error: String) -> keyring::Error { + keyring::Error::PlatformFailure(error.into()) +} + +impl CredentialApi for FileCredential { + fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> { + self.store.set(&self.id, secret).map_err(platform_error) + } + + fn get_secret(&self) -> keyring::Result> { + self.store + .get(&self.id) + .map_err(platform_error)? + .ok_or(keyring::Error::NoEntry) + } + + fn delete_credential(&self) -> keyring::Result<()> { + match self.store.delete(&self.id).map_err(platform_error)? { + true => Ok(()), + false => Err(keyring::Error::NoEntry), + } + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +#[cfg(test)] +#[path = "secret_store_tests.rs"] +mod tests; diff --git a/src-tauri/src/secret_store_tests.rs b/src-tauri/src/secret_store_tests.rs new file mode 100644 index 000000000..1caf99703 --- /dev/null +++ b/src-tauri/src/secret_store_tests.rs @@ -0,0 +1,183 @@ +use super::*; + +const PASSPHRASE: &str = "correct horse battery staple"; + +fn credential(store: &Arc, user: &str) -> Box { + FileCredentialBuilder(store.clone()) + .build(None, "tabularis", user) + .unwrap() +} + +#[test] +fn round_trips_secrets_across_reopen_without_storing_plaintext() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("secrets.enc.json"); + let store = Arc::new(FileSecretStore::open(path.clone(), PASSPHRASE).unwrap()); + + credential(&store, "conn-1:db").set_password("s3cret-value").unwrap(); + assert_eq!( + credential(&store, "conn-1:db").get_password().unwrap(), + "s3cret-value" + ); + assert!(!fs::read_to_string(&path).unwrap().contains("s3cret-value")); + + let reopened = Arc::new(FileSecretStore::open(path, PASSPHRASE).unwrap()); + assert_eq!( + credential(&reopened, "conn-1:db").get_password().unwrap(), + "s3cret-value" + ); +} + +#[test] +fn reports_missing_entries_as_no_entry() { + let temp = tempfile::tempdir().unwrap(); + let store = Arc::new( + FileSecretStore::open(temp.path().join("secrets.enc.json"), PASSPHRASE).unwrap(), + ); + let missing = credential(&store, "missing"); + + assert!(matches!(missing.get_password(), Err(keyring::Error::NoEntry))); + assert!(matches!( + missing.delete_credential(), + Err(keyring::Error::NoEntry) + )); + + missing.set_password("value").unwrap(); + missing.delete_credential().unwrap(); + assert!(matches!(missing.get_password(), Err(keyring::Error::NoEntry))); +} + +#[test] +fn keeps_targets_services_and_users_apart() { + let temp = tempfile::tempdir().unwrap(); + let store = Arc::new( + FileSecretStore::open(temp.path().join("secrets.enc.json"), PASSPHRASE).unwrap(), + ); + let builder = FileCredentialBuilder(store.clone()); + builder + .build(None, "tabularis", "a") + .unwrap() + .set_password("one") + .unwrap(); + builder + .build(Some("other"), "tabularis", "a") + .unwrap() + .set_password("two") + .unwrap(); + + assert_eq!(credential(&store, "a").get_password().unwrap(), "one"); + assert!(matches!( + builder.build(None, "other-service", "a").unwrap().get_password(), + Err(keyring::Error::NoEntry) + )); +} + +#[test] +fn rejects_a_wrong_or_short_key() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("secrets.enc.json"); + FileSecretStore::open(path.clone(), PASSPHRASE).unwrap(); + + let error = FileSecretStore::open(path.clone(), "a different passphrase") + .err() + .unwrap(); + assert!(error.contains("does not match"), "{error}"); + let error = FileSecretStore::open(path, "short").err().unwrap(); + assert!(error.contains("at least"), "{error}"); +} + +#[cfg(unix)] +#[test] +fn writes_the_store_privately() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("nested").join("secrets.enc.json"); + FileSecretStore::open(path.clone(), PASSPHRASE).unwrap(); + + let mode = fs::metadata(&path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); +} + +#[test] +fn generates_and_reuses_a_key_when_none_is_configured() { + let temp = tempfile::tempdir().unwrap(); + let first = generated_key(temp.path(), &temp.path().join(STORE_FILE)).unwrap(); + let second = generated_key(temp.path(), &temp.path().join(STORE_FILE)).unwrap(); + + assert_eq!(first, second); + assert!(first.chars().count() >= MIN_KEY_CHARS); + let store = temp.path().join("secrets.enc.json"); + FileSecretStore::open(store, &first).unwrap(); +} + +#[test] +fn repairs_an_incomplete_generated_key_only_without_an_existing_store() { + let temp = tempfile::tempdir().unwrap(); + let key_path = temp.path().join(GENERATED_KEY_FILE); + fs::write(&key_path, "").unwrap(); + let recovered = generated_key(temp.path(), &temp.path().join(STORE_FILE)).unwrap(); + assert!(recovered.chars().count() >= MIN_KEY_CHARS); + fs::write(temp.path().join(STORE_FILE), "existing encrypted data").unwrap(); + fs::write(&key_path, "short").unwrap(); + let error = generated_key(temp.path(), &temp.path().join(STORE_FILE)).unwrap_err(); + assert!(error.contains(GENERATED_KEY_FILE)); + assert_eq!(fs::read_to_string(&key_path).unwrap(), "short"); +} + +#[test] +fn concurrent_first_starts_publish_one_complete_generated_key() { + let temp = tempfile::tempdir().unwrap(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let root = temp.path().to_path_buf(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + generated_key(&root, &root.join(STORE_FILE)).unwrap() + }) + }) + .collect(); + let keys: Vec<_> = threads + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect(); + assert!(keys + .iter() + .all(|key| key == &keys[0] && key.len() >= MIN_KEY_CHARS)); + assert_eq!( + fs::read_to_string(temp.path().join(GENERATED_KEY_FILE)).unwrap(), + keys[0] + ); +} + +#[test] +fn rejects_a_truncated_base64_generated_key_without_changing_a_custom_store() { + let temp = tempfile::tempdir().unwrap(); + let store = temp.path().join("custom-store.json"); + let key = generated_key(temp.path(), &store).unwrap(); + fs::write(&store, "existing encrypted data").unwrap(); + fs::write(temp.path().join(GENERATED_KEY_FILE), &key[..24]).unwrap(); + let error = generated_key(temp.path(), &store).unwrap_err(); + assert!(error.contains(GENERATED_KEY_FILE)); + assert_eq!( + fs::read_to_string(&store).unwrap(), + "existing encrypted data" + ); + assert_eq!( + fs::read_to_string(temp.path().join(GENERATED_KEY_FILE)).unwrap(), + &key[..24] + ); +} + +#[cfg(unix)] +#[test] +fn does_not_replace_a_key_when_store_presence_cannot_be_checked() { + let temp = tempfile::tempdir().unwrap(); + let key_path = temp.path().join(GENERATED_KEY_FILE); + fs::write(&key_path, "short").unwrap(); + let parent = temp.path().join("not-a-directory"); + fs::write(&parent, "file").unwrap(); + assert!(generated_key(temp.path(), &parent.join(STORE_FILE)).is_err()); + assert_eq!(fs::read_to_string(&key_path).unwrap(), "short"); +} 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 2121dd58d..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"]; @@ -53,7 +51,7 @@ pub(crate) fn expand_sqlite_filename_with_home(value: &str, home: Option<&Path>) } } -fn connection_name(path: &Path) -> Result { +pub(crate) fn connection_name(path: &Path) -> Result { path.file_stem() .and_then(|name| name.to_str()) .filter(|name| !name.trim().is_empty()) @@ -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/ssh_tunnel.rs b/src-tauri/src/ssh_tunnel.rs index 46d8c2ef4..7e6751672 100644 --- a/src-tauri/src/ssh_tunnel.rs +++ b/src-tauri/src/ssh_tunnel.rs @@ -111,7 +111,7 @@ impl SshTunnel { remote_host: &str, remote_port: u16, ) -> Result { - Self::new_with_tcp_override( + Self::new_with_askpass( ssh_host, ssh_port, ssh_user, @@ -123,13 +123,16 @@ impl SshTunnel { remote_port, None, None, + None, ) } - /// Like [`Self::new`], but optionally dials `tcp_host:tcp_port` instead of - /// `ssh_host:ssh_port` (used when an HTTP/SOCKS proxy forward is in front - /// of the bastion). Host-key checks still use the logical `ssh_host`. - pub fn new_with_tcp_override( + /// Like [`Self::new`], but with an optional askpass bridge for interactive + /// passphrase prompts and an optional `tcp_host:tcp_port` to dial instead + /// of `ssh_host:ssh_port` (used when an HTTP/SOCKS proxy forward is in + /// front of the bastion). Host-key checks still use the logical `ssh_host`. + #[allow(clippy::too_many_arguments)] + pub fn new_with_askpass( ssh_host: &str, ssh_port: u16, ssh_user: &str, @@ -139,6 +142,7 @@ impl SshTunnel { ssh_allow_passphrase_prompt: bool, remote_host: &str, remote_port: u16, + askpass_server: Option, tcp_host: Option<&str>, tcp_port: Option, ) -> Result { @@ -172,6 +176,7 @@ impl SshTunnel { remote_host, remote_port, local_port, + askpass_server, connect_host, connect_port, ) { @@ -236,6 +241,7 @@ impl SshTunnel { remote_host: &str, remote_port: u16, local_port: u16, + askpass_server: Option, connect_host: &str, connect_port: u16, ) -> Result { @@ -300,6 +306,7 @@ impl SshTunnel { ssh_password, ssh_key_file, ssh_key_passphrase, + askpass_server, )?; let mut child = command.spawn().map_err(|e| { @@ -650,6 +657,28 @@ pub fn test_ssh_connection( ssh_key_file: Option<&str>, ssh_key_passphrase: Option<&str>, ssh_allow_passphrase_prompt: bool, +) -> Result { + test_ssh_connection_with_askpass( + ssh_host, + ssh_port, + ssh_user, + ssh_password, + ssh_key_file, + ssh_key_passphrase, + ssh_allow_passphrase_prompt, + None, + ) +} + +pub fn test_ssh_connection_with_askpass( + ssh_host: &str, + ssh_port: u16, + ssh_user: &str, + ssh_password: Option<&str>, + ssh_key_file: Option<&str>, + ssh_key_passphrase: Option<&str>, + ssh_allow_passphrase_prompt: bool, + askpass_server: Option, ) -> Result { let use_system_ssh = should_use_system_ssh(ssh_password, ssh_key_file); eprintln!( @@ -666,6 +695,7 @@ pub fn test_ssh_connection( ssh_key_file, ssh_key_passphrase, ssh_allow_passphrase_prompt, + askpass_server, ) { Err(e) if should_fall_back_to_russh(&e, ssh_password, ssh_key_passphrase) => { eprintln!( @@ -704,6 +734,7 @@ fn test_ssh_connection_system( ssh_key_file: Option<&str>, ssh_key_passphrase: Option<&str>, ssh_allow_passphrase_prompt: bool, + askpass_server: Option, ) -> Result { eprintln!("[SSH Test] Using system SSH (supports ~/.ssh/config)"); @@ -753,6 +784,7 @@ fn test_ssh_connection_system( ssh_password, ssh_key_file, ssh_key_passphrase, + askpass_server, )?; let output = command.output().map_err(|e| { @@ -911,6 +943,7 @@ fn configure_askpass( ssh_password: Option<&str>, ssh_key_file: Option<&str>, ssh_key_passphrase: Option<&str>, + askpass_server: Option, ) -> Result, String> { let password = ssh_password.filter(|p| !p.trim().is_empty()); let key_passphrase = ssh_key_passphrase.filter(|p| !p.trim().is_empty()); @@ -924,7 +957,10 @@ fn configure_askpass( key_path: key_path.map(str::to_string), allow_ui: ssh_allow_passphrase_prompt, }; - match crate::askpass::start_frontend_server_with(options) { + let server = askpass_server + .map(Ok) + .unwrap_or_else(|| crate::askpass::start_frontend_server_with(options)); + match server { Ok(server) => { server.configure_command(command)?; eprintln!( 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/task_manager.rs b/src-tauri/src/task_manager.rs deleted file mode 100644 index c0cec67a6..000000000 --- a/src-tauri/src/task_manager.rs +++ /dev/null @@ -1,385 +0,0 @@ -use std::collections::HashSet; -use std::sync::Mutex; - -use once_cell::sync::Lazy; -use serde::{Deserialize, Serialize}; -use sysinfo::{get_current_pid, Pid, ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System}; -use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder}; -use tokio::time::{sleep, Duration}; - -use crate::drivers::registry; -use crate::plugins::installer; -use crate::plugins::manager::load_plugin_from_dir; - -// --------------------------------------------------------------------------- -// Persistent System instance — required so that delta fields (cpu_usage, -// disk read_bytes / written_bytes) are computed between successive polls. -// --------------------------------------------------------------------------- -static SYSTEM: Lazy> = Lazy::new(|| { - Mutex::new(System::new_with_specifics( - RefreshKind::new().with_processes( - ProcessRefreshKind::new() - .with_cpu() - .with_disk_usage() - .with_memory(), - ), - )) -}); - -// --------------------------------------------------------------------------- -// Public types -// --------------------------------------------------------------------------- - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ChildProcessInfo { - pub pid: u32, - pub cpu_percent: f32, - pub memory_bytes: u64, - pub disk_read_bytes: u64, - pub disk_write_bytes: u64, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ProcessInfo { - pub plugin_id: String, - pub plugin_name: String, - pub pid: Option, - pub cpu_percent: f32, - pub memory_bytes: u64, - pub disk_read_bytes: u64, - pub disk_write_bytes: u64, - pub status: String, - pub children: Vec, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct TabularisChildProcess { - pub pid: u32, - pub name: String, - pub cpu_percent: f32, - pub memory_bytes: u64, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct TabularisSelfStats { - pub pid: u32, - /// RSS of the main tabularis process only (bytes). - pub self_memory_bytes: u64, - /// RSS sum across the whole process tree (main + all children, bytes). - pub total_memory_bytes: u64, - pub cpu_percent: f32, - pub disk_read_bytes: u64, - pub disk_write_bytes: u64, - pub child_count: usize, - // children are fetched on-demand via get_tabularis_children, not on every poll -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct SystemStats { - pub cpu_percent: f32, - pub memory_used: u64, - pub memory_total: u64, - pub disk_read_bytes: u64, - pub disk_write_bytes: u64, - pub process_count: usize, - pub tabularis: Option, -} - -// --------------------------------------------------------------------------- -// Helpers (called on blocking thread, inside spawn_blocking) -// --------------------------------------------------------------------------- - -fn refresh_and_collect_process_stats( - plugin_pids: Vec<(String, String, Option)>, -) -> Vec { - let mut sys = SYSTEM.lock().expect("system mutex poisoned"); - sys.refresh_processes_specifics( - ProcessesToUpdate::All, - true, - ProcessRefreshKind::new() - .with_cpu() - .with_disk_usage() - .with_memory(), - ); - sys.refresh_cpu_usage(); - - let mut processes: Vec = plugin_pids - .into_iter() - .map(|(plugin_id, plugin_name, pid_opt)| { - let (cpu_percent, memory_bytes, disk_read_bytes, disk_write_bytes, status, children) = - match pid_opt { - Some(pid) => { - let sysinfo_pid = Pid::from(pid as usize); - match sys.process(sysinfo_pid) { - Some(proc) => { - let du = proc.disk_usage(); - let mut children: Vec = sys - .processes() - .iter() - .filter(|(_, p)| p.parent() == Some(sysinfo_pid)) - .map(|(child_pid, child_proc)| { - let cdu = child_proc.disk_usage(); - ChildProcessInfo { - pid: child_pid.as_u32(), - cpu_percent: child_proc.cpu_usage(), - memory_bytes: child_proc.memory(), - disk_read_bytes: cdu.read_bytes, - disk_write_bytes: cdu.written_bytes, - } - }) - .collect(); - children.sort_by_key(|c| c.pid); - ( - proc.cpu_usage(), - proc.memory(), - du.read_bytes, - du.written_bytes, - "running".to_string(), - children, - ) - } - None => (0.0, 0, 0, 0, "unknown".to_string(), vec![]), - } - } - None => (0.0, 0, 0, 0, "stopped".to_string(), vec![]), - }; - - ProcessInfo { - plugin_id, - plugin_name, - pid: pid_opt, - cpu_percent, - memory_bytes, - disk_read_bytes, - disk_write_bytes, - status, - children, - } - }) - .collect(); - - processes.sort_by(|a, b| a.plugin_name.cmp(&b.plugin_name)); - processes -} - -fn refresh_and_collect_system_stats() -> SystemStats { - let mut sys = SYSTEM.lock().expect("system mutex poisoned"); - sys.refresh_processes_specifics( - ProcessesToUpdate::All, - true, - ProcessRefreshKind::new() - .with_cpu() - .with_disk_usage() - .with_memory(), - ); - sys.refresh_cpu_usage(); - sys.refresh_memory(); - - let cpu_percent = sys.global_cpu_usage(); - let memory_used = sys.used_memory(); - let memory_total = sys.total_memory(); - let process_count = sys.processes().len(); - - // Real-time disk I/O: sum of per-process deltas since last refresh. - let (disk_read_bytes, disk_write_bytes) = { - let mut read: u64 = 0; - let mut write: u64 = 0; - for proc in sys.processes().values() { - let du = proc.disk_usage(); - read = read.saturating_add(du.read_bytes); - write = write.saturating_add(du.written_bytes); - } - (read, write) - }; - - // Tabularis self stats. - let tabularis = get_current_pid().ok().map(|self_pid| { - // Collect descendants recursively. - let mut descendants: HashSet = HashSet::new(); - let mut queue = vec![self_pid]; - while let Some(current) = queue.pop() { - for (pid, proc) in sys.processes() { - if proc.parent() == Some(current) && !descendants.contains(pid) { - descendants.insert(*pid); - queue.push(*pid); - } - } - } - - // Main process stats. - let self_memory_bytes = sys.process(self_pid).map(|p| p.memory()).unwrap_or(0); - - let mut total_cpu: f32 = sys.process(self_pid).map(|p| p.cpu_usage()).unwrap_or(0.0); - let mut total_mem: u64 = self_memory_bytes; - let mut total_dr: u64 = sys - .process(self_pid) - .map(|p| p.disk_usage().read_bytes) - .unwrap_or(0); - let mut total_dw: u64 = sys - .process(self_pid) - .map(|p| p.disk_usage().written_bytes) - .unwrap_or(0); - - for pid in &descendants { - if let Some(proc) = sys.process(*pid) { - total_cpu += proc.cpu_usage(); - total_mem = total_mem.saturating_add(proc.memory()); - let du = proc.disk_usage(); - total_dr = total_dr.saturating_add(du.read_bytes); - total_dw = total_dw.saturating_add(du.written_bytes); - } - } - - TabularisSelfStats { - pid: self_pid.as_u32(), - self_memory_bytes, - total_memory_bytes: total_mem, - cpu_percent: total_cpu, - disk_read_bytes: total_dr, - disk_write_bytes: total_dw, - child_count: descendants.len(), - } - }); - - SystemStats { - cpu_percent, - memory_used, - memory_total, - disk_read_bytes, - disk_write_bytes, - process_count, - tabularis, - } -} - -fn collect_tabularis_children() -> Vec { - let mut sys = SYSTEM.lock().expect("system mutex poisoned"); - sys.refresh_processes_specifics( - ProcessesToUpdate::All, - true, - ProcessRefreshKind::new().with_cpu().with_memory(), - ); - - let self_pid = match get_current_pid() { - Ok(p) => p, - Err(_) => return vec![], - }; - - let mut descendants: HashSet = HashSet::new(); - let mut queue = vec![self_pid]; - while let Some(current) = queue.pop() { - for (pid, proc) in sys.processes() { - if proc.parent() == Some(current) && !descendants.contains(pid) { - descendants.insert(*pid); - queue.push(*pid); - } - } - } - - let mut children: Vec = descendants - .iter() - .filter_map(|pid| { - sys.process(*pid).map(|proc| TabularisChildProcess { - pid: pid.as_u32(), - name: proc.name().to_string_lossy().to_string(), - cpu_percent: proc.cpu_usage(), - memory_bytes: proc.memory(), - }) - }) - .collect(); - children.sort_by_key(|c| c.pid); - children -} - -// --------------------------------------------------------------------------- -// Tauri commands -// --------------------------------------------------------------------------- - -#[tauri::command] -pub async fn get_process_list() -> Result, String> { - let drivers = registry::list_drivers_with_pid().await; - - // Extract the data we need (non-blocking) before entering spawn_blocking. - let plugin_pids: Vec<(String, String, Option)> = drivers - .into_iter() - .filter(|(manifest, _)| !manifest.is_builtin) - .map(|(manifest, pid_opt)| (manifest.id, manifest.name, pid_opt)) - .collect(); - - let processes = - tokio::task::spawn_blocking(move || refresh_and_collect_process_stats(plugin_pids)) - .await - .map_err(|e| format!("Failed to collect process stats: {}", e))?; - - Ok(processes) -} - -#[tauri::command] -pub async fn get_system_stats() -> Result { - tokio::task::spawn_blocking(refresh_and_collect_system_stats) - .await - .map_err(|e| format!("Failed to collect system stats: {}", e)) -} - -#[tauri::command] -pub async fn get_tabularis_children() -> Result, String> { - tokio::task::spawn_blocking(collect_tabularis_children) - .await - .map_err(|e| format!("Failed to collect tabularis children: {}", e)) -} - -#[tauri::command] -pub async fn kill_plugin_process(plugin_id: String) -> Result<(), String> { - registry::unregister_driver(&plugin_id).await; - Ok(()) -} - -#[tauri::command] -pub async fn restart_plugin_process( - app: tauri::AppHandle, - plugin_id: String, -) -> Result<(), String> { - registry::unregister_driver(&plugin_id).await; - - // Give the OS a moment to release process resources before respawning. - sleep(Duration::from_millis(500)).await; - - let plugin_cfg = crate::config::load_config_internal(&app) - .plugins - .and_then(|mut m| m.remove(&plugin_id)); - let interpreter_override = plugin_cfg.as_ref().and_then(|c| c.interpreter.clone()); - let settings = plugin_cfg.map(|c| c.settings).unwrap_or_default(); - let plugin_dir = installer::resolve_plugin_dir(&plugin_id)?; - load_plugin_from_dir(&plugin_dir, interpreter_override, settings) - .await - .map_err(|e| format!("Failed to restart plugin '{}': {}", plugin_id, e))?; - - crate::plugins::connection_metadata::notify_plugin_reload(&app, &plugin_id).await; - - Ok(()) -} - -#[tauri::command] -pub async fn open_task_manager_window(app: AppHandle) -> Result<(), String> { - if let Some(existing) = app.get_webview_window("task-manager") { - existing - .set_focus() - .map_err(|e| format!("Failed to focus task manager window: {}", e))?; - return Ok(()); - } - - WebviewWindowBuilder::new( - &app, - "task-manager", - WebviewUrl::App("/task-manager".into()), - ) - .title("tabularis - Task Manager") - .inner_size(900.0, 600.0) - .min_inner_size(700.0, 450.0) - .center() - .decorations(crate::window_decorations::native_decorations_enabled()) - .build() - .map_err(|e| format!("Failed to create task manager window: {}", e))?; - - Ok(()) -} 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/archive.rs b/src-tauri/src/theme_packages/archive.rs index 0d43b17bf..0b6e60fb2 100644 --- a/src-tauri/src/theme_packages/archive.rs +++ b/src-tauri/src/theme_packages/archive.rs @@ -119,7 +119,7 @@ pub fn validate_theme_archive( ) -> Result { check_cancelled()?; let limits: ArchiveLimits = - serde_json::from_str(include_str!("../../../src/schemas/theme-limits-v1.json")) + serde_json::from_str(include_str!("../../../packages/web-ui/src/schemas/theme-limits-v1.json")) .map_err(|error| error.to_string())?; if bytes.len() > limits.archive_bytes { return Err("Theme archive exceeds the download byte limit".into()); 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 76d44b28f..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)?; @@ -57,22 +37,21 @@ pub fn preview_theme_document(source: String, name: String) -> Result, ) -> Result { - tauri::async_runtime::spawn_blocking(move || { - let bytes = lifecycle::read_local_archive(Path::new(&path))?; + crate::async_rt::spawn_blocking(move || { lifecycle::local_preview(&bytes, env!("CARGO_PKG_VERSION")) }) .await .map_err(|e| e.to_string())? } -#[tauri::command] -pub async fn install_local_theme_package( - app: AppHandle, - path: String, +/// Installs archive bytes that were previewed earlier. `read_archive` runs +/// after the cancellation guard is taken, so a slow read stays cancellable. +pub async fn install_local_package( + read_archive: impl FnOnce() -> Result, String> + Send + 'static, package_name: String, expected_digest: String, ) -> Result { @@ -80,9 +59,9 @@ pub async fn install_local_theme_package( let key = lifecycle::local_registry_key(); let guard = install_cancellation::begin(&operation_id(&key, &package_name))?; let cancellation = guard.cancellation().clone(); - let result = tauri::async_runtime::spawn_blocking(move || { + crate::async_rt::spawn_blocking(move || { cancellation.check()?; - let bytes = lifecycle::read_local_archive(Path::new(&path))?; + let bytes = read_archive()?; if format!("{:x}", Sha256::digest(&bytes)) != expected_digest { return Err("Local package changed after preview; preview it again".into()); } @@ -101,9 +80,26 @@ pub async fn install_local_theme_package( ) }) .await + .map_err(|e| e.to_string())? +} + +/// Reads a local archive from a host path with the package size limits. +pub fn read_local_archive(path: &Path) -> Result, String> { + lifecycle::read_local_archive(path) +} + +/// Largest accepted local theme archive. +pub const MAX_LOCAL_ARCHIVE_BYTES: usize = lifecycle::ARCHIVE_BYTES; + +pub async fn preview_local_theme_package( + path: String, +) -> Result { + let bytes = crate::async_rt::spawn_blocking(move || { + lifecycle::read_local_archive(Path::new(&path)) + }) + .await .map_err(|e| e.to_string())??; - refresh(&app); - Ok(result) + preview_local_package_bytes(bytes).await } #[derive(serde::Serialize)] @@ -114,13 +110,12 @@ pub struct ThemeRegistrySnapshot { pub plugins: Vec, } -#[tauri::command] -pub async fn fetch_theme_registry( - app: AppHandle, +/// Lists theme packages from the configured registry `base`. +pub async fn fetch_registry( + base: String, package_name: Option, expected_registry_key: Option, ) -> Result { - let base = registry_base(&app)?; let key = registry_key(&base)?; if expected_registry_key .as_ref() @@ -148,16 +143,14 @@ pub async fn fetch_theme_registry( }) } -/// Read-only details: never resolve a tracked download during discovery. -#[tauri::command] -pub async fn fetch_theme_package_detail( - app: AppHandle, +/// Read-only package details from the configured registry `base`. +pub async fn fetch_package_detail( + base: String, package_name: String, expected_registry_key: String, requested_registry_url: Option, ) -> Result { lifecycle::validate_package_name(&package_name)?; - let base = registry_base(&app)?; if registry_key(&base)? != expected_registry_key { return Err("Configured theme registry changed; refresh discovery".into()); } @@ -174,71 +167,54 @@ pub async fn fetch_theme_package_detail( Ok(detail) } -#[tauri::command] -pub async fn install_registry_theme( - app: AppHandle, - package_name: String, +/// Downloads and installs one registry package from `base`. +pub async fn install_registry( + base: String, expected_registry_key: String, + package_name: String, version: Option, ) -> Result { - let result = super::transport::install_registry_package( + super::transport::install_registry_package( &crate::paths::get_default_app_data_dir(), - ®istry_base(&app)?, + &base, &expected_registry_key, &package_name, version.as_deref(), env!("CARGO_PKG_VERSION"), ) - .await?; - refresh(&app); - Ok(result) + .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, +pub fn set_package_enabled( + registry_key: &str, + package_name: &str, enabled: bool, ) -> Result<(), String> { lifecycle::set_package_enabled( &crate::paths::get_default_app_data_dir(), - ®istry_key, - &package_name, + registry_key, + package_name, enabled, - )?; - refresh(&app); - Ok(()) + ) } -/// Recovery is an explicit action, never a catalog-read or hydration side effect. -#[tauri::command] -pub fn recover_theme_packages(app: AppHandle) -> Result, String> { +/// 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); - let mut failures = Vec::new(); match recover_theme_transactions(&root, &lifecycle::local_registry_key()) { - Ok(()) => refresh(&app), - Err(error) => failures.push(error), + Ok(()) => Vec::new(), + Err(error) => vec![error], } - Ok(failures) } -#[tauri::command] -pub fn uninstall_theme_package( - app: AppHandle, - registry_key: String, - package_name: String, -) -> Result { - let result = lifecycle::remove_package( +pub fn uninstall_package(registry_key: &str, package_name: &str) -> Result { + lifecycle::remove_package( &crate::paths::get_default_app_data_dir(), - ®istry_key, - &package_name, - )?; - refresh(&app); - Ok(result) + registry_key, + package_name, + ) } diff --git a/src-tauri/src/theme_packages/legacy.rs b/src-tauri/src/theme_packages/legacy.rs index efcc8bf51..cd0238a5b 100644 --- a/src-tauri/src/theme_packages/legacy.rs +++ b/src-tauri/src/theme_packages/legacy.rs @@ -8,7 +8,7 @@ pub(super) const LEGACY_BYTES: usize = 4 * 1024 * 1024; type RawObject = BTreeMap>; pub(super) fn builtin_themes() -> Vec { - serde_json::from_str(include_str!("../../../src/themes/builtin-themes.json")) + serde_json::from_str(include_str!("../../../packages/web-ui/src/themes/builtin-themes.json")) .expect("Bundled builtin catalog must be valid") } 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/theme_packages/validation.rs b/src-tauri/src/theme_packages/validation.rs index 5dae30b3b..ea0e4a0ea 100644 --- a/src-tauri/src/theme_packages/validation.rs +++ b/src-tauri/src/theme_packages/validation.rs @@ -18,7 +18,7 @@ struct Limits { } static LIMITS: Lazy = Lazy::new(|| { - serde_json::from_str(include_str!("../../../src/schemas/theme-limits-v1.json")) + serde_json::from_str(include_str!("../../../packages/web-ui/src/schemas/theme-limits-v1.json")) .expect("Bundled theme limits must be valid") }); @@ -32,12 +32,12 @@ fn compile_schema(source: &str) -> Result { static DEFINITION: Lazy> = Lazy::new(|| { compile_schema(include_str!( - "../../../src/schemas/theme-definition-v1.json" + "../../../packages/web-ui/src/schemas/theme-definition-v1.json" )) }); static MANIFEST: Lazy> = Lazy::new(|| { compile_schema(include_str!( - "../../../src/schemas/theme-package-v1.json" + "../../../packages/web-ui/src/schemas/theme-package-v1.json" )) }); diff --git a/src-tauri/src/transport/desktop/ai.rs b/src-tauri/src/transport/desktop/ai.rs new file mode 100644 index 000000000..cc545d631 --- /dev/null +++ b/src-tauri/src/transport/desktop/ai.rs @@ -0,0 +1,92 @@ +use crate::ai::*; +use crate::credential_cache::CredentialCache; +use crate::runtime::RuntimeContext; +use std::collections::HashMap; +use tauri::{AppHandle, Manager}; + +#[tauri::command] +pub fn clear_ai_models_cache(app: AppHandle) -> Result<(), String> { + clear_models_cache(&app.state::()) +} + +#[tauri::command] +pub async fn get_ai_models( + app: AppHandle, + force_refresh: bool, +) -> Result>, String> { + get_models( + &app.state::(), + &app.state::>(), + force_refresh, + ) + .await +} + +#[tauri::command] +pub async fn generate_ai_query(app: AppHandle, req: AiGenerateRequest) -> Result { + generate_query( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn explain_ai_query(app: AppHandle, req: AiExplainRequest) -> Result { + explain_query( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn analyze_ai_explain_plan( + app: AppHandle, + req: AiExplainRequest, +) -> Result { + analyze_explain_plan( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn generate_cell_name(app: AppHandle, req: AiCellNameRequest) -> Result { + generate_cellname( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn suggest_table_name( + app: AppHandle, + req: AiSuggestTableNameRequest, +) -> Result { + suggest_table_name_with_runtime( + &app.state::(), + &app.state::>(), + req, + ) + .await +} + +#[tauri::command] +pub async fn generate_tab_rename( + app: AppHandle, + req: AiTabRenameRequest, +) -> Result { + generate_tab_name( + &app.state::(), + &app.state::>(), + req, + ) + .await +} diff --git a/src-tauri/src/transport/desktop/ai_approval_watcher.rs b/src-tauri/src/transport/desktop/ai_approval_watcher.rs new file mode 100644 index 000000000..0c4b93a34 --- /dev/null +++ b/src-tauri/src/transport/desktop/ai_approval_watcher.rs @@ -0,0 +1,88 @@ +use crate::ai_approval; +use crate::ai_approval_watcher::*; +use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; +use std::sync::mpsc; +use std::time::Duration; +use tauri::{AppHandle, Emitter, Runtime}; + +/// Spawn the watcher + cleanup tasks. The watcher returns immediately if it +/// fails to initialise (e.g. unsupported filesystem); cleanup keeps running. +pub fn spawn(app: AppHandle) { + let app_for_watcher = app.clone(); + crate::async_rt::spawn_blocking(move || { + if let Err(e) = run_watcher(app_for_watcher) { + log::warn!("AI approval watcher disabled: {}", e); + } + }); + + let app_for_cleanup = app.clone(); + crate::async_rt::spawn(async move { + run_cleanup_loop(app_for_cleanup).await; + }); +} + +fn run_watcher(app: AppHandle) -> Result<(), String> { + let dir = ai_approval::approvals_dir_path(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + + let (tx, rx) = mpsc::channel::>(); + let mut watcher: RecommendedWatcher = + notify::recommended_watcher(tx).map_err(|e| e.to_string())?; + watcher + .watch(&dir, RecursiveMode::NonRecursive) + .map_err(|e| e.to_string())?; + + log::info!("AI approval watcher started on {}", dir.display()); + + // The watcher is dropped when this function returns; keep it alive for the + // process lifetime by looping forever. + for evt in rx { + match evt { + Ok(event) => handle_event(&app, &event), + Err(e) => log::warn!("approval watcher error: {}", e), + } + } + Ok(()) +} + +fn handle_event(app: &AppHandle, event: &Event) { + if !matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_)) { + return; + } + for path in &event.paths { + let name = match path.file_name().and_then(|s| s.to_str()) { + Some(n) => n, + None => continue, + }; + if !name.ends_with(".pending.json") { + continue; + } + let id = name.trim_end_matches(".pending.json").to_string(); + // The file may not yet be fully flushed when notify fires Create — + // try to read; if it fails this iteration we'll catch it on the + // next Modify event. + if let Ok(Some(pending)) = ai_approval::read_pending(&id) { + if let Err(e) = app.emit(PENDING_APPROVAL_EVENT, &pending) { + log::warn!("Failed to emit {}: {}", PENDING_APPROVAL_EVENT, e); + } + } + } +} + +async fn run_cleanup_loop(_app: AppHandle) { + let mut ticker = tokio::time::interval(Duration::from_secs(CLEANUP_INTERVAL_SECS)); + // Skip the immediate first tick. + ticker.tick().await; + loop { + ticker.tick().await; + let cleaned = + tokio::task::spawn_blocking(|| ai_approval::cleanup_expired(CLEANUP_MAX_AGE_SECS)) + .await + .ok() + .and_then(|r| r.ok()) + .unwrap_or(0); + if cleaned > 0 { + log::info!("Cleaned {} stale approval file(s)", cleaned); + } + } +} diff --git a/src-tauri/src/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/transport/desktop/connection_import_commands.rs b/src-tauri/src/transport/desktop/connection_import_commands.rs new file mode 100644 index 000000000..2f21ef168 --- /dev/null +++ b/src-tauri/src/transport/desktop/connection_import_commands.rs @@ -0,0 +1,115 @@ +//! Desktop transport wrappers for shared connection import and export services. + +#[cfg(feature = "desktop")] +use tauri::{AppHandle, Manager, Runtime}; + +use crate::application::connection_files::{ + self, ConnectionExportMode, ConnectionImportFile, GeneratedFile, ImportSourceInfo, + TabularisImportPreviewResult, +}; +use crate::connection_import::{analyzer, convert}; + +pub use crate::application::connection_files::ImportEnvelopeCache; + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn export_connections_file( + app: AppHandle, + mode: ConnectionExportMode, + password: Option, + connection_ids: Option>, +) -> Result { + connection_files::generate_export_file( + app.state::().inner(), + None, + mode, + password, + connection_ids, + ) + .await +} + +#[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<'_, std::sync::Arc>, + source_id: String, + include_passwords: bool, + file: Option, +) -> Result { + connection_files::preview_foreign_import( + app.state::().inner(), + cache.inner(), + None, + source_id, + include_passwords, + file, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn apply_connection_import( + app: AppHandle, + cache: tauri::State<'_, std::sync::Arc>, + connection_cache: tauri::State<'_, std::sync::Arc>, + credential_cache: tauri::State<'_, std::sync::Arc>, + source_id: String, + resolutions: Vec, +) -> Result<(), String> { + connection_files::apply_foreign_import( + app.state::().inner(), + connection_cache.inner().as_ref(), + credential_cache.inner().as_ref(), + cache.inner(), + None, + source_id, + resolutions, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn preview_tabularis_import_file( + app: AppHandle, + cache: tauri::State<'_, std::sync::Arc>, + file: ConnectionImportFile, + password: Option, +) -> Result { + connection_files::preview_tabularis_import_file( + app.state::().inner(), + cache.inner(), + None, + file, + password, + ) + .await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn apply_prepared_tabularis_import( + app: AppHandle, + cache: tauri::State<'_, std::sync::Arc>, + connection_cache: tauri::State<'_, std::sync::Arc>, + credential_cache: tauri::State<'_, std::sync::Arc>, + resolutions: Vec, +) -> Result<(), String> { + connection_files::apply_prepared_tabularis_import( + app.state::().inner(), + connection_cache.inner().as_ref(), + credential_cache.inner().as_ref(), + cache.inner(), + None, + resolutions, + ) + .await +} diff --git a/src-tauri/src/connection_window.rs b/src-tauri/src/transport/desktop/connection_window.rs similarity index 75% rename from src-tauri/src/connection_window.rs rename to src-tauri/src/transport/desktop/connection_window.rs index cef05c998..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; @@ -8,14 +9,28 @@ pub fn window_label(connection_id: &str) -> String { // Connection ids are UUID-like but sanitize defensively so any id is safe. let sanitized: String = connection_id .chars() - .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }) + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') { + c + } else { + '_' + } + }) .collect(); format!("connection-window-{}", sanitized) } +pub fn connection_route(connection_id: &str) -> String { + format!( + "/connections?connect={}&standalone=connection", + encode(connection_id) + ) +} + /// Open (or focus) a standalone window bound to a specific connection. The new -/// window loads the full app at `/` with a `?connect=` query param, which the -/// frontend reads on startup to auto-connect and jump to the editor. +/// 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, @@ -36,14 +51,14 @@ pub async fn open_connection_window( None => "tabularis".to_string(), }; - let url = format!("/?connect={}", encode(&connection_id)); + let url = connection_route(&connection_id); let window = WebviewWindowBuilder::new(&app, &label, WebviewUrl::App(url.into())) .title(&window_title) .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 @@ -61,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 66% rename from src-tauri/src/connection_window_tests.rs rename to src-tauri/src/transport/desktop/connection_window_tests.rs index 11b1cdd70..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::window_label; + use crate::transport::desktop::connection_window::{connection_route, window_label}; #[test] fn uuid_like_id_is_preserved() { @@ -19,14 +19,19 @@ mod tests { #[test] fn disallowed_characters_are_replaced_with_underscore() { // Slashes, spaces, dots and colons are not valid in window labels here. - assert_eq!( - window_label("a/b c.d:e"), - "connection-window-a_b_c_d_e" - ); + assert_eq!(window_label("a/b c.d:e"), "connection-window-a_b_c_d_e"); } #[test] fn empty_id_still_yields_prefix() { assert_eq!(window_label(""), "connection-window-"); } + + #[test] + fn standalone_route_is_encoded_and_refresh_identifiable() { + assert_eq!( + connection_route("connection/id"), + "/connections?connect=connection%2Fid&standalone=connection" + ); + } } diff --git a/src-tauri/src/transport/desktop/database_backup.rs b/src-tauri/src/transport/desktop/database_backup.rs new file mode 100644 index 000000000..e53ac3b24 --- /dev/null +++ b/src-tauri/src/transport/desktop/database_backup.rs @@ -0,0 +1,20 @@ +use crate::database_backup::{self, DatabaseBackupStatus}; +use crate::application::database_transfers::DumpCancellationState; +use crate::runtime::RuntimeContext; +use std::sync::Arc; +use tauri::State; + +#[tauri::command] +pub async fn get_database_backup_status(runtime: State<'_, RuntimeContext>) -> Result { + database_backup::get_database_backup_status(runtime.inner()).await +} + +#[tauri::command] +pub async fn run_database_backup_now(runtime: State<'_, RuntimeContext>, state: State<'_, Arc>) -> Result { + database_backup::run_database_backup_now(runtime.inner(), state.inner()).await +} + +#[tauri::command] +pub async fn cancel_database_backup(state: State<'_, Arc>) -> Result<(), String> { + database_backup::cancel_database_backup(state.inner()).await +} 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..06ee61174 --- /dev/null +++ b/src-tauri/src/transport/desktop/mod.rs @@ -0,0 +1,673 @@ +//! 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 database_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, + database_backup::get_database_backup_status, + database_backup::run_database_backup_now, + database_backup::cancel_database_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/transport/desktop/notebooks.rs b/src-tauri/src/transport/desktop/notebooks.rs new file mode 100644 index 000000000..74c3d2564 --- /dev/null +++ b/src-tauri/src/transport/desktop/notebooks.rs @@ -0,0 +1,103 @@ +use crate::application::notebooks::{execute, NotebookCommand}; +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( + app.state::().paths.config_dir(), + NotebookCommand::Create { + connection_id, + notebook_id, + content, + }, + )?; + Ok(()) +} + +#[tauri::command] +pub async fn save_notebook( + app: AppHandle, + connection_id: String, + notebook_id: String, + content: String, +) -> Result<(), String> { + execute( + app.state::().paths.config_dir(), + NotebookCommand::Save { + connection_id, + notebook_id, + content, + }, + )?; + Ok(()) +} + +#[tauri::command] +pub async fn load_notebook( + app: AppHandle, + connection_id: String, + notebook_id: String, +) -> Result, String> { + let value = execute( + app.state::().paths.config_dir(), + NotebookCommand::Load { + connection_id, + notebook_id, + }, + )?; + serde_json::from_value(value).map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn delete_notebook( + app: AppHandle, + connection_id: String, + notebook_id: String, +) -> Result<(), String> { + execute( + app.state::().paths.config_dir(), + NotebookCommand::Delete { + connection_id, + notebook_id, + }, + )?; + Ok(()) +} + +#[tauri::command] +pub async fn rename_notebook( + app: AppHandle, + connection_id: String, + notebook_id: String, + title: String, +) -> Result<(), String> { + execute( + app.state::().paths.config_dir(), + NotebookCommand::Rename { + connection_id, + notebook_id, + title, + }, + )?; + Ok(()) +} + +#[tauri::command] +pub async fn list_notebooks( + app: AppHandle, + connection_id: String, +) -> Result, String> { + let value = execute( + 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..36d24debf --- /dev/null +++ b/src-tauri/src/transport/desktop/runtime/lifecycle.rs @@ -0,0 +1,17 @@ +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()); + use tauri::Manager; + crate::database_backup::spawn_database_backup_scheduler( + app.state::().inner().clone(), + app.state::>().inner().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/transport/desktop/task_manager.rs b/src-tauri/src/transport/desktop/task_manager.rs new file mode 100644 index 000000000..b1c27af03 --- /dev/null +++ b/src-tauri/src/transport/desktop/task_manager.rs @@ -0,0 +1,63 @@ +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, +}; + +#[cfg_attr(feature = "desktop", tauri::command)] +pub async fn get_process_list() -> Result, String> { + operations::get_process_list().await +} + +#[cfg_attr(feature = "desktop", tauri::command)] +pub async fn get_system_stats() -> Result { + operations::get_system_stats().await +} + +#[cfg_attr(feature = "desktop", tauri::command)] +pub async fn get_tabularis_children() -> Result, String> { + operations::get_tabularis_children().await +} + +#[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>, + plugin_id: String, +) -> Result<(), String> { + 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") { + existing + .set_focus() + .map_err(|error| format!("Failed to focus task manager window: {error}"))?; + return Ok(()); + } + + WebviewWindowBuilder::new( + &app, + "task-manager", + WebviewUrl::App("/task-manager".into()), + ) + .title("tabularis - Task Manager") + .inner_size(900.0, 600.0) + .min_inner_size(700.0, 450.0) + .center() + .decorations(crate::transport::desktop::window_decorations::native_decorations_enabled()) + .build() + .map_err(|error| format!("Failed to create task manager window: {error}"))?; + + Ok(()) +} 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/transport/desktop/ui_state_commands.rs b/src-tauri/src/transport/desktop/ui_state_commands.rs new file mode 100644 index 000000000..e194501b4 --- /dev/null +++ b/src-tauri/src/transport/desktop/ui_state_commands.rs @@ -0,0 +1,42 @@ +//! Desktop entry points for the shared UI state store. + +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, + keys: Option>, +) -> Result { + execute(&app.state::(), UiStateCommand::Get { keys }).await +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn set_ui_state( + app: AppHandle, + key: String, + value: Value, +) -> Result<(), String> { + execute( + &app.state::(), + UiStateCommand::Set { key, value }, + ) + .await?; + Ok(()) +} + +#[cfg(feature = "desktop")] +#[tauri::command] +pub async fn delete_ui_state(app: AppHandle, key: String) -> Result<(), String> { + execute( + &app.state::(), + UiStateCommand::Delete { key }, + ) + .await?; + Ok(()) +} 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 new file mode 100644 index 000000000..3819b6872 --- /dev/null +++ b/src-tauri/src/transport/mod.rs @@ -0,0 +1,3 @@ +#[cfg(feature = "desktop")] +pub mod desktop; +pub mod web; diff --git a/src-tauri/src/transport/web/auth.rs b/src-tauri/src/transport/web/auth.rs new file mode 100644 index 000000000..8d90aedf2 --- /dev/null +++ b/src-tauri/src/transport/web/auth.rs @@ -0,0 +1,621 @@ +use crate::application::AuthorizationLevel; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use sha2::{Digest, Sha256}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fmt; +use std::net::IpAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use url::{Host, Url}; +use uuid::Uuid; + +pub const SESSION_COOKIE_NAME: &str = "tabularis_session"; +pub const CSRF_HEADER_NAME: &str = "x-tabularis-csrf"; +pub const PROXY_SECRET_HEADER_NAME: &str = "x-tabularis-proxy-secret"; +pub const PROXY_USER_HEADER_NAME: &str = "x-tabularis-user"; +pub(crate) const MAX_SESSIONS: usize = 1024; + +#[derive(Clone, Debug)] +pub struct LocalSessionSecurityConfig { + pub bootstrap_ttl: Duration, + pub session_ttl: Duration, + pub max_body_bytes: usize, +} + +impl Default for LocalSessionSecurityConfig { + fn default() -> Self { + Self { + bootstrap_ttl: Duration::from_secs(60), + session_ttl: Duration::from_secs(8 * 60 * 60), + max_body_bytes: 1024 * 1024, + } + } +} + +#[derive(Clone, Debug)] +pub struct LoginRateLimitConfig { + pub max_failures: usize, + pub window: Duration, + pub lockout: Duration, +} + +impl Default for LoginRateLimitConfig { + fn default() -> Self { + Self { + max_failures: 5, + window: Duration::from_secs(60), + lockout: Duration::from_secs(5 * 60), + } + } +} + +#[derive(Clone, Debug)] +pub struct RemoteSessionSecurityConfig { + pub trusted_proxies: Vec, + pub public_origin: String, + pub allowed_origins: Vec, + pub session_ttl: Duration, + pub max_body_bytes: usize, + pub authorization: AuthorizationLevel, + pub rate_limit: LoginRateLimitConfig, +} + +pub enum RemoteAuthentication { + Password { hash: TokenHash, length: usize }, + Proxy { hash: TokenHash, length: usize }, +} + +impl RemoteAuthentication { + pub fn password(secret: &str) -> Self { + Self::Password { + hash: hash_token(secret), + length: secret.len(), + } + } + + pub fn proxy(secret: &str) -> Self { + Self::Proxy { + hash: hash_token(secret), + length: secret.len(), + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AuthenticationError { + InvalidCredentials, + RateLimited, + UnsupportedMode, + SessionLimitReached, +} + +#[derive(Clone)] +pub struct LocalSessionSecurity { + inner: Arc, +} + +struct SecurityInner { + trusted_proxies: Vec, + public_origin: String, + public_host: String, + allowed_origins: HashSet, + allowed_hosts: HashSet, + secure_cookie: bool, + remote: bool, + authorization: AuthorizationLevel, + authentication: Authentication, + config: SessionSecurityConfig, + state: Mutex, +} + +#[derive(Clone, Copy)] +enum Authentication { + LocalBootstrap, + Password(TokenHash), + Proxy(TokenHash), +} + +#[derive(Clone)] +struct SessionSecurityConfig { + session_ttl: Duration, + max_body_bytes: usize, + rate_limit: LoginRateLimitConfig, +} + +struct SecurityState { + bootstrap: Option, + sessions: HashMap, + login_attempts: HashMap, +} + +/// Failed password logins of one client. Counting per client keeps one +/// attacker from locking every user out. +#[derive(Default)] +struct LoginAttempts { + failures: VecDeque, + blocked_until: Option, +} + +/// Clients whose failures are remembered at once; the least recently failing +/// one is forgotten first. +const MAX_TRACKED_LOGIN_CLIENTS: usize = 4096; + +struct ExpiringToken { + hash: TokenHash, + expires_at: Instant, +} + +struct SessionRecord { + csrf_token: String, + expires_at: Instant, + authorization: AuthorizationLevel, + remote: bool, +} + +type TokenHash = [u8; 32]; + +pub struct BootstrapToken(String); + +#[derive(Clone)] +pub struct IssuedSession { + pub cookie_value: String, + pub max_age_seconds: u64, + session_id: Uuid, +} + +#[derive(Clone)] +pub struct AuthenticatedSession { + token_hash: TokenHash, + pub(crate) expires_at: Instant, + pub csrf_token: String, + authorization: AuthorizationLevel, + remote: bool, +} + +impl LocalSessionSecurity { + pub fn new( + expected_origin: String, + config: LocalSessionSecurityConfig, + ) -> Result<(Self, BootstrapToken), String> { + let (origin, host) = parse_origin(&expected_origin, false)?; + let bootstrap_token = generate_token(); + let bootstrap = ExpiringToken { + hash: hash_token(&bootstrap_token), + expires_at: Instant::now() + config.bootstrap_ttl, + }; + let security = Self { + inner: Arc::new(SecurityInner { + trusted_proxies: Vec::new(), + public_origin: origin.clone(), + public_host: host.clone(), + allowed_origins: HashSet::from([origin]), + allowed_hosts: HashSet::from([host]), + secure_cookie: false, + remote: false, + authorization: AuthorizationLevel::LocalAdmin, + authentication: Authentication::LocalBootstrap, + config: SessionSecurityConfig { + session_ttl: config.session_ttl, + max_body_bytes: config.max_body_bytes, + rate_limit: LoginRateLimitConfig::default(), + }, + state: Mutex::new(SecurityState { + bootstrap: Some(bootstrap), + sessions: HashMap::new(), + login_attempts: HashMap::new(), + }), + }), + }; + + Ok((security, BootstrapToken(bootstrap_token))) + } + + pub fn new_remote( + config: RemoteSessionSecurityConfig, + authentication: RemoteAuthentication, + ) -> Result { + if config.rate_limit.max_failures == 0 { + return Err("Remote login rate limit must allow at least one attempt".to_string()); + } + let (public_origin, public_host) = parse_origin(&config.public_origin, true)?; + let mut allowed_origins = HashSet::new(); + let mut allowed_hosts = HashSet::new(); + for origin in &config.allowed_origins { + let (origin, host) = parse_origin(origin, true)?; + allowed_origins.insert(origin); + allowed_hosts.insert(host); + } + if !allowed_origins.contains(&public_origin) { + return Err("The public Web UI URL must be included in --allowed-origin".to_string()); + } + allowed_hosts.insert(public_host.clone()); + // Only a loopback origin may be plain HTTP (see `parse_origin`), and + // browsers drop `Secure` cookies there. + let secure_cookie = public_origin.starts_with("https://"); + + let authentication = match authentication { + RemoteAuthentication::Password { hash, length } if length >= 12 => { + Authentication::Password(hash) + } + RemoteAuthentication::Proxy { hash, length } if length >= 32 => { + Authentication::Proxy(hash) + } + RemoteAuthentication::Password { .. } => { + return Err("TABULARIS_WEB_PASSWORD must contain at least 12 characters".to_string()) + } + RemoteAuthentication::Proxy { .. } => { + return Err( + "TABULARIS_WEB_PROXY_SECRET must contain at least 32 characters".to_string(), + ) + } + }; + + Ok(Self { + inner: Arc::new(SecurityInner { + trusted_proxies: config.trusted_proxies, + public_origin, + public_host, + allowed_origins, + allowed_hosts, + secure_cookie, + remote: true, + authorization: config.authorization, + authentication, + config: SessionSecurityConfig { + session_ttl: config.session_ttl, + max_body_bytes: config.max_body_bytes, + rate_limit: config.rate_limit, + }, + state: Mutex::new(SecurityState { + bootstrap: None, + sessions: HashMap::new(), + login_attempts: HashMap::new(), + }), + }), + }) + } + + pub fn expected_origin(&self) -> &str { + &self.inner.public_origin + } + + pub fn expected_host(&self) -> &str { + &self.inner.public_host + } + + pub fn origin_allowed(&self, origin: &str) -> bool { + parse_origin(origin, self.inner.remote) + .ok() + .is_some_and(|(origin, _)| self.inner.allowed_origins.contains(&origin)) + } + + pub fn host_allowed(&self, host: &str) -> bool { + self.inner + .allowed_hosts + .contains(&host.to_ascii_lowercase()) + } + + pub fn max_body_bytes(&self) -> usize { + self.inner.config.max_body_bytes + } + + pub fn secure_cookie(&self) -> bool { + self.inner.secure_cookie + } + + pub fn is_remote(&self) -> bool { + self.inner.remote + } + + pub fn password_authentication(&self) -> bool { + matches!(self.inner.authentication, Authentication::Password(_)) + } + + pub fn proxy_authentication(&self) -> bool { + matches!(self.inner.authentication, Authentication::Proxy(_)) + } + + pub fn consume_bootstrap(&self, candidate: &str) -> Option { + if !matches!(self.inner.authentication, Authentication::LocalBootstrap) { + return None; + } + let now = Instant::now(); + let candidate_hash = hash_token(candidate); + let mut state = self.lock_state(); + let bootstrap = state.bootstrap.as_ref()?; + if bootstrap.expires_at <= now || bootstrap.hash != candidate_hash { + if bootstrap.expires_at <= now { + state.bootstrap = None; + } + return None; + } + state.bootstrap = None; + self.issue_session(&mut state, now).ok() + } + + pub(crate) fn login_client(&self, peer: Option, forwarded_for: Option<&str>) -> IpAddr { + login_client(peer, forwarded_for, &self.inner.trusted_proxies) + } + + pub fn authenticate_password( + &self, + candidate: &str, + client: IpAddr, + ) -> Result { + let Authentication::Password(expected) = self.inner.authentication else { + return Err(AuthenticationError::UnsupportedMode); + }; + self.authenticate_remote(expected, candidate, client) + } + + pub fn authenticate_proxy( + &self, + candidate: &str, + user: &str, + ) -> Result { + let Authentication::Proxy(expected) = self.inner.authentication else { + return Err(AuthenticationError::UnsupportedMode); + }; + let valid_user = + !user.is_empty() && user.len() <= 256 && !user.chars().any(char::is_control); + // No lockout: the 32+ character secret cannot be brute-forced, and a shared + // lockout would let anyone reaching the port deny every proxied user. + if hash_token(candidate) != expected || !valid_user { + return Err(AuthenticationError::InvalidCredentials); + } + let mut state = self.lock_state(); + self.issue_session(&mut state, Instant::now()) + } + + pub fn authenticate(&self, cookie_value: &str) -> Option { + let now = Instant::now(); + let token_hash = hash_token(cookie_value); + let state = self.lock_state(); + let session = state.sessions.get(&token_hash)?; + if session.expires_at <= now { + return None; + } + + Some(AuthenticatedSession { + token_hash, + expires_at: session.expires_at, + csrf_token: session.csrf_token.clone(), + authorization: session.authorization, + remote: session.remote, + }) + } + + pub(crate) fn take_expired_sessions(&self) -> Vec { + let now = Instant::now(); + let mut expired = Vec::new(); + self.lock_state().sessions.retain(|token_hash, session| { + if session.expires_at > now { + return true; + } + expired.push(session_id(*token_hash)); + false + }); + expired + } + + pub fn logout(&self, session: &AuthenticatedSession) { + self.lock_state().sessions.remove(&session.token_hash); + } + + fn authenticate_remote( + &self, + expected: TokenHash, + candidate: &str, + client: IpAddr, + ) -> Result { + let now = Instant::now(); + let limit = &self.inner.config.rate_limit; + let mut state = self.lock_state(); + state.login_attempts.retain(|_, attempts| { + attempts.blocked_until.is_some_and(|until| until > now) + || attempts + .failures + .back() + .is_some_and(|last| now.duration_since(*last) < limit.window) + }); + if !state.login_attempts.contains_key(&client) + && state.login_attempts.len() >= MAX_TRACKED_LOGIN_CLIENTS + { + // Fail closed: untracked attempts cannot bypass a lockout or displace tracked clients. + return Err(AuthenticationError::RateLimited); + } + let attempts = state.login_attempts.entry(client).or_default(); + if attempts.blocked_until.is_some_and(|until| until > now) { + return Err(AuthenticationError::RateLimited); + } + attempts.blocked_until = None; + while attempts + .failures + .front() + .is_some_and(|attempt| now.duration_since(*attempt) >= limit.window) + { + attempts.failures.pop_front(); + } + + if hash_token(candidate) != expected { + attempts.failures.push_back(now); + if attempts.failures.len() >= limit.max_failures { + attempts.blocked_until = Some(now + limit.lockout); + } + return Err(AuthenticationError::InvalidCredentials); + } + + state.login_attempts.remove(&client); + self.issue_session(&mut state, now) + } + + fn issue_session( + &self, + state: &mut SecurityState, + now: Instant, + ) -> Result { + if state + .sessions + .values() + .filter(|session| session.expires_at > now) + .count() + >= MAX_SESSIONS + { + return Err(AuthenticationError::SessionLimitReached); + } + let cookie_value = generate_token(); + let token_hash = hash_token(&cookie_value); + let csrf_token = generate_token(); + state.sessions.insert( + token_hash, + SessionRecord { + csrf_token, + expires_at: now + self.inner.config.session_ttl, + authorization: self.inner.authorization, + remote: self.inner.remote, + }, + ); + + Ok(IssuedSession { + cookie_value, + max_age_seconds: self.inner.config.session_ttl.as_secs(), + session_id: session_id(token_hash), + }) + } + + fn lock_state(&self) -> std::sync::MutexGuard<'_, SecurityState> { + self.inner + .state + .lock() + .unwrap_or_else(|error| error.into_inner()) + } +} + +/// Only explicitly configured proxies may supply the client address. +pub(crate) fn login_client(peer: Option, forwarded_for: Option<&str>, trusted_proxies: &[ipnet::IpNet]) -> IpAddr { + let peer = peer.unwrap_or(IpAddr::from([0, 0, 0, 0])); + let address = match peer { + IpAddr::V6(address) => address.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(peer), + _ => peer, + }; + if !trusted_proxies.iter().any(|network| network.contains(&address)) { + return peer; + } + forwarded_for + .and_then(|header| header.rsplit(',').next()) + .and_then(|last| last.trim().parse().ok()) + .unwrap_or(peer) +} + +impl AuthenticatedSession { + pub(crate) fn event_scope(&self) -> Uuid { + session_id(self.token_hash) + } + + pub fn authorization(&self) -> AuthorizationLevel { + self.authorization + } + + pub fn is_remote(&self) -> bool { + self.remote + } +} + +impl IssuedSession { + pub(crate) fn session_id(&self) -> Uuid { + self.session_id + } +} + +impl BootstrapToken { + pub fn expose(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for BootstrapToken { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("BootstrapToken([REDACTED])") + } +} + +impl fmt::Debug for LocalSessionSecurity { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("LocalSessionSecurity") + .field("public_origin", &self.inner.public_origin) + .field("allowed_origins", &self.inner.allowed_origins) + .field("secure_cookie", &self.inner.secure_cookie) + .field("remote", &self.inner.remote) + .field("authorization", &self.inner.authorization) + .field("credentials", &"[REDACTED]") + .finish() + } +} + +/// Remote origins must be HTTPS, except a loopback host: a container published +/// on `127.0.0.1` is reached as `http://localhost:` and never crosses a +/// network the browser does not own. +fn parse_origin(origin: &str, require_https: bool) -> Result<(String, String), String> { + let parsed = Url::parse(origin).map_err(|_| "Invalid Web UI origin".to_string())?; + let valid_scheme = if require_https { + parsed.scheme() == "https" || (parsed.scheme() == "http" && is_loopback_origin(&parsed)) + } else { + parsed.scheme() == "http" + }; + if !valid_scheme + || parsed.username() != "" + || parsed.password().is_some() + || parsed.query().is_some() + || parsed.fragment().is_some() + || parsed.path() != "/" + { + return Err(if require_https { + "Remote Web UI origins must be HTTPS (or loopback HTTP) origins without paths, queries, or credentials" + .to_string() + } else { + "Invalid local Web UI origin".to_string() + }); + } + + let host = parsed + .host() + .ok_or_else(|| "Web UI origin is missing a host".to_string())?; + let host = match host { + Host::Domain(host) => host.to_ascii_lowercase(), + Host::Ipv4(host) => host.to_string(), + Host::Ipv6(host) => format!("[{host}]"), + }; + let host = match parsed.port() { + Some(port) => format!("{host}:{port}"), + None => host, + }; + Ok((parsed.origin().ascii_serialization(), host)) +} + +fn is_loopback_origin(url: &Url) -> bool { + match url.host() { + Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + Some(Host::Ipv4(ip)) => ip.is_loopback(), + Some(Host::Ipv6(ip)) => ip.is_loopback(), + None => false, + } +} + +fn generate_token() -> String { + let mut bytes = [0_u8; 32]; + bytes[..16].copy_from_slice(Uuid::new_v4().as_bytes()); + bytes[16..].copy_from_slice(Uuid::new_v4().as_bytes()); + URL_SAFE_NO_PAD.encode(bytes) +} + +fn hash_token(token: &str) -> TokenHash { + Sha256::digest(token.as_bytes()).into() +} + +fn session_id(token_hash: TokenHash) -> Uuid { + let mut bytes = [0_u8; 16]; + bytes.copy_from_slice(&token_hash[..16]); + Uuid::from_bytes(bytes) +} diff --git a/src-tauri/src/transport/web/contract.rs b/src-tauri/src/transport/web/contract.rs new file mode 100644 index 000000000..06f44d722 --- /dev/null +++ b/src-tauri/src/transport/web/contract.rs @@ -0,0 +1,151 @@ +use crate::application::AuthorizationLevel; +use serde::{Deserialize, Serialize}; + +pub const WEB_API_VERSION: &str = "v1"; + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionNegotiation { + pub api_version: String, + pub server_version: String, + pub server_build: ServerBuildInformation, + pub authenticated: bool, + pub csrf_token: String, + pub access: WebSessionAccessPolicy, + pub capabilities: WebTransportCapabilities, + pub query_response_policy: WebQueryResponsePolicy, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WebSessionAccessPolicy { + pub remote: bool, + pub authorization_level: String, + pub high_risk_capabilities: bool, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WebTransportCapabilities { + pub rpc: bool, + pub events: bool, + pub uploads: bool, + pub downloads: bool, + pub plugin_assets: bool, + pub mcp_host_configuration: bool, + pub server_file_browser: bool, + pub native_updater: bool, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerBuildInformation { + pub target: String, + pub profile: String, + pub commit: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WebQueryResponsePolicy { + pub max_rows_per_page: u32, + pub max_response_bytes: usize, + pub streaming: bool, +} + +impl SessionNegotiation { + pub fn skeleton() -> Self { + Self::new( + false, + String::new(), + false, + false, + AuthorizationLevel::LocalAdmin, + ) + } + + pub fn authenticated(csrf_token: String, mcp_host_configuration: bool) -> Self { + Self::authenticated_with_access( + csrf_token, + mcp_host_configuration, + false, + AuthorizationLevel::LocalAdmin, + ) + } + + pub fn authenticated_with_access( + csrf_token: String, + mcp_host_configuration: bool, + remote: bool, + authorization: AuthorizationLevel, + ) -> Self { + Self::new( + true, + csrf_token, + mcp_host_configuration, + remote, + authorization, + ) + } + + pub fn with_server_file_browser(mut self, enabled: bool) -> Self { + self.capabilities.server_file_browser = enabled; + self + } + + fn new( + authenticated: bool, + csrf_token: String, + mcp_host_configuration: bool, + remote: bool, + authorization: AuthorizationLevel, + ) -> Self { + Self { + api_version: WEB_API_VERSION.to_string(), + server_version: env!("CARGO_PKG_VERSION").to_string(), + server_build: ServerBuildInformation { + target: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH), + profile: if cfg!(debug_assertions) { + "debug".to_string() + } else { + "release".to_string() + }, + commit: option_env!("TABULARIS_BUILD_COMMIT") + .map(str::trim) + .filter(|commit| !commit.is_empty()) + .map(str::to_string), + }, + authenticated, + csrf_token, + access: WebSessionAccessPolicy { + remote, + authorization_level: authorization_name(authorization).to_string(), + high_risk_capabilities: authorization == AuthorizationLevel::LocalAdmin, + }, + capabilities: WebTransportCapabilities { + rpc: true, + events: true, + uploads: true, + downloads: true, + plugin_assets: true, + mcp_host_configuration, + server_file_browser: false, + native_updater: false, + }, + query_response_policy: WebQueryResponsePolicy { + max_rows_per_page: crate::application::queries::WEB_MAX_ROWS_PER_PAGE, + max_response_bytes: crate::application::queries::WEB_MAX_RESPONSE_BYTES, + streaming: false, + }, + } + } +} + +fn authorization_name(authorization: AuthorizationLevel) -> &'static str { + match authorization { + AuthorizationLevel::Session => "session", + AuthorizationLevel::Database => "database", + AuthorizationLevel::Sensitive => "sensitive", + AuthorizationLevel::LocalAdmin => "local-admin", + } +} diff --git a/src-tauri/src/transport/web/events.rs b/src-tauri/src/transport/web/events.rs new file mode 100644 index 000000000..ed252fb30 --- /dev/null +++ b/src-tauri/src/transport/web/events.rs @@ -0,0 +1,449 @@ +use crate::application::AuthorizationLevel; +use crate::runtime::events::RuntimeEvents; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::sync::mpsc; +use uuid::Uuid; + +const DEFAULT_CONNECTION_QUEUE_CAPACITY: usize = 64; +const DEFAULT_SESSION_HISTORY_CAPACITY: usize = 128; +const DEFAULT_MAX_SESSIONS: usize = 64; +const DEFAULT_MAX_CONNECTIONS_PER_SESSION: usize = 8; +const DEFAULT_DISCONNECTED_SESSION_TTL: Duration = Duration::from_secs(5 * 60); +const DEFAULT_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15); +const DEFAULT_HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(45); + +#[derive(Clone, Debug)] +pub struct EventBusConfig { + pub connection_queue_capacity: usize, + pub session_history_capacity: usize, + pub max_sessions: usize, + pub max_connections_per_session: usize, + pub disconnected_session_ttl: Duration, + pub heartbeat_interval: Duration, + pub heartbeat_timeout: Duration, +} + +impl Default for EventBusConfig { + fn default() -> Self { + Self { + connection_queue_capacity: DEFAULT_CONNECTION_QUEUE_CAPACITY, + session_history_capacity: DEFAULT_SESSION_HISTORY_CAPACITY, + max_sessions: DEFAULT_MAX_SESSIONS, + max_connections_per_session: DEFAULT_MAX_CONNECTIONS_PER_SESSION, + disconnected_session_ttl: DEFAULT_DISCONNECTED_SESSION_TTL, + heartbeat_interval: DEFAULT_HEARTBEAT_INTERVAL, + heartbeat_timeout: DEFAULT_HEARTBEAT_TIMEOUT, + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EventEnvelope { + pub event: String, + pub payload: Value, + pub sequence: u64, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)] +pub enum ClientEventMessage { + Subscribe { + events: Vec, + #[serde(default)] + since: Option, + }, + Unsubscribe { + events: Vec, + }, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum ServerEventMessage<'a> { + Event { + #[serde(flatten)] + envelope: &'a EventEnvelope, + }, + Subscribed { + events: &'a [String], + replayed: usize, + }, + Unsubscribed { + events: &'a [String], + }, + Error { + code: &'static str, + message: &'a str, + }, +} + +#[derive(Clone)] +pub struct WebEventBus { + inner: Arc, +} + +struct EventBusInner { + config: EventBusConfig, + state: Mutex, +} + +#[derive(Default)] +struct EventBusState { + next_sequence: u64, + sessions: HashMap, +} + +struct SessionState { + authorization: AuthorizationLevel, + history: VecDeque, + connections: HashMap, + last_seen: Instant, +} + +struct ConnectionState { + subscriptions: HashSet, + sender: mpsc::Sender, +} + +pub struct EventConnection { + bus: WebEventBus, + session_id: Uuid, + connection_id: Uuid, + receiver: mpsc::Receiver, +} + +impl Default for WebEventBus { + fn default() -> Self { + Self::new(EventBusConfig::default()) + } +} + +impl WebEventBus { + pub fn new(config: EventBusConfig) -> Self { + assert!(config.connection_queue_capacity > 0); + assert!(config.session_history_capacity > 0); + assert!(config.max_sessions > 0); + assert!(config.max_connections_per_session > 0); + assert!(config.heartbeat_timeout > config.heartbeat_interval); + Self { + inner: Arc::new(EventBusInner { + config, + state: Mutex::new(EventBusState::default()), + }), + } + } + + pub fn connect( + &self, + session_id: Uuid, + authorization: AuthorizationLevel, + ) -> Result { + let now = Instant::now(); + let mut state = self.lock_state(); + self.cleanup_sessions(&mut state, now); + if !state.sessions.contains_key(&session_id) + && state.sessions.len() >= self.inner.config.max_sessions + { + let removable = state + .sessions + .iter() + .filter(|(_, session)| session.connections.is_empty()) + .min_by_key(|(_, session)| session.last_seen) + .map(|(id, _)| *id); + if let Some(id) = removable { + state.sessions.remove(&id); + } else { + return Err("The WebSocket session limit has been reached".to_string()); + } + } + + let session = state + .sessions + .entry(session_id) + .or_insert_with(|| SessionState { + authorization, + history: VecDeque::new(), + connections: HashMap::new(), + last_seen: now, + }); + if session.authorization != authorization { + return Err("The WebSocket session authorization changed".to_string()); + } + if session.connections.len() >= self.inner.config.max_connections_per_session { + return Err("The WebSocket connection limit has been reached".to_string()); + } + + let connection_id = Uuid::new_v4(); + let (sender, receiver) = mpsc::channel(self.inner.config.connection_queue_capacity); + session.last_seen = now; + session.connections.insert( + connection_id, + ConnectionState { + subscriptions: HashSet::new(), + sender, + }, + ); + drop(state); + + Ok(EventConnection { + bus: self.clone(), + session_id, + connection_id, + receiver, + }) + } + + pub fn emit_to(&self, session_id: Uuid, event: &str, payload: Value) -> Result<(), String> { + self.publish(Some(session_id), event, payload) + } + + pub fn remove_session(&self, session_id: Uuid) { + self.lock_state().sessions.remove(&session_id); + } + + pub fn heartbeat_interval(&self) -> Duration { + self.inner.config.heartbeat_interval + } + + pub fn heartbeat_timeout(&self) -> Duration { + self.inner.config.heartbeat_timeout + } + + pub fn authorization_for(event: &str) -> Option { + match event { + "connection-test-progress" + | "connection-health-failed" + | "connections:active-changed" + | "database-dropped" + | "batch-statement-complete" + | "session-transaction-state" + | "query-status" + | "query-cancelled" + | "dump_progress" + | "import_progress" + | "export_progress" + | "connection-metadata-invalidated" + | "tabularis://plugin-activated" => Some(AuthorizationLevel::Database), + "theme-catalog-changed" | "ui-state://changed" | "tabularis://plugin-installed" => { + Some(AuthorizationLevel::Session) + } + "plugin-install-progress" | "tabularis://plugin-install" => { + Some(AuthorizationLevel::Sensitive) + } + "ai://pending_approval" + | "ai://activity" + | "ssh-askpass://request" + | "ssh-askpass://dismiss" => Some(AuthorizationLevel::Sensitive), + "update-progress" | "update-installing" | "server://lifecycle" => { + Some(AuthorizationLevel::LocalAdmin) + } + _ => None, + } + } + + fn publish( + &self, + target_session: Option, + event: &str, + payload: Value, + ) -> Result<(), String> { + let required = Self::authorization_for(event) + .ok_or_else(|| format!("Web event is not registered: {event}"))?; + let now = Instant::now(); + let mut state = self.lock_state(); + self.cleanup_sessions(&mut state, now); + state.next_sequence = state.next_sequence.wrapping_add(1).max(1); + let envelope = EventEnvelope { + event: event.to_string(), + payload, + sequence: state.next_sequence, + }; + + let mut found_scope = target_session.is_none(); + let mut authorized_scope = target_session.is_none(); + for (session_id, session) in &mut state.sessions { + if target_session.is_some_and(|target| target != *session_id) { + continue; + } + found_scope = true; + if !session.authorization.permits(required) { + continue; + } + authorized_scope = true; + session.last_seen = now; + session.history.push_back(envelope.clone()); + while session.history.len() > self.inner.config.session_history_capacity { + session.history.pop_front(); + } + session.connections.retain(|_, connection| { + if !connection.subscriptions.contains(event) { + return true; + } + connection.sender.try_send(envelope.clone()).is_ok() + }); + } + + if !found_scope { + Err("The target WebSocket session is not available".to_string()) + } else if !authorized_scope { + Err("The target WebSocket session is not authorized for this event".to_string()) + } else { + Ok(()) + } + } + + fn subscribe( + &self, + session_id: Uuid, + connection_id: Uuid, + events: &[String], + since: Option, + ) -> Result, String> { + let mut state = self.lock_state(); + let session = state + .sessions + .get_mut(&session_id) + .ok_or_else(|| "The WebSocket session is no longer available".to_string())?; + for event in events { + let required = Self::authorization_for(event) + .ok_or_else(|| format!("Web event is not registered: {event}"))?; + if !session.authorization.permits(required) { + return Err(format!("The session is not authorized for event: {event}")); + } + } + let connection = session + .connections + .get_mut(&connection_id) + .ok_or_else(|| "The WebSocket connection is no longer available".to_string())?; + connection.subscriptions.extend(events.iter().cloned()); + session.last_seen = Instant::now(); + + let Some(sequence) = since else { + return Ok(Vec::new()); + }; + let selected: HashSet<&str> = events.iter().map(String::as_str).collect(); + Ok(session + .history + .iter() + .filter(|envelope| { + envelope.sequence > sequence && selected.contains(envelope.event.as_str()) + }) + .cloned() + .collect()) + } + + fn unsubscribe( + &self, + session_id: Uuid, + connection_id: Uuid, + events: &[String], + ) -> Result<(), String> { + let mut state = self.lock_state(); + let session = state + .sessions + .get_mut(&session_id) + .ok_or_else(|| "The WebSocket session is no longer available".to_string())?; + let connection = session + .connections + .get_mut(&connection_id) + .ok_or_else(|| "The WebSocket connection is no longer available".to_string())?; + for event in events { + connection.subscriptions.remove(event); + } + session.last_seen = Instant::now(); + Ok(()) + } + + fn disconnect(&self, session_id: Uuid, connection_id: Uuid) { + let mut state = self.lock_state(); + if let Some(session) = state.sessions.get_mut(&session_id) { + session.connections.remove(&connection_id); + session.last_seen = Instant::now(); + } + } + + fn is_connected(&self, session_id: Uuid, connection_id: Uuid) -> bool { + self.lock_state() + .sessions + .get(&session_id) + .is_some_and(|session| session.connections.contains_key(&connection_id)) + } + + fn cleanup_sessions(&self, state: &mut EventBusState, now: Instant) { + let ttl = self.inner.config.disconnected_session_ttl; + state.sessions.retain(|_, session| { + !session.connections.is_empty() || now.duration_since(session.last_seen) < ttl + }); + } + + fn lock_state(&self) -> std::sync::MutexGuard<'_, EventBusState> { + self.inner + .state + .lock() + .unwrap_or_else(|error| error.into_inner()) + } + + #[cfg(test)] + pub fn connection_count(&self, session_id: Uuid) -> usize { + self.lock_state() + .sessions + .get(&session_id) + .map_or(0, |session| session.connections.len()) + } + + #[cfg(test)] + pub fn history_len(&self, session_id: Uuid) -> usize { + self.lock_state() + .sessions + .get(&session_id) + .map_or(0, |session| session.history.len()) + } +} + +impl RuntimeEvents for WebEventBus { + fn emit(&self, event: &str, payload: Value) -> Result<(), String> { + self.publish(None, event, payload) + } + + fn emit_to(&self, session_id: Uuid, event: &str, payload: Value) -> Result<(), String> { + self.publish(Some(session_id), event, payload) + } +} + +impl EventConnection { + pub fn subscribe( + &mut self, + events: &[String], + since: Option, + ) -> Result, String> { + self.bus + .subscribe(self.session_id, self.connection_id, events, since) + } + + pub fn unsubscribe(&mut self, events: &[String]) -> Result<(), String> { + self.bus + .unsubscribe(self.session_id, self.connection_id, events) + } + + pub async fn recv(&mut self) -> Option { + let event = self.receiver.recv().await?; + self.bus + .is_connected(self.session_id, self.connection_id) + .then_some(event) + } + + pub fn try_recv(&mut self) -> Result { + self.receiver.try_recv() + } +} + +impl Drop for EventConnection { + fn drop(&mut self) { + self.bus.disconnect(self.session_id, self.connection_id); + } +} diff --git a/src-tauri/src/transport/web/events_tests.rs b/src-tauri/src/transport/web/events_tests.rs new file mode 100644 index 000000000..3b70a8610 --- /dev/null +++ b/src-tauri/src/transport/web/events_tests.rs @@ -0,0 +1,196 @@ +use super::events::{EventBusConfig, WebEventBus}; +use crate::application::AuthorizationLevel; +use crate::runtime::events::RuntimeEvents; +use serde_json::json; +use std::time::Duration; +use uuid::Uuid; + +fn test_config() -> EventBusConfig { + EventBusConfig { + connection_queue_capacity: 1, + session_history_capacity: 2, + max_sessions: 4, + max_connections_per_session: 2, + disconnected_session_ttl: Duration::from_secs(60), + heartbeat_interval: Duration::from_millis(20), + heartbeat_timeout: Duration::from_millis(60), + } +} + +#[tokio::test] +async fn scopes_events_to_authorized_sessions() { + let bus = WebEventBus::new(test_config()); + let database_session = Uuid::new_v4(); + let admin_session = Uuid::new_v4(); + let mut database = bus + .connect(database_session, AuthorizationLevel::Database) + .unwrap(); + let mut admin = bus + .connect(admin_session, AuthorizationLevel::LocalAdmin) + .unwrap(); + + database + .subscribe(&["connection-health-failed".to_string()], None) + .unwrap(); + admin + .subscribe(&["connection-health-failed".to_string()], None) + .unwrap(); + assert!(database + .subscribe(&["ssh-askpass://request".to_string()], None) + .is_err()); + assert!(bus + .emit_to( + database_session, + "ssh-askpass://request", + json!({"id": 1, "prompt": "Password"}), + ) + .is_err()); + + bus.emit_to( + database_session, + "connection-health-failed", + json!({"connectionId": "connection-1", "error": "offline"}), + ) + .unwrap(); + + let event = database.recv().await.unwrap(); + assert_eq!(event.event, "connection-health-failed"); + assert!(admin.try_recv().is_err()); +} + +#[tokio::test] +async fn disconnects_slow_consumers_and_bounds_reconnect_history() { + let bus = WebEventBus::new(test_config()); + let session = Uuid::new_v4(); + let mut connection = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + connection + .subscribe(&["export_progress".to_string()], None) + .unwrap(); + + for rows_processed in 1..=4 { + RuntimeEvents::emit( + &bus, + "export_progress", + json!({"rowsProcessed": rows_processed}), + ) + .unwrap(); + } + + assert_eq!(bus.connection_count(session), 0); + assert_eq!(bus.history_len(session), 2); + assert!(connection.recv().await.is_none()); +} + +#[tokio::test] +async fn replays_only_missed_events_for_the_same_session() { + let bus = WebEventBus::new(test_config()); + let session = Uuid::new_v4(); + let mut first = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + first + .subscribe(&["query-status".to_string()], None) + .unwrap(); + + RuntimeEvents::emit(&bus, "query-status", json!({"status": "running"})).unwrap(); + let first_sequence = first.recv().await.unwrap().sequence; + drop(first); + + RuntimeEvents::emit(&bus, "query-status", json!({"status": "cancelled"})).unwrap(); + + let mut reconnected = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + let replay = reconnected + .subscribe(&["query-status".to_string()], Some(first_sequence)) + .unwrap(); + assert_eq!(replay.len(), 1); + assert_eq!(replay[0].payload, json!({"status": "cancelled"})); + + let other_session = Uuid::new_v4(); + let mut other = bus + .connect(other_session, AuthorizationLevel::LocalAdmin) + .unwrap(); + assert!(other + .subscribe(&["query-status".to_string()], Some(0)) + .unwrap() + .is_empty()); +} + +#[tokio::test] +async fn removing_a_session_discards_queued_events() { + let bus = WebEventBus::new(test_config()); + let session = Uuid::new_v4(); + let mut connection = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + connection + .subscribe(&["query-status".to_string()], None) + .unwrap(); + RuntimeEvents::emit(&bus, "query-status", json!({"status": "running"})).unwrap(); + + bus.remove_session(session); + + assert!(connection.recv().await.is_none()); +} + +#[test] +fn bounds_connections_per_session() { + let bus = WebEventBus::new(test_config()); + let session = Uuid::new_v4(); + let _first = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + let _second = bus + .connect(session, AuthorizationLevel::LocalAdmin) + .unwrap(); + assert!(bus + .connect(session, AuthorizationLevel::LocalAdmin) + .is_err()); +} + +#[test] +fn declares_authorization_for_required_event_groups() { + for event in [ + "connection-health-failed", + "query-status", + "dump_progress", + "import_progress", + "export_progress", + "plugin-install-progress", + "ai://pending_approval", + "ai://activity", + "ssh-askpass://request", + "update-progress", + "server://lifecycle", + "theme-catalog-changed", + "ui-state://changed", + "connection-metadata-invalidated", + "tabularis://plugin-activated", + "tabularis://plugin-installed", + ] { + assert!(WebEventBus::authorization_for(event).is_some(), "{event}"); + } + assert!(WebEventBus::authorization_for("unregistered-sensitive-event").is_none()); +} + +#[test] +fn lets_every_session_follow_shared_catalog_and_ui_state_changes() { + for event in [ + "theme-catalog-changed", + "ui-state://changed", + "tabularis://plugin-installed", + ] { + assert_eq!( + WebEventBus::authorization_for(event), + Some(AuthorizationLevel::Session), + "{event}" + ); + } + assert_eq!( + WebEventBus::authorization_for("connection-metadata-invalidated"), + Some(AuthorizationLevel::Database) + ); +} diff --git a/src-tauri/src/transport/web/mod.rs b/src-tauri/src/transport/web/mod.rs new file mode 100644 index 000000000..d20f9f893 --- /dev/null +++ b/src-tauri/src/transport/web/mod.rs @@ -0,0 +1,12 @@ +pub mod auth; +pub mod contract; +pub mod events; +pub mod rpc; +pub mod server; +pub mod server_files; +pub mod static_assets; + +#[cfg(test)] +mod events_tests; +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/transport/web/rpc.rs b/src-tauri/src/transport/web/rpc.rs new file mode 100644 index 000000000..b5f3f7af8 --- /dev/null +++ b/src-tauri/src/transport/web/rpc.rs @@ -0,0 +1,4388 @@ +use crate::application::{ + ai::AiCommand, + connection_files::{ConnectionExportMode, ConnectionFilesCommand, ConnectionImportFile}, + connections::ConnectionCommand, + database_objects::DatabaseObjectCommand, + database_transfers::{DatabaseTransferCommand, DumpOptions}, + generic_exports::GenericExportCommand, + mcp_host::McpHostCommand, + metadata::MetadataCommand, + notebooks::NotebookCommand, + operations::{GetLogsRequest, OperationalCommand}, + persistence::PersistenceCommand, + plugins::PluginCommand, + productivity::ProductivityCommand, + queries::QueryCommand, + records::RecordCommand, + tunnels::TunnelCommand, + ApplicationApi, ApplicationError, ApplicationRequestContext, AuthorizationLevel, +}; +use crate::models::{ + ColumnDefinition, ConnectionAppearance, ConnectionParams, K8sConnectionInput, RoutineCallArg, + SshConnectionInput, SshTestParams, TestConnectionRequest, +}; +use axum::body::Bytes; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE}; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, Weak}; +use std::time::{Duration, Instant}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + +#[path = "rpc_connection_policy.rs"] +mod connection_policy; + +#[path = "rpc_host_commands.rs"] +mod host_commands; +use host_commands::{ + decode_host_settings_command, decode_theme_command, decode_ui_state_command, + HostSettingsRpcCommand, ReadSqlFileRequest, ThemeRpcCommand, UiStateRpcCommand, + WriteSqlFileRequest, +}; + +pub const RPC_DEADLINE_HEADER_NAME: &str = "x-tabularis-deadline-ms"; +pub const RPC_CANCELLATION_HEADER_NAME: &str = "x-tabularis-cancellation-id"; + +const DEFAULT_DEADLINE: Duration = Duration::from_secs(30); +const MAX_DEADLINE: Duration = Duration::from_secs(6 * 60 * 60); +const MAX_CANCELLATION_ID_LENGTH: usize = 128; +const DEFAULT_MAX_CONCURRENT_RPC_REQUESTS: usize = 64; +const DEFAULT_MAX_CONCURRENT_RPC_REQUESTS_PER_SESSION: usize = 16; + +#[derive(Clone)] +pub struct RpcDispatcher { + application: Arc, + active_cancellations: Arc>>, + access_policy: RpcAccessPolicy, + concurrency: RpcConcurrency, +} + +#[derive(Clone, Copy, Debug)] +struct RpcConcurrencyLimits { + max_global: usize, + max_per_session: usize, +} + +impl Default for RpcConcurrencyLimits { + fn default() -> Self { + Self { + max_global: DEFAULT_MAX_CONCURRENT_RPC_REQUESTS, + max_per_session: DEFAULT_MAX_CONCURRENT_RPC_REQUESTS_PER_SESSION, + } + } +} + +#[derive(Clone)] +struct RpcConcurrency { + global: Arc, + sessions: Arc>>>, + max_per_session: usize, +} + +struct RpcConcurrencyPermit { + _global: OwnedSemaphorePermit, + _session: Option, +} + +enum RpcAdmissionError { + SessionBusy, + ServerBusy, +} + +impl RpcConcurrency { + fn new(limits: RpcConcurrencyLimits) -> Self { + assert!(limits.max_global > 0); + assert!(limits.max_per_session > 0); + Self { + global: Arc::new(Semaphore::new(limits.max_global)), + sessions: Arc::new(Mutex::new(HashMap::new())), + max_per_session: limits.max_per_session, + } + } + + fn try_acquire( + &self, + session_id: Option, + ) -> Result { + let session = session_id.map(|session_id| { + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(|error| error.into_inner()); + sessions.retain(|_, semaphore| semaphore.strong_count() > 0); + if let Some(semaphore) = sessions.get(&session_id).and_then(Weak::upgrade) { + semaphore + } else { + let semaphore = Arc::new(Semaphore::new(self.max_per_session)); + sessions.insert(session_id, Arc::downgrade(&semaphore)); + semaphore + } + }); + let session_permit = session + .map(|semaphore| { + semaphore + .try_acquire_owned() + .map_err(|_| RpcAdmissionError::SessionBusy) + }) + .transpose()?; + let global_permit = self + .global + .clone() + .try_acquire_owned() + .map_err(|_| RpcAdmissionError::ServerBusy)?; + Ok(RpcConcurrencyPermit { + _global: global_permit, + _session: session_permit, + }) + } +} + +#[derive(Clone, Debug)] +pub(crate) struct RpcAccessPolicy { + pub mcp_host_configuration: bool, + pub server_file_browser_roots: Arc<[PathBuf]>, +} + +impl Default for RpcAccessPolicy { + fn default() -> Self { + Self { + mcp_host_configuration: false, + server_file_browser_roots: Arc::default(), + } + } +} + +#[derive(Clone, Debug)] +pub struct RequestId(pub String); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RpcCommand { + IsDebugMode, + GetConnections, + CancelQuery, + ListServerDirectory, + ResolveServerSaveTarget, + CreateSqliteFile, + CreateSqliteDatabase, + ReadSqlFile, + WriteSqlFile, + Theme(ThemeRpcCommand), + HostSettings(HostSettingsRpcCommand), + UiState(UiStateRpcCommand), + Connection(ConnectionRpcCommand), + ConnectionFiles(ConnectionFilesRpcCommand), + DatabaseTransfer(DatabaseTransferRpcCommand), + GenericExport(GenericExportRpcCommand), + Ai(AiRpcCommand), + Metadata(MetadataRpcCommand), + DatabaseObject(DatabaseObjectRpcCommand), + Query(QueryRpcCommand), + Record(RecordRpcCommand), + Tunnel(TunnelRpcCommand), + Persistence(PersistenceRpcCommand), + Productivity(ProductivityRpcCommand), + Notebook(NotebookRpcCommand), + Plugin(PluginRpcCommand), + Operational(OperationalRpcCommand), + McpHost(McpHostRpcCommand), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum McpHostRpcCommand { + GetStatus, + InstallConfig, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum OperationalRpcCommand { + LogFrontendEvent, + + GetLogs, + ClearLogs, + GetLogSettings, + SetLogEnabled, + SetLogMaxSize, + GetProcessList, + GetSystemStats, + GetTabularisChildren, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PluginRpcCommand { + GetRuntimeWarnings, + FetchRegistry, + FetchPreview, + FetchReadme, + Install, + CancelInstall, + Uninstall, + GetInstalled, + Disable, + Enable, + GetManifest, + GetStartupErrors, + KillProcess, + RestartProcess, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum AiRpcCommand { + SetKey, + DeleteKey, + CheckKey, + CheckKeyStatus, + GetModels, + GenerateQuery, + ExplainQuery, + AnalyzeExplainPlan, + GenerateCellName, + GenerateTabRename, + SuggestTableName, + GetSchemaContext, + GetActivity, + GetSessions, + GetSessionEvents, + ClearActivity, + ListPendingApprovals, + DecidePendingApproval, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum DatabaseTransferRpcCommand { + Dump, + CancelDump, + Import, + CancelImport, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum GenericExportRpcCommand { + ExportQuery, + CancelExport, + ExportAiActivityJson, + ExportAiActivityCsv, + ExportAiSessionAsNotebook, + ExportLogs, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ConnectionFilesRpcCommand { + Export, + ListImportSources, + PreviewForeignImport, + ApplyForeignImport, + PreviewTabularisImport, + ApplyPreparedTabularisImport, + GetBackupStatus, + GetDatabaseBackupStatus, + RunDatabaseBackup, + CancelDatabaseBackup, + SetBackupPassword, + SetBackupTargetPassword, + RunBackup, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum NotebookRpcCommand { + Create, + Save, + Load, + Delete, + Rename, + List, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ProductivityRpcCommand { + GetSavedQueries, + SaveQuery, + UpdateSavedQuery, + DeleteSavedQuery, + GetSavedQueryFolders, + CreateSavedQueryFolder, + RenameSavedQueryFolder, + DeleteSavedQueryFolder, + MoveSavedQuery, + GetQueryHistory, + AddQueryHistoryEntry, + DeleteQueryHistoryEntry, + ClearQueryHistory, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PersistenceRpcCommand { + GetConfig, + SaveConfig, + GetConfigJson, + SaveConfigJson, + GetKeybindings, + SaveKeybindings, + GetAllThemes, + SaveCustomTheme, + DeleteCustomTheme, + GetPrompt(crate::application::persistence::PromptKind), + SavePrompt(crate::application::persistence::PromptKind), + ResetPrompt(crate::application::persistence::PromptKind), + LoadEditorPreferences, + SaveEditorPreferences, + DeleteEditorPreferences, + GetLastActiveConnection, + SetLastActiveConnection, + GetLastOpenConnections, + SetLastOpenConnections, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum QueryRpcCommand { + ReleaseSession, + Execute, + ExecuteBatch, + Count, + Explain, + GetServerNow, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RecordRpcCommand { + Delete, + Update, + Insert, + FetchBlob, + DetectBlobMime, + DetectMimeType, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum DatabaseObjectRpcCommand { + GetTableQueryTemplate, + GetColumnStats, + GetDropTableSql, + GetDataTypes, + MapInferredColumnTypes, + ExecuteClipboardImport, + + GetViewDefinition, + CreateView, + AlterView, + DropView, + RefreshMaterializedView, + GetRoutineParameters, + GetRoutineDefinition, + BuildRoutineCallSql, + GetRoutineCreateTemplate, + GetRoutineEditScript, + DropRoutine, + GetTriggerDefinition, + CreateTrigger, + DropTrigger, + GetCreateTableSql, + GetAddColumnSql, + GetAlterColumnSql, + GetCreateIndexSql, + GetCreateForeignKeySql, + DropIndex, + DropForeignKey, + GetDbPrivilegeCatalog, + GetDbUsers, + GetDbUserGrants, + GetDbUserPrivileges, + CreateDbUser, + DropDbUser, + SetDbUserPassword, + ApplyDbUserPrivileges, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum MetadataRpcCommand { + GetConnectionMetadata, + GetAvailableDatabases, + GetSchemas, + GetTables, + GetColumns, + GetForeignKeys, + GetIndexes, + GetViews, + GetViewColumns, + GetMaterializedViews, + GetMaterializedViewColumns, + GetMaterializedViewDefinition, + GetRoutines, + GetTriggers, + GetSchemaSnapshot, + GetSelectedSchemas, + SetSelectedSchemas, + GetSchemaPreference, + SetSchemaPreference, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum TunnelRpcCommand { + GetSshConnections, + SaveSshConnection, + UpdateSshConnection, + DeleteSshConnection, + TestSshConnection, + RespondSshAskpass, + GetK8sConnections, + SaveK8sConnection, + UpdateK8sConnection, + DeleteK8sConnection, + TestK8sConnection, + GetK8sContexts, + GetK8sNamespaces, + GetK8sResources, + GetK8sResourcePorts, + ValidateK8sPath, + TestSsmConnection, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ConnectionRpcCommand { + SetSelectedDatabases, + + GetConnectionById, + GetConnectionsWithGroups, + SaveConnection, + UpdateConnection, + DeleteConnection, + DuplicateConnection, + SetConnectionAppearance, + SaveConnectionIcon, + DeleteConnectionIcon, + GetConnectionGroups, + CreateConnectionGroup, + CreateGroupPath, + UpdateConnectionGroup, + MoveGroupToParent, + DeleteConnectionGroup, + MoveConnectionToGroup, + ReorderGroups, + ReorderConnectionsInGroup, + ListConnectionTags, + CreateConnectionTag, + UpdateConnectionTag, + DeleteConnectionTag, + SetConnectionTags, + GetRegisteredDrivers, + GetDriverManifest, + GetActiveConnections, + RegisterActiveConnection, + DisconnectConnection, + TestConnection, + ListDatabases, +} + +#[derive(Clone, Copy)] +struct CommandMetadata { + authorization: AuthorizationLevel, + application_error_code: &'static str, + application_error_status: StatusCode, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CancelQueryRequest { + connection_id: String, + query_request_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ListServerDirectoryRequest { + path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResolveServerSaveTargetRequest { + directory: String, + file_name: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SqlitePathRequest { + path: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct GetLogsRpcRequest { + request: GetLogsRequest, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SetLogEnabledRequest { + enabled: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetLogMaxSizeRequest { + max_size: usize, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AiProviderRequest { + provider: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SetAiKeyRequest { + provider: String, + key: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AiModelsRequest { + #[serde(default)] + force_refresh: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AiRequest { + req: T, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AiSchemaContextRequest { + connection_id: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AiActivityRequest { + filter: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AiSessionRequest { + session_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AiApprovalDecisionRequest { + approval_id: String, + decision: String, + reason: Option, + edited_query: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExportConnectionsFileRequest { + mode: ConnectionExportMode, + password: Option, + connection_ids: Option>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PreviewConnectionImportRequest { + source_id: String, + include_passwords: bool, + file: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ApplyConnectionImportRequest { + source_id: String, + resolutions: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct PreviewTabularisImportRequest { + file: ConnectionImportFile, + password: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ApplyPreparedImportRequest { + resolutions: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SetBackupPasswordRequest { + password: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetBackupTargetPasswordRequest { + target_id: String, + password: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DumpDatabaseRequest { + connection_id: String, + options: DumpOptions, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ImportDatabaseRequest { + connection_id: String, + upload_token: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveConfigRequest { + config: crate::config::AppConfig, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveConfigJsonRequest { + json: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveKeybindingsRequest { + keybindings: Value, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveThemeRequest { + theme: Value, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TestSsmConnectionRequest { + target: String, + #[serde(default)] + profile: Option, + #[serde(default)] + region: Option, + host: String, + port: u16, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ThemeIdRequest { + theme_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SavePromptRequest { + prompt: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SaveEditorPreferencesRequest { + connection_id: String, + preferences: crate::preferences::EditorPreferences, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetLastActiveConnectionRequest { + connection_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetLastOpenConnectionsRequest { + connection_ids: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct IdRequest { + id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginIdRequest { + plugin_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct McpClientRequest { + client_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct InstallPluginRequest { + plugin_id: String, + version: Option, + registry_url: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginPreviewRequest { + slug: String, + registry_url: Option, + version: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginReadmeRequest { + slug: String, + locale: Option, + registry_url: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConnectionIdRequest { + connection_id: String, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SaveQueryRequest { + connection_id: String, + name: String, + sql: String, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdateSavedQueryRequest { + connection_id: String, + id: String, + name: String, + sql: String, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConnectionItemRequest { + connection_id: String, + id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct NotebookTargetRequest { + connection_id: String, + notebook_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct NotebookContentRequest { + connection_id: String, + notebook_id: String, + content: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RenameNotebookRequest { + connection_id: String, + notebook_id: String, + title: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AddQueryHistoryEntryRequest { + connection_id: String, + sql: String, + executed_at: String, + execution_time_ms: Option, + status: QueryHistoryStatus, + rows_affected: Option, + error: Option, + database: Option, +} + +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(rename_all = "lowercase")] +enum QueryHistoryStatus { + Success, + Error, +} + +impl QueryHistoryStatus { + fn into_string(self) -> String { + match self { + Self::Success => "success", + Self::Error => "error", + } + .to_string() + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MetadataRequest { + connection_id: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TableMetadataRequest { + connection_id: String, + table_name: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ViewMetadataRequest { + connection_id: String, + view_name: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ViewDefinitionRequest { + connection_id: String, + view_name: String, + definition: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RoutineNameRequest { + connection_id: String, + routine_name: String, + schema: Option, + database: Option, + identity_args: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RoutineTargetRequest { + connection_id: String, + routine_name: String, + routine_type: String, + schema: Option, + database: Option, + identity_args: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RoutineCallRequest { + connection_id: String, + routine_name: String, + routine_type: String, + args: Vec, + schema: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RoutineTemplateRequest { + connection_id: String, + routine_type: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TriggerTargetRequest { + connection_id: String, + trigger_name: String, + table_name: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateTriggerRequest { + connection_id: String, + trigger_sql: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateTableSqlRequest { + connection_id: String, + table_name: String, + columns: Vec, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AddColumnSqlRequest { + connection_id: String, + table: String, + column: ColumnDefinition, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AlterColumnSqlRequest { + connection_id: String, + table: String, + old_column: ColumnDefinition, + new_column: ColumnDefinition, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateIndexSqlRequest { + connection_id: String, + table: String, + index_name: String, + columns: Vec, + is_unique: bool, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateForeignKeySqlRequest { + 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, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DropIndexRequest { + connection_id: String, + table: String, + index_name: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DropForeignKeyRequest { + connection_id: String, + table: String, + fk_name: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DbUserTargetRequest { + connection_id: String, + user: String, + host: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DbUserPasswordRequest { + connection_id: String, + user: String, + host: String, + password: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ApplyDbUserPrivilegesRequest { + connection_id: String, + user: String, + host: String, + database: Option, + table: Option, + privileges: Vec, + grant: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetSelectedSchemasRequest { + connection_id: String, + schemas: Vec, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetSchemaPreferenceRequest { + connection_id: String, + schema: String, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReleaseQuerySessionRequest { + connection_id: String, + session_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExecuteQueryRequest { + connection_id: String, + query: String, + limit: Option, + page: Option, + schema: Option, + session_id: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExecuteQueryBatchRequest { + connection_id: String, + queries: Vec, + limit: Option, + page: Option, + schema: Option, + batch_id: Option, + session_id: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CountQueryRequest { + connection_id: String, + query: String, + schema: Option, + session_id: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExplainQueryRequest { + connection_id: String, + query: String, + analyze: bool, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct QueryExportRequest { + connection_id: String, + query: String, + format: String, + csv_delimiter: Option, + database: Option, + session_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AiSessionExportRequest { + session_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RecordIdentityRequest { + connection_id: String, + table: String, + pk_map: std::collections::HashMap, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdateRecordRequest { + connection_id: String, + table: String, + pk_map: std::collections::HashMap, + col_name: String, + new_val: Value, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct InsertRecordRequest { + connection_id: String, + table: String, + data: std::collections::HashMap, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct BlobColumnRequest { + connection_id: String, + table: String, + col_name: String, + pk_map: std::collections::HashMap, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DetectBlobMimeRequest { + base64_data: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DetectMimeTypeRequest { + header_base64: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SaveConnectionRequest { + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdateConnectionRequest { + id: String, + name: String, + params: ConnectionParams, + plugin_secret_changes: Option, + detect_json_in_text_columns: Option, + environment: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AppearanceRequest { + id: String, + appearance: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SaveIconRequest { + connection_id: String, + upload_token: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DeleteIconRequest { + relative_path: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateGroupRequest { + name: String, + parent_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateGroupPathRequest { + path: String, + parent_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdateGroupRequest { + id: String, + name: Option, + collapsed: Option, + sort_order: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MoveGroupRequest { + id: String, + parent_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MoveConnectionRequest { + connection_id: String, + group_id: Option, + sort_order: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReorderGroupsRequest { + group_orders: Vec<(String, i32)>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReorderConnectionsRequest { + connection_orders: Vec<(String, i32)>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TagMutationRequest { + id: String, + name: String, + color: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateTagRequest { + name: String, + color: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetTagsRequest { + connection_id: String, + tag_ids: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DriverManifestRequest { + driver_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct TestRequest { + request: TestConnectionRequest, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveSshRequest { + name: String, + ssh: SshConnectionInput, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct UpdateSshRequest { + id: String, + name: String, + ssh: SshConnectionInput, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct TestSshRequest { + ssh: SshTestParams, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AskpassResponseRequest { + id: u64, + response: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SaveK8sRequest { + k8s: K8sConnectionInput, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct UpdateK8sRequest { + id: String, + k8s: K8sConnectionInput, +} + +#[derive(Debug, Deserialize, Default)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct K8sOptionsRequest { + kubectl_path: Option, + kubeconfig_path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TestK8sRequest { + context: String, + namespace: String, + kubectl_path: Option, + kubeconfig_path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct K8sContextRequest { + context: String, + kubectl_path: Option, + kubeconfig_path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct K8sResourcesRequest { + context: String, + namespace: String, + resource_type: String, + kubectl_path: Option, + kubeconfig_path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct K8sPortsRequest { + context: String, + namespace: String, + resource_type: String, + resource_name: String, + kubectl_path: Option, + kubeconfig_path: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ValidateK8sPathRequest { + path: String, + kind: String, +} + +#[derive(Serialize)] +struct RpcSuccess { + ok: bool, + data: Value, +} + +#[derive(Serialize)] +struct RpcFailure { + ok: bool, + error: RpcError, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct RpcError { + code: &'static str, + message: String, + details: Option, + request_id: String, +} + +enum InvocationError { + Forbidden(&'static str), + InvalidPayload(String), + Application(ApplicationError), +} + +struct CancellationRegistration { + id: String, + active: Arc>>, +} + +impl RpcDispatcher { + pub fn new(application: Arc) -> Self { + Self::with_access_policy(application, RpcAccessPolicy::default()) + } + + pub(crate) fn with_access_policy( + application: Arc, + access_policy: RpcAccessPolicy, + ) -> Self { + Self::with_access_policy_and_limits( + application, + access_policy, + RpcConcurrencyLimits::default(), + ) + } + + fn with_access_policy_and_limits( + application: Arc, + access_policy: RpcAccessPolicy, + concurrency_limits: RpcConcurrencyLimits, + ) -> Self { + Self { + application, + active_cancellations: Arc::new(Mutex::new(HashSet::new())), + access_policy, + concurrency: RpcConcurrency::new(concurrency_limits), + } + } + + pub fn clear_session(&self, session_id: uuid::Uuid) { + self.application.clear_session(session_id); + } + + /// Runs one RPC for a session holding `granted_authorization`. + pub(crate) async fn dispatch( + &self, + command_name: &str, + request_id: RequestId, + headers: &HeaderMap, + body: Bytes, + session_id: Option, + granted_authorization: AuthorizationLevel, + ) -> Response { + let Some(command) = RpcCommand::parse(command_name) else { + return failure( + StatusCode::NOT_FOUND, + "COMMAND_NOT_FOUND", + format!("Unknown RPC command: {command_name}"), + None, + request_id.0, + ); + }; + if matches!(command, RpcCommand::McpHost(_)) && !self.access_policy.mcp_host_configuration { + return failure( + StatusCode::FORBIDDEN, + "MCP_HOST_CONFIGURATION_DISABLED", + "MCP host configuration is disabled for this Web UI mode".to_string(), + None, + request_id.0, + ); + } + let metadata = command.metadata(); + if !granted_authorization.permits(metadata.authorization) { + return failure( + StatusCode::FORBIDDEN, + "FORBIDDEN", + "The session is not authorized for this command".to_string(), + None, + request_id.0, + ); + } + + if !body.is_empty() && !has_json_content_type(headers) { + return failure( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "INVALID_CONTENT_TYPE", + "RPC requests must use application/json".to_string(), + None, + request_id.0, + ); + } + + let deadline = match request_deadline(headers) { + Ok(deadline) => deadline, + Err(message) => { + return failure( + StatusCode::BAD_REQUEST, + "INVALID_DEADLINE", + message, + None, + request_id.0, + ) + } + }; + let cancellation_id = match cancellation_id(headers) { + Ok(id) => id, + Err(message) => { + return failure( + StatusCode::BAD_REQUEST, + "INVALID_CANCELLATION_ID", + message, + None, + request_id.0, + ) + } + }; + let _concurrency_permit = match self.concurrency.try_acquire(session_id) { + Ok(permit) => permit, + Err(RpcAdmissionError::SessionBusy) => { + return failure( + StatusCode::TOO_MANY_REQUESTS, + "SESSION_BUSY", + "The session has too many active RPC requests".to_string(), + None, + request_id.0, + ) + } + Err(RpcAdmissionError::ServerBusy) => { + return failure( + StatusCode::SERVICE_UNAVAILABLE, + "SERVER_BUSY", + "The server has too many active RPC requests".to_string(), + None, + request_id.0, + ) + } + }; + let _registration = match self.register_cancellation(cancellation_id.as_deref(), session_id) + { + Ok(registration) => registration, + Err(message) => { + return failure( + StatusCode::CONFLICT, + "CANCELLATION_ID_IN_USE", + message, + None, + request_id.0, + ) + } + }; + + let context = ApplicationRequestContext { + request_id: request_id.0.clone(), + deadline: Instant::now() + deadline, + cancellation_id, + authorization: granted_authorization, + session_id, + }; + let invocation = self.invoke(command, context, &body, granted_authorization); + match tokio::time::timeout(deadline, invocation).await { + Ok(Ok(data)) => success(data), + Ok(Err(InvocationError::Forbidden(message))) => failure( + StatusCode::FORBIDDEN, + "FORBIDDEN", + message.to_string(), + None, + request_id.0, + ), + Ok(Err(InvocationError::InvalidPayload(message))) => failure( + StatusCode::BAD_REQUEST, + "INVALID_REQUEST", + message, + None, + request_id.0, + ), + Ok(Err(InvocationError::Application(error))) => failure( + metadata.application_error_status, + metadata.application_error_code, + error.message, + error.details, + request_id.0, + ), + Err(_) => failure( + StatusCode::GATEWAY_TIMEOUT, + "DEADLINE_EXCEEDED", + "The RPC request exceeded its deadline".to_string(), + None, + request_id.0, + ), + } + } + + async fn invoke( + &self, + command: RpcCommand, + context: ApplicationRequestContext, + body: &[u8], + granted_authorization: AuthorizationLevel, + ) -> Result { + connection_policy::authorize_saved_access( + self.application.as_ref(), + command, + &context, + body, + granted_authorization, + ) + .await?; + match command { + RpcCommand::IsDebugMode => { + decode_empty_payload(body).map_err(InvocationError::InvalidPayload)?; + let result = self + .application + .is_debug_mode(context) + .await + .map_err(InvocationError::Application)?; + serde_json::to_value(result).map_err(|error| { + InvocationError::Application(ApplicationError::new(error.to_string())) + }) + } + RpcCommand::GetConnections => { + decode_empty_payload(body).map_err(InvocationError::InvalidPayload)?; + let result = self + .application + .get_connections(context) + .await + .map_err(InvocationError::Application)?; + serde_json::to_value(result).map_err(|error| { + InvocationError::Application(ApplicationError::new(error.to_string())) + }) + } + RpcCommand::CancelQuery => { + let request: CancelQueryRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + if let Some(request_id) = request.query_request_id.as_deref() { + validate_query_request_id(request_id) + .map_err(InvocationError::InvalidPayload)?; + } + self.application + .cancel_query(context, request.connection_id, request.query_request_id) + .await + .map_err(InvocationError::Application)?; + Ok(Value::Null) + } + RpcCommand::ListServerDirectory => { + let request: ListServerDirectoryRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let listing = super::server_files::list_directory( + &self.access_policy.server_file_browser_roots, + request.path.as_deref(), + ) + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + serde_json::to_value(listing).map_err(|error| { + InvocationError::Application(ApplicationError::new(error.to_string())) + }) + } + RpcCommand::ResolveServerSaveTarget => { + let request: ResolveServerSaveTargetRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let path = super::server_files::resolve_save_target( + &self.access_policy.server_file_browser_roots, + &request.directory, + &request.file_name, + ) + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + Ok(serde_json::json!({ "path": path })) + } + RpcCommand::CreateSqliteFile | RpcCommand::CreateSqliteDatabase => { + let request: SqlitePathRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let path = super::server_files::validate_save_target( + &self.access_policy.server_file_browser_roots, + &request.path, + ) + .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)); + } + self.application + .execute_connection_command( + context, + ConnectionCommand::CreateSqliteDatabase { path }, + ) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Query(command) => { + let command = + decode_query_command(command, body).map_err(InvocationError::InvalidPayload)?; + self.application + .execute_query_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Connection(command) => { + let command = decode_connection_command(command, context.session_id, body) + .map_err(InvocationError::InvalidPayload)?; + connection_policy::authorize(&command, granted_authorization) + .map_err(InvocationError::Forbidden)?; + connection_policy::authorize_saved_credentials( + self.application.as_ref(), + &context, + &command, + granted_authorization, + ) + .await?; + self.application + .execute_connection_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::ConnectionFiles(command) => { + let command = decode_connection_files_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_connection_files_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::DatabaseTransfer(command) => { + let command = decode_database_transfer_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_database_transfer_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::GenericExport(command) => { + let command = decode_generic_export_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_generic_export_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Ai(command) => { + let command = + decode_ai_command(command, body).map_err(InvocationError::InvalidPayload)?; + self.application + .execute_ai_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Metadata(command) => { + let command = decode_metadata_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_metadata_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Record(command) => { + let command = decode_record_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_record_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::DatabaseObject(command) => { + let command = decode_database_object_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_database_object_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Tunnel(command) => { + let command = decode_tunnel_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_tunnel_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Persistence(command) => { + let command = decode_persistence_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_persistence_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Productivity(command) => { + let command = decode_productivity_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_productivity_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Notebook(command) => { + let command = decode_notebook_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_notebook_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Plugin(command) => { + let command = decode_plugin_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_plugin_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::Operational(command) => { + let command = decode_operational_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_operational_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::McpHost(command) => { + let command = decode_mcp_host_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_mcp_host_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::ReadSqlFile => { + let request: ReadSqlFileRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let path = super::server_files::validate_existing_file( + &self.access_policy.server_file_browser_roots, + &request.path, + ) + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + let path = path.to_str().map(str::to_string).ok_or_else(|| { + InvocationError::Application(ApplicationError::new( + "The selected server path is not valid UTF-8", + )) + })?; + let content = crate::sql_file::read_sql_file(path) + .await + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + Ok(Value::String(content)) + } + RpcCommand::WriteSqlFile => { + let request: WriteSqlFileRequest = + decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let path = super::server_files::validate_save_target( + &self.access_policy.server_file_browser_roots, + &request.path, + ) + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + crate::sql_file::write_sql_file(path, request.content) + .await + .map_err(|error| InvocationError::Application(ApplicationError::new(error)))?; + Ok(Value::Null) + } + RpcCommand::Theme(command) => { + let command = decode_theme_command( + command, + body, + &self.access_policy.server_file_browser_roots, + context.session_id, + ) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_theme_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::HostSettings(command) => { + let command = decode_host_settings_command( + command, + body, + &self.access_policy.server_file_browser_roots, + ) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_host_settings_command(context, command) + .await + .map_err(InvocationError::Application) + } + RpcCommand::UiState(command) => { + let command = decode_ui_state_command(command, body) + .map_err(InvocationError::InvalidPayload)?; + self.application + .execute_ui_state_command(context, command) + .await + .map_err(InvocationError::Application) + } + } + } + + fn register_cancellation( + &self, + cancellation_id: Option<&str>, + session_id: Option, + ) -> Result, String> { + let Some(id) = cancellation_id else { + return Ok(None); + }; + let id = + session_id.map_or_else(|| id.to_string(), |session_id| format!("{session_id}:{id}")); + let mut active = self + .active_cancellations + .lock() + .unwrap_or_else(|error| error.into_inner()); + if !active.insert(id.clone()) { + return Err("The cancellation identifier is already active".to_string()); + } + drop(active); + Ok(Some(CancellationRegistration { + id, + active: self.active_cancellations.clone(), + })) + } +} + +impl RpcCommand { + fn parse(name: &str) -> Option { + match name { + "is_debug_mode" => Some(Self::IsDebugMode), + "get_connections" => Some(Self::GetConnections), + "cancel_query" => Some(Self::CancelQuery), + "list_server_directory" => Some(Self::ListServerDirectory), + "resolve_server_save_target" => Some(Self::ResolveServerSaveTarget), + "create_sqlite_file" => Some(Self::CreateSqliteFile), + "create_sqlite_database" => Some(Self::CreateSqliteDatabase), + "read_sql_file" => Some(Self::ReadSqlFile), + "write_sql_file" => Some(Self::WriteSqlFile), + name => QueryRpcCommand::parse(name) + .map(Self::Query) + .or_else(|| RecordRpcCommand::parse(name).map(Self::Record)) + .or_else(|| TunnelRpcCommand::parse(name).map(Self::Tunnel)) + .or_else(|| DatabaseObjectRpcCommand::parse(name).map(Self::DatabaseObject)) + .or_else(|| MetadataRpcCommand::parse(name).map(Self::Metadata)) + .or_else(|| ConnectionRpcCommand::parse(name).map(Self::Connection)) + .or_else(|| ConnectionFilesRpcCommand::parse(name).map(Self::ConnectionFiles)) + .or_else(|| DatabaseTransferRpcCommand::parse(name).map(Self::DatabaseTransfer)) + .or_else(|| GenericExportRpcCommand::parse(name).map(Self::GenericExport)) + .or_else(|| AiRpcCommand::parse(name).map(Self::Ai)) + .or_else(|| PersistenceRpcCommand::parse(name).map(Self::Persistence)) + .or_else(|| ProductivityRpcCommand::parse(name).map(Self::Productivity)) + .or_else(|| NotebookRpcCommand::parse(name).map(Self::Notebook)) + .or_else(|| PluginRpcCommand::parse(name).map(Self::Plugin)) + .or_else(|| OperationalRpcCommand::parse(name).map(Self::Operational)) + .or_else(|| McpHostRpcCommand::parse(name).map(Self::McpHost)) + .or_else(|| ThemeRpcCommand::parse(name).map(Self::Theme)) + .or_else(|| HostSettingsRpcCommand::parse(name).map(Self::HostSettings)) + .or_else(|| UiStateRpcCommand::parse(name).map(Self::UiState)), + } + } + + fn metadata(self) -> CommandMetadata { + match self { + Self::IsDebugMode => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "DEBUG_MODE_FAILED", + application_error_status: StatusCode::INTERNAL_SERVER_ERROR, + }, + Self::GetConnections => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "CONNECTIONS_LOAD_FAILED", + application_error_status: StatusCode::INTERNAL_SERVER_ERROR, + }, + Self::CancelQuery => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "QUERY_CANCELLATION_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::ListServerDirectory => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "SERVER_DIRECTORY_LIST_FAILED", + application_error_status: StatusCode::BAD_REQUEST, + }, + Self::ResolveServerSaveTarget => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "SERVER_SAVE_TARGET_FAILED", + application_error_status: StatusCode::BAD_REQUEST, + }, + Self::CreateSqliteFile | Self::CreateSqliteDatabase => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "SQLITE_DATABASE_CREATE_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Query(_) => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "QUERY_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Connection(_) => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "CONNECTION_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::ConnectionFiles(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "CONNECTION_FILE_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::DatabaseTransfer(_) => CommandMetadata { + authorization: AuthorizationLevel::Sensitive, + application_error_code: "DATABASE_TRANSFER_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::GenericExport(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "EXPORT_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Ai(command) => CommandMetadata { + authorization: if command == AiRpcCommand::GetSchemaContext { + AuthorizationLevel::Database + } else { + AuthorizationLevel::Sensitive + }, + application_error_code: "AI_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Metadata(_) => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "METADATA_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Record(command) => CommandMetadata { + authorization: if matches!( + command, + RecordRpcCommand::DetectBlobMime | RecordRpcCommand::DetectMimeType + ) { + AuthorizationLevel::Sensitive + } else { + AuthorizationLevel::Database + }, + application_error_code: "RECORD_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::DatabaseObject(command) => CommandMetadata { + authorization: if command.requires_sensitive_authorization() { + AuthorizationLevel::Sensitive + } else { + AuthorizationLevel::Database + }, + application_error_code: "DATABASE_OBJECT_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Tunnel(command) => CommandMetadata { + authorization: if command == TunnelRpcCommand::RespondSshAskpass { + AuthorizationLevel::Sensitive + } else { + AuthorizationLevel::LocalAdmin + }, + application_error_code: "TUNNEL_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Persistence(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "PREFERENCE_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Productivity(_) => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "PRODUCTIVITY_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Notebook(_) => CommandMetadata { + authorization: AuthorizationLevel::Database, + application_error_code: "NOTEBOOK_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Plugin(_) => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "PLUGIN_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Operational(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "OPERATIONAL_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::McpHost(_) => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "MCP_HOST_CONFIGURATION_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::ReadSqlFile | Self::WriteSqlFile => CommandMetadata { + authorization: AuthorizationLevel::LocalAdmin, + application_error_code: "SQL_FILE_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::Theme(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "THEME_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::HostSettings(command) => CommandMetadata { + authorization: command.authorization(), + application_error_code: "HOST_SETTINGS_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + Self::UiState(_) => CommandMetadata { + authorization: AuthorizationLevel::Session, + application_error_code: "UI_STATE_COMMAND_FAILED", + application_error_status: StatusCode::CONFLICT, + }, + } + } +} + +impl McpHostRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_mcp_status" => Self::GetStatus, + "install_mcp_config" => Self::InstallConfig, + _ => return None, + }) + } +} + +impl OperationalRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "log_frontend_event" => Self::LogFrontendEvent, + "get_logs" => Self::GetLogs, + "clear_logs" => Self::ClearLogs, + "get_log_settings" => Self::GetLogSettings, + "set_log_enabled" => Self::SetLogEnabled, + "set_log_max_size" => Self::SetLogMaxSize, + "get_process_list" => Self::GetProcessList, + "get_system_stats" => Self::GetSystemStats, + "get_tabularis_children" => Self::GetTabularisChildren, + _ => return None, + }) + } + + fn authorization(self) -> AuthorizationLevel { + match self { + Self::LogFrontendEvent => AuthorizationLevel::Session, + Self::GetLogs + | Self::GetLogSettings + | Self::GetProcessList + | Self::GetSystemStats + | Self::GetTabularisChildren => AuthorizationLevel::Sensitive, + Self::ClearLogs | Self::SetLogEnabled | Self::SetLogMaxSize => { + AuthorizationLevel::LocalAdmin + } + } + } +} + +impl PluginRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_plugin_runtime_warnings" => Self::GetRuntimeWarnings, + "fetch_plugin_registry" => Self::FetchRegistry, + "fetch_tabularium_plugin_preview" => Self::FetchPreview, + "fetch_plugin_readme" => Self::FetchReadme, + "install_plugin" => Self::Install, + "cancel_plugin_install" => Self::CancelInstall, + "uninstall_plugin" => Self::Uninstall, + "get_installed_plugins" => Self::GetInstalled, + "disable_plugin" => Self::Disable, + "enable_plugin" => Self::Enable, + "get_plugin_manifest" => Self::GetManifest, + "get_plugin_startup_errors" => Self::GetStartupErrors, + "kill_plugin_process" => Self::KillProcess, + "restart_plugin_process" => Self::RestartProcess, + _ => return None, + }) + } +} + +impl AiRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "set_ai_key" => Self::SetKey, + "delete_ai_key" => Self::DeleteKey, + "check_ai_key" => Self::CheckKey, + "check_ai_key_status" => Self::CheckKeyStatus, + "get_ai_models" => Self::GetModels, + "generate_ai_query" => Self::GenerateQuery, + "explain_ai_query" => Self::ExplainQuery, + "analyze_ai_explain_plan" => Self::AnalyzeExplainPlan, + "generate_cell_name" => Self::GenerateCellName, + "generate_tab_rename" => Self::GenerateTabRename, + "suggest_table_name" => Self::SuggestTableName, + "get_ai_schema_context" => Self::GetSchemaContext, + "get_ai_activity" => Self::GetActivity, + "get_ai_sessions" => Self::GetSessions, + "get_ai_session_events" => Self::GetSessionEvents, + "clear_ai_activity" => Self::ClearActivity, + "list_pending_approvals" => Self::ListPendingApprovals, + "decide_pending_approval" => Self::DecidePendingApproval, + _ => return None, + }) + } +} + +impl DatabaseTransferRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "dump_database" => Self::Dump, + "cancel_dump" => Self::CancelDump, + "import_database" => Self::Import, + "cancel_import" => Self::CancelImport, + _ => return None, + }) + } +} + +impl GenericExportRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "export_query_to_file" => Self::ExportQuery, + "cancel_export" => Self::CancelExport, + "export_ai_activity_json" => Self::ExportAiActivityJson, + "export_ai_activity_csv" => Self::ExportAiActivityCsv, + "export_ai_session_as_notebook" => Self::ExportAiSessionAsNotebook, + "export_logs" => Self::ExportLogs, + _ => return None, + }) + } + + fn authorization(self) -> AuthorizationLevel { + match self { + Self::ExportQuery | Self::CancelExport => AuthorizationLevel::Database, + Self::ExportAiActivityJson + | Self::ExportAiActivityCsv + | Self::ExportAiSessionAsNotebook + | Self::ExportLogs => AuthorizationLevel::Sensitive, + } + } +} + +impl ConnectionFilesRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "export_connections_file" => Self::Export, + "list_connection_import_sources" => Self::ListImportSources, + "preview_connection_import" => Self::PreviewForeignImport, + "apply_connection_import" => Self::ApplyForeignImport, + "preview_tabularis_import_file" => Self::PreviewTabularisImport, + "apply_prepared_tabularis_import" => Self::ApplyPreparedTabularisImport, + "get_connections_backup_status" => Self::GetBackupStatus, + "get_database_backup_status" => Self::GetDatabaseBackupStatus, + "run_database_backup_now" => Self::RunDatabaseBackup, + "cancel_database_backup" => Self::CancelDatabaseBackup, + "set_connections_backup_password" => Self::SetBackupPassword, + "set_connections_backup_target_password" => Self::SetBackupTargetPassword, + "run_connections_backup" => Self::RunBackup, + _ => return None, + }) + } + + fn authorization(self) -> AuthorizationLevel { + match self { + Self::ListImportSources + | Self::PreviewForeignImport + | Self::ApplyForeignImport + | Self::GetBackupStatus | Self::GetDatabaseBackupStatus | Self::RunDatabaseBackup | Self::CancelDatabaseBackup => AuthorizationLevel::LocalAdmin, + Self::Export + | Self::PreviewTabularisImport + | Self::ApplyPreparedTabularisImport + | Self::SetBackupPassword + | Self::SetBackupTargetPassword + | Self::RunBackup => AuthorizationLevel::Sensitive, + } + } +} + +impl NotebookRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "create_notebook" => Self::Create, + "save_notebook" => Self::Save, + "load_notebook" => Self::Load, + "delete_notebook" => Self::Delete, + "rename_notebook" => Self::Rename, + "list_notebooks" => Self::List, + _ => return None, + }) + } +} + +impl ProductivityRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_saved_queries" => Self::GetSavedQueries, + "save_query" => Self::SaveQuery, + "update_saved_query" => Self::UpdateSavedQuery, + "delete_saved_query" => Self::DeleteSavedQuery, + "get_saved_query_folders" => Self::GetSavedQueryFolders, + "create_saved_query_folder" => Self::CreateSavedQueryFolder, + "rename_saved_query_folder" => Self::RenameSavedQueryFolder, + "delete_saved_query_folder" => Self::DeleteSavedQueryFolder, + "move_saved_query" => Self::MoveSavedQuery, + "get_query_history" => Self::GetQueryHistory, + "add_query_history_entry" => Self::AddQueryHistoryEntry, + "delete_query_history_entry" => Self::DeleteQueryHistoryEntry, + "clear_query_history" => Self::ClearQueryHistory, + _ => return None, + }) + } +} + +impl PersistenceRpcCommand { + fn parse(name: &str) -> Option { + use crate::application::persistence::PromptKind; + Some(match name { + "get_config" => Self::GetConfig, + "save_config" => Self::SaveConfig, + "get_config_json" => Self::GetConfigJson, + "save_config_json" => Self::SaveConfigJson, + "get_keybindings" => Self::GetKeybindings, + "save_keybindings" => Self::SaveKeybindings, + "get_all_themes" => Self::GetAllThemes, + "save_custom_theme" => Self::SaveCustomTheme, + "delete_custom_theme" => Self::DeleteCustomTheme, + "get_system_prompt" => Self::GetPrompt(PromptKind::System), + "save_system_prompt" => Self::SavePrompt(PromptKind::System), + "reset_system_prompt" => Self::ResetPrompt(PromptKind::System), + "get_explain_prompt" => Self::GetPrompt(PromptKind::Explain), + "save_explain_prompt" => Self::SavePrompt(PromptKind::Explain), + "reset_explain_prompt" => Self::ResetPrompt(PromptKind::Explain), + "get_explainplan_prompt" => Self::GetPrompt(PromptKind::ExplainPlan), + "save_explainplan_prompt" => Self::SavePrompt(PromptKind::ExplainPlan), + "reset_explainplan_prompt" => Self::ResetPrompt(PromptKind::ExplainPlan), + "get_cellname_prompt" => Self::GetPrompt(PromptKind::CellName), + "save_cellname_prompt" => Self::SavePrompt(PromptKind::CellName), + "reset_cellname_prompt" => Self::ResetPrompt(PromptKind::CellName), + "get_tabrename_prompt" => Self::GetPrompt(PromptKind::TabRename), + "save_tabrename_prompt" => Self::SavePrompt(PromptKind::TabRename), + "reset_tabrename_prompt" => Self::ResetPrompt(PromptKind::TabRename), + "load_editor_preferences" => Self::LoadEditorPreferences, + "save_editor_preferences" => Self::SaveEditorPreferences, + "delete_editor_preferences" => Self::DeleteEditorPreferences, + "get_last_active_connection" => Self::GetLastActiveConnection, + "set_last_active_connection" => Self::SetLastActiveConnection, + "get_last_open_connections" => Self::GetLastOpenConnections, + "set_last_open_connections" => Self::SetLastOpenConnections, + _ => return None, + }) + } + + fn authorization(self) -> AuthorizationLevel { + match self { + Self::LoadEditorPreferences + | Self::SaveEditorPreferences + | Self::DeleteEditorPreferences => AuthorizationLevel::Database, + Self::GetLastActiveConnection + | Self::SetLastActiveConnection + | Self::GetLastOpenConnections + | Self::SetLastOpenConnections => AuthorizationLevel::Session, + _ => AuthorizationLevel::LocalAdmin, + } + } +} + +impl QueryRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "release_query_session" => Self::ReleaseSession, + "execute_query" => Self::Execute, + "execute_query_batch" => Self::ExecuteBatch, + "count_query" => Self::Count, + "explain_query_plan" => Self::Explain, + "get_server_now" => Self::GetServerNow, + _ => return None, + }) + } +} + +impl RecordRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "delete_record" => Self::Delete, + "update_record" => Self::Update, + "insert_record" => Self::Insert, + "fetch_blob" => Self::FetchBlob, + "detect_blob_mime" => Self::DetectBlobMime, + "detect_mime_type" => Self::DetectMimeType, + _ => return None, + }) + } +} + +impl DatabaseObjectRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_table_query_template" => Self::GetTableQueryTemplate, + "get_column_stats" => Self::GetColumnStats, + "get_drop_table_sql" => Self::GetDropTableSql, + "get_data_types" => Self::GetDataTypes, + "map_inferred_column_types" => Self::MapInferredColumnTypes, + "execute_clipboard_import" => Self::ExecuteClipboardImport, + "get_view_definition" => Self::GetViewDefinition, + "create_view" => Self::CreateView, + "alter_view" => Self::AlterView, + "drop_view" => Self::DropView, + "refresh_materialized_view" => Self::RefreshMaterializedView, + "get_routine_parameters" => Self::GetRoutineParameters, + "get_routine_definition" => Self::GetRoutineDefinition, + "build_routine_call_sql" => Self::BuildRoutineCallSql, + "get_routine_create_template" => Self::GetRoutineCreateTemplate, + "get_routine_edit_script" => Self::GetRoutineEditScript, + "drop_routine" => Self::DropRoutine, + "get_trigger_definition" => Self::GetTriggerDefinition, + "create_trigger" => Self::CreateTrigger, + "drop_trigger" => Self::DropTrigger, + "get_create_table_sql" => Self::GetCreateTableSql, + "get_add_column_sql" => Self::GetAddColumnSql, + "get_alter_column_sql" => Self::GetAlterColumnSql, + "get_create_index_sql" => Self::GetCreateIndexSql, + "get_create_foreign_key_sql" => Self::GetCreateForeignKeySql, + "drop_index_action" => Self::DropIndex, + "drop_foreign_key_action" => Self::DropForeignKey, + "get_db_privilege_catalog" => Self::GetDbPrivilegeCatalog, + "get_db_users" => Self::GetDbUsers, + "get_db_user_grants" => Self::GetDbUserGrants, + "get_db_user_privileges" => Self::GetDbUserPrivileges, + "create_db_user" => Self::CreateDbUser, + "drop_db_user" => Self::DropDbUser, + "set_db_user_password" => Self::SetDbUserPassword, + "apply_db_user_privileges" => Self::ApplyDbUserPrivileges, + _ => return None, + }) + } + + fn requires_sensitive_authorization(self) -> bool { + matches!( + self, + Self::GetDbPrivilegeCatalog + | Self::GetDbUsers + | Self::GetDbUserGrants + | Self::GetDbUserPrivileges + | Self::CreateDbUser + | Self::DropDbUser + | Self::SetDbUserPassword + | Self::ApplyDbUserPrivileges + ) + } +} + +impl MetadataRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_connection_metadata" => Self::GetConnectionMetadata, + "get_available_databases" => Self::GetAvailableDatabases, + "get_schemas" => Self::GetSchemas, + "get_tables" => Self::GetTables, + "get_columns" => Self::GetColumns, + "get_foreign_keys" => Self::GetForeignKeys, + "get_indexes" => Self::GetIndexes, + "get_views" => Self::GetViews, + "get_view_columns" => Self::GetViewColumns, + "get_materialized_views" => Self::GetMaterializedViews, + "get_materialized_view_columns" => Self::GetMaterializedViewColumns, + "get_materialized_view_definition" => Self::GetMaterializedViewDefinition, + "get_routines" => Self::GetRoutines, + "get_triggers" => Self::GetTriggers, + "get_schema_snapshot" => Self::GetSchemaSnapshot, + "get_selected_schemas" => Self::GetSelectedSchemas, + "set_selected_schemas" => Self::SetSelectedSchemas, + "get_schema_preference" => Self::GetSchemaPreference, + "set_schema_preference" => Self::SetSchemaPreference, + _ => return None, + }) + } +} + +impl TunnelRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "get_ssh_connections" => Self::GetSshConnections, + "save_ssh_connection" => Self::SaveSshConnection, + "update_ssh_connection" => Self::UpdateSshConnection, + "delete_ssh_connection" => Self::DeleteSshConnection, + "test_ssh_connection" => Self::TestSshConnection, + "respond_ssh_askpass" => Self::RespondSshAskpass, + "get_k8s_connections" => Self::GetK8sConnections, + "save_k8s_connection" => Self::SaveK8sConnection, + "update_k8s_connection" => Self::UpdateK8sConnection, + "delete_k8s_connection" => Self::DeleteK8sConnection, + "test_k8s_connection_cmd" => Self::TestK8sConnection, + "get_k8s_contexts_cmd" => Self::GetK8sContexts, + "get_k8s_namespaces_cmd" => Self::GetK8sNamespaces, + "get_k8s_resources_cmd" => Self::GetK8sResources, + "get_k8s_resource_ports_cmd" => Self::GetK8sResourcePorts, + "validate_k8s_path_cmd" => Self::ValidateK8sPath, + "test_ssm_connection_cmd" => Self::TestSsmConnection, + _ => return None, + }) + } +} + +impl ConnectionRpcCommand { + fn parse(name: &str) -> Option { + Some(match name { + "set_selected_databases" => Self::SetSelectedDatabases, + "get_connection_by_id" => Self::GetConnectionById, + "get_connections_with_groups" => Self::GetConnectionsWithGroups, + "save_connection" => Self::SaveConnection, + "update_connection" => Self::UpdateConnection, + "delete_connection" => Self::DeleteConnection, + "duplicate_connection" => Self::DuplicateConnection, + "set_connection_appearance" => Self::SetConnectionAppearance, + "save_connection_icon" => Self::SaveConnectionIcon, + "delete_connection_icon" => Self::DeleteConnectionIcon, + "get_connection_groups" => Self::GetConnectionGroups, + "create_connection_group" => Self::CreateConnectionGroup, + "create_group_path" => Self::CreateGroupPath, + "update_connection_group" => Self::UpdateConnectionGroup, + "move_group_to_parent" => Self::MoveGroupToParent, + "delete_connection_group" => Self::DeleteConnectionGroup, + "move_connection_to_group" => Self::MoveConnectionToGroup, + "reorder_groups" => Self::ReorderGroups, + "reorder_connections_in_group" => Self::ReorderConnectionsInGroup, + "list_connection_tags" => Self::ListConnectionTags, + "create_connection_tag" => Self::CreateConnectionTag, + "update_connection_tag" => Self::UpdateConnectionTag, + "delete_connection_tag" => Self::DeleteConnectionTag, + "set_connection_tags" => Self::SetConnectionTags, + "get_registered_drivers" => Self::GetRegisteredDrivers, + "get_driver_manifest" => Self::GetDriverManifest, + "get_active_connections" => Self::GetActiveConnections, + "register_active_connection" => Self::RegisterActiveConnection, + "disconnect_connection" => Self::DisconnectConnection, + "test_connection" => Self::TestConnection, + "list_databases" => Self::ListDatabases, + _ => return None, + }) + } +} + +fn decode_ai_command(command: AiRpcCommand, body: &[u8]) -> Result { + Ok(match command { + AiRpcCommand::SetKey => { + let request: SetAiKeyRequest = decode_payload(body)?; + AiCommand::SetKey { + provider: request.provider, + key: request.key, + } + } + AiRpcCommand::DeleteKey | AiRpcCommand::CheckKey | AiRpcCommand::CheckKeyStatus => { + let request: AiProviderRequest = decode_payload(body)?; + match command { + AiRpcCommand::DeleteKey => AiCommand::DeleteKey { + provider: request.provider, + }, + AiRpcCommand::CheckKey => AiCommand::CheckKey { + provider: request.provider, + }, + AiRpcCommand::CheckKeyStatus => AiCommand::CheckKeyStatus { + provider: request.provider, + }, + _ => unreachable!(), + } + } + AiRpcCommand::GetModels => { + let request: Option = decode_payload(body)?; + AiCommand::GetModels { + force_refresh: request.is_some_and(|request| request.force_refresh), + } + } + AiRpcCommand::GenerateQuery => { + let request: AiRequest = decode_payload(body)?; + AiCommand::GenerateQuery(request.req) + } + AiRpcCommand::ExplainQuery => { + let request: AiRequest = decode_payload(body)?; + AiCommand::ExplainQuery(request.req) + } + AiRpcCommand::AnalyzeExplainPlan => { + let request: AiRequest = decode_payload(body)?; + AiCommand::AnalyzeExplainPlan(request.req) + } + AiRpcCommand::GenerateCellName => { + let request: AiRequest = decode_payload(body)?; + AiCommand::GenerateCellName(request.req) + } + AiRpcCommand::GenerateTabRename => { + let request: AiRequest = decode_payload(body)?; + AiCommand::GenerateTabRename(request.req) + } + AiRpcCommand::SuggestTableName => { + let request: AiRequest = decode_payload(body)?; + AiCommand::SuggestTableName(request.req) + } + AiRpcCommand::GetSchemaContext => { + let request: AiSchemaContextRequest = decode_payload(body)?; + AiCommand::GetSchemaContext { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + AiRpcCommand::GetActivity => { + let request: Option = decode_payload(body)?; + AiCommand::GetActivity { + filter: request.and_then(|request| request.filter), + } + } + AiRpcCommand::GetSessions => { + decode_empty_payload(body)?; + AiCommand::GetSessions + } + AiRpcCommand::GetSessionEvents => { + let request: AiSessionRequest = decode_payload(body)?; + AiCommand::GetSessionEvents { + session_id: request.session_id, + } + } + AiRpcCommand::ClearActivity => { + decode_empty_payload(body)?; + AiCommand::ClearActivity + } + AiRpcCommand::ListPendingApprovals => { + decode_empty_payload(body)?; + AiCommand::ListPendingApprovals + } + AiRpcCommand::DecidePendingApproval => { + let request: AiApprovalDecisionRequest = decode_payload(body)?; + AiCommand::DecidePendingApproval { + approval_id: request.approval_id, + decision: request.decision, + reason: request.reason, + edited_query: request.edited_query, + } + } + }) +} + +fn decode_database_transfer_command( + command: DatabaseTransferRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + DatabaseTransferRpcCommand::Dump => { + let request: DumpDatabaseRequest = decode_payload(body)?; + DatabaseTransferCommand::Dump { + connection_id: request.connection_id, + options: request.options, + schema: request.schema, + database: request.database, + } + } + DatabaseTransferRpcCommand::CancelDump => { + let request: ConnectionIdRequest = decode_payload(body)?; + DatabaseTransferCommand::CancelDump { + connection_id: request.connection_id, + } + } + DatabaseTransferRpcCommand::Import => { + let request: ImportDatabaseRequest = decode_payload(body)?; + DatabaseTransferCommand::Import { + connection_id: request.connection_id, + upload_token: request.upload_token, + schema: request.schema, + database: request.database, + } + } + DatabaseTransferRpcCommand::CancelImport => { + let request: ConnectionIdRequest = decode_payload(body)?; + DatabaseTransferCommand::CancelImport { + connection_id: request.connection_id, + } + } + }) +} + +fn decode_generic_export_command( + command: GenericExportRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + GenericExportRpcCommand::ExportQuery => { + let request: QueryExportRequest = decode_payload(body)?; + GenericExportCommand::ExportQuery { + connection_id: request.connection_id, + query: request.query, + format: request.format, + csv_delimiter: request.csv_delimiter, + database: request.database, + query_session_id: request.session_id, + } + } + GenericExportRpcCommand::CancelExport => { + let request: ConnectionIdRequest = decode_payload(body)?; + GenericExportCommand::CancelExport { + connection_id: request.connection_id, + } + } + GenericExportRpcCommand::ExportAiActivityJson => { + decode_empty_payload(body)?; + GenericExportCommand::ExportAiActivityJson + } + GenericExportRpcCommand::ExportAiActivityCsv => { + decode_empty_payload(body)?; + GenericExportCommand::ExportAiActivityCsv + } + GenericExportRpcCommand::ExportAiSessionAsNotebook => { + let request: AiSessionExportRequest = decode_payload(body)?; + GenericExportCommand::ExportAiSessionAsNotebook { + session_id: request.session_id, + } + } + GenericExportRpcCommand::ExportLogs => { + decode_empty_payload(body)?; + GenericExportCommand::ExportLogs + } + }) +} + +fn decode_connection_files_command( + command: ConnectionFilesRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + ConnectionFilesRpcCommand::Export => { + let request: ExportConnectionsFileRequest = decode_payload(body)?; + ConnectionFilesCommand::Export { + mode: request.mode, + password: request.password, + connection_ids: request.connection_ids, + } + } + ConnectionFilesRpcCommand::ListImportSources => { + decode_empty_payload(body)?; + ConnectionFilesCommand::ListImportSources + } + ConnectionFilesRpcCommand::PreviewForeignImport => { + let request: PreviewConnectionImportRequest = decode_payload(body)?; + ConnectionFilesCommand::PreviewForeignImport { + source_id: request.source_id, + include_passwords: request.include_passwords, + file: request.file, + } + } + ConnectionFilesRpcCommand::ApplyForeignImport => { + let request: ApplyConnectionImportRequest = decode_payload(body)?; + ConnectionFilesCommand::ApplyForeignImport { + source_id: request.source_id, + resolutions: request.resolutions, + } + } + ConnectionFilesRpcCommand::PreviewTabularisImport => { + let request: PreviewTabularisImportRequest = decode_payload(body)?; + ConnectionFilesCommand::PreviewTabularisImport { + file: request.file, + password: request.password, + } + } + ConnectionFilesRpcCommand::ApplyPreparedTabularisImport => { + let request: ApplyPreparedImportRequest = decode_payload(body)?; + ConnectionFilesCommand::ApplyPreparedTabularisImport { + resolutions: request.resolutions, + } + } + ConnectionFilesRpcCommand::GetDatabaseBackupStatus => { + decode_empty_payload(body)?; + ConnectionFilesCommand::GetDatabaseBackupStatus + } + ConnectionFilesRpcCommand::RunDatabaseBackup => { + decode_empty_payload(body)?; + ConnectionFilesCommand::RunDatabaseBackup + } + ConnectionFilesRpcCommand::CancelDatabaseBackup => { + decode_empty_payload(body)?; + ConnectionFilesCommand::CancelDatabaseBackup + } + ConnectionFilesRpcCommand::GetBackupStatus => { + decode_empty_payload(body)?; + ConnectionFilesCommand::GetBackupStatus + } + ConnectionFilesRpcCommand::SetBackupPassword => { + let request: SetBackupPasswordRequest = decode_payload(body)?; + ConnectionFilesCommand::SetBackupPassword { + password: request.password, + } + } + ConnectionFilesRpcCommand::SetBackupTargetPassword => { + let request: SetBackupTargetPasswordRequest = decode_payload(body)?; + ConnectionFilesCommand::SetBackupTargetPassword { + target_id: request.target_id, + password: request.password, + } + } + ConnectionFilesRpcCommand::RunBackup => { + decode_empty_payload(body)?; + ConnectionFilesCommand::RunBackup + } + }) +} + +fn decode_notebook_command( + command: NotebookRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + NotebookRpcCommand::Create | NotebookRpcCommand::Save => { + let request: NotebookContentRequest = decode_payload(body)?; + if command == NotebookRpcCommand::Create { + NotebookCommand::Create { + connection_id: request.connection_id, + notebook_id: request.notebook_id, + content: request.content, + } + } else { + NotebookCommand::Save { + connection_id: request.connection_id, + notebook_id: request.notebook_id, + content: request.content, + } + } + } + NotebookRpcCommand::Load | NotebookRpcCommand::Delete => { + let request: NotebookTargetRequest = decode_payload(body)?; + if command == NotebookRpcCommand::Load { + NotebookCommand::Load { + connection_id: request.connection_id, + notebook_id: request.notebook_id, + } + } else { + NotebookCommand::Delete { + connection_id: request.connection_id, + notebook_id: request.notebook_id, + } + } + } + NotebookRpcCommand::Rename => { + let request: RenameNotebookRequest = decode_payload(body)?; + NotebookCommand::Rename { + connection_id: request.connection_id, + notebook_id: request.notebook_id, + title: request.title, + } + } + NotebookRpcCommand::List => { + let request: ConnectionIdRequest = decode_payload(body)?; + NotebookCommand::List { + connection_id: request.connection_id, + } + } + }) +} + +fn decode_operational_command( + command: OperationalRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + OperationalRpcCommand::LogFrontendEvent => { + let request: LogFrontendEventRequest = decode_payload(body)?; + OperationalCommand::LogFrontendEvent { + level: request.level, + message: request.message, + } + } + OperationalRpcCommand::GetLogs => { + let request: GetLogsRpcRequest = decode_payload(body)?; + OperationalCommand::GetLogs(request.request) + } + OperationalRpcCommand::ClearLogs => { + decode_empty_payload(body)?; + OperationalCommand::ClearLogs + } + OperationalRpcCommand::GetLogSettings => { + decode_empty_payload(body)?; + OperationalCommand::GetLogSettings + } + OperationalRpcCommand::SetLogEnabled => { + let request: SetLogEnabledRequest = decode_payload(body)?; + OperationalCommand::SetLogEnabled { + enabled: request.enabled, + } + } + OperationalRpcCommand::SetLogMaxSize => { + let request: SetLogMaxSizeRequest = decode_payload(body)?; + OperationalCommand::SetLogMaxSize { + max_size: request.max_size, + } + } + OperationalRpcCommand::GetProcessList => { + decode_empty_payload(body)?; + OperationalCommand::GetProcessList + } + OperationalRpcCommand::GetSystemStats => { + decode_empty_payload(body)?; + OperationalCommand::GetSystemStats + } + OperationalRpcCommand::GetTabularisChildren => { + decode_empty_payload(body)?; + OperationalCommand::GetTabularisChildren + } + }) +} + +fn decode_mcp_host_command( + command: McpHostRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + McpHostRpcCommand::GetStatus => { + decode_empty_payload(body)?; + McpHostCommand::GetStatus + } + McpHostRpcCommand::InstallConfig => { + let request: McpClientRequest = decode_payload(body)?; + McpHostCommand::InstallConfig { + client_id: request.client_id, + } + } + }) +} + +fn decode_plugin_command(command: PluginRpcCommand, body: &[u8]) -> Result { + Ok(match command { + PluginRpcCommand::FetchRegistry => { + decode_empty_payload(body)?; + PluginCommand::FetchRegistry + } + PluginRpcCommand::FetchPreview => { + let request: PluginPreviewRequest = decode_payload(body)?; + PluginCommand::FetchPreview { + slug: request.slug, + registry_url: request.registry_url, + version: request.version, + } + } + PluginRpcCommand::FetchReadme => { + let request: PluginReadmeRequest = decode_payload(body)?; + PluginCommand::FetchReadme { + slug: request.slug, + locale: request.locale, + registry_url: request.registry_url, + } + } + PluginRpcCommand::Install => { + let request: InstallPluginRequest = decode_payload(body)?; + PluginCommand::Install { + plugin_id: request.plugin_id, + version: request.version, + registry_url: request.registry_url, + } + } + PluginRpcCommand::CancelInstall => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::CancelInstall { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::Uninstall => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::Uninstall { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::GetInstalled => { + decode_empty_payload(body)?; + PluginCommand::GetInstalled + } + PluginRpcCommand::Disable => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::Disable { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::Enable => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::Enable { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::GetManifest => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::GetManifest { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::GetStartupErrors => { + decode_empty_payload(body)?; + PluginCommand::GetStartupErrors + } + PluginRpcCommand::GetRuntimeWarnings => { + decode_empty_payload(body)?; + PluginCommand::GetRuntimeWarnings + } + PluginRpcCommand::KillProcess => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::KillProcess { + plugin_id: request.plugin_id, + } + } + PluginRpcCommand::RestartProcess => { + let request: PluginIdRequest = decode_payload(body)?; + PluginCommand::RestartProcess { + plugin_id: request.plugin_id, + } + } + }) +} + +fn decode_productivity_command( + command: ProductivityRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + ProductivityRpcCommand::GetSavedQueries => { + let request: ConnectionIdRequest = decode_payload(body)?; + ProductivityCommand::GetSavedQueries { + connection_id: request.connection_id, + } + } + ProductivityRpcCommand::SaveQuery => { + let request: SaveQueryRequest = decode_payload(body)?; + ProductivityCommand::SaveQuery { + connection_id: request.connection_id, + name: request.name, + sql: request.sql, + database: request.database, + } + } + ProductivityRpcCommand::UpdateSavedQuery => { + let request: UpdateSavedQueryRequest = decode_payload(body)?; + ProductivityCommand::UpdateSavedQuery { + connection_id: Some(request.connection_id), + id: request.id, + name: request.name, + sql: request.sql, + database: request.database, + } + } + ProductivityRpcCommand::DeleteSavedQuery => { + let request: ConnectionItemRequest = decode_payload(body)?; + ProductivityCommand::DeleteSavedQuery { + connection_id: Some(request.connection_id), + id: request.id, + } + } + ProductivityRpcCommand::GetSavedQueryFolders => { + let request: ConnectionIdRequest = decode_payload(body)?; + ProductivityCommand::GetSavedQueryFolders { + connection_id: request.connection_id, + } + } + ProductivityRpcCommand::CreateSavedQueryFolder => { + let request: CreateSavedQueryFolderRequest = decode_payload(body)?; + ProductivityCommand::CreateSavedQueryFolder { + connection_id: request.connection_id, + name: request.name, + } + } + ProductivityRpcCommand::RenameSavedQueryFolder => { + let request: RenameSavedQueryFolderRequest = decode_payload(body)?; + ProductivityCommand::RenameSavedQueryFolder { + connection_id: Some(request.connection_id), + id: request.id, + name: request.name, + } + } + ProductivityRpcCommand::DeleteSavedQueryFolder => { + let request: ConnectionItemRequest = decode_payload(body)?; + ProductivityCommand::DeleteSavedQueryFolder { + connection_id: Some(request.connection_id), + id: request.id, + } + } + ProductivityRpcCommand::MoveSavedQuery => { + let request: MoveSavedQueryRequest = decode_payload(body)?; + ProductivityCommand::MoveSavedQuery { + connection_id: Some(request.connection_id), + id: request.id, + folder_id: request.folder_id, + } + } + ProductivityRpcCommand::GetQueryHistory => { + let request: ConnectionIdRequest = decode_payload(body)?; + ProductivityCommand::GetQueryHistory { + connection_id: request.connection_id, + } + } + ProductivityRpcCommand::AddQueryHistoryEntry => { + let request: AddQueryHistoryEntryRequest = decode_payload(body)?; + ProductivityCommand::AddQueryHistoryEntry { + connection_id: request.connection_id, + sql: request.sql, + executed_at: request.executed_at, + execution_time_ms: request.execution_time_ms, + status: request.status.into_string(), + rows_affected: request.rows_affected, + error: request.error, + database: request.database, + } + } + ProductivityRpcCommand::DeleteQueryHistoryEntry => { + let request: ConnectionItemRequest = decode_payload(body)?; + ProductivityCommand::DeleteQueryHistoryEntry { + connection_id: request.connection_id, + id: request.id, + } + } + ProductivityRpcCommand::ClearQueryHistory => { + let request: ConnectionIdRequest = decode_payload(body)?; + ProductivityCommand::ClearQueryHistory { + connection_id: request.connection_id, + } + } + }) +} + +fn decode_persistence_command( + command: PersistenceRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + PersistenceRpcCommand::GetConfig => { + decode_empty_payload(body)?; + PersistenceCommand::GetConfig + } + PersistenceRpcCommand::SaveConfig => { + let request: SaveConfigRequest = decode_payload(body)?; + PersistenceCommand::SaveConfig(request.config) + } + PersistenceRpcCommand::GetConfigJson => { + decode_empty_payload(body)?; + PersistenceCommand::GetConfigJson + } + PersistenceRpcCommand::SaveConfigJson => { + let request: SaveConfigJsonRequest = decode_payload(body)?; + PersistenceCommand::SaveConfigJson(request.json) + } + PersistenceRpcCommand::GetKeybindings => { + decode_empty_payload(body)?; + PersistenceCommand::GetKeybindings + } + PersistenceRpcCommand::SaveKeybindings => { + let request: SaveKeybindingsRequest = decode_payload(body)?; + PersistenceCommand::SaveKeybindings(request.keybindings) + } + PersistenceRpcCommand::GetAllThemes => { + decode_empty_payload(body)?; + PersistenceCommand::GetAllThemes + } + PersistenceRpcCommand::SaveCustomTheme => { + let request: SaveThemeRequest = decode_payload(body)?; + PersistenceCommand::SaveCustomTheme(request.theme) + } + PersistenceRpcCommand::DeleteCustomTheme => { + let request: ThemeIdRequest = decode_payload(body)?; + PersistenceCommand::DeleteCustomTheme(request.theme_id) + } + PersistenceRpcCommand::GetPrompt(kind) => { + decode_empty_payload(body)?; + PersistenceCommand::GetPrompt(kind) + } + PersistenceRpcCommand::SavePrompt(kind) => { + let request: SavePromptRequest = decode_payload(body)?; + PersistenceCommand::SavePrompt(kind, request.prompt) + } + PersistenceRpcCommand::ResetPrompt(kind) => { + decode_empty_payload(body)?; + PersistenceCommand::ResetPrompt(kind) + } + PersistenceRpcCommand::LoadEditorPreferences => { + let request: ConnectionIdRequest = decode_payload(body)?; + PersistenceCommand::LoadEditorPreferences(request.connection_id) + } + PersistenceRpcCommand::SaveEditorPreferences => { + let request: SaveEditorPreferencesRequest = decode_payload(body)?; + PersistenceCommand::SaveEditorPreferences(request.connection_id, request.preferences) + } + PersistenceRpcCommand::DeleteEditorPreferences => { + let request: ConnectionIdRequest = decode_payload(body)?; + PersistenceCommand::DeleteEditorPreferences(request.connection_id) + } + PersistenceRpcCommand::GetLastActiveConnection => { + decode_empty_payload(body)?; + PersistenceCommand::GetLastActiveConnection + } + PersistenceRpcCommand::SetLastActiveConnection => { + let request: SetLastActiveConnectionRequest = decode_payload(body)?; + PersistenceCommand::SetLastActiveConnection(request.connection_id) + } + PersistenceRpcCommand::GetLastOpenConnections => { + decode_empty_payload(body)?; + PersistenceCommand::GetLastOpenConnections + } + PersistenceRpcCommand::SetLastOpenConnections => { + let request: SetLastOpenConnectionsRequest = decode_payload(body)?; + PersistenceCommand::SetLastOpenConnections(request.connection_ids) + } + }) +} + +fn decode_query_command(command: QueryRpcCommand, body: &[u8]) -> Result { + Ok(match command { + QueryRpcCommand::ReleaseSession => { + let request: ReleaseQuerySessionRequest = decode_payload(body)?; + QueryCommand::ReleaseSession { + connection_id: request.connection_id, + query_session_id: request.session_id, + } + } + QueryRpcCommand::Execute => { + let request: ExecuteQueryRequest = decode_payload(body)?; + QueryCommand::Execute { + connection_id: request.connection_id, + query: request.query, + limit: request.limit, + page: request.page, + schema: request.schema, + query_session_id: request.session_id, + database: request.database, + } + } + QueryRpcCommand::ExecuteBatch => { + let request: ExecuteQueryBatchRequest = decode_payload(body)?; + QueryCommand::ExecuteBatch { + connection_id: request.connection_id, + queries: request.queries, + limit: request.limit, + page: request.page, + schema: request.schema, + query_session_id: request.session_id, + batch_id: request.batch_id, + database: request.database, + } + } + QueryRpcCommand::Count => { + let request: CountQueryRequest = decode_payload(body)?; + QueryCommand::Count { + connection_id: request.connection_id, + query: request.query, + schema: request.schema, + query_session_id: request.session_id, + database: request.database, + } + } + QueryRpcCommand::Explain => { + let request: ExplainQueryRequest = decode_payload(body)?; + QueryCommand::Explain { + connection_id: request.connection_id, + query: request.query, + analyze: request.analyze, + schema: request.schema, + database: request.database, + } + } + QueryRpcCommand::GetServerNow => { + let request: ConnectionIdRequest = decode_payload(body)?; + QueryCommand::GetServerNow { + connection_id: request.connection_id, + } + } + }) +} + +fn decode_record_command(command: RecordRpcCommand, body: &[u8]) -> Result { + Ok(match command { + RecordRpcCommand::Delete => { + let request: RecordIdentityRequest = decode_payload(body)?; + RecordCommand::Delete { + connection_id: request.connection_id, + table: request.table, + pk_map: request.pk_map, + schema: request.schema, + database: request.database, + } + } + RecordRpcCommand::Update => { + let request: UpdateRecordRequest = decode_payload(body)?; + RecordCommand::Update { + connection_id: request.connection_id, + table: request.table, + pk_map: request.pk_map, + col_name: request.col_name, + new_val: request.new_val, + schema: request.schema, + database: request.database, + } + } + RecordRpcCommand::Insert => { + let request: InsertRecordRequest = decode_payload(body)?; + RecordCommand::Insert { + connection_id: request.connection_id, + table: request.table, + data: request.data, + schema: request.schema, + database: request.database, + } + } + RecordRpcCommand::FetchBlob => { + let request: BlobColumnRequest = decode_payload(body)?; + RecordCommand::FetchBlob { + connection_id: request.connection_id, + table: request.table, + col_name: request.col_name, + pk_map: request.pk_map, + schema: request.schema, + database: request.database, + } + } + RecordRpcCommand::DetectBlobMime => { + let request: DetectBlobMimeRequest = decode_payload(body)?; + RecordCommand::DetectBlobMime { + base64_data: request.base64_data, + } + } + RecordRpcCommand::DetectMimeType => { + let request: DetectMimeTypeRequest = decode_payload(body)?; + RecordCommand::DetectMimeType { + header_base64: request.header_base64, + } + } + }) +} + +fn decode_database_object_command( + command: DatabaseObjectRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + DatabaseObjectRpcCommand::GetColumnStats => { + let request: ColumnStatsRpcRequest = decode_payload(body)?; + DatabaseObjectCommand::GetColumnStats { + connection_id: request.connection_id, + request: request.request, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetDropTableSql => { + let request: DropTableSqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetDropTableSql { + connection_id: request.connection_id, + table: request.table, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetTableQueryTemplate => { + let request: TableQueryTemplateRequest = decode_payload(body)?; + DatabaseObjectCommand::GetTableQueryTemplate { + connection_id: request.connection_id, + request: request.request, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetDataTypes => { + let request: DriverTypesRequest = decode_payload(body)?; + DatabaseObjectCommand::GetDataTypes { + driver: request.driver, + } + } + DatabaseObjectRpcCommand::MapInferredColumnTypes => { + let request: MapInferredTypesRequest = decode_payload(body)?; + DatabaseObjectCommand::MapInferredColumnTypes { + driver: request.driver, + kinds: request.kinds, + connection_id: request.connection_id, + } + } + DatabaseObjectRpcCommand::ExecuteClipboardImport => { + let request: ClipboardImportRpcRequest = decode_payload(body)?; + DatabaseObjectCommand::ExecuteClipboardImport { req: request.req } + } + DatabaseObjectRpcCommand::GetViewDefinition + | DatabaseObjectRpcCommand::DropView + | DatabaseObjectRpcCommand::RefreshMaterializedView => { + let request: ViewMetadataRequest = decode_payload(body)?; + match command { + DatabaseObjectRpcCommand::GetViewDefinition => { + DatabaseObjectCommand::GetViewDefinition { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::DropView => DatabaseObjectCommand::DropView { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + }, + DatabaseObjectRpcCommand::RefreshMaterializedView => { + DatabaseObjectCommand::RefreshMaterializedView { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + } + } + _ => unreachable!(), + } + } + DatabaseObjectRpcCommand::CreateView | DatabaseObjectRpcCommand::AlterView => { + let request: ViewDefinitionRequest = decode_payload(body)?; + if command == DatabaseObjectRpcCommand::CreateView { + DatabaseObjectCommand::CreateView { + connection_id: request.connection_id, + view_name: request.view_name, + definition: request.definition, + schema: request.schema, + database: request.database, + } + } else { + DatabaseObjectCommand::AlterView { + connection_id: request.connection_id, + view_name: request.view_name, + definition: request.definition, + schema: request.schema, + database: request.database, + } + } + } + DatabaseObjectRpcCommand::GetRoutineParameters => { + let request: RoutineNameRequest = decode_payload(body)?; + DatabaseObjectCommand::GetRoutineParameters { + connection_id: request.connection_id, + routine_name: request.routine_name, + schema: request.schema, + database: request.database, + identity_args: request.identity_args, + } + } + DatabaseObjectRpcCommand::GetRoutineDefinition + | DatabaseObjectRpcCommand::GetRoutineEditScript + | DatabaseObjectRpcCommand::DropRoutine => { + let request: RoutineTargetRequest = decode_payload(body)?; + match command { + DatabaseObjectRpcCommand::GetRoutineDefinition => { + DatabaseObjectCommand::GetRoutineDefinition { + connection_id: request.connection_id, + routine_name: request.routine_name, + routine_type: request.routine_type, + schema: request.schema, + database: request.database, + identity_args: request.identity_args, + } + } + DatabaseObjectRpcCommand::GetRoutineEditScript => { + DatabaseObjectCommand::GetRoutineEditScript { + connection_id: request.connection_id, + routine_name: request.routine_name, + routine_type: request.routine_type, + schema: request.schema, + database: request.database, + identity_args: request.identity_args, + } + } + DatabaseObjectRpcCommand::DropRoutine => DatabaseObjectCommand::DropRoutine { + connection_id: request.connection_id, + routine_name: request.routine_name, + routine_type: request.routine_type, + schema: request.schema, + database: request.database, + identity_args: request.identity_args, + }, + _ => unreachable!(), + } + } + DatabaseObjectRpcCommand::BuildRoutineCallSql => { + let request: RoutineCallRequest = decode_payload(body)?; + DatabaseObjectCommand::BuildRoutineCallSql { + connection_id: request.connection_id, + routine_name: request.routine_name, + routine_type: request.routine_type, + args: request.args, + schema: request.schema, + } + } + DatabaseObjectRpcCommand::GetRoutineCreateTemplate => { + let request: RoutineTemplateRequest = decode_payload(body)?; + DatabaseObjectCommand::GetRoutineCreateTemplate { + connection_id: request.connection_id, + routine_type: request.routine_type, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetTriggerDefinition | DatabaseObjectRpcCommand::DropTrigger => { + let request: TriggerTargetRequest = decode_payload(body)?; + if command == DatabaseObjectRpcCommand::GetTriggerDefinition { + DatabaseObjectCommand::GetTriggerDefinition { + connection_id: request.connection_id, + trigger_name: request.trigger_name, + table_name: request.table_name, + schema: request.schema, + database: request.database, + } + } else { + DatabaseObjectCommand::DropTrigger { + connection_id: request.connection_id, + trigger_name: request.trigger_name, + table_name: request.table_name, + schema: request.schema, + database: request.database, + } + } + } + DatabaseObjectRpcCommand::CreateTrigger => { + let request: CreateTriggerRequest = decode_payload(body)?; + DatabaseObjectCommand::CreateTrigger { + connection_id: request.connection_id, + trigger_sql: request.trigger_sql, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetCreateTableSql => { + let request: CreateTableSqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetCreateTableSql { + connection_id: request.connection_id, + table_name: request.table_name, + columns: request.columns, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetAddColumnSql => { + let request: AddColumnSqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetAddColumnSql { + connection_id: request.connection_id, + table: request.table, + column: request.column, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetAlterColumnSql => { + let request: AlterColumnSqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetAlterColumnSql { + connection_id: request.connection_id, + table: request.table, + old_column: request.old_column, + new_column: request.new_column, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetCreateIndexSql => { + let request: CreateIndexSqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetCreateIndexSql { + connection_id: request.connection_id, + table: request.table, + index_name: request.index_name, + columns: request.columns, + is_unique: request.is_unique, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetCreateForeignKeySql => { + let request: CreateForeignKeySqlRequest = decode_payload(body)?; + DatabaseObjectCommand::GetCreateForeignKeySql { + connection_id: request.connection_id, + table: request.table, + fk_name: request.fk_name, + column: request.column, + ref_table: request.ref_table, + ref_column: request.ref_column, + on_delete: request.on_delete, + on_update: request.on_update, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::DropIndex => { + let request: DropIndexRequest = decode_payload(body)?; + DatabaseObjectCommand::DropIndex { + connection_id: request.connection_id, + table: request.table, + index_name: request.index_name, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::DropForeignKey => { + let request: DropForeignKeyRequest = decode_payload(body)?; + DatabaseObjectCommand::DropForeignKey { + connection_id: request.connection_id, + table: request.table, + fk_name: request.fk_name, + schema: request.schema, + database: request.database, + } + } + DatabaseObjectRpcCommand::GetDbPrivilegeCatalog => { + let request: ConnectionIdRequest = decode_payload(body)?; + DatabaseObjectCommand::GetDbPrivilegeCatalog { + connection_id: request.connection_id, + } + } + DatabaseObjectRpcCommand::GetDbUsers => { + let request: ConnectionIdRequest = decode_payload(body)?; + DatabaseObjectCommand::GetDbUsers { + connection_id: request.connection_id, + } + } + DatabaseObjectRpcCommand::GetDbUserGrants + | DatabaseObjectRpcCommand::GetDbUserPrivileges + | DatabaseObjectRpcCommand::DropDbUser => { + let request: DbUserTargetRequest = decode_payload(body)?; + match command { + DatabaseObjectRpcCommand::GetDbUserGrants => { + DatabaseObjectCommand::GetDbUserGrants { + connection_id: request.connection_id, + user: request.user, + host: request.host, + } + } + DatabaseObjectRpcCommand::GetDbUserPrivileges => { + DatabaseObjectCommand::GetDbUserPrivileges { + connection_id: request.connection_id, + user: request.user, + host: request.host, + } + } + DatabaseObjectRpcCommand::DropDbUser => DatabaseObjectCommand::DropDbUser { + connection_id: request.connection_id, + user: request.user, + host: request.host, + }, + _ => unreachable!(), + } + } + DatabaseObjectRpcCommand::CreateDbUser | DatabaseObjectRpcCommand::SetDbUserPassword => { + let request: DbUserPasswordRequest = decode_payload(body)?; + if command == DatabaseObjectRpcCommand::CreateDbUser { + DatabaseObjectCommand::CreateDbUser { + connection_id: request.connection_id, + user: request.user, + host: request.host, + password: request.password, + } + } else { + DatabaseObjectCommand::SetDbUserPassword { + connection_id: request.connection_id, + user: request.user, + host: request.host, + password: request.password, + } + } + } + DatabaseObjectRpcCommand::ApplyDbUserPrivileges => { + let request: ApplyDbUserPrivilegesRequest = decode_payload(body)?; + DatabaseObjectCommand::ApplyDbUserPrivileges { + connection_id: request.connection_id, + user: request.user, + host: request.host, + database: request.database, + table: request.table, + privileges: request.privileges, + grant: request.grant, + } + } + }) +} + +fn decode_metadata_command( + command: MetadataRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + MetadataRpcCommand::GetConnectionMetadata => { + let request: ConnectionIdRequest = decode_payload(body)?; + MetadataCommand::GetConnectionMetadata { + connection_id: request.connection_id, + } + } + MetadataRpcCommand::GetAvailableDatabases => { + let request: ConnectionIdRequest = decode_payload(body)?; + MetadataCommand::GetAvailableDatabases { + connection_id: request.connection_id, + } + } + MetadataRpcCommand::GetSchemas => { + let request: ConnectionIdRequest = decode_payload(body)?; + MetadataCommand::GetSchemas { + connection_id: request.connection_id, + database: request.database, + } + } + MetadataRpcCommand::GetTables => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetTables { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetColumns => { + let request: TableMetadataRequest = decode_payload(body)?; + MetadataCommand::GetColumns { + connection_id: request.connection_id, + table_name: request.table_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetForeignKeys => { + let request: TableMetadataRequest = decode_payload(body)?; + MetadataCommand::GetForeignKeys { + connection_id: request.connection_id, + table_name: request.table_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetIndexes => { + let request: TableMetadataRequest = decode_payload(body)?; + MetadataCommand::GetIndexes { + connection_id: request.connection_id, + table_name: request.table_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetViews => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetViews { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetViewColumns => { + let request: ViewMetadataRequest = decode_payload(body)?; + MetadataCommand::GetViewColumns { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetMaterializedViews => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetMaterializedViews { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetMaterializedViewColumns => { + let request: ViewMetadataRequest = decode_payload(body)?; + MetadataCommand::GetMaterializedViewColumns { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetMaterializedViewDefinition => { + let request: ViewMetadataRequest = decode_payload(body)?; + MetadataCommand::GetMaterializedViewDefinition { + connection_id: request.connection_id, + view_name: request.view_name, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetRoutines => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetRoutines { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetTriggers => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetTriggers { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetSchemaSnapshot => { + let request: MetadataRequest = decode_payload(body)?; + MetadataCommand::GetSchemaSnapshot { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + MetadataRpcCommand::GetSelectedSchemas => { + let request: ConnectionIdRequest = decode_payload(body)?; + MetadataCommand::GetSelectedSchemas { + connection_id: request.connection_id, + database: request.database, + } + } + MetadataRpcCommand::SetSelectedSchemas => { + let request: SetSelectedSchemasRequest = decode_payload(body)?; + MetadataCommand::SetSelectedSchemas { + connection_id: request.connection_id, + schemas: request.schemas, + database: request.database, + } + } + MetadataRpcCommand::GetSchemaPreference => { + let request: ConnectionIdRequest = decode_payload(body)?; + MetadataCommand::GetSchemaPreference { + connection_id: request.connection_id, + database: request.database, + } + } + MetadataRpcCommand::SetSchemaPreference => { + let request: SetSchemaPreferenceRequest = decode_payload(body)?; + MetadataCommand::SetSchemaPreference { + connection_id: request.connection_id, + schema: request.schema, + database: request.database, + } + } + }) +} + +fn decode_tunnel_command(command: TunnelRpcCommand, body: &[u8]) -> Result { + Ok(match command { + TunnelRpcCommand::GetSshConnections => { + decode_empty_payload(body)?; + TunnelCommand::GetSshConnections + } + TunnelRpcCommand::SaveSshConnection => { + let request: SaveSshRequest = decode_payload(body)?; + TunnelCommand::SaveSshConnection { + name: request.name, + ssh: request.ssh, + } + } + TunnelRpcCommand::UpdateSshConnection => { + let request: UpdateSshRequest = decode_payload(body)?; + TunnelCommand::UpdateSshConnection { + id: request.id, + name: request.name, + ssh: request.ssh, + } + } + TunnelRpcCommand::DeleteSshConnection => { + let request: IdRequest = decode_payload(body)?; + TunnelCommand::DeleteSshConnection { id: request.id } + } + TunnelRpcCommand::TestSshConnection => { + let request: TestSshRequest = decode_payload(body)?; + TunnelCommand::TestSshConnection { ssh: request.ssh } + } + TunnelRpcCommand::RespondSshAskpass => { + let request: AskpassResponseRequest = decode_payload(body)?; + TunnelCommand::RespondSshAskpass { + id: request.id, + response: request.response, + } + } + TunnelRpcCommand::GetK8sConnections => { + decode_empty_payload(body)?; + TunnelCommand::GetK8sConnections + } + TunnelRpcCommand::SaveK8sConnection => { + let request: SaveK8sRequest = decode_payload(body)?; + TunnelCommand::SaveK8sConnection { k8s: request.k8s } + } + TunnelRpcCommand::UpdateK8sConnection => { + let request: UpdateK8sRequest = decode_payload(body)?; + TunnelCommand::UpdateK8sConnection { + id: request.id, + k8s: request.k8s, + } + } + TunnelRpcCommand::DeleteK8sConnection => { + let request: IdRequest = decode_payload(body)?; + TunnelCommand::DeleteK8sConnection { id: request.id } + } + TunnelRpcCommand::TestK8sConnection => { + let request: TestK8sRequest = decode_payload(body)?; + TunnelCommand::TestK8sConnection { + context: request.context, + namespace: request.namespace, + options: k8s_options(request.kubectl_path, request.kubeconfig_path), + } + } + TunnelRpcCommand::GetK8sContexts => { + let request: K8sOptionsRequest = decode_optional_payload(body)?; + TunnelCommand::GetK8sContexts { + options: k8s_options(request.kubectl_path, request.kubeconfig_path), + } + } + TunnelRpcCommand::GetK8sNamespaces => { + let request: K8sContextRequest = decode_payload(body)?; + TunnelCommand::GetK8sNamespaces { + context: request.context, + options: k8s_options(request.kubectl_path, request.kubeconfig_path), + } + } + TunnelRpcCommand::GetK8sResources => { + let request: K8sResourcesRequest = decode_payload(body)?; + TunnelCommand::GetK8sResources { + context: request.context, + namespace: request.namespace, + resource_type: request.resource_type, + options: k8s_options(request.kubectl_path, request.kubeconfig_path), + } + } + TunnelRpcCommand::GetK8sResourcePorts => { + let request: K8sPortsRequest = decode_payload(body)?; + TunnelCommand::GetK8sResourcePorts { + context: request.context, + namespace: request.namespace, + resource_type: request.resource_type, + resource_name: request.resource_name, + options: k8s_options(request.kubectl_path, request.kubeconfig_path), + } + } + TunnelRpcCommand::ValidateK8sPath => { + let request: ValidateK8sPathRequest = decode_payload(body)?; + TunnelCommand::ValidateK8sPath { + path: request.path, + kind: request.kind, + } + } + TunnelRpcCommand::TestSsmConnection => { + let request: TestSsmConnectionRequest = decode_payload(body)?; + TunnelCommand::TestSsmConnection { + target: request.target, + profile: request.profile, + region: request.region, + host: request.host, + port: request.port, + } + } + }) +} + +fn k8s_options( + kubectl_path: Option, + kubeconfig_path: Option, +) -> crate::k8s_tunnel::K8sCommandOptions { + crate::k8s_tunnel::K8sCommandOptions::new(kubectl_path, kubeconfig_path) +} + +fn decode_optional_payload Deserialize<'de> + Default>( + body: &[u8], +) -> Result { + if body.is_empty() { + return Ok(T::default()); + } + let value: Value = decode_payload(body)?; + if value.is_null() { + Ok(T::default()) + } else { + serde_json::from_value(value).map_err(|error| format!("Invalid command payload: {error}")) + } +} + +fn decode_connection_command( + command: ConnectionRpcCommand, + session_id: Option, + body: &[u8], +) -> Result { + Ok(match command { + ConnectionRpcCommand::SetSelectedDatabases => { + let request: SetSelectedDatabasesRequest = decode_payload(body)?; + ConnectionCommand::SetSelectedDatabases { + connection_id: request.connection_id, + databases: request.databases, + } + } + ConnectionRpcCommand::GetConnectionById => { + let request: IdRequest = decode_payload(body)?; + ConnectionCommand::GetConnectionById { id: request.id } + } + ConnectionRpcCommand::GetConnectionsWithGroups => { + decode_empty_payload(body)?; + ConnectionCommand::GetConnectionsWithGroups + } + ConnectionRpcCommand::SaveConnection => { + let request: SaveConnectionRequest = decode_payload(body)?; + ConnectionCommand::SaveConnection { + name: request.name, + params: request.params, + plugin_secret_changes: request.plugin_secret_changes, + detect_json_in_text_columns: request.detect_json_in_text_columns, + environment: request.environment, + } + } + ConnectionRpcCommand::UpdateConnection => { + let request: UpdateConnectionRequest = decode_payload(body)?; + ConnectionCommand::UpdateConnection { + id: request.id, + name: request.name, + params: request.params, + plugin_secret_changes: request.plugin_secret_changes, + detect_json_in_text_columns: request.detect_json_in_text_columns, + environment: request.environment, + } + } + ConnectionRpcCommand::DeleteConnection => { + let request: IdRequest = decode_payload(body)?; + ConnectionCommand::DeleteConnection { id: request.id } + } + ConnectionRpcCommand::DuplicateConnection => { + let request: IdRequest = decode_payload(body)?; + ConnectionCommand::DuplicateConnection { id: request.id } + } + ConnectionRpcCommand::SetConnectionAppearance => { + let request: AppearanceRequest = decode_payload(body)?; + ConnectionCommand::SetConnectionAppearance { + id: request.id, + appearance: request.appearance, + } + } + ConnectionRpcCommand::SaveConnectionIcon => { + let request: SaveIconRequest = decode_payload(body)?; + ConnectionCommand::SaveConnectionIcon { + connection_id: request.connection_id, + upload_token: request.upload_token, + session_id: session_id + .ok_or_else(|| "An authenticated upload session is required".to_string())?, + } + } + ConnectionRpcCommand::DeleteConnectionIcon => { + let request: DeleteIconRequest = decode_payload(body)?; + ConnectionCommand::DeleteConnectionIcon { + relative_path: request.relative_path, + } + } + ConnectionRpcCommand::GetConnectionGroups => { + decode_empty_payload(body)?; + ConnectionCommand::GetConnectionGroups + } + ConnectionRpcCommand::CreateConnectionGroup => { + let request: CreateGroupRequest = decode_payload(body)?; + ConnectionCommand::CreateConnectionGroup { + name: request.name, + parent_id: request.parent_id, + } + } + ConnectionRpcCommand::CreateGroupPath => { + let request: CreateGroupPathRequest = decode_payload(body)?; + ConnectionCommand::CreateGroupPath { + path: request.path, + parent_id: request.parent_id, + } + } + ConnectionRpcCommand::UpdateConnectionGroup => { + let request: UpdateGroupRequest = decode_payload(body)?; + ConnectionCommand::UpdateConnectionGroup { + id: request.id, + name: request.name, + collapsed: request.collapsed, + sort_order: request.sort_order, + } + } + ConnectionRpcCommand::MoveGroupToParent => { + let request: MoveGroupRequest = decode_payload(body)?; + ConnectionCommand::MoveGroupToParent { + id: request.id, + parent_id: request.parent_id, + } + } + ConnectionRpcCommand::DeleteConnectionGroup => { + let request: IdRequest = decode_payload(body)?; + ConnectionCommand::DeleteConnectionGroup { id: request.id } + } + ConnectionRpcCommand::MoveConnectionToGroup => { + let request: MoveConnectionRequest = decode_payload(body)?; + ConnectionCommand::MoveConnectionToGroup { + connection_id: request.connection_id, + group_id: request.group_id, + sort_order: request.sort_order, + } + } + ConnectionRpcCommand::ReorderGroups => { + let request: ReorderGroupsRequest = decode_payload(body)?; + ConnectionCommand::ReorderGroups { + group_orders: request.group_orders, + } + } + ConnectionRpcCommand::ReorderConnectionsInGroup => { + let request: ReorderConnectionsRequest = decode_payload(body)?; + ConnectionCommand::ReorderConnectionsInGroup { + connection_orders: request.connection_orders, + } + } + ConnectionRpcCommand::ListConnectionTags => { + decode_empty_payload(body)?; + ConnectionCommand::ListConnectionTags + } + ConnectionRpcCommand::CreateConnectionTag => { + let request: CreateTagRequest = decode_payload(body)?; + ConnectionCommand::CreateConnectionTag { + name: request.name, + color: request.color, + } + } + ConnectionRpcCommand::UpdateConnectionTag => { + let request: TagMutationRequest = decode_payload(body)?; + ConnectionCommand::UpdateConnectionTag { + id: request.id, + name: request.name, + color: request.color, + } + } + ConnectionRpcCommand::DeleteConnectionTag => { + let request: IdRequest = decode_payload(body)?; + ConnectionCommand::DeleteConnectionTag { id: request.id } + } + ConnectionRpcCommand::SetConnectionTags => { + let request: SetTagsRequest = decode_payload(body)?; + ConnectionCommand::SetConnectionTags { + connection_id: request.connection_id, + tag_ids: request.tag_ids, + } + } + ConnectionRpcCommand::GetRegisteredDrivers => { + decode_empty_payload(body)?; + ConnectionCommand::GetRegisteredDrivers + } + ConnectionRpcCommand::GetDriverManifest => { + let request: DriverManifestRequest = decode_payload(body)?; + ConnectionCommand::GetDriverManifest { + driver_id: request.driver_id, + } + } + ConnectionRpcCommand::GetActiveConnections => { + decode_empty_payload(body)?; + ConnectionCommand::GetActiveConnections + } + ConnectionRpcCommand::RegisterActiveConnection => { + let request: ConnectionIdRequest = decode_payload(body)?; + ConnectionCommand::RegisterActiveConnection { + connection_id: request.connection_id, + } + } + ConnectionRpcCommand::DisconnectConnection => { + let request: ConnectionIdRequest = decode_payload(body)?; + ConnectionCommand::DisconnectConnection { + connection_id: request.connection_id, + } + } + ConnectionRpcCommand::TestConnection => { + let request: TestRequest = decode_payload(body)?; + ConnectionCommand::TestConnection { + request: request.request, + } + } + ConnectionRpcCommand::ListDatabases => { + let request: TestRequest = decode_payload(body)?; + ConnectionCommand::ListDatabases { + request: request.request, + } + } + }) +} + +impl Drop for CancellationRegistration { + fn drop(&mut self) { + self.active + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&self.id); + } +} + +fn decode_empty_payload(body: &[u8]) -> Result<(), String> { + if body.is_empty() { + return Ok(()); + } + let value: Value = decode_payload(body)?; + if value.is_null() || value.as_object().is_some_and(|object| object.is_empty()) { + Ok(()) + } else { + Err("This command does not accept a payload".to_string()) + } +} + +fn decode_payload Deserialize<'de>>(body: &[u8]) -> Result { + serde_json::from_slice(body).map_err(|error| format!("Invalid command payload: {error}")) +} + +fn request_deadline(headers: &HeaderMap) -> Result { + let Some(value) = headers.get(RPC_DEADLINE_HEADER_NAME) else { + return Ok(DEFAULT_DEADLINE); + }; + let milliseconds = value + .to_str() + .ok() + .and_then(|value| value.parse::().ok()) + .filter(|value| *value > 0) + .ok_or_else(|| "The RPC deadline must be a positive number of milliseconds".to_string())?; + let deadline = Duration::from_millis(milliseconds); + if deadline > MAX_DEADLINE { + return Err(format!( + "The RPC deadline cannot exceed {} milliseconds", + MAX_DEADLINE.as_millis() + )); + } + Ok(deadline) +} + +fn cancellation_id(headers: &HeaderMap) -> Result, String> { + let Some(value) = headers.get(RPC_CANCELLATION_HEADER_NAME) else { + return Ok(None); + }; + let value = value + .to_str() + .map_err(|_| "The cancellation identifier is not valid text".to_string())?; + if value.is_empty() + || value.len() > MAX_CANCELLATION_ID_LENGTH + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')) + { + return Err("The cancellation identifier has an invalid format".to_string()); + } + Ok(Some(value.to_string())) +} + +fn validate_query_request_id(request_id: &str) -> Result<(), String> { + if request_id.is_empty() + || request_id.len() > MAX_CANCELLATION_ID_LENGTH + || !request_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')) + { + return Err("The query request identifier has an invalid format".to_string()); + } + Ok(()) +} + +fn has_json_content_type(headers: &HeaderMap) -> bool { + headers + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(';') + .next() + .is_some_and(|mime| mime.trim().eq_ignore_ascii_case("application/json")) + }) +} + +fn success(data: Value) -> Response { + ( + StatusCode::OK, + [(CACHE_CONTROL, "no-store")], + Json(RpcSuccess { ok: true, data }), + ) + .into_response() +} + +fn failure( + status: StatusCode, + code: &'static str, + message: String, + details: Option, + request_id: String, +) -> Response { + ( + status, + [(CACHE_CONTROL, "no-store")], + Json(RpcFailure { + ok: false, + error: RpcError { + code, + message, + details, + request_id, + }, + }), + ) + .into_response() +} + +#[cfg(test)] +#[path = "rpc_tests.rs"] +mod tests; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CreateSavedQueryFolderRequest { + connection_id: String, + name: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RenameSavedQueryFolderRequest { + connection_id: String, + id: String, + name: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MoveSavedQueryRequest { + connection_id: String, + id: String, + folder_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ColumnStatsRpcRequest { + connection_id: String, + request: crate::models::ColumnStatsRequest, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DropTableSqlRequest { + connection_id: String, + table: String, + schema: Option, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TableQueryTemplateRequest { + connection_id: String, + request: crate::models::TableQueryTemplateRequest, + database: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DriverTypesRequest { + driver: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MapInferredTypesRequest { + driver: String, + kinds: Vec, + connection_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ClipboardImportRpcRequest { + req: crate::clipboard_import::ClipboardImportRequest, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetSelectedDatabasesRequest { + connection_id: String, + databases: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LogFrontendEventRequest { + level: String, + message: String, +} diff --git a/src-tauri/src/transport/web/rpc_connection_policy.rs b/src-tauri/src/transport/web/rpc_connection_policy.rs new file mode 100644 index 000000000..8aa17806e --- /dev/null +++ b/src-tauri/src/transport/web/rpc_connection_policy.rs @@ -0,0 +1,185 @@ +use super::{ConnectionRpcCommand, DatabaseObjectRpcCommand, InvocationError, RpcCommand}; +use crate::application::{ + connections::ConnectionCommand, ApplicationApi, ApplicationRequestContext, AuthorizationLevel, +}; +use crate::models::ConnectionParams; +use serde_json::Value; + +/// Saved tunnel IDs resolve to administrator-controlled settings. Inline settings +/// can select host executables, credentials and files, even on Database RPCs. +pub(super) fn authorize( + command: &ConnectionCommand, + granted: AuthorizationLevel, +) -> Result<(), &'static str> { + if granted.permits(AuthorizationLevel::LocalAdmin) { + return Ok(()); + } + let params = match command { + ConnectionCommand::SaveConnection { params, .. } + | ConnectionCommand::UpdateConnection { params, .. } => params, + ConnectionCommand::TestConnection { request } + | ConnectionCommand::ListDatabases { request } => &request.params, + _ => return Ok(()), + }; + + authorize_driver(¶ms.driver)?; + // This runtime-only ID can select pooled connections and saved proxy secrets. + if params.connection_id.is_some() { + return Err("Runtime connection IDs require local administrator authorization"); + } + + // Reject dormant inline settings too: saving them must not bypass the + // authorization required to execute them later through a saved connection. + // The form always supplies ssh_port, which is harmless while SSH is off + // and replaced by the stored port when using a saved SSH profile. + let inline_tunnel = (params.ssh_enabled == Some(true) && params.ssh_connection_id.is_none()) + || params.ssh_host.is_some() + || params.ssh_user.is_some() + || params.ssh_password.is_some() + || params.ssh_key_file.is_some() + || params.ssh_key_passphrase.is_some() + || params.ssh_allow_passphrase_prompt == Some(true) + || (params.k8s_enabled == Some(true) && params.k8s_connection_id.is_none()) + || params.k8s_context.is_some() + || params.k8s_namespace.is_some() + || params.k8s_resource_type.is_some() + || params.k8s_resource_name.is_some() + || params.k8s_port.is_some() + || params.k8s_kubectl_path.is_some() + || params.k8s_kubeconfig_path.is_some() + || params.ssm_enabled == Some(true) + || params.ssm_target.is_some() + || params.ssm_profile.is_some() + || params.ssm_region.is_some(); + let host_certificate = + params.ssl_ca.is_some() || params.ssl_cert.is_some() || params.ssl_key.is_some(); + // A custom endpoint can receive a saved proxy password selected by the + // connection ID. Only administrators may choose that credential's host. + let custom_proxy = params.proxy.as_ref().is_some_and(|proxy| { + proxy.mode == crate::proxy::ProxyMode::Custom || proxy.endpoint.is_some() + }); + if inline_tunnel || host_certificate || custom_proxy { + return Err("Inline tunnel, host certificate and proxy settings require local administrator authorization"); + } + Ok(()) +} + +fn authorize_driver(driver: &str) -> Result<(), &'static str> { + if driver == "sqlite" || crate::drivers::registry::is_local_path_driver(driver) { + Err("File and folder database drivers require local administrator authorization") + } else { + Ok(()) + } +} + +/// Check saved references before any RPC branch can resolve a file-backed connection. +pub(super) async fn authorize_saved_access( + application: &dyn ApplicationApi, + command: RpcCommand, + context: &ApplicationRequestContext, + body: &[u8], + granted: AuthorizationLevel, +) -> Result<(), InvocationError> { + if granted.permits(AuthorizationLevel::LocalAdmin) || body.is_empty() { + return Ok(()); + } + let payload: Value = super::decode_payload(body).map_err(InvocationError::InvalidPayload)?; + let reference = match command { + RpcCommand::Connection( + ConnectionRpcCommand::GetConnectionById + | ConnectionRpcCommand::UpdateConnection + | ConnectionRpcCommand::DeleteConnection + | ConnectionRpcCommand::DuplicateConnection + | ConnectionRpcCommand::SetConnectionAppearance, + ) => &payload["id"], + RpcCommand::Connection( + ConnectionRpcCommand::TestConnection | ConnectionRpcCommand::ListDatabases, + ) => &payload["request"]["connection_id"], + RpcCommand::DatabaseObject(DatabaseObjectRpcCommand::ExecuteClipboardImport) => { + &payload["req"]["connection_id"] + } + _ => &payload["connectionId"], + }; + if let Some(id) = reference.as_str() { + if let Some(params) = application + .connection_params_for_authorization(context.clone(), id) + .await + .map_err(InvocationError::Application)? + { + authorize_driver(¶ms.driver).map_err(InvocationError::Forbidden)?; + } + } + Ok(()) +} + +pub(super) async fn authorize_saved_credentials( + application: &dyn ApplicationApi, + context: &ApplicationRequestContext, + command: &ConnectionCommand, + granted: AuthorizationLevel, +) -> Result<(), InvocationError> { + if granted.permits(AuthorizationLevel::LocalAdmin) { + return Ok(()); + } + let (id, params) = match command { + ConnectionCommand::TestConnection { request } + | ConnectionCommand::ListDatabases { request } => { + let Some(id) = request.connection_id.as_deref() else { + return Ok(()); + }; + (id, &request.params) + } + ConnectionCommand::UpdateConnection { id, params, .. } => (id.as_str(), params), + _ => return Ok(()), + }; + let Some(saved) = application + .connection_params_for_authorization(context.clone(), id) + .await + .map_err(InvocationError::Application)? + else { + return Ok(()); + }; + // Replacing a password can leave older keychain entries behind, so bind the + // saved identity even when this request supplies a replacement credential. + if security_target(params) != security_target(&saved) { + return Err(InvocationError::Forbidden( + "Changing a saved connection security target requires local administrator authorization", + )); + } + Ok(()) +} + +fn security_target(params: &ConnectionParams) -> Value { + // Include opaque plugin fields and all transport/authentication settings by default. + // Only secrets and settings that cannot retarget a connection are excluded. + let mut target = serde_json::to_value(params).expect("Connection parameters serialize"); + let target_fields = target + .as_object_mut() + .expect("Connection parameters are an object"); + // The connection form tests the primary database of a multi-selection. + target_fields.insert( + "database".into(), + Value::String(params.database.primary().into()), + ); + // The form omits blank legacy TLS modes; both use the driver's default. + if params + .ssl_mode + .as_deref() + .is_none_or(|mode| mode.trim().is_empty()) + { + target_fields.remove("ssl_mode"); + } + for field in [ + "password", + "ssh_password", + "ssh_key_passphrase", + "save_in_keychain", + "connection_uri_in_keychain", + "connection_id", + "startup_script", + "pipes_as_concat", + ] { + target_fields.remove(field); + } + target +} diff --git a/src-tauri/src/transport/web/rpc_host_commands.rs b/src-tauri/src/transport/web/rpc_host_commands.rs new file mode 100644 index 000000000..a0f9e2b4d --- /dev/null +++ b/src-tauri/src/transport/web/rpc_host_commands.rs @@ -0,0 +1,542 @@ +//! Browser RPC routes for theme packages, host settings, SQL files and the +//! shared UI state store. +//! +//! Every path a browser sends is a path on the server. Paths are resolved +//! against the configured server file-browser roots before they reach the +//! application layer, exactly like the SQLite file helpers in `rpc.rs`. + +use super::{decode_empty_payload, decode_payload}; +use crate::application::host_settings::HostSettingsCommand; +use crate::application::themes::{LocalThemeArchive, ThemeCommand}; +use crate::application::ui_state::UiStateCommand; +use crate::application::AuthorizationLevel; +use crate::transport::web::server_files; +use serde::Deserialize; +use serde_json::Value; +use std::path::PathBuf; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum ThemeRpcCommand { + GetCatalog, + CreatePersonalTheme, + CreatePersonalSnapshot, + UpdatePersonalTheme, + UpdatePersonalSnapshot, + DuplicatePersonalTheme, + ImportTheme, + ExportTheme, + PreviewThemeDocument, + PreviewLocalPackage, + InstallLocalPackage, + FetchRegistry, + FetchPackageDetail, + InstallRegistryTheme, + CancelInstall, + SetPackageEnabled, + UninstallPackage, + RecoverPackages, +} + +impl ThemeRpcCommand { + pub(super) fn parse(name: &str) -> Option { + Some(match name { + "get_theme_catalog" => Self::GetCatalog, + "create_personal_theme" => Self::CreatePersonalTheme, + "create_personal_snapshot" => Self::CreatePersonalSnapshot, + "update_personal_theme" => Self::UpdatePersonalTheme, + "update_personal_snapshot" => Self::UpdatePersonalSnapshot, + "duplicate_personal_theme" => Self::DuplicatePersonalTheme, + "import_theme" => Self::ImportTheme, + "export_theme" => Self::ExportTheme, + "preview_theme_document" => Self::PreviewThemeDocument, + "preview_local_theme_package" => Self::PreviewLocalPackage, + "install_local_theme_package" => Self::InstallLocalPackage, + "fetch_theme_registry" => Self::FetchRegistry, + "fetch_theme_package_detail" => Self::FetchPackageDetail, + "install_registry_theme" => Self::InstallRegistryTheme, + "cancel_theme_install" => Self::CancelInstall, + "set_theme_package_enabled" => Self::SetPackageEnabled, + "uninstall_theme_package" => Self::UninstallPackage, + "recover_theme_packages" => Self::RecoverPackages, + _ => return None, + }) + } + + /// Reading the catalog is needed by every session to render; changing + /// themes or packages changes host files and stays local-admin. + pub(super) fn authorization(self) -> AuthorizationLevel { + match self { + Self::GetCatalog | Self::PreviewThemeDocument => AuthorizationLevel::Session, + _ => AuthorizationLevel::LocalAdmin, + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum HostSettingsRpcCommand { + ProxyPasswordIsSet, + SetProxyPassword, + DeleteProxyPassword, + GetStorageLocation, + InspectStorageLocation, + SetStorageLocation, + ResetStorageLocation, + GetAppDataDir, +} + +impl HostSettingsRpcCommand { + pub(super) fn parse(name: &str) -> Option { + Some(match name { + "proxy_password_is_set" => Self::ProxyPasswordIsSet, + "set_proxy_password" => Self::SetProxyPassword, + "delete_proxy_password" => Self::DeleteProxyPassword, + "get_storage_location" => Self::GetStorageLocation, + "inspect_storage_location" => Self::InspectStorageLocation, + "set_storage_location" => Self::SetStorageLocation, + "reset_storage_location" => Self::ResetStorageLocation, + "get_app_data_dir" => Self::GetAppDataDir, + _ => return None, + }) + } + + pub(super) fn authorization(self) -> AuthorizationLevel { + match self { + Self::ProxyPasswordIsSet | Self::SetProxyPassword | Self::DeleteProxyPassword => { + AuthorizationLevel::Sensitive + } + _ => AuthorizationLevel::LocalAdmin, + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum UiStateRpcCommand { + Get, + Set, + Delete, +} + +impl UiStateRpcCommand { + pub(super) fn parse(name: &str) -> Option { + Some(match name { + "get_ui_state" => Self::Get, + "set_ui_state" => Self::Set, + "delete_ui_state" => Self::Delete, + _ => return None, + }) + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct NameSourceRequest { + name: String, + source: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdatePersonalThemeRequest { + theme_id: String, + name: String, + source: String, + expected_revision: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdatePersonalSnapshotRequest { + theme_id: String, + name: String, + source: String, + editor: Value, + expected_revision: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DuplicatePersonalThemeRequest { + theme_id: String, + name: String, + #[serde(default)] + editor: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ImportThemeRequest { + theme_json: String, + #[serde(default)] + name: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ThemeIdRequest { + theme_id: String, +} + +/// Browsers either upload the archive (`uploadToken`) or pick it with the +/// server file browser (`path`). +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LocalPackageRequest { + #[serde(default)] + path: Option, + #[serde(default)] + upload_token: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct InstallLocalPackageRequest { + #[serde(default)] + path: Option, + #[serde(default)] + upload_token: Option, + package_name: String, + expected_digest: String, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FetchThemeRegistryRequest { + #[serde(default)] + package_name: Option, + #[serde(default)] + expected_registry_key: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FetchThemePackageDetailRequest { + package_name: String, + expected_registry_key: String, + #[serde(default)] + requested_registry_url: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct InstallRegistryThemeRequest { + package_name: String, + expected_registry_key: String, + #[serde(default)] + version: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ThemePackageRequest { + registry_key: String, + package_name: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetThemePackageEnabledRequest { + registry_key: String, + package_name: String, + enabled: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProxySlotRequest { + slot: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetProxyPasswordRequest { + slot: String, + password: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StoragePathRequest { + path: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetStorageLocationRequest { + path: String, + copy_data: bool, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct GetUiStateRequest { + #[serde(default)] + keys: Option>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SetUiStateRequest { + key: String, + value: Value, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UiStateKeyRequest { + key: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ReadSqlFileRequest { + pub(super) path: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct WriteSqlFileRequest { + pub(super) path: String, + pub(super) content: String, +} + +fn decode_optional Deserialize<'de> + Default>(body: &[u8]) -> Result { + if body.is_empty() { + return Ok(T::default()); + } + let value: Value = decode_payload(body)?; + if value.is_null() { + return Ok(T::default()); + } + serde_json::from_value(value).map_err(|error| format!("Invalid command payload: {error}")) +} + +fn local_archive( + roots: &[PathBuf], + session_id: Option, + path: Option, + upload_token: Option, +) -> Result { + match (path, upload_token) { + (Some(path), None) => Ok(LocalThemeArchive::Path( + server_files::validate_existing_file(roots, &path)?, + )), + (None, Some(token)) => Ok(LocalThemeArchive::Upload { + owner: session_id.ok_or_else(|| "A browser session is required".to_string())?, + token, + }), + _ => Err("Provide either a server path or an upload token".to_string()), + } +} + +/// Decoding errors are payload errors; path confinement errors are too, +/// because they reject the request before any work starts. +pub(super) fn decode_theme_command( + command: ThemeRpcCommand, + body: &[u8], + roots: &[PathBuf], + session_id: Option, +) -> Result { + Ok(match command { + ThemeRpcCommand::GetCatalog => { + decode_empty_payload(body)?; + ThemeCommand::GetCatalog + } + ThemeRpcCommand::CreatePersonalTheme => { + let request: NameSourceRequest = decode_payload(body)?; + ThemeCommand::CreatePersonalTheme { + name: request.name, + source: request.source, + } + } + ThemeRpcCommand::CreatePersonalSnapshot => { + let request: NameSourceRequest = decode_payload(body)?; + ThemeCommand::CreatePersonalSnapshot { + name: request.name, + source: request.source, + } + } + ThemeRpcCommand::UpdatePersonalTheme => { + let request: UpdatePersonalThemeRequest = decode_payload(body)?; + ThemeCommand::UpdatePersonalTheme { + theme_id: request.theme_id, + name: request.name, + source: request.source, + expected_revision: request.expected_revision, + } + } + ThemeRpcCommand::UpdatePersonalSnapshot => { + let request: UpdatePersonalSnapshotRequest = decode_payload(body)?; + ThemeCommand::UpdatePersonalSnapshot { + theme_id: request.theme_id, + name: request.name, + source: request.source, + editor: request.editor, + expected_revision: request.expected_revision, + } + } + ThemeRpcCommand::DuplicatePersonalTheme => { + let request: DuplicatePersonalThemeRequest = decode_payload(body)?; + ThemeCommand::DuplicatePersonalTheme { + theme_id: request.theme_id, + name: request.name, + editor: request.editor, + } + } + ThemeRpcCommand::ImportTheme => { + let request: ImportThemeRequest = decode_payload(body)?; + ThemeCommand::ImportTheme { + theme_json: request.theme_json, + name: request.name, + } + } + ThemeRpcCommand::ExportTheme => { + let request: ThemeIdRequest = decode_payload(body)?; + ThemeCommand::ExportTheme { + theme_id: request.theme_id, + } + } + ThemeRpcCommand::PreviewThemeDocument => { + let request: NameSourceRequest = decode_payload(body)?; + ThemeCommand::PreviewThemeDocument { + source: request.source, + name: request.name, + } + } + ThemeRpcCommand::PreviewLocalPackage => { + let request: LocalPackageRequest = decode_payload(body)?; + ThemeCommand::PreviewLocalPackage { + archive: local_archive(roots, session_id, request.path, request.upload_token)?, + } + } + ThemeRpcCommand::InstallLocalPackage => { + let request: InstallLocalPackageRequest = decode_payload(body)?; + ThemeCommand::InstallLocalPackage { + archive: local_archive(roots, session_id, request.path, request.upload_token)?, + package_name: request.package_name, + expected_digest: request.expected_digest, + } + } + ThemeRpcCommand::FetchRegistry => { + let request: FetchThemeRegistryRequest = decode_optional(body)?; + ThemeCommand::FetchRegistry { + package_name: request.package_name, + expected_registry_key: request.expected_registry_key, + } + } + ThemeRpcCommand::FetchPackageDetail => { + let request: FetchThemePackageDetailRequest = decode_payload(body)?; + ThemeCommand::FetchPackageDetail { + package_name: request.package_name, + expected_registry_key: request.expected_registry_key, + requested_registry_url: request.requested_registry_url, + } + } + ThemeRpcCommand::InstallRegistryTheme => { + let request: InstallRegistryThemeRequest = decode_payload(body)?; + ThemeCommand::InstallRegistryTheme { + package_name: request.package_name, + expected_registry_key: request.expected_registry_key, + version: request.version, + } + } + ThemeRpcCommand::CancelInstall => { + let request: ThemePackageRequest = decode_payload(body)?; + ThemeCommand::CancelInstall { + registry_key: request.registry_key, + package_name: request.package_name, + } + } + ThemeRpcCommand::SetPackageEnabled => { + let request: SetThemePackageEnabledRequest = decode_payload(body)?; + ThemeCommand::SetPackageEnabled { + registry_key: request.registry_key, + package_name: request.package_name, + enabled: request.enabled, + } + } + ThemeRpcCommand::UninstallPackage => { + let request: ThemePackageRequest = decode_payload(body)?; + ThemeCommand::UninstallPackage { + registry_key: request.registry_key, + package_name: request.package_name, + } + } + ThemeRpcCommand::RecoverPackages => { + decode_empty_payload(body)?; + ThemeCommand::RecoverPackages + } + }) +} + +pub(super) fn decode_host_settings_command( + command: HostSettingsRpcCommand, + body: &[u8], + roots: &[PathBuf], +) -> Result { + Ok(match command { + HostSettingsRpcCommand::ProxyPasswordIsSet => { + let request: ProxySlotRequest = decode_payload(body)?; + HostSettingsCommand::ProxyPasswordIsSet { slot: request.slot } + } + HostSettingsRpcCommand::SetProxyPassword => { + let request: SetProxyPasswordRequest = decode_payload(body)?; + HostSettingsCommand::SetProxyPassword { + slot: request.slot, + password: request.password, + } + } + HostSettingsRpcCommand::DeleteProxyPassword => { + let request: ProxySlotRequest = decode_payload(body)?; + HostSettingsCommand::DeleteProxyPassword { slot: request.slot } + } + HostSettingsRpcCommand::GetStorageLocation => { + decode_empty_payload(body)?; + HostSettingsCommand::GetStorageLocation + } + HostSettingsRpcCommand::InspectStorageLocation => { + let request: StoragePathRequest = decode_payload(body)?; + HostSettingsCommand::InspectStorageLocation { + path: server_files::validate_directory_target(roots, &request.path)?, + } + } + HostSettingsRpcCommand::SetStorageLocation => { + let request: SetStorageLocationRequest = decode_payload(body)?; + HostSettingsCommand::SetStorageLocation { + path: server_files::validate_directory_target(roots, &request.path)?, + copy_data: request.copy_data, + } + } + HostSettingsRpcCommand::ResetStorageLocation => { + decode_empty_payload(body)?; + HostSettingsCommand::ResetStorageLocation + } + HostSettingsRpcCommand::GetAppDataDir => { + decode_empty_payload(body)?; + HostSettingsCommand::GetAppDataDir + } + }) +} + +pub(super) fn decode_ui_state_command( + command: UiStateRpcCommand, + body: &[u8], +) -> Result { + Ok(match command { + UiStateRpcCommand::Get => { + let request: GetUiStateRequest = decode_optional(body)?; + UiStateCommand::Get { keys: request.keys } + } + UiStateRpcCommand::Set => { + let request: SetUiStateRequest = decode_payload(body)?; + UiStateCommand::Set { + key: request.key, + value: request.value, + } + } + UiStateRpcCommand::Delete => { + let request: UiStateKeyRequest = decode_payload(body)?; + UiStateCommand::Delete { key: request.key } + } + }) +} diff --git a/src-tauri/src/transport/web/rpc_tests.rs b/src-tauri/src/transport/web/rpc_tests.rs new file mode 100644 index 000000000..b85aeb863 --- /dev/null +++ b/src-tauri/src/transport/web/rpc_tests.rs @@ -0,0 +1,3057 @@ +use super::*; +use crate::models::DatabaseSelection; +use async_trait::async_trait; +use axum::body::to_bytes; +use axum::http::header::CONTENT_TYPE; +use axum::http::HeaderValue; +use uuid::Uuid; + +struct FixtureApplication { + delay: Duration, + saved_params: HashMap, + contexts: Arc>>, +} + +impl FixtureApplication { + fn new(delay: Duration) -> Self { + Self { + delay, + saved_params: HashMap::new(), + contexts: Arc::new(Mutex::new(Vec::new())), + } + } + + async fn record(&self, context: ApplicationRequestContext) { + self.contexts + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(context); + tokio::time::sleep(self.delay).await; + } +} + +#[async_trait] +impl ApplicationApi for FixtureApplication { + fn clear_session(&self, _session_id: uuid::Uuid) {} + + async fn is_debug_mode( + &self, + context: ApplicationRequestContext, + ) -> Result { + self.record(context).await; + Ok(true) + } + + async fn get_connections( + &self, + context: ApplicationRequestContext, + ) -> Result, ApplicationError> { + self.record(context).await; + Ok(Vec::new()) + } + + async fn connection_params_for_authorization( + &self, + _context: ApplicationRequestContext, + connection_id: &str, + ) -> Result, ApplicationError> { + Ok(self.saved_params.get(connection_id).cloned()) + } + + async fn cancel_query( + &self, + context: ApplicationRequestContext, + _connection_id: String, + query_request_id: Option, + ) -> Result<(), ApplicationError> { + self.record(context).await; + if query_request_id.is_some() { + Ok(()) + } else { + Err(ApplicationError::new("No running query found")) + } + } + + async fn execute_query_command( + &self, + context: ApplicationRequestContext, + _command: QueryCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_connection_command( + &self, + context: ApplicationRequestContext, + _command: ConnectionCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_connection_files_command( + &self, + context: ApplicationRequestContext, + command: crate::application::connection_files::ConnectionFilesCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::connection_files::ConnectionFilesCommand::ListImportSources => { + serde_json::json!([]) + } + crate::application::connection_files::ConnectionFilesCommand::GetBackupStatus => { + serde_json::json!({ + "passwordSet": true, + "targetPasswordSet": true, + "lastBackupAt": null, + "targetKind": "serverDirectory", + "targetDisplay": "/srv/tabularis/backups" + }) + } + _ => Value::Null, + }) + } + + async fn execute_database_transfer_command( + &self, + context: ApplicationRequestContext, + command: crate::application::database_transfers::DatabaseTransferCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::database_transfers::DatabaseTransferCommand::Dump { .. } => { + serde_json::json!({ + "kind": "download", + "fileName": "fixture.sql", + "mimeType": "application/sql", + "token": "fixture-download-token", + "size": 128 + }) + } + _ => Value::Null, + }) + } + + async fn execute_generic_export_command( + &self, + context: ApplicationRequestContext, + command: crate::application::generic_exports::GenericExportCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::generic_exports::GenericExportCommand::ExportQuery { .. } => { + serde_json::json!({ + "kind": "download", + "fileName": "result.csv", + "mimeType": "text/csv", + "token": "query-export-download-token", + "size": 14 + }) + } + crate::application::generic_exports::GenericExportCommand::ExportAiActivityJson => { + serde_json::json!("{\"id\":\"activity-1\"}\n") + } + crate::application::generic_exports::GenericExportCommand::ExportAiActivityCsv => { + serde_json::json!("id,status\nactivity-1,success\n") + } + crate::application::generic_exports::GenericExportCommand::ExportAiSessionAsNotebook { .. } => { + serde_json::json!({"title": "AI session", "cells": []}) + } + crate::application::generic_exports::GenericExportCommand::ExportLogs => { + serde_json::json!({ + "kind": "download", + "fileName": "tabularis-logs.log", + "mimeType": "text/plain", + "token": "logs-download-token", + "size": 64 + }) + } + crate::application::generic_exports::GenericExportCommand::CancelExport { .. } => { + Value::Null + } + }) + } + + async fn execute_ai_command( + &self, + context: ApplicationRequestContext, + command: crate::application::ai::AiCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::ai::AiCommand::CheckKeyStatus { .. } => { + serde_json::json!({"configured": true, "fromEnv": false}) + } + crate::application::ai::AiCommand::GetModels { .. } => { + serde_json::json!({"openai": ["gpt-contract"]}) + } + crate::application::ai::AiCommand::GenerateQuery(_) => { + serde_json::json!("SELECT 1") + } + crate::application::ai::AiCommand::GetActivity { .. } + | crate::application::ai::AiCommand::GetSessions + | crate::application::ai::AiCommand::GetSessionEvents { .. } + | crate::application::ai::AiCommand::ListPendingApprovals => serde_json::json!([]), + crate::application::ai::AiCommand::GetSchemaContext { .. } => { + serde_json::json!("table values(id integer)") + } + _ => Value::Null, + }) + } + + async fn execute_metadata_command( + &self, + context: ApplicationRequestContext, + _command: MetadataCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_database_object_command( + &self, + context: ApplicationRequestContext, + _command: DatabaseObjectCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_record_command( + &self, + context: ApplicationRequestContext, + command: RecordCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + RecordCommand::Insert { .. } + | RecordCommand::Update { .. } + | RecordCommand::Delete { .. } => serde_json::json!(1), + RecordCommand::FetchBlob { .. } => serde_json::json!({ + "kind": "inline", + "wireValue": "BLOB:4:application/octet-stream:AAECAw==" + }), + RecordCommand::DetectBlobMime { .. } => { + serde_json::json!("BLOB:4:application/octet-stream:AAECAw==") + } + RecordCommand::DetectMimeType { .. } => { + serde_json::json!("application/octet-stream") + } + }) + } + + async fn execute_tunnel_command( + &self, + context: ApplicationRequestContext, + _command: TunnelCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_persistence_command( + &self, + context: ApplicationRequestContext, + command: crate::application::persistence::PersistenceCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::persistence::PersistenceCommand::GetConfig => { + serde_json::json!({"theme": "tabularis-dark"}) + } + crate::application::persistence::PersistenceCommand::GetKeybindings => { + serde_json::json!({}) + } + crate::application::persistence::PersistenceCommand::GetAllThemes => { + serde_json::json!([]) + } + crate::application::persistence::PersistenceCommand::GetPrompt(_) + | crate::application::persistence::PersistenceCommand::ResetPrompt(_) => { + serde_json::json!("Generate SQL only") + } + crate::application::persistence::PersistenceCommand::LoadEditorPreferences(_) => { + Value::Null + } + crate::application::persistence::PersistenceCommand::GetLastActiveConnection => { + Value::Null + } + crate::application::persistence::PersistenceCommand::GetLastOpenConnections => { + serde_json::json!([]) + } + _ => Value::Null, + }) + } + + async fn execute_productivity_command( + &self, + context: ApplicationRequestContext, + _command: crate::application::productivity::ProductivityCommand, + ) -> Result { + self.record(context).await; + Ok(Value::Null) + } + + async fn execute_notebook_command( + &self, + context: ApplicationRequestContext, + command: crate::application::notebooks::NotebookCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::notebooks::NotebookCommand::Load { .. } => { + serde_json::json!("{}") + } + crate::application::notebooks::NotebookCommand::List { .. } => { + serde_json::json!([]) + } + _ => Value::Null, + }) + } + + async fn execute_plugin_command( + &self, + context: ApplicationRequestContext, + command: crate::application::plugins::PluginCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::plugins::PluginCommand::FetchRegistry => serde_json::json!([]), + crate::application::plugins::PluginCommand::FetchPreview { slug, .. } => { + serde_json::json!({"id": slug, "install_action": "install"}) + } + crate::application::plugins::PluginCommand::FetchReadme { locale, .. } => { + serde_json::json!({"html": "

Plugin

", "locale": locale}) + } + crate::application::plugins::PluginCommand::GetInstalled + | crate::application::plugins::PluginCommand::GetStartupErrors => { + serde_json::json!([]) + } + crate::application::plugins::PluginCommand::CancelInstall { .. } => { + serde_json::json!(true) + } + _ => Value::Null, + }) + } + + async fn execute_operational_command( + &self, + context: ApplicationRequestContext, + command: crate::application::operations::OperationalCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::operations::OperationalCommand::GetLogs(_) => { + serde_json::json!([{ + "timestamp": "2026-08-22 09:00:00.000", + "level": "ERROR", + "message": "Contract log", + "target": "contract" + }]) + } + crate::application::operations::OperationalCommand::GetLogSettings => { + serde_json::json!({"enabled": true, "max_size": 1000, "current_count": 1}) + } + crate::application::operations::OperationalCommand::GetProcessList => { + serde_json::json!([{ + "plugin_id": "postgres-driver", + "plugin_name": "PostgreSQL Driver", + "pid": 4100, + "cpu_percent": 1.5, + "memory_bytes": 2048, + "disk_read_bytes": 128, + "disk_write_bytes": 64, + "status": "running", + "children": [] + }]) + } + crate::application::operations::OperationalCommand::GetSystemStats => { + serde_json::json!({ + "cpu_percent": 12.5, + "memory_used": 4096, + "memory_total": 8192, + "disk_read_bytes": 256, + "disk_write_bytes": 128, + "process_count": 4, + "tabularis": null + }) + } + crate::application::operations::OperationalCommand::GetTabularisChildren => { + serde_json::json!([{ + "pid": 4200, + "name": "tabularis-plugin", + "cpu_percent": 0.5, + "memory_bytes": 1024 + }]) + } + _ => Value::Null, + }) + } + + async fn execute_mcp_host_command( + &self, + context: ApplicationRequestContext, + command: crate::application::mcp_host::McpHostCommand, + ) -> Result { + self.record(context).await; + Ok(match command { + crate::application::mcp_host::McpHostCommand::GetStatus => serde_json::json!([{ + "client_id": "claude", + "client_name": "Claude Desktop", + "installed": false, + "config_path": "/home/test/.config/Claude/claude_desktop_config.json", + "executable_path": "/usr/bin/tabularis", + "client_type": "file", + "manual_command": null + }]), + crate::application::mcp_host::McpHostCommand::InstallConfig { client_id } => { + assert_eq!(client_id, "claude"); + serde_json::json!("Claude Desktop") + } + }) + } + + async fn execute_theme_command( + &self, + context: ApplicationRequestContext, + command: crate::application::themes::ThemeCommand, + ) -> Result { + self.record(context).await; + Ok(Value::String(format!("{command:?}"))) + } + + async fn execute_host_settings_command( + &self, + context: ApplicationRequestContext, + command: crate::application::host_settings::HostSettingsCommand, + ) -> Result { + self.record(context).await; + Ok(Value::String(format!("{command:?}"))) + } + + async fn execute_ui_state_command( + &self, + context: ApplicationRequestContext, + command: crate::application::ui_state::UiStateCommand, + ) -> Result { + self.record(context).await; + Ok(Value::String(format!("{command:?}"))) + } +} + +fn json_headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + headers +} + +async fn response_json(response: Response) -> Value { + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + serde_json::from_slice(&body).unwrap() +} + +async fn wait_for_recorded_contexts(application: &FixtureApplication, expected: usize) { + tokio::time::timeout(Duration::from_secs(1), async { + loop { + if application + .contexts + .lock() + .unwrap_or_else(|error| error.into_inner()) + .len() + >= expected + { + return; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("RPC fixture did not start in time"); +} + +#[tokio::test] +async fn preserves_shared_serialization_fixture_in_success_envelopes() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../packages/web-ui/tests/fixtures/transportSerialization.json" + )) + .unwrap(); + + let body = response_json(success(fixture.clone())).await; + + assert_eq!(body, serde_json::json!({ "ok": true, "data": fixture })); + assert_eq!( + body["data"]["rows"][0][1], + "BLOB:4:application/octet-stream:AAECAw==" + ); + assert_eq!(body["data"]["rows"][0][2], "12345678901234567890.123456789"); + assert_eq!(body["data"]["rows"][0][3], "2026-08-21T19:20:21.123Z"); + assert!(body["data"]["rows"][0][4].is_null()); +} + +#[test] +fn decodes_selected_registry_for_plugin_install() { + let command = decode_plugin_command( + PluginRpcCommand::Install, + br#"{"pluginId":"postgres-driver","version":"1.2.3","registryUrl":"https://registry.example/api"}"#, + ) + .expect("plugin install request"); + + match command { + PluginCommand::Install { + plugin_id, + version, + registry_url, + } => { + assert_eq!(plugin_id, "postgres-driver"); + assert_eq!(version.as_deref(), Some("1.2.3")); + assert_eq!( + registry_url.as_deref(), + Some("https://registry.example/api") + ); + } + _ => panic!("unexpected plugin command"), + } +} + +#[test] +fn declares_authorization_for_each_registered_command() { + assert_eq!( + RpcCommand::IsDebugMode.metadata().authorization, + AuthorizationLevel::LocalAdmin + ); + assert_eq!( + RpcCommand::GetConnections.metadata().authorization, + AuthorizationLevel::Database + ); + assert_eq!( + RpcCommand::CancelQuery.metadata().authorization, + AuthorizationLevel::Database + ); + for command in [ + ConnectionFilesRpcCommand::Export, + ConnectionFilesRpcCommand::PreviewTabularisImport, + ConnectionFilesRpcCommand::ApplyPreparedTabularisImport, + ConnectionFilesRpcCommand::SetBackupPassword, + ConnectionFilesRpcCommand::SetBackupTargetPassword, + ConnectionFilesRpcCommand::RunBackup, + ] { + assert_eq!( + RpcCommand::ConnectionFiles(command) + .metadata() + .authorization, + AuthorizationLevel::Sensitive, + "{command:?}", + ); + } + for command in [ + ConnectionFilesRpcCommand::ListImportSources, + ConnectionFilesRpcCommand::PreviewForeignImport, + ConnectionFilesRpcCommand::ApplyForeignImport, + ConnectionFilesRpcCommand::GetBackupStatus, + ] { + assert_eq!( + RpcCommand::ConnectionFiles(command) + .metadata() + .authorization, + AuthorizationLevel::LocalAdmin, + "{command:?}", + ); + } + for command in [ + DatabaseTransferRpcCommand::Dump, + DatabaseTransferRpcCommand::CancelDump, + DatabaseTransferRpcCommand::Import, + DatabaseTransferRpcCommand::CancelImport, + ] { + assert_eq!( + RpcCommand::DatabaseTransfer(command) + .metadata() + .authorization, + AuthorizationLevel::Sensitive, + "{command:?}", + ); + } + assert_eq!( + RpcCommand::Metadata(MetadataRpcCommand::GetTables) + .metadata() + .authorization, + AuthorizationLevel::Database + ); + assert_eq!( + RpcCommand::Query(QueryRpcCommand::Execute) + .metadata() + .authorization, + AuthorizationLevel::Database + ); + assert_eq!( + RpcCommand::Record(RecordRpcCommand::Update) + .metadata() + .authorization, + AuthorizationLevel::Database + ); + assert_eq!( + RpcCommand::Record(RecordRpcCommand::DetectMimeType) + .metadata() + .authorization, + AuthorizationLevel::Sensitive + ); + assert_eq!( + RpcCommand::DatabaseObject(DatabaseObjectRpcCommand::CreateView) + .metadata() + .authorization, + AuthorizationLevel::Database + ); + for command in [ + DatabaseObjectRpcCommand::GetDbPrivilegeCatalog, + DatabaseObjectRpcCommand::GetDbUsers, + DatabaseObjectRpcCommand::GetDbUserGrants, + DatabaseObjectRpcCommand::GetDbUserPrivileges, + DatabaseObjectRpcCommand::CreateDbUser, + DatabaseObjectRpcCommand::DropDbUser, + DatabaseObjectRpcCommand::SetDbUserPassword, + DatabaseObjectRpcCommand::ApplyDbUserPrivileges, + ] { + assert_eq!( + RpcCommand::DatabaseObject(command).metadata().authorization, + AuthorizationLevel::Sensitive, + "{command:?}", + ); + } + assert_eq!( + RpcCommand::Tunnel(TunnelRpcCommand::GetSshConnections) + .metadata() + .authorization, + AuthorizationLevel::LocalAdmin + ); + assert_eq!( + RpcCommand::Tunnel(TunnelRpcCommand::RespondSshAskpass) + .metadata() + .authorization, + AuthorizationLevel::Sensitive + ); +} + +#[test] +fn registers_generic_export_commands_with_explicit_authorization() { + for name in ["export_query_to_file", "cancel_export"] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Database, + "{name}", + ); + } + for name in [ + "export_ai_activity_json", + "export_ai_activity_csv", + "export_ai_session_as_notebook", + "export_logs", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Sensitive, + "{name}", + ); + } +} + +#[test] +fn registers_ai_commands_with_explicit_authorization() { + for name in [ + "set_ai_key", + "delete_ai_key", + "check_ai_key", + "check_ai_key_status", + "get_ai_models", + "generate_ai_query", + "explain_ai_query", + "analyze_ai_explain_plan", + "generate_cell_name", + "generate_tab_rename", + "suggest_table_name", + "get_ai_activity", + "get_ai_sessions", + "get_ai_session_events", + "clear_ai_activity", + "list_pending_approvals", + "decide_pending_approval", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Sensitive, + "{name}", + ); + } + + let schema_context = + RpcCommand::parse("get_ai_schema_context").expect("missing get_ai_schema_context"); + assert_eq!( + schema_context.metadata().authorization, + AuthorizationLevel::Database + ); +} + +#[test] +fn registers_plugin_lifecycle_commands_with_local_admin_authorization() { + for name in [ + "fetch_plugin_registry", + "fetch_tabularium_plugin_preview", + "fetch_plugin_readme", + "install_plugin", + "cancel_plugin_install", + "uninstall_plugin", + "get_installed_plugins", + "disable_plugin", + "enable_plugin", + "get_plugin_manifest", + "get_plugin_startup_errors", + "kill_plugin_process", + "restart_plugin_process", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::LocalAdmin, + "{name}", + ); + } + + for desktop_only in ["get_plugin_dir", "open_plugins_dir", "read_plugin_file"] { + assert!( + RpcCommand::parse(desktop_only).is_none(), + "{desktop_only} must not expose server filesystem paths over browser RPC", + ); + } +} + +#[test] +fn registers_mcp_host_commands_with_local_admin_authorization() { + for name in ["get_mcp_status", "install_mcp_config"] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::LocalAdmin, + "{name}", + ); + } +} + +#[tokio::test] +async fn lists_only_configured_server_directories_for_local_admin_sessions() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("main.sqlite"), b"").unwrap(); + let roots = + crate::transport::web::server_files::canonicalize_roots(&[root.path().to_path_buf()]) + .unwrap(); + let dispatcher = RpcDispatcher::with_access_policy( + Arc::new(FixtureApplication::new(Duration::ZERO)), + RpcAccessPolicy { + server_file_browser_roots: roots, + ..RpcAccessPolicy::default() + }, + ); + let payload = serde_json::json!({ "path": root.path() }); + + let response = dispatcher + .dispatch( + "list_server_directory", + RequestId("server-files".to_string()), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response_json(response).await["data"]["entries"][0]["name"], + "main.sqlite" + ); +} + +#[tokio::test] +async fn creates_sqlite_files_only_inside_configured_server_roots() { + let root = tempfile::tempdir().unwrap(); + let roots = + crate::transport::web::server_files::canonicalize_roots(&[root.path().to_path_buf()]) + .unwrap(); + let dispatcher = RpcDispatcher::with_access_policy( + Arc::new(FixtureApplication::new(Duration::ZERO)), + RpcAccessPolicy { + server_file_browser_roots: roots, + ..RpcAccessPolicy::default() + }, + ); + let path = root.path().join("customers.db"); + + let response = dispatcher + .dispatch( + "create_sqlite_file", + RequestId("create-sqlite-file".to_string()), + &json_headers(), + Bytes::from( + serde_json::to_vec(&serde_json::json!({ "path": path.to_string_lossy() })).unwrap(), + ), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + + assert_eq!(response.status(), StatusCode::OK); + assert!(path.exists()); + + let database_path = root.path().join("inventory.sqlite"); + let response = dispatcher + .dispatch( + "create_sqlite_database", + RequestId("create-sqlite-database".to_string()), + &json_headers(), + Bytes::from( + serde_json::to_vec(&serde_json::json!({ + "path": database_path.to_string_lossy() + })) + .unwrap(), + ), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + + // The application layer creates the file; the fixture only records the call. + assert_eq!(response.status(), StatusCode::OK); +} + +#[tokio::test] +async fn rejects_mcp_host_configuration_without_local_admin_authorization() { + let dispatcher = RpcDispatcher::with_access_policy( + Arc::new(FixtureApplication::new(Duration::ZERO)), + RpcAccessPolicy { + mcp_host_configuration: true, + ..RpcAccessPolicy::default() + }, + ); + for (command, payload) in [ + ("get_mcp_status", Value::Null), + ( + "install_mcp_config", + serde_json::json!({"clientId": "claude"}), + ), + ] { + let response = dispatcher + .dispatch( + command, + RequestId(format!("restricted-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::Sensitive, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{command}"); + assert_eq!(response_json(response).await["error"]["code"], "FORBIDDEN"); + } +} + +#[tokio::test] +async fn disables_mcp_host_configuration_when_web_policy_is_remote() { + let dispatcher = RpcDispatcher::with_access_policy( + Arc::new(FixtureApplication::new(Duration::ZERO)), + RpcAccessPolicy { + mcp_host_configuration: false, + ..RpcAccessPolicy::default() + }, + ); + for (command, payload) in [ + ("get_mcp_status", Value::Null), + ( + "install_mcp_config", + serde_json::json!({"clientId": "claude"}), + ), + ] { + let response = dispatcher + .dispatch( + command, + RequestId(format!("remote-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{command}"); + assert_eq!( + response_json(response).await["error"]["code"], + "MCP_HOST_CONFIGURATION_DISABLED" + ); + } +} + +#[tokio::test] +async fn routes_mcp_host_commands_through_the_shared_application_api() { + let application = Arc::new(FixtureApplication::new(Duration::ZERO)); + let dispatcher = RpcDispatcher::with_access_policy( + application.clone(), + RpcAccessPolicy { + mcp_host_configuration: true, + ..RpcAccessPolicy::default() + }, + ); + + let status = dispatcher + .dispatch( + "get_mcp_status", + RequestId("local-mcp-status".to_string()), + &json_headers(), + Bytes::from_static(b"null"), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(status.status(), StatusCode::OK); + assert_eq!( + response_json(status).await["data"][0]["client_id"], + "claude" + ); + + let install = dispatcher + .dispatch( + "install_mcp_config", + RequestId("local-mcp-install".to_string()), + &json_headers(), + Bytes::from_static(br#"{"clientId":"claude"}"#), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(install.status(), StatusCode::OK); + assert_eq!(response_json(install).await["data"], "Claude Desktop"); + + let contexts = application + .contexts + .lock() + .unwrap_or_else(|error| error.into_inner()); + assert_eq!(contexts.len(), 2); + assert!(contexts + .iter() + .all(|context| context.authorization == AuthorizationLevel::LocalAdmin)); +} + +#[test] +fn registers_operational_commands_with_remote_safe_authorization() { + for name in [ + "get_logs", + "get_log_settings", + "get_process_list", + "get_system_stats", + "get_tabularis_children", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Sensitive, + "{name}", + ); + } + + for name in ["clear_logs", "set_log_enabled", "set_log_max_size"] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::LocalAdmin, + "{name}", + ); + } +} + +#[tokio::test] +async fn rejects_destructive_operations_without_local_admin_authorization() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + for (command, payload) in [ + ("clear_logs", Value::Null), + ("set_log_enabled", serde_json::json!({"enabled": false})), + ("set_log_max_size", serde_json::json!({"maxSize": 500})), + ( + "kill_plugin_process", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ( + "restart_plugin_process", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ] { + let response = dispatcher + .dispatch( + command, + RequestId(format!("restricted-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::Sensitive, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{command}"); + assert_eq!(response_json(response).await["error"]["code"], "FORBIDDEN"); + } +} + +#[test] +fn registers_notebook_commands_with_database_authorization() { + for name in [ + "create_notebook", + "save_notebook", + "load_notebook", + "delete_notebook", + "rename_notebook", + "list_notebooks", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Database, + "{name}", + ); + } +} + +#[test] +fn registers_saved_query_and_history_commands_with_database_authorization() { + for name in [ + "get_saved_queries", + "save_query", + "update_saved_query", + "delete_saved_query", + "get_saved_query_folders", + "create_saved_query_folder", + "rename_saved_query_folder", + "delete_saved_query_folder", + "move_saved_query", + "get_query_history", + "add_query_history_entry", + "delete_query_history_entry", + "clear_query_history", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Database, + "{name}", + ); + } +} + +#[test] +fn registers_every_settings_and_preference_command_with_explicit_authorization() { + let local_admin_commands = [ + "get_config", + "save_config", + "get_config_json", + "save_config_json", + "get_keybindings", + "save_keybindings", + "get_all_themes", + "save_custom_theme", + "delete_custom_theme", + "get_system_prompt", + "save_system_prompt", + "reset_system_prompt", + "get_explain_prompt", + "save_explain_prompt", + "reset_explain_prompt", + "get_explainplan_prompt", + "save_explainplan_prompt", + "reset_explainplan_prompt", + "get_cellname_prompt", + "save_cellname_prompt", + "reset_cellname_prompt", + "get_tabrename_prompt", + "save_tabrename_prompt", + "reset_tabrename_prompt", + ]; + for name in local_admin_commands { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::LocalAdmin + ); + } + + for name in [ + "load_editor_preferences", + "save_editor_preferences", + "delete_editor_preferences", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Database + ); + } + + for name in [ + "get_last_active_connection", + "set_last_active_connection", + "get_last_open_connections", + "set_last_open_connections", + ] { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!( + command.metadata().authorization, + AuthorizationLevel::Session + ); + } +} + +#[tokio::test] +async fn routes_connection_file_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let resolution = serde_json::json!({"index": 0, "action": "import", "groupId": ""}); + let file = serde_json::json!({"kind": "upload", "token": Uuid::new_v4().to_string()}); + let commands = [ + ( + "export_connections_file", + serde_json::json!({"mode": "encrypted", "password": "secret"}), + ), + ("list_connection_import_sources", Value::Null), + ( + "preview_connection_import", + serde_json::json!({ + "sourceId": "dbeaver", + "includePasswords": false, + "file": file.clone() + }), + ), + ( + "apply_connection_import", + serde_json::json!({"sourceId": "dbeaver", "resolutions": [resolution.clone()]}), + ), + ( + "preview_tabularis_import_file", + serde_json::json!({"file": file, "password": "secret"}), + ), + ( + "apply_prepared_tabularis_import", + serde_json::json!({"resolutions": [resolution]}), + ), + ("get_connections_backup_status", Value::Null), + ( + "set_connections_backup_password", + serde_json::json!({"password": "secret"}), + ), + ( + "set_connections_backup_target_password", + serde_json::json!({"targetId": "webdav", "password": "secret"}), + ), + ("run_connections_backup", Value::Null), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_database_transfer_jobs_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let session_id = Some(Uuid::new_v4()); + let commands = [ + ( + "dump_database", + serde_json::json!({ + "connectionId": "connection-1", + "options": {"structure": true, "data": true, "tables": ["users"]}, + "schema": "public" + }), + ), + ( + "import_database", + serde_json::json!({ + "connectionId": "connection-1", + "uploadToken": Uuid::new_v4().to_string(), + "schema": "public" + }), + ), + ( + "cancel_dump", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "cancel_import", + serde_json::json!({"connectionId": "connection-1"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + session_id, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_all_metadata_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let commands = [ + ( + "get_available_databases", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_schemas", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_tables", + serde_json::json!({"connectionId": "connection-1", "schema": "public"}), + ), + ( + "get_columns", + serde_json::json!({"connectionId": "connection-1", "tableName": "users"}), + ), + ( + "get_foreign_keys", + serde_json::json!({"connectionId": "connection-1", "tableName": "users"}), + ), + ( + "get_indexes", + serde_json::json!({"connectionId": "connection-1", "tableName": "users"}), + ), + ( + "get_views", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_view_columns", + serde_json::json!({"connectionId": "connection-1", "viewName": "users_view"}), + ), + ( + "get_materialized_views", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_materialized_view_columns", + serde_json::json!({"connectionId": "connection-1", "viewName": "users_view"}), + ), + ( + "get_materialized_view_definition", + serde_json::json!({"connectionId": "connection-1", "viewName": "users_view"}), + ), + ( + "get_routines", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_triggers", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_schema_snapshot", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "get_selected_schemas", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "set_selected_schemas", + serde_json::json!({"connectionId": "connection-1", "schemas": ["public"]}), + ), + ( + "get_schema_preference", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "set_schema_preference", + serde_json::json!({"connectionId": "connection-1", "schema": "public"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + None, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_database_object_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let connection = "connection-1"; + let user = serde_json::json!({"connectionId": connection, "user": "app", "host": "%"}); + let commands = [ + ( + "get_view_definition", + serde_json::json!({"connectionId": connection, "viewName": "active_users"}), + ), + ( + "create_view", + serde_json::json!({"connectionId": connection, "viewName": "active_users", "definition": "SELECT 1"}), + ), + ( + "alter_view", + serde_json::json!({"connectionId": connection, "viewName": "active_users", "definition": "SELECT 2"}), + ), + ( + "drop_view", + serde_json::json!({"connectionId": connection, "viewName": "active_users"}), + ), + ( + "refresh_materialized_view", + serde_json::json!({"connectionId": connection, "viewName": "active_users"}), + ), + ( + "get_routine_parameters", + serde_json::json!({"connectionId": connection, "routineName": "refresh_users"}), + ), + ( + "get_routine_definition", + serde_json::json!({"connectionId": connection, "routineName": "refresh_users", "routineType": "FUNCTION"}), + ), + ( + "build_routine_call_sql", + serde_json::json!({"connectionId": connection, "routineName": "refresh_users", "routineType": "FUNCTION", "args": []}), + ), + ( + "get_routine_create_template", + serde_json::json!({"connectionId": connection, "routineType": "FUNCTION"}), + ), + ( + "get_routine_edit_script", + serde_json::json!({"connectionId": connection, "routineName": "refresh_users", "routineType": "FUNCTION"}), + ), + ( + "drop_routine", + serde_json::json!({"connectionId": connection, "routineName": "refresh_users", "routineType": "FUNCTION"}), + ), + ( + "get_trigger_definition", + serde_json::json!({"connectionId": connection, "triggerName": "audit_users", "tableName": "users"}), + ), + ( + "create_trigger", + serde_json::json!({"connectionId": connection, "triggerSql": "CREATE TRIGGER audit_users"}), + ), + ( + "drop_trigger", + serde_json::json!({"connectionId": connection, "triggerName": "audit_users", "tableName": "users"}), + ), + ( + "get_create_table_sql", + serde_json::json!({"connectionId": connection, "tableName": "users", "columns": [], "database": "app_db"}), + ), + ( + "get_drop_table_sql", + serde_json::json!({"connectionId": connection, "table": "users", "schema": null, "database": "app_db"}), + ), + ( + "get_column_stats", + serde_json::json!({"connectionId": connection, "request": {"table": "users", "column": "email", "top_values_limit": 5, "include": {"distinct": true, "min_max": true, "top_values": true}}, "database": "app_db"}), + ), + ( + "get_add_column_sql", + serde_json::json!({"connectionId": connection, "table": "users", "column": column_fixture("email")}), + ), + ( + "get_alter_column_sql", + serde_json::json!({"connectionId": connection, "table": "users", "oldColumn": column_fixture("email"), "newColumn": column_fixture("address")}), + ), + ( + "get_create_index_sql", + serde_json::json!({"connectionId": connection, "table": "users", "indexName": "idx_users", "columns": ["email"], "isUnique": true}), + ), + ( + "get_create_foreign_key_sql", + serde_json::json!({"connectionId": connection, "table": "users", "fkName": "fk_users_org", "column": "org_id", "refTable": "orgs", "refColumn": "id"}), + ), + ( + "drop_index_action", + serde_json::json!({"connectionId": connection, "table": "users", "indexName": "idx_users"}), + ), + ( + "drop_foreign_key_action", + serde_json::json!({"connectionId": connection, "table": "users", "fkName": "fk_users_org"}), + ), + ( + "get_db_privilege_catalog", + serde_json::json!({"connectionId": connection}), + ), + ( + "get_db_users", + serde_json::json!({"connectionId": connection}), + ), + ("get_db_user_grants", user.clone()), + ("get_db_user_privileges", user.clone()), + ( + "create_db_user", + serde_json::json!({"connectionId": connection, "user": "app", "host": "%", "password": "secret"}), + ), + ("drop_db_user", user.clone()), + ( + "set_db_user_password", + serde_json::json!({"connectionId": connection, "user": "app", "host": "%", "password": "secret"}), + ), + ( + "apply_db_user_privileges", + serde_json::json!({"connectionId": connection, "user": "app", "host": "%", "database": "app_db", "table": null, "privileges": ["SELECT"], "grant": true}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(uuid::Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +fn column_fixture(name: &str) -> Value { + serde_json::json!({ + "name": name, + "data_type": "TEXT", + "is_nullable": true, + "is_pk": false, + "is_auto_increment": false, + "default_value": null + }) +} + +#[tokio::test] +async fn routes_query_execution_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let commands = [ + ( + "execute_query", + serde_json::json!({ + "connectionId": "connection-1", + "query": "SELECT 1", + "limit": 100, + "page": 1 + }), + ), + ( + "execute_query_batch", + serde_json::json!({ + "connectionId": "connection-1", + "queries": ["SELECT 1"], + "limit": 100, + "page": 1, + "batchId": "batch-1" + }), + ), + ( + "count_query", + serde_json::json!({"connectionId": "connection-1", "query": "SELECT 1"}), + ), + ( + "explain_query_plan", + serde_json::json!({ + "connectionId": "connection-1", + "query": "SELECT 1", + "analyze": false + }), + ), + ( + "get_server_now", + serde_json::json!({"connectionId": "connection-1"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(uuid::Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_ai_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let generate = serde_json::json!({ + "req": { + "provider": "openai", + "model": "gpt-contract", + "prompt": "Select one", + "schema": "table values(id integer)" + } + }); + let explain = serde_json::json!({ + "req": { + "provider": "openai", + "model": "gpt-contract", + "query": "SELECT 1", + "language": "English" + } + }); + let commands = [ + ( + "set_ai_key", + serde_json::json!({"provider": "openai", "key": "write-only"}), + ), + ("delete_ai_key", serde_json::json!({"provider": "openai"})), + ("check_ai_key", serde_json::json!({"provider": "openai"})), + ( + "check_ai_key_status", + serde_json::json!({"provider": "openai"}), + ), + ("get_ai_models", serde_json::json!({"forceRefresh": false})), + ("generate_ai_query", generate), + ("explain_ai_query", explain.clone()), + ("analyze_ai_explain_plan", explain), + ( + "generate_cell_name", + serde_json::json!({"req": {"provider": "openai", "model": "gpt-contract", "query": "SELECT 1"}}), + ), + ( + "generate_tab_rename", + serde_json::json!({"req": {"provider": "openai", "model": "gpt-contract", "query": "SELECT 1"}}), + ), + ( + "suggest_table_name", + serde_json::json!({"req": {"provider": "openai", "model": "gpt-contract", "headers": ["id"], "sample_rows": [["1"]]}}), + ), + ( + "get_ai_schema_context", + serde_json::json!({"connectionId": "connection-1", "schema": "public"}), + ), + ( + "get_ai_activity", + serde_json::json!({"filter": {"status": "success"}}), + ), + ("get_ai_sessions", Value::Null), + ( + "get_ai_session_events", + serde_json::json!({"sessionId": "mcp-session"}), + ), + ("clear_ai_activity", Value::Null), + ("list_pending_approvals", Value::Null), + ( + "decide_pending_approval", + serde_json::json!({"approvalId": "approval-1", "decision": "deny", "reason": "fixture"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(uuid::Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_plugin_lifecycle_commands_through_the_shared_application_api() { + let application = Arc::new(FixtureApplication::new(Duration::ZERO)); + let dispatcher = RpcDispatcher::new(application.clone()); + let commands = [ + ("fetch_plugin_registry", Value::Null), + ( + "fetch_tabularium_plugin_preview", + serde_json::json!({ + "slug": "postgres-driver", + "registryUrl": null, + "version": "1.2.3" + }), + ), + ( + "fetch_plugin_readme", + serde_json::json!({ + "slug": "postgres-driver", + "locale": "en", + "registryUrl": null + }), + ), + ( + "install_plugin", + serde_json::json!({"pluginId": "postgres-driver", "version": "1.2.3"}), + ), + ( + "cancel_plugin_install", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ( + "uninstall_plugin", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ("get_installed_plugins", Value::Null), + ( + "disable_plugin", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ( + "enable_plugin", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ( + "get_plugin_manifest", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ("get_plugin_startup_errors", Value::Null), + ( + "kill_plugin_process", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ( + "restart_plugin_process", + serde_json::json!({"pluginId": "postgres-driver"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } + + let contexts = application + .contexts + .lock() + .unwrap_or_else(|error| error.into_inner()); + assert_eq!(contexts.len(), 13); + assert!(contexts + .iter() + .all(|context| context.authorization == AuthorizationLevel::LocalAdmin)); +} + +#[tokio::test] +async fn routes_operational_commands_through_the_shared_application_api() { + let application = Arc::new(FixtureApplication::new(Duration::ZERO)); + let dispatcher = RpcDispatcher::new(application.clone()); + let commands = [ + ( + "get_logs", + serde_json::json!({ + "request": {"limit": 100, "level_filter": "ERROR"} + }), + ), + ("get_log_settings", Value::Null), + ("get_process_list", Value::Null), + ("get_system_stats", Value::Null), + ("get_tabularis_children", Value::Null), + ("set_log_enabled", serde_json::json!({"enabled": false})), + ("set_log_max_size", serde_json::json!({"maxSize": 500})), + ("clear_logs", Value::Null), + ]; + + for (command, payload) in &commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(payload).unwrap()), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } + + // Each call reached the application with the session's granted level. + assert!(application + .contexts + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .all(|context| context.authorization == AuthorizationLevel::LocalAdmin)); + let required = commands + .iter() + .map(|(command, _)| RpcCommand::parse(command).unwrap().metadata().authorization) + .collect::>(); + assert_eq!( + required, + vec![ + AuthorizationLevel::Sensitive, + AuthorizationLevel::Sensitive, + AuthorizationLevel::Sensitive, + AuthorizationLevel::Sensitive, + AuthorizationLevel::Sensitive, + AuthorizationLevel::LocalAdmin, + AuthorizationLevel::LocalAdmin, + AuthorizationLevel::LocalAdmin, + ] + ); +} + +#[tokio::test] +async fn routes_notebook_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let target = serde_json::json!({ + "connectionId": "connection-1", + "notebookId": "notebook-1" + }); + let commands = [ + ( + "create_notebook", + serde_json::json!({ + "connectionId": "connection-1", + "notebookId": "notebook-1", + "content": "{}" + }), + ), + ( + "save_notebook", + serde_json::json!({ + "connectionId": "connection-1", + "notebookId": "notebook-1", + "content": "{}" + }), + ), + ("load_notebook", target.clone()), + ("delete_notebook", target), + ( + "rename_notebook", + serde_json::json!({ + "connectionId": "connection-1", + "notebookId": "notebook-1", + "title": "Renamed" + }), + ), + ( + "list_notebooks", + serde_json::json!({"connectionId": "connection-1"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(uuid::Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_data_editing_and_blob_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let session_id = uuid::Uuid::new_v4(); + let commands = [ + ( + "insert_record", + serde_json::json!({ + "connectionId": "connection-1", + "table": "files", + "data": {"id": 1, "payload": null} + }), + ), + ( + "update_record", + serde_json::json!({ + "connectionId": "connection-1", + "table": "files", + "pkMap": {"id": 1}, + "colName": "payload", + "newVal": "BLOB_UPLOAD_REF:4:application/octet-stream:00000000-0000-4000-8000-000000000000" + }), + ), + ( + "delete_record", + serde_json::json!({ + "connectionId": "connection-1", + "table": "files", + "pkMap": {"id": 1} + }), + ), + ( + "fetch_blob", + serde_json::json!({ + "connectionId": "connection-1", + "table": "files", + "pkMap": {"id": 1}, + "colName": "payload" + }), + ), + ( + "detect_blob_mime", + serde_json::json!({"base64Data": "AAECAw=="}), + ), + ( + "detect_mime_type", + serde_json::json!({"headerBase64": "AAECAw=="}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(session_id), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn routes_settings_and_preferences_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let commands = [ + ("get_config", serde_json::Value::Null), + ( + "save_config", + serde_json::json!({"config": {"language": "en", "resultPageSize": 250}}), + ), + ("get_keybindings", serde_json::Value::Null), + ( + "save_keybindings", + serde_json::json!({"keybindings": {"editor.run": {}}}), + ), + ("get_all_themes", serde_json::Value::Null), + ("get_system_prompt", serde_json::Value::Null), + ( + "save_system_prompt", + serde_json::json!({"prompt": "Generate safe SQL"}), + ), + ("reset_system_prompt", serde_json::Value::Null), + ( + "load_editor_preferences", + serde_json::json!({"connectionId": "connection-1"}), + ), + ( + "save_editor_preferences", + serde_json::json!({ + "connectionId": "connection-1", + "preferences": {"tabs": [], "active_tab_id": null} + }), + ), + ("get_last_open_connections", serde_json::Value::Null), + ( + "set_last_active_connection", + serde_json::json!({"connectionId": "connection-1"}), + ), + ]; + + for (command, payload) in commands { + let response = dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + Some(uuid::Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } +} + +#[tokio::test] +async fn rejects_invalid_payloads_with_a_stable_error_envelope() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let response = dispatcher + .dispatch( + "cancel_query", + RequestId("request-invalid".to_string()), + &json_headers(), + Bytes::from_static(br#"{"unknown":true}"#), + None, + AuthorizationLevel::LocalAdmin, + ) + .await; + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = response_json(response).await; + assert_eq!(body["ok"], false); + assert_eq!(body["error"]["code"], "INVALID_REQUEST"); + assert_eq!(body["error"]["details"], Value::Null); + assert_eq!(body["error"]["requestId"], "request-invalid"); + assert!(body["error"]["message"] + .as_str() + .unwrap() + .contains("unknown field `unknown`")); +} + +#[tokio::test] +async fn enforces_deadlines_and_releases_cancellation_identifiers() { + let application = Arc::new(FixtureApplication::new(Duration::from_millis(40))); + let dispatcher = RpcDispatcher::new(application.clone()); + let mut deadline_headers = json_headers(); + deadline_headers.insert(RPC_DEADLINE_HEADER_NAME, HeaderValue::from_static("1")); + deadline_headers.insert( + RPC_CANCELLATION_HEADER_NAME, + HeaderValue::from_static("query-1"), + ); + + let timeout = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-timeout".to_string()), + &deadline_headers, + Bytes::from_static(b"null"), + None, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(timeout.status(), StatusCode::GATEWAY_TIMEOUT); + assert_eq!( + response_json(timeout).await["error"]["code"], + "DEADLINE_EXCEEDED" + ); + + let retry = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-retry".to_string()), + &json_headers_with_cancellation("query-1"), + Bytes::from_static(b"null"), + None, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(retry.status(), StatusCode::OK); + + let contexts = application + .contexts + .lock() + .unwrap_or_else(|error| error.into_inner()); + assert_eq!(contexts.len(), 2); + assert_eq!(contexts[0].request_id, "request-timeout"); + assert_eq!(contexts[0].cancellation_id.as_deref(), Some("query-1")); + assert_eq!(contexts[0].authorization, AuthorizationLevel::LocalAdmin); + assert!(contexts[0].deadline <= Instant::now()); +} + +#[tokio::test] +async fn rejects_duplicate_active_cancellation_identifiers() { + let dispatcher = + RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::from_millis(40)))); + let first_dispatcher = dispatcher.clone(); + let first = tokio::spawn(async move { + first_dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-first".to_string()), + &json_headers_with_cancellation("shared"), + Bytes::from_static(b"null"), + None, + AuthorizationLevel::LocalAdmin, + ) + .await + }); + tokio::time::sleep(Duration::from_millis(5)).await; + + let duplicate = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-duplicate".to_string()), + &json_headers_with_cancellation("shared"), + Bytes::from_static(b"null"), + None, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(duplicate.status(), StatusCode::CONFLICT); + assert_eq!( + response_json(duplicate).await["error"]["code"], + "CANCELLATION_ID_IN_USE" + ); + assert_eq!(first.await.unwrap().status(), StatusCode::OK); +} + +#[tokio::test] +async fn scopes_active_cancellation_identifiers_to_browser_sessions() { + let dispatcher = + RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::from_millis(20)))); + let session_a = uuid::Uuid::new_v4(); + let session_b = uuid::Uuid::new_v4(); + let first_dispatcher = dispatcher.clone(); + let first = tokio::spawn(async move { + first_dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-session-a".to_string()), + &json_headers_with_cancellation("shared"), + Bytes::from_static(b"null"), + Some(session_a), + AuthorizationLevel::LocalAdmin, + ) + .await + }); + tokio::time::sleep(Duration::from_millis(5)).await; + + let second = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-session-b".to_string()), + &json_headers_with_cancellation("shared"), + Bytes::from_static(b"null"), + Some(session_b), + AuthorizationLevel::LocalAdmin, + ) + .await; + + assert_eq!(second.status(), StatusCode::OK); + assert_eq!(first.await.unwrap().status(), StatusCode::OK); +} + +#[tokio::test] +async fn bounds_slow_rpc_work_per_session_and_across_the_server() { + let defaults = RpcConcurrencyLimits::default(); + assert_eq!(defaults.max_global, 64); + assert_eq!(defaults.max_per_session, 16); + + let application = Arc::new(FixtureApplication::new(Duration::from_millis(100))); + let dispatcher = RpcDispatcher::with_access_policy_and_limits( + application.clone(), + RpcAccessPolicy::default(), + RpcConcurrencyLimits { + max_global: 2, + max_per_session: 1, + }, + ); + let session_a = Uuid::new_v4(); + let session_b = Uuid::new_v4(); + let session_c = Uuid::new_v4(); + + let first_dispatcher = dispatcher.clone(); + let first = tokio::spawn(async move { + first_dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-session-a-first".to_string()), + &json_headers(), + Bytes::from_static(b"null"), + Some(session_a), + AuthorizationLevel::LocalAdmin, + ) + .await + }); + wait_for_recorded_contexts(&application, 1).await; + + let same_session = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-session-a-overload".to_string()), + &json_headers(), + Bytes::from_static(b"null"), + Some(session_a), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(same_session.status(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!( + response_json(same_session).await["error"]["code"], + "SESSION_BUSY" + ); + + let second_dispatcher = dispatcher.clone(); + let second = tokio::spawn(async move { + second_dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-session-b".to_string()), + &json_headers(), + Bytes::from_static(b"null"), + Some(session_b), + AuthorizationLevel::LocalAdmin, + ) + .await + }); + wait_for_recorded_contexts(&application, 2).await; + + let server_busy = dispatcher + .dispatch( + "is_debug_mode", + RequestId("request-server-overload".to_string()), + &json_headers(), + Bytes::from_static(b"null"), + Some(session_c), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(server_busy.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + response_json(server_busy).await["error"]["code"], + "SERVER_BUSY" + ); + + assert_eq!(first.await.unwrap().status(), StatusCode::OK); + assert_eq!(second.await.unwrap().status(), StatusCode::OK); +} + +fn json_headers_with_cancellation(id: &str) -> HeaderMap { + let mut headers = json_headers(); + headers.insert( + RPC_CANCELLATION_HEADER_NAME, + HeaderValue::from_str(id).unwrap(), + ); + headers +} + +async fn dispatch_json( + dispatcher: &RpcDispatcher, + command: &str, + payload: serde_json::Value, + session_id: Option, + authorization: AuthorizationLevel, +) -> Response { + dispatcher + .dispatch( + command, + RequestId(format!("request-{command}")), + &json_headers(), + Bytes::from(serde_json::to_vec(&payload).unwrap()), + session_id, + authorization, + ) + .await +} + +fn dispatcher_with_roots(root: &std::path::Path) -> RpcDispatcher { + let roots = + crate::transport::web::server_files::canonicalize_roots(&[root.to_path_buf()]).unwrap(); + RpcDispatcher::with_access_policy( + Arc::new(FixtureApplication::new(Duration::ZERO)), + RpcAccessPolicy { + server_file_browser_roots: roots, + ..RpcAccessPolicy::default() + }, + ) +} + +#[test] +fn registers_merged_host_commands_with_explicit_authorization() { + let expectations = [ + ("get_theme_catalog", AuthorizationLevel::Session), + ("preview_theme_document", AuthorizationLevel::Session), + ("create_personal_theme", AuthorizationLevel::LocalAdmin), + ("create_personal_snapshot", AuthorizationLevel::LocalAdmin), + ("update_personal_theme", AuthorizationLevel::LocalAdmin), + ("update_personal_snapshot", AuthorizationLevel::LocalAdmin), + ("duplicate_personal_theme", AuthorizationLevel::LocalAdmin), + ("import_theme", AuthorizationLevel::LocalAdmin), + ("export_theme", AuthorizationLevel::LocalAdmin), + ( + "preview_local_theme_package", + AuthorizationLevel::LocalAdmin, + ), + ( + "install_local_theme_package", + AuthorizationLevel::LocalAdmin, + ), + ("fetch_theme_registry", AuthorizationLevel::LocalAdmin), + ("fetch_theme_package_detail", AuthorizationLevel::LocalAdmin), + ("install_registry_theme", AuthorizationLevel::LocalAdmin), + ("cancel_theme_install", AuthorizationLevel::LocalAdmin), + ("set_theme_package_enabled", AuthorizationLevel::LocalAdmin), + ("uninstall_theme_package", AuthorizationLevel::LocalAdmin), + ("recover_theme_packages", AuthorizationLevel::LocalAdmin), + ("proxy_password_is_set", AuthorizationLevel::Sensitive), + ("set_proxy_password", AuthorizationLevel::Sensitive), + ("delete_proxy_password", AuthorizationLevel::Sensitive), + ("get_storage_location", AuthorizationLevel::LocalAdmin), + ("inspect_storage_location", AuthorizationLevel::LocalAdmin), + ("set_storage_location", AuthorizationLevel::LocalAdmin), + ("reset_storage_location", AuthorizationLevel::LocalAdmin), + ("get_app_data_dir", AuthorizationLevel::LocalAdmin), + ("read_sql_file", AuthorizationLevel::LocalAdmin), + ("write_sql_file", AuthorizationLevel::LocalAdmin), + ("get_connection_metadata", AuthorizationLevel::Database), + ( + "get_plugin_runtime_warnings", + AuthorizationLevel::LocalAdmin, + ), + ("test_ssm_connection_cmd", AuthorizationLevel::LocalAdmin), + ("get_ui_state", AuthorizationLevel::Session), + ("set_ui_state", AuthorizationLevel::Session), + ("delete_ui_state", AuthorizationLevel::Session), + ]; + for (name, authorization) in expectations { + let command = RpcCommand::parse(name).unwrap_or_else(|| panic!("missing {name}")); + assert_eq!(command.metadata().authorization, authorization, "{name}"); + } + // Desktop-only integrations never get a browser route. + for name in ["open_storage_location", "get_linux_system_theme"] { + assert!(RpcCommand::parse(name).is_none(), "{name}"); + } +} + +#[tokio::test] +async fn routes_theme_host_and_ui_state_commands_through_the_shared_application_api() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let session = Some(Uuid::new_v4()); + let commands = [ + ("get_theme_catalog", serde_json::Value::Null, "GetCatalog"), + ( + "update_personal_snapshot", + serde_json::json!({ + "themeId": "personal:a", + "name": "A", + "source": "{}", + "editor": {"base": "vs-dark"}, + "expectedRevision": "r1" + }), + "UpdatePersonalSnapshot", + ), + ( + "duplicate_personal_theme", + serde_json::json!({"themeId": "builtin:x", "name": "Copy"}), + "DuplicatePersonalTheme", + ), + ( + "import_theme", + serde_json::json!({"themeJson": "{}"}), + "ImportTheme", + ), + ( + "fetch_theme_registry", + serde_json::Value::Null, + "FetchRegistry", + ), + ( + "install_local_theme_package", + serde_json::json!({ + "uploadToken": "token-1", + "packageName": "acme/nord", + "expectedDigest": "abc" + }), + "Upload", + ), + ( + "set_theme_package_enabled", + serde_json::json!({"registryKey": "r", "packageName": "p", "enabled": false}), + "SetPackageEnabled", + ), + ( + "proxy_password_is_set", + serde_json::json!({"slot": "proxy:global"}), + "ProxyPasswordIsSet", + ), + ( + "get_storage_location", + serde_json::Value::Null, + "GetStorageLocation", + ), + ("get_ui_state", serde_json::json!({"keys": ["a"]}), "Get"), + ( + "set_ui_state", + serde_json::json!({"key": "tabularis_sidebar_width", "value": 320}), + "Set", + ), + ("delete_ui_state", serde_json::json!({"key": "k"}), "Delete"), + ]; + for (command, payload, expected) in commands { + let response = dispatch_json( + &dispatcher, + command, + payload, + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + let body = response_json(response).await; + let routed = body["data"].as_str().unwrap_or_default().to_string(); + assert!(routed.contains(expected), "{command}: {routed}"); + } +} + +#[tokio::test] +async fn keeps_host_commands_behind_their_authorization_level() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let session = Some(Uuid::new_v4()); + let response = dispatch_json( + &dispatcher, + "get_theme_catalog", + serde_json::Value::Null, + session, + AuthorizationLevel::Session, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + for command in ["import_theme", "set_proxy_password", "set_storage_location"] { + let response = dispatch_json( + &dispatcher, + command, + serde_json::json!({}), + session, + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{command}"); + } +} + +#[tokio::test] +async fn confines_server_paths_for_sql_files_theme_archives_and_storage() { + let root = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let dispatcher = dispatcher_with_roots(root.path()); + let session = Some(Uuid::new_v4()); + let inside_sql = root.path().join("report.sql"); + std::fs::write(&inside_sql, "select 1;").unwrap(); + let outside_sql = outside.path().join("secret.sql"); + std::fs::write(&outside_sql, "select 2;").unwrap(); + + let response = dispatch_json( + &dispatcher, + "read_sql_file", + serde_json::json!({"path": inside_sql.to_string_lossy()}), + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response_json(response).await["data"], "select 1;"); + + let written = root.path().join("saved.sql"); + let response = dispatch_json( + &dispatcher, + "write_sql_file", + serde_json::json!({"path": written.to_string_lossy(), "content": "select 3;"}), + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(std::fs::read_to_string(&written).unwrap(), "select 3;"); + + for (command, payload) in [ + ( + "read_sql_file", + serde_json::json!({"path": outside_sql.to_string_lossy()}), + ), + ( + "write_sql_file", + serde_json::json!({ + "path": outside.path().join("x.sql").to_string_lossy(), + "content": "" + }), + ), + ] { + let response = dispatch_json( + &dispatcher, + command, + payload, + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_ne!(response.status(), StatusCode::OK, "{command}"); + } + assert!(!outside.path().join("x.sql").exists()); + + for (command, payload) in [ + ( + "preview_local_theme_package", + serde_json::json!({"path": outside_sql.to_string_lossy()}), + ), + ( + "preview_local_theme_package", + serde_json::json!({"path": inside_sql.to_string_lossy(), "uploadToken": "t"}), + ), + ( + "set_storage_location", + serde_json::json!({"path": outside.path().join("data").to_string_lossy(), "copyData": false}), + ), + ( + "inspect_storage_location", + serde_json::json!({"path": "relative/folder"}), + ), + ] { + let response = dispatch_json( + &dispatcher, + command, + payload, + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{command}"); + } + + let response = dispatch_json( + &dispatcher, + "inspect_storage_location", + serde_json::json!({"path": root.path().join("sync/tabularis").to_string_lossy()}), + session, + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); +} + +#[tokio::test] +async fn rejects_server_paths_when_the_file_browser_is_disabled() { + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("report.sql"); + std::fs::write(&file, "select 1;").unwrap(); + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + let response = dispatch_json( + &dispatcher, + "read_sql_file", + serde_json::json!({"path": file.to_string_lossy()}), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_ne!(response.status(), StatusCode::OK); +} + +#[test] +fn decodes_merged_database_commands_and_tab_sessions() { + for (name, payload) in [ + ( + "execute_query", + serde_json::json!({"connectionId":"db", "query":"BEGIN", "sessionId":"tab"}), + ), + ( + "execute_query_batch", + serde_json::json!({"connectionId":"db", "queries":["BEGIN"], "sessionId":"tab"}), + ), + ( + "count_query", + serde_json::json!({"connectionId":"db", "query":"SELECT 1", "sessionId":"tab"}), + ), + ( + "release_query_session", + serde_json::json!({"connectionId":"db", "sessionId":"tab"}), + ), + ] { + let command = decode_query_command( + QueryRpcCommand::parse(name).unwrap(), + &serde_json::to_vec(&payload).unwrap(), + ) + .unwrap(); + match command { + QueryCommand::Execute { + query_session_id, .. + } + | QueryCommand::ExecuteBatch { + query_session_id, .. + } + | QueryCommand::Count { + query_session_id, .. + } => assert_eq!(query_session_id.as_deref(), Some("tab")), + QueryCommand::ReleaseSession { + query_session_id, .. + } => assert_eq!(query_session_id, "tab"), + _ => panic!("unexpected query command"), + } + } + for (name, payload) in [ + ("get_data_types", serde_json::json!({"driver":"sqlite"})), + ( + "map_inferred_column_types", + serde_json::json!({"driver":"sqlite", "connectionId":"db", "kinds":["text"]}), + ), + ( + "execute_clipboard_import", + serde_json::json!({"req":{"connection_id":"db", "table_name":"test", "columns":[], "rows":[], "create_table":true, "if_exists":"fail"}}), + ), + ] { + decode_database_object_command( + DatabaseObjectRpcCommand::parse(name).unwrap(), + &serde_json::to_vec(&payload).unwrap(), + ) + .unwrap(); + } + assert_eq!( + crate::transport::web::events::WebEventBus::authorization_for("session-transaction-state"), + Some(AuthorizationLevel::Database) + ); +} + +fn connection_policy_payload(command: &str, params: Value) -> Value { + match command { + "test_connection" => { + serde_json::json!({"request": {"params": params, "connection_id": "saved-db"}}) + } + "save_connection" => serde_json::json!({"name": "Database", "params": params}), + "update_connection" => { + serde_json::json!({"id": "saved-db", "name": "Database", "params": params}) + } + _ => unreachable!(), + } +} + +fn connection_policy_host_fields() -> Vec<(&'static str, Value)> { + vec![ + ("ssh_enabled", serde_json::json!(true)), + ("ssh_host", serde_json::json!("bastion")), + ("ssh_user", serde_json::json!("user")), + ("ssh_password", serde_json::json!("password")), + ("ssh_key_file", serde_json::json!("/host/key")), + ("ssh_key_passphrase", serde_json::json!("passphrase")), + ("ssh_allow_passphrase_prompt", serde_json::json!(true)), + ("k8s_enabled", serde_json::json!(true)), + ("k8s_context", serde_json::json!("context")), + ("k8s_namespace", serde_json::json!("default")), + ("k8s_resource_type", serde_json::json!("service")), + ("k8s_resource_name", serde_json::json!("database")), + ("k8s_port", serde_json::json!(5432)), + ("k8s_kubectl_path", serde_json::json!("/untrusted/program")), + ("k8s_kubeconfig_path", serde_json::json!("/host/config")), + ("ssm_enabled", serde_json::json!(true)), + ("ssm_target", serde_json::json!("i-example")), + ("ssm_profile", serde_json::json!("profile")), + ("ssm_region", serde_json::json!("region")), + ("ssl_ca", serde_json::json!("/host/ca")), + ("ssl_cert", serde_json::json!("/host/cert")), + ("ssl_key", serde_json::json!("/host/key")), + ( + "proxy", + serde_json::json!({"mode": "custom", "endpoint": { + "protocol": "http", "host": "untrusted", "port": 8080, "username": "user" + }}), + ), + ] +} + +#[tokio::test] +async fn connection_policy_rejects_inline_host_capabilities_before_application_dispatch() { + let application = Arc::new(FixtureApplication::new(Duration::ZERO)); + let dispatcher = RpcDispatcher::new(application.clone()); + for authorization in [AuthorizationLevel::Database, AuthorizationLevel::Sensitive] { + for command in ["test_connection", "save_connection", "update_connection"] { + for (field, value) in connection_policy_host_fields() { + let mut params = serde_json::json!({"driver": "postgres", "database": "db"}); + params[field] = value; + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload(command, params), + Some(Uuid::new_v4()), + authorization, + ) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "{command}: {field} ({authorization:?})" + ); + assert_eq!(response_json(response).await["error"]["code"], "FORBIDDEN"); + assert!( + application.contexts.lock().unwrap().is_empty(), + "rejected payload reached application" + ); + } + } + } +} + +#[tokio::test] +async fn connection_policy_preserves_local_admin_inline_host_capabilities() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + for command in ["test_connection", "save_connection", "update_connection"] { + for (field, value) in connection_policy_host_fields() { + let mut params = serde_json::json!({"driver": "postgres", "database": "db"}); + params[field] = value; + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload(command, params), + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}: {field}"); + } + } +} + +#[tokio::test] +async fn connection_policy_preserves_database_access_and_saved_tunnel_references() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + for command in ["test_connection", "save_connection", "update_connection"] { + for settings in [ + serde_json::json!({}), + serde_json::json!({"ssh_enabled": true, "ssh_connection_id": "admin-ssh"}), + serde_json::json!({"k8s_enabled": true, "k8s_connection_id": "admin-k8s"}), + serde_json::json!({"ssh_enabled": false, "k8s_enabled": false, "ssm_enabled": false}), + serde_json::json!({"proxy": {"mode": "inherit"}}), + serde_json::json!({"proxy": {"mode": "disabled"}}), + ] { + let mut params = serde_json::json!({"driver": "postgres", "database": "db", "password": "db-password"}); + params + .as_object_mut() + .unwrap() + .extend(settings.as_object().unwrap().clone()); + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload(command, params), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + } + } + let response = dispatch_json( + &dispatcher, + "execute_query", + serde_json::json!({ + "connectionId": "admin-configured-db", "query": "SELECT 1" + }), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + for command in [ + "get_connection_metadata", + "get_available_databases", + "get_tables", + ] { + let response = dispatch_json( + &dispatcher, + command, + serde_json::json!({"connectionId": "admin-configured-db"}), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}"); + let response = dispatch_json(&dispatcher, command, serde_json::json!({"connectionId": "admin-configured-db", + "params": {"driver": "postgres", "database": "db", "k8s_kubectl_path": "/untrusted/program"}}), + Some(Uuid::new_v4()), AuthorizationLevel::Database).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{command}"); + } +} + +#[tokio::test] +async fn connection_policy_accepts_new_connection_modal_wire_defaults() { + let application = Arc::new(FixtureApplication::new(Duration::ZERO)); + let dispatcher = RpcDispatcher::new(application.clone()); + let session = Some(Uuid::new_v4()); + for authorization in [AuthorizationLevel::Database, AuthorizationLevel::Sensitive] { + for command in ["test_connection", "save_connection", "update_connection"] { + for tunnel in [ + serde_json::json!({}), + serde_json::json!({"ssh_enabled": true, "ssh_connection_id": "admin-ssh"}), + serde_json::json!({"k8s_enabled": true, "k8s_connection_id": "admin-k8s"}), + ] { + // NewConnectionModal keeps ssh_port in its initial/reset form + // data, and spreads that data into test and save requests. + let mut params = serde_json::json!({ + "driver": "mysql", "host": "localhost", "port": 3306, + "username": "", "password": "", "database": "", + "ssl_mode": "", "ssh_enabled": false, "ssh_port": 22, + "k8s_enabled": false, "ssm_enabled": false, + "save_in_keychain": false + }); + params + .as_object_mut() + .unwrap() + .extend(tunnel.as_object().unwrap().clone()); + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload(command, params), + session, + authorization, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}: {tunnel}"); + } + } + } + assert_eq!(application.contexts.lock().unwrap().len(), 18); +} + +#[test] +fn decodes_database_scope_and_routine_overload_for_web_commands() { + let body = br#"{"connectionId":"connection","database":"secondary","schema":"public"}"#; + let command = decode_metadata_command(MetadataRpcCommand::GetTables, body).unwrap(); + assert!( + matches!(command, MetadataCommand::GetTables { database: Some(ref db), .. } if db == "secondary") + ); + + let body = br#"{"connectionId":"connection","database":"secondary","schema":"public","routineName":"calculate","identityArgs":"integer"}"#; + let command = + decode_database_object_command(DatabaseObjectRpcCommand::GetRoutineParameters, body) + .unwrap(); + assert!( + matches!(command, DatabaseObjectCommand::GetRoutineParameters { database: Some(ref db), identity_args: Some(ref args), .. } if db == "secondary" && args == "integer") + ); +} + +#[tokio::test] +async fn connection_policy_blocks_file_drivers_in_inline_and_saved_requests() { + let plugin = "rpc-policy-file-plugin"; + crate::drivers::registry::set_local_path_driver(plugin, true); + for driver in ["sqlite", plugin] { + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + ConnectionParams { + driver: driver.into(), + database: DatabaseSelection::Single("/outside/private.db".into()), + ..Default::default() + }, + ); + let application = Arc::new(application); + let dispatcher = RpcDispatcher::new(application.clone()); + let mut requests = vec![ + ( + "execute_query", + serde_json::json!({"connectionId":"saved-db", "query":"ATTACH '/outside/other.db' AS other", "database":"/outside/override.db"}), + ), + ( + "execute_query_batch", + serde_json::json!({"connectionId":"saved-db", "queries":["SELECT 1"]}), + ), + ("get_tables", serde_json::json!({"connectionId":"saved-db"})), + ( + "get_ai_schema_context", + serde_json::json!({"connectionId":"saved-db"}), + ), + ( + "get_table_query_template", + serde_json::json!({"connectionId":"saved-db", "request":{"table":"secret", "kind":"select"}}), + ), + ( + "insert_record", + serde_json::json!({"connectionId":"saved-db", "table":"secret", "data":{"id":1}}), + ), + ( + "fetch_blob", + serde_json::json!({"connectionId":"saved-db", "table":"secret", "pkMap":{"id":1}, "colName":"data"}), + ), + ( + "export_query_to_file", + serde_json::json!({"connectionId":"saved-db", "query":"SELECT * FROM secret", "format":"csv"}), + ), + ( + "dump_database", + serde_json::json!({"connectionId":"saved-db", "options":{"structure":true, "data":true, "tables":[]}}), + ), + ( + "import_database", + serde_json::json!({"connectionId":"saved-db", "uploadToken":"upload"}), + ), + ( + "get_available_databases", + serde_json::json!({"connectionId":"saved-db"}), + ), + ( + "set_selected_databases", + serde_json::json!({"connectionId":"saved-db", "databases":["/outside/other.db"]}), + ), + ("duplicate_connection", serde_json::json!({"id":"saved-db"})), + ( + "register_active_connection", + serde_json::json!({"connectionId":"saved-db"}), + ), + ( + "execute_clipboard_import", + serde_json::json!({"req":{"connection_id":"saved-db", "table_name":"secret", "columns":[], "rows":[], "create_table":false, "if_exists":"append"}}), + ), + ]; + for name in ["save_connection", "update_connection", "test_connection"] { + requests.push(( + name, + connection_policy_payload( + name, + serde_json::json!({"driver":driver,"database":"/outside/private.db"}), + ), + )); + } + for (command, payload) in requests { + for authorization in [AuthorizationLevel::Database, AuthorizationLevel::Sensitive] { + let response = dispatch_json( + &dispatcher, + command, + payload.clone(), + Some(Uuid::new_v4()), + authorization, + ) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "{command} / {driver}" + ); + assert!( + application.contexts.lock().unwrap().is_empty(), + "denied request was dispatched" + ); + } + let response = dispatch_json( + &dispatcher, + command, + payload, + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!( + response.status(), + StatusCode::OK, + "admin: {command} / {driver}" + ); + application.contexts.lock().unwrap().clear(); + } + } + crate::drivers::registry::set_local_path_driver(plugin, false); +} + +#[tokio::test] +async fn connection_policy_binds_stored_credentials_to_the_full_security_target() { + let params = serde_json::json!({"driver":"postgres", "host":"trusted", "port":5432, "username":"owner", "database":"db", "ssl_mode":"verify-full"}); + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + serde_json::from_value(params.clone()).unwrap(), + ); + let application = Arc::new(application); + let dispatcher = RpcDispatcher::new(application.clone()); + for command in ["test_connection", "update_connection"] { + for (field, value) in [ + ("host", serde_json::json!("attacker")), + ("port", serde_json::json!(9999)), + ("driver", serde_json::json!("mysql")), + ("username", serde_json::json!("attacker")), + ("ssl_mode", serde_json::json!("disable")), + ("database", serde_json::json!("other-db")), + ( + "connection_uri", + serde_json::json!("postgres://attacker/db"), + ), + ("extra", serde_json::json!({"endpoint":"attacker"})), + ("ssh_connection_id", serde_json::json!("other-tunnel")), + ("enable_cleartext_plugin", serde_json::json!(true)), + ] { + let mut changed = params.clone(); + changed[field] = value; + let payload = connection_policy_payload(command, changed); + let response = dispatch_json( + &dispatcher, + command, + payload.clone(), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "{command}: {field}" + ); + assert!(application.contexts.lock().unwrap().is_empty()); + let response = dispatch_json( + &dispatcher, + command, + payload, + Some(Uuid::new_v4()), + AuthorizationLevel::LocalAdmin, + ) + .await; + assert_eq!( + response.status(), + StatusCode::OK, + "admin: {command}: {field}" + ); + application.contexts.lock().unwrap().clear(); + } + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload(command, params.clone()), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "same target: {command}"); + application.contexts.lock().unwrap().clear(); + } + let mut injected = params; + injected["connection_id"] = serde_json::json!("other-saved-db"); + let response = dispatch_json( + &dispatcher, + "test_connection", + connection_policy_payload("test_connection", injected), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "runtime connection ID cannot select another credential" + ); +} + +#[tokio::test] +async fn connection_policy_rejects_retargeting_even_when_supplied_password_can_leave_stale_secrets() +{ + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + ConnectionParams { + driver: "postgres".into(), + host: Some("trusted".into()), + save_in_keychain: Some(true), + ..Default::default() + }, + ); + let dispatcher = RpcDispatcher::new(Arc::new(application)); + let response = dispatch_json(&dispatcher, "update_connection", connection_policy_payload("update_connection", + serde_json::json!({"driver":"postgres", "host":"attacker", "database":"", "password":"replacement", "save_in_keychain":false})), + Some(Uuid::new_v4()), AuthorizationLevel::Database).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); +} + +#[tokio::test] +async fn connection_policy_preserves_same_target_metadata_and_credentials_edits() { + let params = serde_json::json!({"driver":"postgres", "host":"trusted", "database":"db", "save_in_keychain":true, "connection_uri_in_keychain":true}); + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + serde_json::from_value(params.clone()).unwrap(), + ); + let dispatcher = RpcDispatcher::new(Arc::new(application)); + for password in [ + Value::Null, + serde_json::json!(""), + serde_json::json!("replacement"), + ] { + let mut params = params.clone(); + params["password"] = password; + params["save_in_keychain"] = serde_json::json!(false); + let response = dispatch_json(&dispatcher, "update_connection", + serde_json::json!({"id":"saved-db", "name":"New display name", "environment":"production", "params":params}), + Some(Uuid::new_v4()), AuthorizationLevel::Database).await; + assert_eq!(response.status(), StatusCode::OK); + } +} + +#[tokio::test] +async fn connection_policy_tests_the_primary_database_of_a_saved_multiple_selection() { + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + ConnectionParams { + driver: "postgres".into(), + host: Some("trusted".into()), + database: DatabaseSelection::Multiple(vec!["first".into(), "second".into()]), + ..Default::default() + }, + ); + let dispatcher = RpcDispatcher::new(Arc::new(application)); + let response = dispatch_json( + &dispatcher, + "test_connection", + connection_policy_payload( + "test_connection", + serde_json::json!({"driver":"postgres", "host":"trusted", "database":"first"}), + ), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); +} + +#[tokio::test] +async fn connection_policy_accepts_omitted_blank_ssl_mode_on_saved_connections() { + for mode in ["", " \t"] { + let mut application = FixtureApplication::new(Duration::ZERO); + application.saved_params.insert( + "saved-db".into(), + ConnectionParams { + driver: "postgres".into(), + host: Some("trusted".into()), + ssl_mode: Some(mode.into()), + ..Default::default() + }, + ); + let dispatcher = RpcDispatcher::new(Arc::new(application)); + for command in ["test_connection", "update_connection"] { + let response = dispatch_json( + &dispatcher, + command, + connection_policy_payload( + command, + serde_json::json!({"driver":"postgres", "host":"trusted", "database":""}), + ), + Some(Uuid::new_v4()), + AuthorizationLevel::Database, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{command}: {mode:?}"); + } + } +} + +#[tokio::test] +async fn database_backup_rpc_requires_local_admin_and_uses_the_shared_application() { + let dispatcher = RpcDispatcher::new(Arc::new(FixtureApplication::new(Duration::ZERO))); + for command in ["get_database_backup_status", "run_database_backup_now", "cancel_database_backup"] { + for (authorization, expected) in [(AuthorizationLevel::Database, StatusCode::FORBIDDEN), (AuthorizationLevel::LocalAdmin, StatusCode::OK)] { + let response = dispatcher.dispatch(command, RequestId(command.to_string()), &json_headers(), Bytes::from_static(b"null"), Some(Uuid::new_v4()), authorization).await; + assert_eq!(response.status(), expected, "{command}"); + } + } +} diff --git a/src-tauri/src/transport/web/server.rs b/src-tauri/src/transport/web/server.rs new file mode 100644 index 000000000..2025e8126 --- /dev/null +++ b/src-tauri/src/transport/web/server.rs @@ -0,0 +1,1339 @@ +use super::auth::{ + AuthenticatedSession, AuthenticationError, IssuedSession, LocalSessionSecurity, + LocalSessionSecurityConfig, RemoteAuthentication, RemoteSessionSecurityConfig, + CSRF_HEADER_NAME, PROXY_SECRET_HEADER_NAME, PROXY_USER_HEADER_NAME, SESSION_COOKIE_NAME, +}; +use super::contract::SessionNegotiation; +use super::events::{ClientEventMessage, EventConnection, ServerEventMessage, WebEventBus}; +use super::rpc::{RequestId, RpcAccessPolicy, RpcDispatcher}; +use crate::application::file_transfers::{ + FileTransferStore, TransferReader, UploadError, MAX_FILE_TRANSFER_BYTES, +}; +use crate::application::{ApplicationApi, AuthorizationLevel}; +use crate::cli::WebAuthMode; +use axum::body::{Body, Bytes}; +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{ConnectInfo, Extension, Path, Query, Request, State}; +use axum::http::header::{ + CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_SECURITY_POLICY, CONTENT_TYPE, + COOKIE, HOST, LOCATION, ORIGIN, REFERRER_POLICY, RETRY_AFTER, SET_COOKIE, + X_CONTENT_TYPE_OPTIONS, +}; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{any, get, post}; +use axum::{Json, Router}; +use futures::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use std::future::Future; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use tokio::net::TcpListener; +use tokio::time::{Instant, MissedTickBehavior}; +use tokio_util::io::ReaderStream; +use tower_http::limit::RequestBodyLimitLayer; +use tower_http::services::{ServeDir, ServeFile}; +use url::Host; +use uuid::Uuid; + +const BOOTSTRAP_PATH: &str = "/api/v1/auth/bootstrap"; +const LOGIN_PATH: &str = "/api/v1/auth/login"; +const LOGIN_PAGE_PATH: &str = "/login"; +const REQUEST_ID_HEADER_NAME: &str = "x-request-id"; +const MAX_EVENT_CONTROL_BYTES: usize = 16 * 1024; +const FILE_NAME_HEADER_NAME: &str = "x-tabularis-file-name"; +const FILE_PURPOSE_HEADER_NAME: &str = "x-tabularis-purpose"; +const BLOB_TRANSFER_PURPOSE: &str = "blob"; +const PLUGIN_ASSET_CSP: &str = "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'; sandbox"; +const CROSS_ORIGIN_RESOURCE_POLICY: HeaderName = + HeaderName::from_static("cross-origin-resource-policy"); + +pub struct WebServerOptions { + pub trusted_proxies: Vec, + pub host: String, + pub port: u16, + pub web_root: PathBuf, + pub data_dir: PathBuf, + pub plugins_dir: PathBuf, + pub open_browser: bool, + pub auth: Option, + pub public_url: Option, + pub allowed_origins: Vec, + pub allow_high_risk: bool, + pub server_file_browser_roots: Vec, + pub application: Arc, + pub events: WebEventBus, +} + +#[derive(Clone)] +struct WebServerState { + security: LocalSessionSecurity, + rpc: RpcDispatcher, + events: WebEventBus, + transfers: FileTransferStore, + data_dir: PathBuf, + plugins_dir: PathBuf, + mcp_host_configuration: bool, + server_file_browser: bool, +} + +#[derive(Deserialize)] +struct BootstrapQuery { + token: String, +} + +#[derive(Serialize)] +struct IconUploadResponse { + token: String, +} + +#[derive(Serialize)] +struct BlobUploadResponse { + value: String, +} + +pub async fn run(options: WebServerOptions) -> Result<(), String> { + let server_file_browser_roots = + super::server_files::canonicalize_roots(&options.server_file_browser_roots)?; + let listener = TcpListener::bind((options.host.as_str(), options.port)) + .await + .map_err(|error| { + format!( + "Failed to bind the Web UI server to {}:{}: {error}", + options.host, options.port + ) + })?; + let address = listener + .local_addr() + .map_err(|error| format!("Failed to read the Web UI server address: {error}"))?; + + let (security, launch_url, public_url) = match options.auth { + Some(auth_mode) => { + let public_url = options.public_url.clone().ok_or_else(|| { + "Remote Web UI mode requires --public-url with an HTTPS (or loopback HTTP) origin".to_string() + })?; + let authentication = remote_authentication(auth_mode)?; + let authorization = if options.allow_high_risk { + AuthorizationLevel::LocalAdmin + } else { + AuthorizationLevel::Database + }; + let security = LocalSessionSecurity::new_remote( + RemoteSessionSecurityConfig { + trusted_proxies: options.trusted_proxies.clone(), + public_origin: public_url.clone(), + allowed_origins: options.allowed_origins.clone(), + session_ttl: LocalSessionSecurityConfig::default().session_ttl, + max_body_bytes: LocalSessionSecurityConfig::default().max_body_bytes, + authorization, + rate_limit: Default::default(), + }, + authentication, + )?; + let launch_url = if auth_mode == WebAuthMode::Password { + format!("{}{LOGIN_PAGE_PATH}", security.expected_origin()) + } else { + format!("{}/", security.expected_origin()) + }; + (security, launch_url, public_url) + } + None => { + if !address.ip().is_loopback() { + return Err( + "Non-loopback Web UI binding requires --auth, --public-url, and --allowed-origin" + .to_string(), + ); + } + let public_url = format!("http://{address}"); + let (security, bootstrap_token) = LocalSessionSecurity::new( + public_url.clone(), + LocalSessionSecurityConfig::default(), + )?; + let launch_url = format!( + "{public_url}{BOOTSTRAP_PATH}?token={}", + bootstrap_token.expose() + ); + drop(bootstrap_token); + (security, launch_url, public_url) + } + }; + + println!("Tabularis Web is available at {public_url}"); + if options.open_browser && open::that(&launch_url).is_err() { + log::warn!("Failed to open the Web UI in the default browser"); + // The user asked for a browser, so hand over the URL instead. It goes to + // the terminal only: `--no-open` services never print it. + eprintln!( + "Open this URL in a browser to sign in (valid once, for one minute):\n {launch_url}" + ); + } + drop(launch_url); + + serve_with_events( + listener, + options.web_root, + options.data_dir, + options.plugins_dir, + security, + options.application, + options.events, + server_file_browser_roots, + shutdown_signal(), + ) + .await + .map_err(|error| format!("Web UI server failed: {error}")) +} + +fn remote_authentication(auth_mode: WebAuthMode) -> Result { + match auth_mode { + WebAuthMode::Password => std::env::var("TABULARIS_WEB_PASSWORD") + .map(|password| RemoteAuthentication::password(&password)) + .map_err(|_| "Password authentication requires TABULARIS_WEB_PASSWORD".to_string()), + WebAuthMode::Proxy => std::env::var("TABULARIS_WEB_PROXY_SECRET") + .map(|secret| RemoteAuthentication::proxy(&secret)) + .map_err(|_| "Proxy authentication requires TABULARIS_WEB_PROXY_SECRET".to_string()), + } +} + +#[cfg(test)] +pub(crate) async fn serve( + listener: TcpListener, + web_root: PathBuf, + security: LocalSessionSecurity, + application: Arc, + shutdown: F, +) -> std::io::Result<()> +where + F: Future + Send + 'static, +{ + let data_dir = web_root.clone(); + serve_with_events( + listener, + web_root, + data_dir.clone(), + data_dir.join("plugins"), + security, + application, + WebEventBus::default(), + Arc::default(), + shutdown, + ) + .await +} + +pub(crate) async fn serve_with_events( + listener: TcpListener, + web_root: PathBuf, + data_dir: PathBuf, + plugins_dir: PathBuf, + security: LocalSessionSecurity, + application: Arc, + events: WebEventBus, + server_file_browser_roots: Arc<[PathBuf]>, + shutdown: F, +) -> std::io::Result<()> +where + F: Future + Send + 'static, +{ + let (router, state) = router( + web_root, + data_dir, + plugins_dir, + security, + application, + events, + server_file_browser_roots, + ); + // Keep reclamation owned by the server future, including cancellation and shutdown. + tokio::select! { + result = async { + axum::serve(listener, router.into_make_service_with_connect_info::()) + .with_graceful_shutdown(shutdown) + .await + } => result, + _ = reclaim_expired_sessions(state) => unreachable!("session reclamation runs until the server stops"), + } +} + +async fn reclaim_expired_sessions(state: WebServerState) { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(1)); + interval.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + interval.tick().await; + for session_id in state.security.take_expired_sessions() { + state.events.remove_session(session_id); + state.rpc.clear_session(session_id); + state.transfers.cleanup_session(session_id); + } + } +} + +fn router( + web_root: PathBuf, + data_dir: PathBuf, + plugins_dir: PathBuf, + security: LocalSessionSecurity, + application: Arc, + events: WebEventBus, + server_file_browser_roots: Arc<[PathBuf]>, +) -> (Router, WebServerState) { + let index = web_root.join("index.html"); + let static_files = ServeDir::new(web_root).fallback(ServeFile::new(index)); + let max_body_bytes = security.max_body_bytes(); + let mcp_host_configuration = + !security.is_remote() && mcp_host_configuration_enabled(security.expected_origin()); + let server_file_browser = !server_file_browser_roots.is_empty(); + let state = WebServerState { + security, + rpc: RpcDispatcher::with_access_policy( + application, + RpcAccessPolicy { + mcp_host_configuration, + server_file_browser_roots, + }, + ), + events, + transfers: FileTransferStore::new(&data_dir), + data_dir, + plugins_dir, + mcp_host_configuration, + server_file_browser, + }; + + let standard_routes = Router::new() + .route("/api/v1/session", get(session)) + .route(LOGIN_PAGE_PATH, get(login_page)) + .route(LOGIN_PATH, post(login)) + .route("/api/v1/logout", post(logout)) + .route("/api/v1/events", get(event_stream)) + .route("/api/v1/rpc/:command", post(rpc)) + .route( + "/api/v1/uploads/connection-icons", + post(upload_connection_icon), + ) + .route( + "/api/v1/assets/connection-icons/:filename", + get(connection_icon_asset), + ) + .route( + "/api/v1/assets/plugins/:plugin_id/*asset_path", + get(plugin_asset), + ) + .route("/api/*path", any(StatusCode::NOT_FOUND)) + .layer(RequestBodyLimitLayer::new(max_body_bytes)); + let file_routes = Router::new() + .route("/api/v1/uploads", post(upload_file)) + .route("/api/v1/downloads/:token", get(download_blob)) + .layer(RequestBodyLimitLayer::new(MAX_FILE_TRANSFER_BYTES as usize)); + let blob_routes = Router::new() + .route("/api/v1/uploads/blobs", post(upload_blob)) + .route("/api/v1/uploads/blobs/:token", get(uploaded_blob)) + .layer(RequestBodyLimitLayer::new( + crate::application::records::MAX_WEB_BLOB_BYTES as usize, + )); + + let router = Router::new() + .route("/healthz", get(health)) + .route(BOOTSTRAP_PATH, get(bootstrap)) + .merge(standard_routes) + .merge(file_routes) + .merge(blob_routes) + .fallback_service(static_files) + .with_state(state.clone()) + .layer(middleware::from_fn_with_state(state.clone(), security_gate)) + .layer(middleware::from_fn(add_request_id)) + .layer(middleware::map_response(baseline_security_headers)); + (router, state) +} + +/// Defaults for the SPA shell and every other response; handlers with a stricter policy keep theirs. +async fn baseline_security_headers(mut response: Response) -> Response { + let headers = response.headers_mut(); + headers + .entry(X_CONTENT_TYPE_OPTIONS) + .or_insert(HeaderValue::from_static("nosniff")); + headers + .entry(REFERRER_POLICY) + .or_insert(HeaderValue::from_static("same-origin")); + // No script-src yet: Monaco workers and plugin UI extensions need a tested allowlist first. + headers + .entry(CONTENT_SECURITY_POLICY) + .or_insert(HeaderValue::from_static( + "base-uri 'self'; object-src 'none'; frame-ancestors 'none'", + )); + response +} + +async fn health() -> impl IntoResponse { + ( + [(CACHE_CONTROL, "no-store"), (CONTENT_TYPE, "text/plain")], + "ok", + ) +} + +async fn bootstrap( + State(state): State, + Query(query): Query, + Extension(request_id): Extension, +) -> Response { + let Some(session) = state.security.consume_bootstrap(&query.token) else { + audit_event( + "authentication", + &request_id.0, + None, + "method=bootstrap outcome=denied", + ); + return status_response(StatusCode::UNAUTHORIZED); + }; + audit_event( + "authentication", + &request_id.0, + Some(session.session_id()), + "method=bootstrap outcome=success", + ); + + let mut response = StatusCode::SEE_OTHER.into_response(); + response + .headers_mut() + .insert(LOCATION, HeaderValue::from_static("/")); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response + .headers_mut() + .insert(REFERRER_POLICY, HeaderValue::from_static("no-referrer")); + response.headers_mut().insert( + SET_COOKIE, + session_cookie(&session, state.security.secure_cookie()), + ); + response +} + +async fn login_page(State(state): State) -> Response { + if !state.security.password_authentication() { + return status_response(StatusCode::NOT_FOUND); + } + login_page_response(StatusCode::OK, None) +} + +async fn login( + State(state): State, + Extension(request_id): Extension, + peer: Option>, + headers: HeaderMap, + body: Bytes, +) -> Response { + if !state.security.password_authentication() { + return status_response(StatusCode::NOT_FOUND); + } + let Some(password) = form_password(&body) else { + audit_event( + "authentication", + &request_id.0, + None, + "method=password outcome=denied", + ); + return login_page_response(StatusCode::UNAUTHORIZED, Some("Invalid credentials")); + }; + let client = state.security.login_client( + peer.map(|ConnectInfo(address)| address.ip()), + headers + .get("x-forwarded-for") + .and_then(|value| value.to_str().ok()), + ); + match state.security.authenticate_password(&password, client) { + Ok(session) => { + audit_event( + "authentication", + &request_id.0, + Some(session.session_id()), + "method=password outcome=success", + ); + let mut response = StatusCode::SEE_OTHER.into_response(); + response + .headers_mut() + .insert(LOCATION, HeaderValue::from_static("/")); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response.headers_mut().insert( + SET_COOKIE, + session_cookie(&session, state.security.secure_cookie()), + ); + response + } + Err(error) => { + audit_authentication_error(&request_id.0, "password", error); + authentication_error_response(error, true) + } + } +} + +async fn session( + State(state): State, + Extension(session): Extension, +) -> impl IntoResponse { + ( + [(CACHE_CONTROL, "no-store")], + Json( + SessionNegotiation::authenticated_with_access( + session.csrf_token.clone(), + state.mcp_host_configuration, + session.is_remote(), + session.authorization(), + ) + .with_server_file_browser( + state.server_file_browser + && session.authorization() == AuthorizationLevel::LocalAdmin, + ), + ), + ) +} + +pub(crate) fn mcp_host_configuration_enabled(origin: &str) -> bool { + url::Url::parse(origin) + .ok() + .and_then(|url| { + url.host().map(|host| match host { + Host::Domain(host) => host.eq_ignore_ascii_case("localhost"), + Host::Ipv4(host) => host.is_loopback(), + Host::Ipv6(host) => host.is_loopback(), + }) + }) + .unwrap_or(false) +} + +async fn rpc( + State(state): State, + Path(command): Path, + Extension(session): Extension, + Extension(request_id): Extension, + headers: HeaderMap, + body: Bytes, +) -> Response { + let session_id = session.event_scope(); + let request_id_text = request_id.0.clone(); + let response = state + .rpc + .dispatch( + &command, + request_id, + &headers, + body, + Some(session_id), + session.authorization(), + ) + .await; + let audited_command = if response.status() == StatusCode::NOT_FOUND { + "unknown" + } else { + command.as_str() + }; + audit_event( + "rpc", + &request_id_text, + Some(session_id), + &format!( + "command={audited_command} status={}", + response.status().as_u16() + ), + ); + response +} + +async fn upload_connection_icon( + State(state): State, + Extension(session): Extension, + body: Bytes, +) -> Response { + match crate::application::connections::store_icon_upload( + &state.data_dir, + session.event_scope(), + &body, + ) { + Ok(token) => ( + StatusCode::CREATED, + [(CACHE_CONTROL, "no-store")], + Json(IconUploadResponse { token }), + ) + .into_response(), + Err(error) => ( + StatusCode::BAD_REQUEST, + [(CACHE_CONTROL, "no-store")], + error, + ) + .into_response(), + } +} + +async fn upload_file( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + body: Body, +) -> Response { + let Some(purpose) = header_text(&headers, FILE_PURPOSE_HEADER_NAME) else { + return upload_error_response(UploadError::Failed( + "A file transfer purpose is required".to_string(), + )); + }; + let Some(encoded_name) = header_text(&headers, FILE_NAME_HEADER_NAME) else { + return upload_error_response(UploadError::Failed("A file name is required".to_string())); + }; + let file_name = match urlencoding::decode(encoded_name) { + Ok(file_name) => file_name, + Err(_) => { + return upload_error_response(UploadError::Failed( + "The file name is invalid".to_string(), + )) + } + }; + let content_type = header_text(&headers, CONTENT_TYPE.as_str()); + match state + .transfers + .store_upload( + session.event_scope(), + purpose, + &file_name, + content_type, + body.into_data_stream(), + ) + .await + { + Ok(metadata) => ( + StatusCode::CREATED, + [(CACHE_CONTROL, "no-store")], + Json(metadata), + ) + .into_response(), + Err(error) => upload_error_response(error), + } +} + +async fn upload_blob( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + body: Body, +) -> Response { + let content_type = header_text(&headers, CONTENT_TYPE.as_str()); + match state + .transfers + .store_upload( + session.event_scope(), + BLOB_TRANSFER_PURPOSE, + "blob-upload.bin", + content_type, + body.into_data_stream(), + ) + .await + { + Ok(metadata) if metadata.size > 0 => { + let value = format!( + "BLOB_UPLOAD_REF:{}:{}:{}", + metadata.size, metadata.mime_type, metadata.token + ); + ( + StatusCode::CREATED, + [(CACHE_CONTROL, "no-store")], + Json(BlobUploadResponse { value }), + ) + .into_response() + } + Ok(metadata) => { + let _ = state.transfers.claim_upload( + session.event_scope(), + &metadata.token, + BLOB_TRANSFER_PURPOSE, + ); + upload_error_response(UploadError::Failed( + "The uploaded BLOB is empty".to_string(), + )) + } + Err(error) => upload_error_response(error), + } +} + +async fn uploaded_blob( + State(state): State, + Path(token): Path, + Extension(session): Extension, +) -> Response { + match state + .transfers + .open_upload(session.event_scope(), &token, BLOB_TRANSFER_PURPOSE) + .await + { + Ok(reader) => streaming_transfer_response(reader, false, true), + Err(_) => status_response(StatusCode::NOT_FOUND), + } +} + +async fn download_blob( + State(state): State, + Path(token): Path, + Extension(session): Extension, +) -> Response { + match state + .transfers + .consume_download(session.event_scope(), &token) + .await + { + Ok(reader) => streaming_transfer_response(reader, true, false), + Err(_) => status_response(StatusCode::NOT_FOUND), + } +} + +fn streaming_transfer_response( + reader: TransferReader, + attachment: bool, + sandbox: bool, +) -> Response { + let metadata = reader.metadata().clone(); + let disposition = if attachment { "attachment" } else { "inline" }; + let content_disposition = format!("{disposition}; filename=\"{}\"", metadata.file_name); + let mut response = Response::new(Body::from_stream(ReaderStream::new(reader))); + *response.status_mut() = StatusCode::OK; + let headers = response.headers_mut(); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_str(&metadata.mime_type) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")), + ); + headers.insert( + CONTENT_LENGTH, + HeaderValue::from_str(&metadata.size.to_string()) + .expect("file transfer sizes are valid header values"), + ); + headers.insert( + CONTENT_DISPOSITION, + HeaderValue::from_str(&content_disposition) + .expect("sanitized file names are valid header values"), + ); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + if sandbox { + headers.insert( + CONTENT_SECURITY_POLICY, + HeaderValue::from_static("sandbox; default-src 'none'"), + ); + } + response +} + +fn header_text<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers.get(name)?.to_str().ok() +} + +fn upload_error_response(error: UploadError) -> Response { + let status = match error { + UploadError::TooLarge(_) => StatusCode::PAYLOAD_TOO_LARGE, + UploadError::Failed(_) => StatusCode::BAD_REQUEST, + }; + (status, [(CACHE_CONTROL, "no-store")], error.to_string()).into_response() +} + +async fn plugin_asset( + State(state): State, + Path((plugin_id, asset_path)): Path<(String, String)>, +) -> Response { + let asset = match crate::application::plugin_assets::read_plugin_asset( + &state.plugins_dir, + &plugin_id, + &asset_path, + ) { + Ok(asset) => asset, + Err(_) => return status_response(StatusCode::NOT_FOUND), + }; + + let mut response = Response::new(Body::from(asset.bytes)); + *response.status_mut() = StatusCode::OK; + let headers = response.headers_mut(); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-store")); + headers.insert(CONTENT_TYPE, HeaderValue::from_static(asset.content_type)); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + headers.insert(REFERRER_POLICY, HeaderValue::from_static("no-referrer")); + headers.insert( + CONTENT_SECURITY_POLICY, + HeaderValue::from_static(PLUGIN_ASSET_CSP), + ); + headers.insert( + CROSS_ORIGIN_RESOURCE_POLICY, + HeaderValue::from_static("same-origin"), + ); + response +} + +async fn connection_icon_asset( + State(state): State, + Path(filename): Path, +) -> Response { + let relative_path = format!("connection-icons/{filename}"); + let path = match crate::application::connections::resolve_icon_asset( + &state.data_dir, + &relative_path, + ) { + Ok(path) => path, + Err(_) => return status_response(StatusCode::NOT_FOUND), + }; + let bytes = match tokio::fs::read(&path).await { + Ok(bytes) => bytes, + Err(_) => return status_response(StatusCode::NOT_FOUND), + }; + let content_type = match path.extension().and_then(|extension| extension.to_str()) { + Some("png") => "image/png", + Some("jpg" | "jpeg") => "image/jpeg", + Some("webp") => "image/webp", + Some("svg") => "image/svg+xml", + _ => "application/octet-stream", + }; + // The SVG upload filter is a denylist; the sandbox CSP stops scripts when an icon is opened directly. + ( + StatusCode::OK, + [ + (CACHE_CONTROL, "private, max-age=300"), + (CONTENT_TYPE, content_type), + (X_CONTENT_TYPE_OPTIONS, "nosniff"), + (CONTENT_SECURITY_POLICY, PLUGIN_ASSET_CSP), + (CROSS_ORIGIN_RESOURCE_POLICY, "same-origin"), + ], + bytes, + ) + .into_response() +} + +async fn event_stream( + State(state): State, + Extension(session): Extension, + websocket: WebSocketUpgrade, +) -> Response { + let connection = match state + .events + .connect(session.event_scope(), session.authorization()) + { + Ok(connection) => connection, + Err(error) => { + log::warn!("Rejected WebSocket event connection: {error}"); + return status_response(StatusCode::SERVICE_UNAVAILABLE); + } + }; + let events = state.events.clone(); + websocket.on_upgrade(move |socket| { + event_socket( + socket, + connection, + events, + Instant::from_std(session.expires_at), + ) + }) +} + +async fn event_socket( + socket: WebSocket, + mut connection: EventConnection, + events: WebEventBus, + expires_at: Instant, +) { + let (mut sender, mut receiver) = socket.split(); + let mut heartbeat = tokio::time::interval(events.heartbeat_interval()); + heartbeat.set_missed_tick_behavior(MissedTickBehavior::Delay); + heartbeat.tick().await; + let mut last_pong = Instant::now(); + + let process_messages = async { + loop { + tokio::select! { + event = connection.recv() => { + let Some(event) = event else { + let _ = sender.send(Message::Close(None)).await; + break; + }; + let message = ServerEventMessage::Event { envelope: &event }; + if send_event_message(&mut sender, &message).await.is_err() { + break; + } + } + _ = heartbeat.tick() => { + if last_pong.elapsed() >= events.heartbeat_timeout() { + let _ = sender.send(Message::Close(None)).await; + break; + } + if sender.send(Message::Ping(Vec::new())).await.is_err() { + break; + } + } + message = receiver.next() => { + let Some(Ok(message)) = message else { + break; + }; + match message { + Message::Text(text) => { + if text.len() > MAX_EVENT_CONTROL_BYTES { + let message = ServerEventMessage::Error { + code: "CONTROL_MESSAGE_TOO_LARGE", + message: "The WebSocket control message is too large", + }; + if send_event_message(&mut sender, &message).await.is_err() { + break; + } + continue; + } + let control = match serde_json::from_str::(&text) { + Ok(control) => control, + Err(_) => { + let message = ServerEventMessage::Error { + code: "INVALID_CONTROL_MESSAGE", + message: "The WebSocket control message is invalid", + }; + if send_event_message(&mut sender, &message).await.is_err() { + break; + } + continue; + } + }; + if handle_event_control(&mut sender, &mut connection, control).await.is_err() { + break; + } + } + Message::Ping(payload) => { + if sender.send(Message::Pong(payload)).await.is_err() { + break; + } + } + Message::Pong(_) => last_pong = Instant::now(), + Message::Close(_) => break, + Message::Binary(_) => { + let message = ServerEventMessage::Error { + code: "INVALID_CONTROL_MESSAGE", + message: "WebSocket control messages must be JSON text", + }; + if send_event_message(&mut sender, &message).await.is_err() { + break; + } + } + } + } + } + } + }; + tokio::select! { + biased; + _ = tokio::time::sleep_until(expires_at) => {}, + _ = process_messages => return, + } + // Expiry cancels in-flight sends and replay too; a stalled peer cannot retain the socket. + let _ = tokio::time::timeout( + std::time::Duration::from_millis(100), + sender.send(Message::Close(None)), + ) + .await; +} + +async fn handle_event_control( + sender: &mut S, + connection: &mut EventConnection, + control: ClientEventMessage, +) -> Result<(), ()> +where + S: futures::Sink + Unpin, +{ + match control { + ClientEventMessage::Subscribe { events, since } => { + match connection.subscribe(&events, since) { + Ok(replay) => { + let acknowledgement = ServerEventMessage::Subscribed { + events: &events, + replayed: replay.len(), + }; + send_event_message(sender, &acknowledgement).await?; + for event in &replay { + send_event_message(sender, &ServerEventMessage::Event { envelope: event }) + .await?; + } + } + Err(error) => { + send_event_message( + sender, + &ServerEventMessage::Error { + code: "SUBSCRIPTION_REJECTED", + message: &error, + }, + ) + .await?; + } + } + } + ClientEventMessage::Unsubscribe { events } => match connection.unsubscribe(&events) { + Ok(()) => { + send_event_message( + sender, + &ServerEventMessage::Unsubscribed { events: &events }, + ) + .await?; + } + Err(error) => { + send_event_message( + sender, + &ServerEventMessage::Error { + code: "SUBSCRIPTION_REJECTED", + message: &error, + }, + ) + .await?; + } + }, + } + Ok(()) +} + +async fn send_event_message(sender: &mut S, message: &ServerEventMessage<'_>) -> Result<(), ()> +where + S: futures::Sink + Unpin, +{ + let text = serde_json::to_string(message).map_err(|_| ())?; + sender.send(Message::Text(text)).await.map_err(|_| ()) +} + +async fn logout( + State(state): State, + Extension(session): Extension, + Extension(request_id): Extension, +) -> Response { + let session_id = session.event_scope(); + state.events.remove_session(session_id); + state.rpc.clear_session(session.event_scope()); + state.transfers.cleanup_session(session.event_scope()); + state.security.logout(&session); + audit_event("logout", &request_id.0, Some(session_id), "outcome=success"); + let mut response = StatusCode::NO_CONTENT.into_response(); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + let secure = if state.security.secure_cookie() { + "; Secure" + } else { + "" + }; + response.headers_mut().insert( + SET_COOKIE, + HeaderValue::from_str(&format!( + "tabularis_session=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0{secure}" + )) + .expect("the session cookie attributes are valid"), + ); + response +} + +async fn security_gate( + State(state): State, + mut request: Request, + next: Next, +) -> Response { + let request_id = request + .extensions() + .get::() + .map(|request_id| request_id.0.as_str()) + .unwrap_or("unknown"); + let host = request + .headers() + .get(HOST) + .and_then(|value| value.to_str().ok()); + if !host.is_some_and(|host| state.security.host_allowed(host)) { + audit_event("request", request_id, None, "outcome=denied reason=host"); + return status_response(StatusCode::FORBIDDEN); + } + + let origin = request + .headers() + .get(ORIGIN) + .and_then(|value| value.to_str().ok()); + if origin.is_some_and(|value| !state.security.origin_allowed(value)) { + audit_event("request", request_id, None, "outcome=denied reason=origin"); + return status_response(StatusCode::FORBIDDEN); + } + + let path = request.uri().path(); + let local_bootstrap = + !state.security.is_remote() && path == BOOTSTRAP_PATH && request.method() == Method::GET; + let password_login = state.security.password_authentication() + && ((path == LOGIN_PAGE_PATH && request.method() == Method::GET) + || (path == LOGIN_PATH && request.method() == Method::POST)); + if path == "/healthz" || local_bootstrap || password_login { + if path == LOGIN_PATH && !origin.is_some_and(|origin| state.security.origin_allowed(origin)) + { + audit_event( + "authentication", + request_id, + None, + "method=password outcome=denied reason=origin", + ); + return status_response(StatusCode::FORBIDDEN); + } + return next.run(request).await; + } + + let mut issued_session = None; + let session = session_cookie_value(request.headers().get(COOKIE)) + .and_then(|cookie_value| state.security.authenticate(cookie_value)); + let session = match session { + Some(session) => session, + None if state.security.proxy_authentication() => { + let secret = request + .headers() + .get(PROXY_SECRET_HEADER_NAME) + .and_then(|value| value.to_str().ok()); + let user = request + .headers() + .get(PROXY_USER_HEADER_NAME) + .and_then(|value| value.to_str().ok()); + let (Some(secret), Some(user)) = (secret, user) else { + audit_event( + "authentication", + request_id, + None, + "method=proxy outcome=denied reason=missing_headers", + ); + return status_response(StatusCode::UNAUTHORIZED); + }; + match state.security.authenticate_proxy(secret, user) { + Ok(issued) => { + let session = state + .security + .authenticate(&issued.cookie_value) + .expect("a newly issued proxy session is active"); + audit_event( + "authentication", + request_id, + Some(issued.session_id()), + "method=proxy outcome=success", + ); + issued_session = Some(issued); + session + } + Err(error) => { + audit_authentication_error(request_id, "proxy", error); + return authentication_error_response(error, false); + } + } + } + None if state.security.password_authentication() && request.method() == Method::GET => { + let mut response = StatusCode::SEE_OTHER.into_response(); + response + .headers_mut() + .insert(LOCATION, HeaderValue::from_static(LOGIN_PAGE_PATH)); + return response; + } + None => return status_response(StatusCode::UNAUTHORIZED), + }; + + if requires_csrf(request.method()) { + if !origin.is_some_and(|origin| state.security.origin_allowed(origin)) + || request + .headers() + .get(CSRF_HEADER_NAME) + .and_then(|value| value.to_str().ok()) + != Some(session.csrf_token.as_str()) + { + audit_event( + "request", + request_id, + Some(session.event_scope()), + "outcome=denied reason=csrf", + ); + return status_response(StatusCode::FORBIDDEN); + } + } + + request.headers_mut().remove(PROXY_SECRET_HEADER_NAME); + request.headers_mut().remove(PROXY_USER_HEADER_NAME); + let expires_at = Instant::from_std(session.expires_at); + request.extensions_mut().insert(session); + // Include body extraction: a slow request must not recreate state after expiry cleanup. + let mut response = tokio::select! { + biased; + _ = tokio::time::sleep_until(expires_at) => return status_response(StatusCode::UNAUTHORIZED), + response = next.run(request) => response, + }; + if let Some(issued) = issued_session { + response.headers_mut().insert( + SET_COOKIE, + session_cookie(&issued, state.security.secure_cookie()), + ); + } + response +} + +async fn add_request_id(mut request: Request, next: Next) -> Response { + let request_id = request + .headers() + .get(REQUEST_ID_HEADER_NAME) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_request_id(value)) + .map(str::to_owned) + .unwrap_or_else(|| Uuid::new_v4().to_string()); + request + .extensions_mut() + .insert(RequestId(request_id.clone())); + let mut response = next.run(request).await; + if let Ok(value) = HeaderValue::from_str(&request_id) { + response.headers_mut().insert(REQUEST_ID_HEADER_NAME, value); + } + response +} + +fn requires_csrf(method: &Method) -> bool { + !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) +} + +fn valid_request_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')) +} + +fn session_cookie_value(cookie_header: Option<&HeaderValue>) -> Option<&str> { + cookie_header? + .to_str() + .ok()? + .split(';') + .filter_map(|cookie| cookie.trim().split_once('=')) + .find_map(|(name, value)| (name == SESSION_COOKIE_NAME).then_some(value)) +} + +fn session_cookie(session: &IssuedSession, secure: bool) -> HeaderValue { + let secure = if secure { "; Secure" } else { "" }; + HeaderValue::from_str(&format!( + "{SESSION_COOKIE_NAME}={}; Path=/; HttpOnly; SameSite=Strict; Max-Age={}{secure}", + session.cookie_value, session.max_age_seconds + )) + .expect("generated session cookies contain only valid header characters") +} + +fn form_password(body: &[u8]) -> Option { + url::form_urlencoded::parse(body) + .find_map(|(name, value)| (name == "password").then(|| value.into_owned())) +} + +fn login_page_response(status: StatusCode, error: Option<&str>) -> Response { + let error = error + .map(|message| format!("

{message}

")) + .unwrap_or_default(); + let body = format!( + "Tabularis Web sign in

Sign in to Tabularis Web

{error}
" + ); + let mut response = (status, body).into_response(); + let headers = response.headers_mut(); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + headers.insert(REFERRER_POLICY, HeaderValue::from_static("no-referrer")); + headers.insert( + CONTENT_SECURITY_POLICY, + HeaderValue::from_static( + "default-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'", + ), + ); + response +} + +fn authentication_error_response(error: AuthenticationError, html: bool) -> Response { + match error { + AuthenticationError::SessionLimitReached => { + if html { + login_page_response( + StatusCode::SERVICE_UNAVAILABLE, + Some("The server has reached its session limit. Try again later."), + ) + } else { + status_response(StatusCode::SERVICE_UNAVAILABLE) + } + } + AuthenticationError::RateLimited => { + let mut response = if html { + login_page_response(StatusCode::TOO_MANY_REQUESTS, Some("Too many attempts")) + } else { + status_response(StatusCode::TOO_MANY_REQUESTS) + }; + response + .headers_mut() + .insert(RETRY_AFTER, HeaderValue::from_static("300")); + response + } + AuthenticationError::InvalidCredentials | AuthenticationError::UnsupportedMode => { + if html { + login_page_response(StatusCode::UNAUTHORIZED, Some("Invalid credentials")) + } else { + status_response(StatusCode::UNAUTHORIZED) + } + } + } +} + +fn audit_authentication_error(request_id: &str, method: &str, error: AuthenticationError) { + let outcome = match error { + AuthenticationError::RateLimited => "rate_limited", + AuthenticationError::SessionLimitReached => "session_limit", + AuthenticationError::InvalidCredentials | AuthenticationError::UnsupportedMode => "denied", + }; + audit_event( + "authentication", + request_id, + None, + &format!("method={method} outcome={outcome}"), + ); +} + +fn audit_event(event: &str, request_id: &str, session_id: Option, detail: &str) { + let session_id = session_id + .map(|session_id| session_id.to_string()) + .unwrap_or_else(|| "none".to_string()); + log::info!( + target: "tabularis::web_audit", + "event={event} request_id={request_id} session_id={session_id} {detail}" + ); +} + +fn status_response(status: StatusCode) -> Response { + let mut response = status.into_response(); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} + +async fn shutdown_signal() { + let ctrl_c = async { + if let Err(error) = tokio::signal::ctrl_c().await { + log::error!("Failed to install the Ctrl+C shutdown handler: {error}"); + } + }; + + #[cfg(unix)] + let terminate = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut signal) => { + signal.recv().await; + } + Err(error) => { + log::error!("Failed to install the terminate shutdown handler: {error}"); + std::future::pending::<()>().await; + } + } + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {} + _ = terminate => {} + } + + log::info!("Web UI shutdown signal received"); +} diff --git a/src-tauri/src/transport/web/server_files.rs b/src-tauri/src/transport/web/server_files.rs new file mode 100644 index 000000000..731375843 --- /dev/null +++ b/src-tauri/src/transport/web/server_files.rs @@ -0,0 +1,240 @@ +use serde::Serialize; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +#[cfg(test)] +mod tests; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerDirectoryListing { + pub path: Option, + pub parent: Option, + pub entries: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerPathEntry { + pub name: String, + pub path: String, + pub kind: ServerPathKind, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ServerPathKind { + File, + Directory, +} + +pub fn canonicalize_roots(roots: &[PathBuf]) -> Result, String> { + let mut canonical = Vec::with_capacity(roots.len()); + for root in roots { + let path = fs::canonicalize(root).map_err(|error| { + format!( + "Failed to resolve server file browser root {}: {error}", + root.display() + ) + })?; + if !path.is_dir() { + return Err(format!( + "Server file browser root is not a directory: {}", + path.display() + )); + } + if !canonical.contains(&path) { + canonical.push(path); + } + } + Ok(canonical.into()) +} + +pub fn resolve_save_target( + roots: &[PathBuf], + directory: &str, + file_name: &str, +) -> Result { + if roots.is_empty() { + return Err("Server file browsing is disabled".to_string()); + } + let file_name_path = Path::new(file_name); + if file_name.trim().is_empty() + || file_name_path.file_name().and_then(|name| name.to_str()) != Some(file_name) + { + return Err("Choose a valid file name without directory separators".to_string()); + } + let directory = fs::canonicalize(directory) + .map_err(|error| format!("Failed to resolve server directory: {error}"))?; + if !directory.is_dir() || !roots.iter().any(|root| directory.starts_with(root)) { + return Err("The requested path is outside the configured browser roots".to_string()); + } + let target = path_text(&directory.join(file_name)) + .ok_or_else(|| "The selected server path is not valid UTF-8".to_string())?; + // Inspect the leaf without following it: a dangling symlink is not a new file. + match fs::symlink_metadata(&target) { + Ok(_) => path_text(&validate_existing_file(roots, &target)?) + .ok_or_else(|| "The selected server path is not valid UTF-8".to_string()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(target), + Err(error) => Err(format!("Failed to inspect server save target: {error}")), + } +} + +pub fn validate_save_target(roots: &[PathBuf], target: &str) -> Result { + let target = Path::new(target); + let directory = target + .parent() + .and_then(path_text) + .ok_or_else(|| "Choose a valid server directory".to_string())?; + let file_name = target + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| "Choose a valid file name".to_string())?; + resolve_save_target(roots, &directory, file_name) +} + +/// Resolves an existing file inside the configured roots (for server-side +/// reads such as opening a SQL file or a local theme archive). +pub fn validate_existing_file(roots: &[PathBuf], target: &str) -> Result { + if roots.is_empty() { + return Err("Server file browsing is disabled".to_string()); + } + let path = fs::canonicalize(target) + .map_err(|error| format!("Failed to resolve server file: {error}"))?; + if !roots.iter().any(|root| path.starts_with(root)) { + return Err("The requested path is outside the configured browser roots".to_string()); + } + if !path.is_file() { + return Err("The requested server path is not a file".to_string()); + } + Ok(path) +} + +/// Resolves a directory that may not exist yet. Its nearest existing ancestor +/// must sit inside the configured roots and the remaining components must be +/// plain names, so the result can never escape them. +pub fn validate_directory_target(roots: &[PathBuf], target: &str) -> Result { + if roots.is_empty() { + return Err("Server file browsing is disabled".to_string()); + } + let requested = Path::new(target); + if !requested.is_absolute() { + return Err("Choose an absolute server directory".to_string()); + } + let mut existing = requested; + let mut missing = Vec::new(); + // `exists()` follows links, so a dangling symlink would pass as a plain missing name. + while fs::symlink_metadata(existing).is_err() { + let name = existing + .file_name() + .ok_or_else(|| "Choose a valid server directory".to_string())?; + missing.push(name.to_owned()); + existing = existing + .parent() + .ok_or_else(|| "Choose a valid server directory".to_string())?; + } + let mut resolved = fs::canonicalize(existing) + .map_err(|error| format!("Failed to resolve server directory: {error}"))?; + if !resolved.is_dir() || !roots.iter().any(|root| resolved.starts_with(root)) { + return Err("The requested path is outside the configured browser roots".to_string()); + } + for name in missing.into_iter().rev() { + if name == ".." || name == "." { + return Err("Choose a valid server directory".to_string()); + } + resolved.push(name); + } + Ok(resolved) +} + +pub fn list_directory( + roots: &[PathBuf], + requested_path: Option<&str>, +) -> Result { + if roots.is_empty() { + return Err("Server file browsing is disabled".to_string()); + } + + let Some(requested_path) = requested_path else { + return Ok(root_listing(roots)); + }; + let directory = fs::canonicalize(requested_path) + .map_err(|error| format!("Failed to resolve server path: {error}"))?; + if !directory.is_dir() { + return Err("The requested server path is not a directory".to_string()); + } + let root = roots + .iter() + .find(|root| directory.starts_with(root)) + .ok_or_else(|| "The requested path is outside the configured browser roots".to_string())?; + + let mut entries = fs::read_dir(&directory) + .map_err(|error| format!("Failed to read server directory: {error}"))? + .filter_map(Result::ok) + .filter_map(|entry| server_entry(entry.path(), root)) + .collect::>(); + entries.sort_by(|left, right| { + entry_rank(&left.kind) + .cmp(&entry_rank(&right.kind)) + .then_with(|| left.name.to_lowercase().cmp(&right.name.to_lowercase())) + }); + + let parent = if directory == *root { + None + } else { + directory.parent().and_then(path_text) + }; + Ok(ServerDirectoryListing { + path: path_text(&directory), + parent, + entries, + }) +} + +fn root_listing(roots: &[PathBuf]) -> ServerDirectoryListing { + ServerDirectoryListing { + path: None, + parent: None, + entries: roots + .iter() + .filter_map(|path| { + Some(ServerPathEntry { + name: path_text(path)?, + path: path_text(path)?, + kind: ServerPathKind::Directory, + }) + }) + .collect(), + } +} + +fn server_entry(path: PathBuf, root: &Path) -> Option { + let canonical = fs::canonicalize(path).ok()?; + if !canonical.starts_with(root) { + return None; + } + let kind = if canonical.is_dir() { + ServerPathKind::Directory + } else if canonical.is_file() { + ServerPathKind::File + } else { + return None; + }; + Some(ServerPathEntry { + name: canonical.file_name()?.to_string_lossy().into_owned(), + path: path_text(&canonical)?, + kind, + }) +} + +fn entry_rank(kind: &ServerPathKind) -> u8 { + match kind { + ServerPathKind::Directory => 0, + ServerPathKind::File => 1, + } +} + +fn path_text(path: &Path) -> Option { + path.to_str().map(str::to_owned) +} diff --git a/src-tauri/src/transport/web/server_files/tests.rs b/src-tauri/src/transport/web/server_files/tests.rs new file mode 100644 index 000000000..91a2a7e5d --- /dev/null +++ b/src-tauri/src/transport/web/server_files/tests.rs @@ -0,0 +1,194 @@ +use super::{ + canonicalize_roots, list_directory, resolve_save_target, validate_directory_target, + validate_existing_file, validate_save_target, +}; +use std::fs; +use tempfile::tempdir; + +#[test] +fn lists_only_paths_inside_configured_roots() { + let root = tempdir().unwrap(); + fs::create_dir(root.path().join("databases")).unwrap(); + fs::write(root.path().join("main.sqlite"), b"").unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let listing = list_directory(&roots, root.path().to_str()).unwrap(); + + assert_eq!(listing.entries.len(), 2); + assert_eq!(listing.entries[0].name, "databases"); + assert_eq!(listing.entries[1].name, "main.sqlite"); +} + +#[test] +fn rejects_paths_outside_configured_roots() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let error = list_directory(&roots, outside.path().to_str()).unwrap_err(); + + assert!(error.contains("outside the configured browser roots")); +} + +#[test] +fn resolves_new_files_inside_configured_roots() { + let root = tempdir().unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let target = + resolve_save_target(&roots, root.path().to_str().unwrap(), "customers.db").unwrap(); + + assert_eq!(target, roots[0].join("customers.db").to_str().unwrap()); + assert_eq!(validate_save_target(&roots, &target).unwrap(), target); +} + +#[test] +fn resolves_existing_save_files_inside_configured_roots() { + let root = tempdir().unwrap(); + let file = root.path().join("query.sql"); + fs::write(&file, "select 1").unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let target = validate_save_target(&roots, file.to_str().unwrap()).unwrap(); + + assert_eq!( + std::path::Path::new(&target), + fs::canonicalize(file).unwrap() + ); +} + +#[cfg(unix)] +#[test] +fn rejects_save_links_outside_roots_without_overwriting_the_target() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let file = outside.path().join("private.sql"); + fs::write(&file, "original").unwrap(); + let link = root.path().join("query.sql"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let result = validate_save_target(&roots, link.to_str().unwrap()).and_then(|path| { + crate::sql_file::write_sql_file_to_disk(std::path::Path::new(&path), "replacement") + }); + + assert!(result.is_err()); + assert_eq!(fs::read_to_string(file).unwrap(), "original"); + assert!(resolve_save_target(&roots, root.path().to_str().unwrap(), "query.sql").is_err()); +} + +#[cfg(unix)] +#[test] +fn rejects_dangling_save_links_without_creating_files_outside_roots() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let file = outside.path().join("new.sql"); + let link = root.path().join("query.sql"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let result = validate_save_target(&roots, link.to_str().unwrap()).and_then(|path| { + crate::sql_file::write_sql_file_to_disk(std::path::Path::new(&path), "replacement") + }); + + assert!(result.is_err()); + assert!(!file.exists()); +} + +#[cfg(unix)] +#[test] +fn resolves_internal_save_links_to_their_checked_target() { + let root = tempdir().unwrap(); + let file = root.path().join("actual.sql"); + fs::write(&file, "original").unwrap(); + let link = root.path().join("query.sql"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let target = validate_save_target(&roots, link.to_str().unwrap()).unwrap(); + + assert_eq!( + std::path::Path::new(&target), + fs::canonicalize(&file).unwrap() + ); + crate::sql_file::write_sql_file_to_disk(std::path::Path::new(&target), "replacement").unwrap(); + assert_eq!(fs::read_to_string(file).unwrap(), "replacement"); +} + +#[test] +fn rejects_save_file_names_with_path_traversal() { + let root = tempdir().unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let error = + resolve_save_target(&roots, root.path().to_str().unwrap(), "../outside.db").unwrap_err(); + + assert!(error.contains("without directory separators")); +} + +#[test] +fn rejects_missing_roots_during_startup_validation() { + let root = tempdir().unwrap(); + let missing = root.path().join("missing"); + + let error = canonicalize_roots(&[missing]).unwrap_err(); + + assert!(error.contains("Failed to resolve server file browser root")); +} + +#[test] +fn validates_existing_files_inside_configured_roots() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + fs::write(root.path().join("query.sql"), b"select 1").unwrap(); + fs::write(outside.path().join("secret.sql"), b"").unwrap(); + fs::create_dir(root.path().join("folder")).unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let file = root.path().join("query.sql"); + assert_eq!( + validate_existing_file(&roots, file.to_str().unwrap()).unwrap(), + roots[0].join("query.sql") + ); + let escaped = root + .path() + .join("folder/../../") + .join(outside.path().file_name().unwrap()); + assert!(validate_existing_file(&roots, escaped.join("secret.sql").to_str().unwrap()).is_err()); + assert!(validate_existing_file(&roots, root.path().join("folder").to_str().unwrap()).is_err()); + assert!(validate_existing_file(&[], file.to_str().unwrap()).is_err()); +} + +#[test] +fn validates_new_directories_inside_configured_roots() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + let nested = root.path().join("sync/tabularis"); + assert_eq!( + validate_directory_target(&roots, nested.to_str().unwrap()).unwrap(), + roots[0].join("sync/tabularis") + ); + assert!( + validate_directory_target(&roots, outside.path().join("new").to_str().unwrap()).is_err() + ); + assert!(validate_directory_target(&roots, "relative/dir").is_err()); + assert!(validate_directory_target( + &roots, + root.path().join("missing/../../escape").to_str().unwrap() + ) + .is_err()); +} + +#[cfg(unix)] +#[test] +fn rejects_new_directories_below_dangling_links_outside_roots() { + let root = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let link = root.path().join("sync"); + std::os::unix::fs::symlink(outside.path().join("missing"), &link).unwrap(); + let roots = canonicalize_roots(&[root.path().to_path_buf()]).unwrap(); + + assert!(validate_directory_target(&roots, link.join("tabularis").to_str().unwrap()).is_err()); +} diff --git a/src-tauri/src/transport/web/static_assets.rs b/src-tauri/src/transport/web/static_assets.rs new file mode 100644 index 000000000..de973c13c --- /dev/null +++ b/src-tauri/src/transport/web/static_assets.rs @@ -0,0 +1,62 @@ +use std::path::{Path, PathBuf}; + +const DEVELOPMENT_WEB_ROOT: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../packages/web-ui/dist"); + +pub fn resolve_web_root(explicit_root: Option<&Path>) -> Result { + if let Some(root) = explicit_root { + return validate_web_root(root).map_err(|error| { + format!("Invalid Web UI asset directory {}: {error}", root.display()) + }); + } + + let executable = std::env::current_exe() + .map_err(|error| format!("Failed to locate the Tabularis executable: {error}"))?; + let candidates = candidate_web_roots(&executable, Path::new(DEVELOPMENT_WEB_ROOT)); + + for candidate in &candidates { + if let Ok(root) = validate_web_root(candidate) { + return Ok(root); + } + } + + let searched = candidates + .iter() + .map(|candidate| candidate.display().to_string()) + .collect::>() + .join(", "); + Err(format!( + "Web UI assets were not found. Expected index.html in one of: {searched}. Build @tabularis/web-ui or pass --web-root." + )) +} + +pub(crate) fn candidate_web_roots(executable: &Path, development_root: &Path) -> Vec { + let mut candidates = Vec::new(); + + if let Some(executable_dir) = executable.parent() { + // Windows portable and installed bundles keep resources beside the binary. + candidates.push(executable_dir.join("web-ui")); + + if let Some(installation_root) = executable_dir.parent() { + // macOS: Tabularis.app/Contents/MacOS -> Contents/Resources/web-ui. + candidates.push(installation_root.join("Resources/web-ui")); + // Linux packages: /usr/bin -> /usr/lib/tabularis/web-ui. + candidates.push(installation_root.join("lib/tabularis/web-ui")); + } + } + + candidates.push(development_root.to_path_buf()); + candidates.dedup(); + candidates +} + +fn validate_web_root(root: &Path) -> Result { + if !root.is_dir() { + return Err("the path is not a directory".to_string()); + } + if !root.join("index.html").is_file() { + return Err("index.html is missing".to_string()); + } + + root.canonicalize() + .map_err(|error| format!("failed to resolve the directory: {error}")) +} diff --git a/src-tauri/src/transport/web/tests.rs b/src-tauri/src/transport/web/tests.rs new file mode 100644 index 000000000..c6830e51d --- /dev/null +++ b/src-tauri/src/transport/web/tests.rs @@ -0,0 +1,3207 @@ +use super::auth::{ + AuthenticationError, LocalSessionSecurity, LocalSessionSecurityConfig, LoginRateLimitConfig, + RemoteAuthentication, RemoteSessionSecurityConfig, +}; +use super::contract::{SessionNegotiation, WEB_API_VERSION}; +use super::events::{EventBusConfig, WebEventBus}; +use super::rpc::{RPC_CANCELLATION_HEADER_NAME, RPC_DEADLINE_HEADER_NAME}; +use super::{server, static_assets}; +use crate::application::{ApplicationApi, AuthorizationLevel, RuntimeApplicationApi}; +use crate::runtime::{ + paths::FixedRuntimePaths, secrets::RuntimeSecrets, state::ApplicationState, RuntimeContext, +}; +use futures::{SinkExt, StreamExt}; +use reqwest::header::{COOKIE, HOST, LOCATION, ORIGIN, SET_COOKIE}; +use serde_json::Value; +use std::collections::HashMap; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::net::TcpListener; +use tokio::sync::oneshot; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::{Error as WebSocketError, Message as WebSocketMessage}; + +const CSRF_HEADER: &str = "x-tabularis-csrf"; +const REQUEST_ID_HEADER: &str = "x-request-id"; + +#[derive(Default)] +struct TestRuntimeSecrets { + values: Mutex>, +} + +impl RuntimeSecrets for TestRuntimeSecrets { + fn get(&self, account: &str) -> Result, String> { + Ok(self.values.lock().unwrap().get(account).cloned()) + } + + fn set(&self, account: &str, secret: &str) -> Result<(), String> { + self.values + .lock() + .unwrap() + .insert(account.to_string(), secret.to_string()); + Ok(()) + } + + fn delete(&self, account: &str) -> Result<(), String> { + self.values.lock().unwrap().remove(account); + Ok(()) + } +} + +#[test] +fn enforces_remote_credentials_origins_rate_limits_and_capability_policy() { + let config = RemoteSessionSecurityConfig { + trusted_proxies: Vec::new(), + public_origin: "https://tabularis.example.com".to_string(), + allowed_origins: vec![ + "https://tabularis.example.com".to_string(), + "https://admin.example.com".to_string(), + ], + session_ttl: Duration::from_secs(60), + max_body_bytes: 1_048_576, + authorization: AuthorizationLevel::Database, + rate_limit: LoginRateLimitConfig { + max_failures: 2, + window: Duration::from_secs(60), + lockout: Duration::from_secs(60), + }, + }; + let mut insecure_config = config.clone(); + insecure_config.public_origin = "http://tabularis.example.com".to_string(); + insecure_config.allowed_origins = vec![insecure_config.public_origin.clone()]; + assert!(LocalSessionSecurity::new_remote( + insecure_config, + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap_err() + .contains("HTTPS")); + + let mut loopback_config = config.clone(); + loopback_config.public_origin = "http://localhost:8080".to_string(); + loopback_config.allowed_origins = vec![ + loopback_config.public_origin.clone(), + "http://127.0.0.1:8080".to_string(), + ]; + let loopback_security = LocalSessionSecurity::new_remote( + loopback_config, + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap(); + assert!(loopback_security.is_remote()); + assert!(!loopback_security.secure_cookie()); + assert!(loopback_security.host_allowed("localhost:8080")); + assert!(loopback_security.origin_allowed("http://127.0.0.1:8080")); + assert!(!loopback_security.origin_allowed("http://tabularis.example.com")); + + let password_security = LocalSessionSecurity::new_remote( + config.clone(), + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap(); + + assert!(password_security.is_remote()); + assert!(password_security.secure_cookie()); + assert!(password_security.origin_allowed("https://admin.example.com")); + assert!(password_security.host_allowed("tabularis.example.com")); + assert!(!password_security.origin_allowed("https://attacker.invalid")); + let attacker: std::net::IpAddr = "203.0.113.7".parse().unwrap(); + let user: std::net::IpAddr = "198.51.100.20".parse().unwrap(); + assert!(matches!( + password_security.authenticate_password("wrong", attacker), + Err(AuthenticationError::InvalidCredentials) + )); + assert!(matches!( + password_security.authenticate_password("still-wrong", attacker), + Err(AuthenticationError::InvalidCredentials) + )); + assert!(matches!( + password_security.authenticate_password("correct horse battery staple", attacker), + Err(AuthenticationError::RateLimited) + )); + // The lockout is per client: another client still logs in. + assert!(password_security + .authenticate_password("correct horse battery staple", user) + .is_ok()); + + let password_security = LocalSessionSecurity::new_remote( + config.clone(), + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap(); + let issued = password_security + .authenticate_password("correct horse battery staple", user) + .unwrap(); + let session = password_security + .authenticate(&issued.cookie_value) + .unwrap(); + assert!(session.is_remote()); + assert_eq!(session.authorization(), AuthorizationLevel::Database); + + let proxy_security = LocalSessionSecurity::new_remote( + config, + RemoteAuthentication::proxy("a-proxy-shared-secret-with-32-bytes"), + ) + .unwrap(); + // Wrong proxy secrets must not lock out the proxy's legitimate users. + for _ in 0..3 { + assert!(matches!( + proxy_security.authenticate_proxy("wrong", "alice@example.com"), + Err(AuthenticationError::InvalidCredentials) + )); + } + let issued = proxy_security + .authenticate_proxy("a-proxy-shared-secret-with-32-bytes", "alice@example.com") + .unwrap(); + assert!(proxy_security.authenticate(&issued.cookie_value).is_some()); +} + +#[test] +fn bounds_the_session_store_without_displacing_live_sessions() { + let proxy_security = LocalSessionSecurity::new_remote( + RemoteSessionSecurityConfig { + trusted_proxies: Vec::new(), + public_origin: "https://tabularis.example.com".to_string(), + allowed_origins: vec!["https://tabularis.example.com".to_string()], + session_ttl: Duration::from_secs(60), + max_body_bytes: 1_048_576, + authorization: AuthorizationLevel::Database, + rate_limit: LoginRateLimitConfig::default(), + }, + RemoteAuthentication::proxy("a-proxy-shared-secret-with-32-bytes"), + ) + .unwrap(); + let secret = "a-proxy-shared-secret-with-32-bytes"; + let oldest = proxy_security.authenticate_proxy(secret, "alice").unwrap(); + for _ in 1..super::auth::MAX_SESSIONS { + proxy_security.authenticate_proxy(secret, "alice").unwrap(); + } + assert!(proxy_security.authenticate(&oldest.cookie_value).is_some()); + + assert!(matches!( + proxy_security.authenticate_proxy(secret, "alice"), + Err(AuthenticationError::SessionLimitReached) + )); + assert!(proxy_security.authenticate(&oldest.cookie_value).is_some()); + assert!(proxy_security.take_expired_sessions().is_empty()); + let session = proxy_security.authenticate(&oldest.cookie_value).unwrap(); + proxy_security.logout(&session); + assert!(proxy_security.authenticate_proxy(secret, "alice").is_ok()); +} + +#[test] +fn advertises_mcp_host_configuration_only_for_loopback_web_origins() { + for origin in [ + "http://127.0.0.1:8080", + "http://[::1]:8080", + "http://localhost:8080", + ] { + assert!(server::mcp_host_configuration_enabled(origin), "{origin}"); + } + for origin in ["http://0.0.0.0:8080", "http://192.0.2.10:8080"] { + assert!(!server::mcp_host_configuration_enabled(origin), "{origin}"); + } + + let local = SessionNegotiation::authenticated("csrf".to_string(), true); + let remote = SessionNegotiation::authenticated("csrf".to_string(), false); + assert!(local.capabilities.mcp_host_configuration); + assert!(!remote.capabilities.mcp_host_configuration); +} + +async fn rpc_data( + client: &reqwest::Client, + base_url: &str, + cookie: &str, + csrf_token: &str, + command: &str, + payload: serde_json::Value, +) -> serde_json::Value { + let response = client + .post(format!("{base_url}/api/v1/rpc/{command}")) + .header(COOKIE, cookie) + .header(ORIGIN, base_url) + .header(CSRF_HEADER, csrf_token) + .json(&payload) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK, "{command}"); + response.json::().await.unwrap()["data"].clone() +} + +fn test_application(root: &Path) -> Arc { + test_application_with_state(root, Arc::new(ApplicationState::default())) +} + +fn test_application_with_state( + root: &Path, + state: Arc, +) -> Arc { + let context = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + root.to_path_buf(), + root.to_path_buf(), + )), + Arc::new(crate::runtime::events::NoopRuntimeEvents), + Arc::new(TestRuntimeSecrets::default()), + ); + Arc::new(RuntimeApplicationApi::new(context, state)) +} + +#[tokio::test] +async fn requires_a_single_use_bootstrap_and_authenticated_session() { + let temp = tempfile::tempdir().unwrap(); + let assets = temp.path(); + std::fs::create_dir_all(assets.join("assets")).unwrap(); + std::fs::write(assets.join("index.html"), "
Tabularis Web
").unwrap(); + std::fs::write(assets.join("assets/app.js"), "window.tabularis = true;").unwrap(); + let plugin_dir = assets.join("plugins/example-plugin"); + std::fs::create_dir_all(plugin_dir.join("ui/dist")).unwrap(); + std::fs::write( + plugin_dir.join(".tabularium"), + r#"{ + "id": "example-plugin", + "name": "Example Plugin", + "version": "1.0.0", + "description": "Web asset fixture", + "ui_extensions": [{ + "slot": "data-grid.toolbar.actions", + "module": "ui/dist/index.js", + "api_version": "0.1.1" + }] +}"#, + ) + .unwrap(); + std::fs::write( + plugin_dir.join("ui/dist/index.js"), + "window.pluginLoaded = true;", + ) + .unwrap(); + std::fs::write(plugin_dir.join("ui/dist/private.txt"), "not public").unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, bootstrap_token) = + LocalSessionSecurity::new(base_url.clone(), LocalSessionSecurityConfig::default()).unwrap(); + let bootstrap_url = format!( + "{base_url}/api/v1/auth/bootstrap?token={}", + bootstrap_token.expose() + ); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + assets.to_path_buf(), + security, + test_application(assets), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + + let health = client + .get(format!("{base_url}/healthz")) + .send() + .await + .unwrap(); + assert_eq!(health.status(), reqwest::StatusCode::OK); + assert_eq!(health.text().await.unwrap(), "ok"); + + let unauthorized = client + .get(format!("{base_url}/api/v1/session")) + .send() + .await + .unwrap(); + assert_eq!(unauthorized.status(), reqwest::StatusCode::UNAUTHORIZED); + let unauthorized_plugin_asset = client + .get(format!( + "{base_url}/api/v1/assets/plugins/example-plugin/ui/dist/index.js" + )) + .send() + .await + .unwrap(); + assert_eq!( + unauthorized_plugin_asset.status(), + reqwest::StatusCode::UNAUTHORIZED + ); + assert!(uuid::Uuid::parse_str( + unauthorized + .headers() + .get(REQUEST_ID_HEADER) + .unwrap() + .to_str() + .unwrap() + ) + .is_ok()); + + let invalid_bootstrap = client + .get(format!("{base_url}/api/v1/auth/bootstrap?token=invalid")) + .send() + .await + .unwrap(); + assert_eq!( + invalid_bootstrap.status(), + reqwest::StatusCode::UNAUTHORIZED + ); + + let cross_origin_bootstrap = client + .get(&bootstrap_url) + .header(ORIGIN, "https://attacker.invalid") + .send() + .await + .unwrap(); + assert_eq!( + cross_origin_bootstrap.status(), + reqwest::StatusCode::FORBIDDEN + ); + + let bootstrap = client.get(&bootstrap_url).send().await.unwrap(); + assert_eq!(bootstrap.status(), reqwest::StatusCode::SEE_OTHER); + assert_eq!(bootstrap.headers().get(LOCATION).unwrap(), "/"); + assert_eq!( + bootstrap.headers().get("referrer-policy").unwrap(), + "no-referrer" + ); + let set_cookie = bootstrap + .headers() + .get(SET_COOKIE) + .unwrap() + .to_str() + .unwrap(); + assert!(set_cookie.contains("HttpOnly")); + assert!(set_cookie.contains("SameSite=Strict")); + assert!(set_cookie.contains("Path=/")); + let cookie = set_cookie.split(';').next().unwrap().to_string(); + + let replay = client.get(&bootstrap_url).send().await.unwrap(); + assert_eq!(replay.status(), reqwest::StatusCode::UNAUTHORIZED); + + let session = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(session.status(), reqwest::StatusCode::OK); + let session: SessionNegotiation = session.json().await.unwrap(); + assert_eq!(session.api_version, WEB_API_VERSION); + assert_eq!(session.server_version, env!("CARGO_PKG_VERSION")); + let session_json = serde_json::to_value(&session).unwrap(); + assert_eq!(session_json["capabilities"]["nativeUpdater"], false); + assert!(session_json["serverBuild"]["target"] + .as_str() + .is_some_and(|target| !target.is_empty())); + assert!(session_json["serverBuild"]["profile"] + .as_str() + .is_some_and(|profile| !profile.is_empty())); + assert!(session.authenticated); + assert!(!session.csrf_token.is_empty()); + assert!(!session.access.remote); + assert_eq!(session.access.authorization_level, "local-admin"); + assert!(session.access.high_risk_capabilities); + assert!(session.capabilities.rpc); + assert!(session.capabilities.events); + assert!(session.capabilities.uploads); + assert!(session.capabilities.downloads); + assert!(session.capabilities.plugin_assets); + assert_eq!( + session.query_response_policy.max_rows_per_page, + crate::application::queries::WEB_MAX_ROWS_PER_PAGE + ); + assert_eq!( + session.query_response_policy.max_response_bytes, + crate::application::queries::WEB_MAX_RESPONSE_BYTES + ); + assert!(!session.query_response_policy.streaming); + + let index = client + .get(&base_url) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(index.status(), reqwest::StatusCode::OK); + assert_eq!(index.headers()["x-content-type-options"], "nosniff"); + assert_eq!( + index.headers()["content-security-policy"], + "base-uri 'self'; object-src 'none'; frame-ancestors 'none'" + ); + assert_eq!(index.text().await.unwrap(), "
Tabularis Web
"); + + let asset = client + .get(format!("{base_url}/assets/app.js")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(asset.status(), reqwest::StatusCode::OK); + assert_eq!(asset.text().await.unwrap(), "window.tabularis = true;"); + + let plugin_asset = client + .get(format!( + "{base_url}/api/v1/assets/plugins/example-plugin/ui/dist/index.js" + )) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(plugin_asset.status(), reqwest::StatusCode::OK); + assert_eq!( + plugin_asset.headers().get("content-type").unwrap(), + "text/javascript; charset=utf-8" + ); + assert_eq!( + plugin_asset.headers().get("content-security-policy").unwrap(), + "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'; sandbox" + ); + assert_eq!( + plugin_asset + .headers() + .get("cross-origin-resource-policy") + .unwrap(), + "same-origin" + ); + assert_eq!( + plugin_asset.text().await.unwrap(), + "window.pluginLoaded = true;" + ); + + let undeclared_plugin_asset = client + .get(format!( + "{base_url}/api/v1/assets/plugins/example-plugin/ui/dist/private.txt" + )) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!( + undeclared_plugin_asset.status(), + reqwest::StatusCode::NOT_FOUND + ); + + let spa_route = client + .get(format!("{base_url}/connections/example")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(spa_route.status(), reqwest::StatusCode::OK); + assert_eq!( + spa_route.text().await.unwrap(), + "
Tabularis Web
" + ); + + let cross_origin = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, &cookie) + .header(ORIGIN, "https://attacker.invalid") + .send() + .await + .unwrap(); + assert_eq!(cross_origin.status(), reqwest::StatusCode::FORBIDDEN); + + let bad_host = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, &cookie) + .header(HOST, "attacker.invalid") + .send() + .await + .unwrap(); + assert_eq!(bad_host.status(), reqwest::StatusCode::FORBIDDEN); + + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_ai_activity", + Value::Null, + ) + .await, + serde_json::json!([]) + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_ai_sessions", + Value::Null, + ) + .await, + serde_json::json!([]) + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "list_pending_approvals", + Value::Null, + ) + .await, + serde_json::json!([]) + ); + + let missing_csrf = client + .post(format!("{base_url}/api/v1/logout")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .send() + .await + .unwrap(); + assert_eq!(missing_csrf.status(), reqwest::StatusCode::FORBIDDEN); + + let oversized = client + .post(format!("{base_url}/api/v1/not-implemented")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header(reqwest::header::CONTENT_LENGTH, 1_048_577) + .body("x") + .send() + .await + .unwrap(); + assert_eq!(oversized.status(), reqwest::StatusCode::PAYLOAD_TOO_LARGE); + + let logout = client + .post(format!("{base_url}/api/v1/logout")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .send() + .await + .unwrap(); + assert_eq!(logout.status(), reqwest::StatusCode::NO_CONTENT); + assert!(logout + .headers() + .get(SET_COOKIE) + .unwrap() + .to_str() + .unwrap() + .contains("Max-Age=0")); + + let logged_out = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, cookie) + .send() + .await + .unwrap(); + assert_eq!(logged_out.status(), reqwest::StatusCode::UNAUTHORIZED); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn rejects_non_loopback_binding_without_explicit_remote_authentication() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let error = server::run(server::WebServerOptions { + trusted_proxies: Vec::new(), + host: "0.0.0.0".to_string(), + port: 0, + web_root: temp.path().to_path_buf(), + data_dir: temp.path().to_path_buf(), + plugins_dir: temp.path().join("plugins"), + open_browser: false, + auth: None, + public_url: None, + allowed_origins: Vec::new(), + allow_high_risk: false, + server_file_browser_roots: Vec::new(), + application: test_application(temp.path()), + events: WebEventBus::default(), + }) + .await + .unwrap_err(); + + assert!(error.contains("Non-loopback")); +} + +#[tokio::test] +async fn authenticates_remote_password_and_proxy_requests_with_auditing() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let log_buffer = crate::runtime::bootstrap::initialize_logging(false); + let public_origin = "https://tabularis.example.com"; + let remote_config = RemoteSessionSecurityConfig { + trusted_proxies: Vec::new(), + public_origin: public_origin.to_string(), + allowed_origins: vec![public_origin.to_string()], + session_ttl: Duration::from_secs(60), + max_body_bytes: 1_048_576, + authorization: AuthorizationLevel::Database, + rate_limit: LoginRateLimitConfig::default(), + }; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let security = LocalSessionSecurity::new_remote( + remote_config.clone(), + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application(temp.path()), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + + let login_page = client + .get(format!("{base_url}/login")) + .header(HOST, "tabularis.example.com") + .send() + .await + .unwrap(); + assert_eq!(login_page.status(), reqwest::StatusCode::OK); + assert!(login_page.text().await.unwrap().contains("Sign in")); + + let login = client + .post(format!("{base_url}/api/v1/auth/login")) + .header(HOST, "tabularis.example.com") + .header(ORIGIN, public_origin) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body("password=correct%20horse%20battery%20staple") + .send() + .await + .unwrap(); + assert_eq!(login.status(), reqwest::StatusCode::SEE_OTHER); + let set_cookie = login.headers().get(SET_COOKIE).unwrap().to_str().unwrap(); + assert!(set_cookie.contains("Secure")); + let cookie = set_cookie.split(';').next().unwrap().to_string(); + + for _ in 0..5 { + let invalid_login = client + .post(format!("{base_url}/api/v1/auth/login")) + .header(HOST, "tabularis.example.com") + .header(ORIGIN, public_origin) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body("password=wrong") + .send() + .await + .unwrap(); + assert_eq!(invalid_login.status(), reqwest::StatusCode::UNAUTHORIZED); + } + let rate_limited = client + .post(format!("{base_url}/api/v1/auth/login")) + .header(HOST, "tabularis.example.com") + .header(ORIGIN, public_origin) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body("password=wrong") + .send() + .await + .unwrap(); + assert_eq!( + rate_limited.status(), + reqwest::StatusCode::TOO_MANY_REQUESTS + ); + assert_eq!(rate_limited.headers().get("retry-after").unwrap(), "300"); + + let session = client + .get(format!("{base_url}/api/v1/session")) + .header(HOST, "tabularis.example.com") + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(session.status(), reqwest::StatusCode::OK); + let session: SessionNegotiation = session.json().await.unwrap(); + assert!(session.access.remote); + assert_eq!(session.access.authorization_level, "database"); + assert!(!session.access.high_risk_capabilities); + + let blocked = client + .post(format!("{base_url}/api/v1/rpc/clear_logs")) + .header(HOST, "tabularis.example.com") + .header(COOKIE, &cookie) + .header(ORIGIN, public_origin) + .header(CSRF_HEADER, &session.csrf_token) + .json(&Value::Null) + .send() + .await + .unwrap(); + assert_eq!(blocked.status(), reqwest::StatusCode::FORBIDDEN); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let security = LocalSessionSecurity::new_remote( + remote_config, + RemoteAuthentication::proxy("a-proxy-shared-secret-with-32-bytes"), + ) + .unwrap(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application(temp.path()), + async move { + let _ = shutdown_rx.await; + }, + )); + + let proxy_session = client + .get(format!("{base_url}/api/v1/session")) + .header(HOST, "tabularis.example.com") + .header( + "x-tabularis-proxy-secret", + "a-proxy-shared-secret-with-32-bytes", + ) + .header("x-tabularis-user", "alice@example.com") + .send() + .await + .unwrap(); + assert_eq!(proxy_session.status(), reqwest::StatusCode::OK); + assert!(proxy_session + .headers() + .get(SET_COOKIE) + .unwrap() + .to_str() + .unwrap() + .contains("Secure")); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); + + let logs = log_buffer.lock().unwrap().get_entries(None, None); + assert!(logs.iter().any(|entry| { + entry.target.as_deref() == Some("tabularis::web_audit") + && entry.message.contains("request_id=") + && entry.message.contains("session_id=") + })); + assert!(!logs + .iter() + .any(|entry| entry.message.contains("correct horse battery staple"))); +} + +#[tokio::test] +async fn expires_bootstrap_tokens_and_sessions() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, expired_bootstrap) = LocalSessionSecurity::new( + base_url.clone(), + LocalSessionSecurityConfig { + bootstrap_ttl: Duration::from_millis(20), + session_ttl: Duration::from_secs(1), + max_body_bytes: 1_048_576, + }, + ) + .unwrap(); + tokio::time::sleep(Duration::from_millis(30)).await; + assert!(security + .consume_bootstrap(expired_bootstrap.expose()) + .is_none()); + + let (security, bootstrap_token) = LocalSessionSecurity::new( + base_url.clone(), + LocalSessionSecurityConfig { + bootstrap_ttl: Duration::from_secs(1), + session_ttl: Duration::from_millis(20), + max_body_bytes: 1_048_576, + }, + ) + .unwrap(); + let bootstrap_url = format!( + "{base_url}/api/v1/auth/bootstrap?token={}", + bootstrap_token.expose() + ); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application(temp.path()), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let bootstrap = client.get(bootstrap_url).send().await.unwrap(); + let cookie = bootstrap + .headers() + .get(SET_COOKIE) + .unwrap() + .to_str() + .unwrap() + .split(';') + .next() + .unwrap() + .to_string(); + + tokio::time::sleep(Duration::from_millis(30)).await; + let expired_session = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, cookie) + .send() + .await + .unwrap(); + assert_eq!(expired_session.status(), reqwest::StatusCode::UNAUTHORIZED); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + +#[test] +fn redacts_generated_security_tokens() { + let (security, bootstrap_token) = LocalSessionSecurity::new( + "http://127.0.0.1:8080".to_string(), + LocalSessionSecurityConfig::default(), + ) + .unwrap(); + let token = bootstrap_token.expose().to_string(); + + assert!(token.len() >= 43); + assert!(!format!("{bootstrap_token:?}").contains(&token)); + assert!(!format!("{security:?}").contains(&token)); +} + +#[test] +fn resolves_explicit_and_packaged_web_roots() { + let temp = tempfile::tempdir().unwrap(); + let explicit = temp.path().join("explicit"); + std::fs::create_dir_all(&explicit).unwrap(); + std::fs::write(explicit.join("index.html"), "Tabularis").unwrap(); + + assert_eq!( + static_assets::resolve_web_root(Some(&explicit)).unwrap(), + explicit.canonicalize().unwrap() + ); + + let candidates = static_assets::candidate_web_roots( + Path::new("/opt/Tabularis.app/Contents/MacOS/tabularis"), + Path::new("/workspace/packages/web-ui/dist"), + ); + assert!(candidates + .contains(&Path::new("/opt/Tabularis.app/Contents/Resources/web-ui").to_path_buf())); + assert!(candidates.contains(&Path::new("/workspace/packages/web-ui/dist").to_path_buf())); + + let linux_candidates = static_assets::candidate_web_roots( + Path::new("/usr/bin/tabularis"), + Path::new("/workspace/packages/web-ui/dist"), + ); + assert!(linux_candidates.contains(&Path::new("/usr/lib/tabularis/web-ui").to_path_buf())); + + let portable_candidates = static_assets::candidate_web_roots( + Path::new("/portable/tabularis.exe"), + Path::new("/workspace/packages/web-ui/dist"), + ); + assert!(portable_candidates.contains(&Path::new("/portable/web-ui").to_path_buf())); +} + +#[test] +fn rejects_a_web_root_without_an_index() { + let temp = tempfile::tempdir().unwrap(); + let error = static_assets::resolve_web_root(Some(temp.path())).unwrap_err(); + + assert!(error.contains("index.html")); +} + +#[tokio::test] +async fn streams_safe_session_owned_file_uploads() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "
Tabularis Web
").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, bootstrap_token) = + LocalSessionSecurity::new(base_url.clone(), LocalSessionSecurityConfig::default()).unwrap(); + let issued = security + .consume_bootstrap(bootstrap_token.expose()) + .unwrap(); + let session = security.authenticate(&issued.cookie_value).unwrap(); + let cookie = format!("tabularis_session={}", issued.cookie_value); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application(temp.path()), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::new(); + + let response = client + .post(format!("{base_url}/api/v1/uploads")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header("content-type", "text/csv; charset=utf-8") + .header("x-tabularis-file-name", "..%2Fquarterly%0Areport.csv") + .header("x-tabularis-purpose", "connection-import") + .body("region,total\nwest,42\n") + .send() + .await + .unwrap(); + + assert_eq!(response.status(), reqwest::StatusCode::CREATED); + let metadata = response.json::().await.unwrap(); + assert_eq!(metadata["fileName"], "quarterly_report.csv"); + assert_eq!(metadata["mimeType"], "text/csv"); + assert_eq!(metadata["size"], 21); + assert!(metadata["token"].as_str().unwrap().len() >= 36); + assert!(metadata["expiresAt"].as_str().unwrap().ends_with('Z')); + + let guessed = client + .get(format!( + "{base_url}/api/v1/downloads/00000000-0000-4000-8000-000000000000" + )) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(guessed.status(), reqwest::StatusCode::NOT_FOUND); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn executes_representative_commands_over_versioned_rpc() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let log_buffer = crate::runtime::bootstrap::initialize_logging(false); + crate::application::operations::clear_logs(&log_buffer).unwrap(); + log_buffer.lock().unwrap().push(crate::logger::LogEntry { + timestamp: "2026-08-22 09:00:00.000".to_string(), + level: "ERROR".to_string(), + message: "Authenticated operational RPC fixture".to_string(), + target: Some("web-contract".to_string()), + }); + + crate::drivers::registry::register_driver(crate::drivers::sqlite::SqliteDriver::new()).await; + let sqlite_path = temp.path().join("metadata.sqlite"); + crate::sqlite_database::initialize_sqlite_file(&sqlite_path) + .await + .unwrap(); + let sqlite_params = crate::models::ConnectionParams { + driver: "sqlite".to_string(), + database: crate::models::DatabaseSelection::Single( + sqlite_path.to_string_lossy().into_owned(), + ), + ..Default::default() + }; + for statement in [ + "CREATE TABLE teams (id INTEGER PRIMARY KEY, name TEXT NOT NULL)", + "CREATE TABLE files (id INTEGER PRIMARY KEY, name TEXT NOT NULL, payload BLOB)", + "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, team_id INTEGER, name TEXT, FOREIGN KEY (team_id) REFERENCES teams(id))", + "CREATE INDEX idx_users_name ON users(name)", + "CREATE VIEW active_users AS SELECT id, name FROM users", + "CREATE TRIGGER users_name_required BEFORE INSERT ON users WHEN NEW.name IS NULL BEGIN SELECT RAISE(ABORT, 'name required'); END", + ] { + crate::drivers::sqlite::execute_query(&sqlite_params, statement, None, 1) + .await + .unwrap(); + } + crate::persistence::save_connections_file( + &crate::paths::resolve_connections_path(temp.path()), + &crate::models::ConnectionsFile { + connections: vec![crate::models::SavedConnection { + id: "metadata-fixture".to_string(), + name: "Metadata fixture".to_string(), + params: sqlite_params, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + }], + ..Default::default() + }, + ) + .unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, bootstrap_token) = + LocalSessionSecurity::new(base_url.clone(), LocalSessionSecurityConfig::default()).unwrap(); + let bootstrap_url = format!( + "{base_url}/api/v1/auth/bootstrap?token={}", + bootstrap_token.expose() + ); + let application_state = Arc::new(ApplicationState::default()); + let session_security = security.clone(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application_with_state(temp.path(), application_state.clone()), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let bootstrap = client.get(bootstrap_url).send().await.unwrap(); + let cookie = bootstrap + .headers() + .get(SET_COOKIE) + .unwrap() + .to_str() + .unwrap() + .split(';') + .next() + .unwrap() + .to_string(); + let session: SessionNegotiation = client + .get(format!("{base_url}/api/v1/session")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + + let logs = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_logs", + serde_json::json!({ + "request": {"limit": 100, "level_filter": "ERROR"} + }), + ) + .await; + assert!(logs + .as_array() + .unwrap() + .iter() + .any(|entry| { entry["message"] == "Authenticated operational RPC fixture" })); + let log_settings = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_log_settings", + Value::Null, + ) + .await; + assert_eq!(log_settings["enabled"], true); + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_process_list", + Value::Null, + ) + .await + .is_array()); + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_system_stats", + Value::Null, + ) + .await["process_count"] + .is_number()); + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_tabularis_children", + Value::Null, + ) + .await + .is_array()); + for (command, payload) in [ + ("set_log_max_size", serde_json::json!({"maxSize": 500})), + ("set_log_enabled", serde_json::json!({"enabled": false})), + ("set_log_enabled", serde_json::json!({"enabled": true})), + ("clear_logs", Value::Null), + ("set_log_max_size", serde_json::json!({"maxSize": 1000})), + ] { + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + command, + payload, + ) + .await + .is_null()); + } + + let query_export = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "export_query_to_file", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "SELECT 1 AS value UNION ALL SELECT 2", + "format": "csv", + "csvDelimiter": ";" + }), + ) + .await; + assert_eq!(query_export["kind"], "download"); + let query_export_response = client + .get(format!( + "{base_url}/api/v1/downloads/{}", + query_export["token"].as_str().unwrap() + )) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(query_export_response.status(), reqwest::StatusCode::OK); + assert_eq!(query_export_response.text().await.unwrap(), "value\n1\n2\n"); + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_config", + serde_json::json!({"config": {"language": "en", "formatterTabWidth": 4}}), + ) + .await; + let config = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_config", + serde_json::Value::Null, + ) + .await; + assert_eq!(config["language"], "en"); + assert_eq!(config["formatterTabWidth"], 4); + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_keybindings", + serde_json::json!({"keybindings": {"editor.run": {"key": "Enter"}}}), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_keybindings", + serde_json::Value::Null, + ) + .await["editor.run"]["key"], + "Enter" + ); + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_system_prompt", + serde_json::json!({"prompt": "Generate safe SQL"}), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_system_prompt", + serde_json::Value::Null, + ) + .await, + "Generate safe SQL" + ); + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_editor_preferences", + serde_json::json!({ + "connectionId": "metadata-fixture", + "preferences": { + "tabs": [{"id": "tab-1", "title": "Browser console"}], + "active_tab_id": "tab-1" + } + }), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "load_editor_preferences", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await["active_tab_id"], + "tab-1" + ); + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "set_last_open_connections", + serde_json::json!({"connectionIds": ["metadata-fixture"]}), + ) + .await; + let exported = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "export_connections_file", + serde_json::json!({"mode": "noSecrets"}), + ) + .await; + assert_eq!(exported["kind"], "download"); + let export_token = exported["token"].as_str().unwrap(); + let export_response = client + .get(format!("{base_url}/api/v1/downloads/{export_token}")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(export_response.status(), reqwest::StatusCode::OK); + let export_content = export_response.text().await.unwrap(); + assert!(export_content.contains("metadata-fixture")); + let exported_payload: Value = serde_json::from_str(&export_content).unwrap(); + assert!(exported_payload["connections"][0]["params"]["password"].is_null()); + assert!(exported_payload["connections"][0]["params"]["connection_uri"].is_null()); + + let upload = client + .post(format!("{base_url}/api/v1/uploads")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header("content-type", "application/json") + .header("x-tabularis-file-name", "connections.json") + .header("x-tabularis-purpose", "connection-import") + .body(export_content) + .send() + .await + .unwrap(); + assert_eq!(upload.status(), reqwest::StatusCode::CREATED); + let upload_token = upload.json::().await.unwrap()["token"] + .as_str() + .unwrap() + .to_string(); + let preview = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "preview_tabularis_import_file", + serde_json::json!({ + "file": {"kind": "upload", "token": upload_token} + }), + ) + .await; + assert_eq!(preview["kind"], "preview"); + assert_eq!( + preview["preview"]["items"][0]["status"]["kind"], + "duplicate" + ); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "apply_prepared_tabularis_import", + serde_json::json!({"resolutions": [{"index": 0, "action": "skip"}]}), + ) + .await; + + let dump = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "dump_database", + serde_json::json!({ + "connectionId": "metadata-fixture", + "options": {"structure": true, "data": true, "tables": ["teams"]} + }), + ) + .await; + assert_eq!(dump["kind"], "download"); + let dump_token = dump["token"].as_str().unwrap(); + let dump_response = client + .get(format!("{base_url}/api/v1/downloads/{dump_token}")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(dump_response.status(), reqwest::StatusCode::OK); + let dump_sql = dump_response.text().await.unwrap(); + assert!(dump_sql.contains("CREATE TABLE teams")); + assert!(!dump_sql.contains(temp.path().to_string_lossy().as_ref())); + + let database_import = client + .post(format!("{base_url}/api/v1/uploads")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header("content-type", "application/sql") + .header("x-tabularis-file-name", "database-import.sql") + .header("x-tabularis-purpose", "database-import") + .body( + "CREATE TABLE imported_transfer (id INTEGER PRIMARY KEY, name TEXT);\n\ + INSERT INTO imported_transfer (id, name) VALUES (1, 'Platform');\n", + ) + .send() + .await + .unwrap(); + assert_eq!(database_import.status(), reqwest::StatusCode::CREATED); + let database_import_token = database_import.json::().await.unwrap()["token"] + .as_str() + .unwrap() + .to_string(); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "import_database", + serde_json::json!({ + "connectionId": "metadata-fixture", + "uploadToken": database_import_token + }), + ) + .await; + let imported_rows = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "execute_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "SELECT name FROM imported_transfer WHERE id = 1", + "limit": 10, + "page": 1 + }), + ) + .await; + assert_eq!(imported_rows["rows"][0][0], "Platform"); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "execute_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "DROP TABLE imported_transfer", + "limit": 10, + "page": 1 + }), + ) + .await; + + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "set_last_active_connection", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_last_open_connections", + serde_json::Value::Null, + ) + .await, + serde_json::json!(["metadata-fixture"]) + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_last_active_connection", + serde_json::Value::Null, + ) + .await, + "metadata-fixture" + ); + assert!(!temp.path().join("preferences").exists()); + + let saved_query = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "name": "All users", + "sql": "SELECT * FROM users", + "database": "main" + }), + ) + .await; + let saved_query_id = saved_query["id"].as_str().unwrap(); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_saved_queries", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await[0]["sql"], + "SELECT * FROM users" + ); + let cross_connection_update = client + .post(format!("{base_url}/api/v1/rpc/update_saved_query")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "connectionId": "another-connection", + "id": saved_query_id, + "name": "Unsafe update", + "sql": "SELECT 2", + "database": null + })) + .send() + .await + .unwrap(); + assert_eq!( + cross_connection_update.status(), + reqwest::StatusCode::CONFLICT + ); + let folder = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "create_saved_query_folder", + serde_json::json!({"connectionId": "metadata-fixture", "name": "Reports"}), + ) + .await; + let folder_id = folder["id"].as_str().unwrap(); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "move_saved_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "id": saved_query_id, + "folderId": folder_id + }), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_saved_queries", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await[0]["folder_id"], + folder_id + ); + let cross_connection_rename = client + .post(format!("{base_url}/api/v1/rpc/rename_saved_query_folder")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "connectionId": "another-connection", + "id": folder_id, + "name": "Hijacked" + })) + .send() + .await + .unwrap(); + assert_ne!(cross_connection_rename.status(), reqwest::StatusCode::OK); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "move_saved_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "id": saved_query_id, + "folderId": null + }), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "delete_saved_query_folder", + serde_json::json!({"connectionId": "metadata-fixture", "id": folder_id}), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_saved_query_folders", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await, + serde_json::json!([]) + ); + let updated_query = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "update_saved_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "id": saved_query_id, + "name": "Named users", + "sql": "SELECT name FROM users", + "database": "main" + }), + ) + .await; + assert_eq!(updated_query["name"], "Named users"); + + let history_entry = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "add_query_history_entry", + serde_json::json!({ + "connectionId": "metadata-fixture", + "sql": "SELECT name FROM users", + "executedAt": "2026-08-22T00:00:00Z", + "executionTimeMs": 1.5, + "status": "success", + "rowsAffected": 0, + "error": null, + "database": "main" + }), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_query_history", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await["entries"][0]["id"], + history_entry["id"] + ); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "delete_query_history_entry", + serde_json::json!({ + "connectionId": "metadata-fixture", + "id": history_entry["id"] + }), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "clear_query_history", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "delete_saved_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "id": saved_query_id + }), + ) + .await; + + let notebook_content = serde_json::json!({ + "version": 2, + "title": "Web notebook", + "createdAt": "2026-08-22T00:00:00Z", + "cells": [{ + "type": "sql", + "content": "SELECT 1", + "chartConfig": { + "type": "bar", + "labelColumn": "value", + "valueColumns": ["value"] + } + }], + "stopOnError": true + }) + .to_string(); + let notebook_target = serde_json::json!({ + "connectionId": "metadata-fixture", + "notebookId": "notebook-web-1" + }); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "create_notebook", + serde_json::json!({ + "connectionId": "metadata-fixture", + "notebookId": "notebook-web-1", + "content": notebook_content + }), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "load_notebook", + notebook_target.clone(), + ) + .await, + notebook_content + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "load_notebook", + serde_json::json!({ + "connectionId": "another-connection", + "notebookId": "notebook-web-1" + }), + ) + .await, + Value::Null + ); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "save_notebook", + serde_json::json!({ + "connectionId": "metadata-fixture", + "notebookId": "notebook-web-1", + "content": notebook_content + }), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "rename_notebook", + serde_json::json!({ + "connectionId": "metadata-fixture", + "notebookId": "notebook-web-1", + "title": "Renamed web notebook" + }), + ) + .await; + let notebooks = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "list_notebooks", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await; + assert_eq!(notebooks[0]["id"], "notebook-web-1"); + assert_eq!(notebooks[0]["title"], "Renamed web notebook"); + assert_eq!(notebooks[0]["createdAt"], "2026-08-22T00:00:00Z"); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "delete_notebook", + notebook_target.clone(), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "load_notebook", + notebook_target, + ) + .await, + Value::Null + ); + + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_tables", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await, + serde_json::json!([{"name": "files"}, {"name": "teams"}, {"name": "users"}]) + ); + let columns = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_columns", + serde_json::json!({"connectionId": "metadata-fixture", "tableName": "users"}), + ) + .await; + assert_eq!(columns.as_array().unwrap().len(), 3); + assert_eq!(columns[0]["name"], "id"); + assert_eq!(columns[0]["is_pk"], true); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_foreign_keys", + serde_json::json!({"connectionId": "metadata-fixture", "tableName": "users"}), + ) + .await[0]["ref_table"], + "teams" + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_indexes", + serde_json::json!({"connectionId": "metadata-fixture", "tableName": "users"}), + ) + .await[0]["name"], + "idx_users_name" + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_views", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await[0]["name"], + "active_users" + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_triggers", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await[0]["name"], + "users_name_required" + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_schema_snapshot", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await + .as_array() + .unwrap() + .len(), + 3 + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "set_selected_schemas", + serde_json::json!({"connectionId": "metadata-fixture", "schemas": ["main"]}), + ) + .await, + serde_json::Value::Null + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_selected_schemas", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await, + serde_json::json!(["main"]) + ); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "set_schema_preference", + serde_json::json!({"connectionId": "metadata-fixture", "schema": "main"}), + ) + .await; + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_schema_preference", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await, + "main" + ); + + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_view_definition", + serde_json::json!({"connectionId": "metadata-fixture", "viewName": "active_users"}), + ) + .await + .as_str() + .unwrap() + .contains("SELECT id, name FROM users")); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "create_view", + serde_json::json!({ + "connectionId": "metadata-fixture", + "viewName": "web_users", + "definition": "SELECT id FROM users" + }), + ) + .await, + serde_json::Value::Null + ); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "alter_view", + serde_json::json!({ + "connectionId": "metadata-fixture", + "viewName": "web_users", + "definition": "SELECT id, name FROM users" + }), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "drop_view", + serde_json::json!({"connectionId": "metadata-fixture", "viewName": "web_users"}), + ) + .await; + assert!(rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_trigger_definition", + serde_json::json!({ + "connectionId": "metadata-fixture", + "triggerName": "users_name_required", + "tableName": "users" + }), + ) + .await + .as_str() + .unwrap() + .contains("CREATE TRIGGER")); + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "create_trigger", + serde_json::json!({ + "connectionId": "metadata-fixture", + "triggerSql": "CREATE TRIGGER web_users_audit AFTER UPDATE ON users BEGIN SELECT 1; END" + }), + ) + .await; + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "drop_trigger", + serde_json::json!({ + "connectionId": "metadata-fixture", + "triggerName": "web_users_audit", + "tableName": "users" + }), + ) + .await; + let create_index_sql = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_create_index_sql", + serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "users", + "indexName": "idx_users_team", + "columns": ["team_id"], + "isUnique": false + }), + ) + .await; + assert!(create_index_sql[0] + .as_str() + .unwrap() + .contains("idx_users_team")); + + let inserted = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "execute_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "INSERT INTO teams (name) VALUES ('core')", + "limit": 100, + "page": 1 + }), + ) + .await; + assert_eq!(inserted["affected_rows"], 1); + + let queried = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "execute_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "SELECT id, name FROM teams ORDER BY id", + "limit": 100, + "page": 1 + }), + ) + .await; + assert_eq!(queried["rows"], serde_json::json!([[1, "core"]])); + assert_eq!(queried["pagination"]["page_size"], 100); + + let batch = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "execute_query_batch", + serde_json::json!({ + "connectionId": "metadata-fixture", + "queries": [ + "INSERT INTO teams (name) VALUES ('batch')", + "SELECT COUNT(*) AS total FROM teams" + ], + "limit": 100, + "page": 1, + "batchId": "http-batch-1" + }), + ) + .await; + assert_eq!(batch.as_array().unwrap().len(), 2); + assert!(batch[0]["result"].is_object()); + assert_eq!(batch[1]["result"]["rows"], serde_json::json!([[2]])); + + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "count_query", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "SELECT * FROM teams" + }), + ) + .await, + serde_json::json!(2) + ); + assert!(!rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "get_server_now", + serde_json::json!({"connectionId": "metadata-fixture"}), + ) + .await + .as_str() + .unwrap() + .is_empty()); + let explain = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "explain_query_plan", + serde_json::json!({ + "connectionId": "metadata-fixture", + "query": "SELECT * FROM teams", + "analyze": false + }), + ) + .await; + assert_eq!(explain["kind"], "raw"); + assert_eq!(explain["raw"]["engine"], "sqlite"); + + let forged_path = client + .post(format!("{base_url}/api/v1/rpc/insert_record")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "files", + "data": { + "id": 99, + "name": "forged", + "payload": "BLOB_FILE_REF:4:text/plain:/etc/passwd" + } + })) + .send() + .await + .unwrap(); + assert_eq!(forged_path.status(), reqwest::StatusCode::CONFLICT); + assert!( + forged_path.json::().await.unwrap()["error"]["message"] + .as_str() + .unwrap() + .contains("cannot contain server file paths") + ); + + let blob_bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + let upload = client + .post(format!("{base_url}/api/v1/uploads/blobs")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header(reqwest::header::CONTENT_TYPE, "image/png") + .body(blob_bytes.clone()) + .send() + .await + .unwrap(); + assert_eq!(upload.status(), reqwest::StatusCode::CREATED); + let upload_value = upload.json::().await.unwrap()["value"] + .as_str() + .unwrap() + .to_string(); + assert!(upload_value.starts_with("BLOB_UPLOAD_REF:8:image/png:")); + assert!(!upload_value.contains(temp.path().to_string_lossy().as_ref())); + let upload_token = upload_value.rsplit(':').next().unwrap(); + let preview = client + .get(format!("{base_url}/api/v1/uploads/blobs/{upload_token}")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(preview.status(), reqwest::StatusCode::OK); + assert_eq!( + preview.headers()["content-security-policy"], + "sandbox; default-src 'none'" + ); + assert_eq!(preview.headers()["x-content-type-options"], "nosniff"); + assert_eq!( + preview.bytes().await.unwrap().as_ref(), + blob_bytes.as_slice() + ); + + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "insert_record", + serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "files", + "data": {"id": 1, "name": "before", "payload": upload_value} + }), + ) + .await, + serde_json::json!(1) + ); + assert_eq!( + client + .get(format!("{base_url}/api/v1/uploads/blobs/{upload_token}")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap() + .status(), + reqwest::StatusCode::NOT_FOUND + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "update_record", + serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "files", + "pkMap": {"id": 1}, + "colName": "name", + "newVal": "after" + }), + ) + .await, + serde_json::json!(1) + ); + let blob_download = rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "fetch_blob", + serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "files", + "pkMap": {"id": 1}, + "colName": "payload" + }), + ) + .await; + assert_eq!(blob_download["kind"], "download"); + assert_eq!(blob_download["size"], 8); + assert_eq!(blob_download["mimeType"], "image/png"); + let download_token = blob_download["token"].as_str().unwrap(); + let download_url = format!("{base_url}/api/v1/downloads/{download_token}"); + let download = client + .get(&download_url) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(download.status(), reqwest::StatusCode::OK); + assert_eq!( + download.bytes().await.unwrap().as_ref(), + blob_bytes.as_slice() + ); + assert_eq!( + client + .get(&download_url) + .header(COOKIE, &cookie) + .send() + .await + .unwrap() + .status(), + reqwest::StatusCode::NOT_FOUND + ); + let oversized_blob = client + .post(format!("{base_url}/api/v1/uploads/blobs")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header( + reqwest::header::CONTENT_LENGTH, + crate::application::records::MAX_WEB_BLOB_BYTES + 1, + ) + .body("x") + .send() + .await + .unwrap(); + assert_eq!( + oversized_blob.status(), + reqwest::StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + rpc_data( + &client, + &base_url, + &cookie, + &session.csrf_token, + "delete_record", + serde_json::json!({ + "connectionId": "metadata-fixture", + "table": "files", + "pkMap": {"id": 1} + }), + ) + .await, + serde_json::json!(1) + ); + + let debug = client + .post(format!("{base_url}/api/v1/rpc/is_debug_mode")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::Value::Null) + .send() + .await + .unwrap(); + assert_eq!(debug.status(), reqwest::StatusCode::OK); + assert_eq!(debug.json::().await.unwrap()["ok"], true); + + let connections = client + .post(format!("{base_url}/api/v1/rpc/get_connections")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::Value::Null) + .send() + .await + .unwrap(); + assert_eq!(connections.status(), reqwest::StatusCode::OK); + let direct_connections = crate::application::connections::load_connections( + &crate::paths::resolve_connections_path(temp.path()), + ) + .unwrap(); + assert_eq!( + connections.json::().await.unwrap(), + serde_json::json!({"ok": true, "data": direct_connections}) + ); + + let saved = client + .post(format!("{base_url}/api/v1/rpc/save_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "name": "Browser connection", + "params": { + "driver": "postgres", + "host": "127.0.0.1", + "port": 5432, + "username": "browser-user", + "password": "browser-secret", + "database": "browser-db", + "save_in_keychain": false + }, + "environment": "development" + })) + .send() + .await + .unwrap(); + assert_eq!(saved.status(), reqwest::StatusCode::OK); + let saved = saved.json::().await.unwrap(); + assert_eq!(saved["data"]["name"], "Browser connection"); + assert!(saved["data"]["params"]["password"].is_null()); + let saved_id = saved["data"]["id"].as_str().unwrap().to_string(); + + let upload = client + .post(format!("{base_url}/api/v1/uploads/connection-icons")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header("content-type", "image/png") + .body(vec![0x89, b'P', b'N', b'G']) + .send() + .await + .unwrap(); + assert_eq!(upload.status(), reqwest::StatusCode::CREATED); + let upload_token = upload.json::().await.unwrap()["token"] + .as_str() + .unwrap() + .to_string(); + let icon = client + .post(format!("{base_url}/api/v1/rpc/save_connection_icon")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "connectionId": saved_id, + "uploadToken": upload_token + })) + .send() + .await + .unwrap(); + assert_eq!(icon.status(), reqwest::StatusCode::OK); + let icon_path = icon.json::().await.unwrap()["data"] + .as_str() + .unwrap() + .to_string(); + let icon_asset = client + .get(format!("{base_url}/api/v1/assets/{icon_path}")) + .header(COOKIE, &cookie) + .send() + .await + .unwrap(); + assert_eq!(icon_asset.status(), reqwest::StatusCode::OK); + assert_eq!(icon_asset.headers()["x-content-type-options"], "nosniff"); + assert!(icon_asset.headers()["content-security-policy"] + .to_str() + .unwrap() + .ends_with("sandbox")); + assert_eq!( + icon_asset.bytes().await.unwrap().as_ref(), + &[0x89, b'P', b'N', b'G'] + ); + + let listed = client + .post(format!("{base_url}/api/v1/rpc/get_connections_with_groups")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::Value::Null) + .send() + .await + .unwrap(); + assert_eq!(listed.status(), reqwest::StatusCode::OK); + let listed = listed.json::().await.unwrap(); + let browser_connection = listed["data"]["connections"] + .as_array() + .unwrap() + .iter() + .find(|connection| connection["name"] == "Browser connection") + .unwrap(); + assert!(browser_connection["params"]["password"].is_null()); + + let saved_ssh = client + .post(format!("{base_url}/api/v1/rpc/save_ssh_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "name": "Browser bastion", + "ssh": { + "host": "bastion.example.com", + "port": 22, + "user": "browser-user", + "auth_type": "password", + "password": "write-only-secret", + "save_in_keychain": false + } + })) + .send() + .await + .unwrap(); + assert_eq!(saved_ssh.status(), reqwest::StatusCode::OK); + let saved_ssh = saved_ssh.json::().await.unwrap(); + assert!(saved_ssh["data"]["password"].is_null()); + let ssh_id = saved_ssh["data"]["id"].as_str().unwrap().to_string(); + + let listed_ssh = client + .post(format!("{base_url}/api/v1/rpc/get_ssh_connections")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::Value::Null) + .send() + .await + .unwrap(); + assert_eq!(listed_ssh.status(), reqwest::StatusCode::OK); + let listed_ssh = listed_ssh.json::().await.unwrap(); + assert_eq!(listed_ssh["data"][0]["name"], "Browser bastion"); + assert!(listed_ssh["data"][0]["password"].is_null()); + + let updated_ssh = client + .post(format!("{base_url}/api/v1/rpc/update_ssh_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "id": ssh_id, + "name": "Updated bastion", + "ssh": { + "host": "updated.example.com", + "port": 2222, + "user": "browser-user", + "auth_type": "password", + "save_in_keychain": false + } + })) + .send() + .await + .unwrap(); + assert_eq!(updated_ssh.status(), reqwest::StatusCode::OK); + assert_eq!( + updated_ssh.json::().await.unwrap()["data"]["host"], + "updated.example.com" + ); + + let deleted_ssh = client + .post(format!("{base_url}/api/v1/rpc/delete_ssh_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({"id": ssh_id})) + .send() + .await + .unwrap(); + assert_eq!(deleted_ssh.status(), reqwest::StatusCode::OK); + + let saved_k8s = client + .post(format!("{base_url}/api/v1/rpc/save_k8s_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "k8s": { + "name": "Browser cluster", + "context": "local", + "namespace": "database", + "resource_type": "service", + "resource_name": "postgres", + "port": 5432 + } + })) + .send() + .await + .unwrap(); + assert_eq!(saved_k8s.status(), reqwest::StatusCode::OK); + let saved_k8s = saved_k8s.json::().await.unwrap(); + assert_eq!(saved_k8s["data"]["name"], "Browser cluster"); + let k8s_id = saved_k8s["data"]["id"].as_str().unwrap().to_string(); + + let updated_k8s = client + .post(format!("{base_url}/api/v1/rpc/update_k8s_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({ + "id": k8s_id, + "k8s": { + "name": "Updated cluster", + "context": "local", + "namespace": "database", + "resource_type": "service", + "resource_name": "postgres-primary", + "port": 5432 + } + })) + .send() + .await + .unwrap(); + assert_eq!(updated_k8s.status(), reqwest::StatusCode::OK); + assert_eq!( + updated_k8s.json::().await.unwrap()["data"]["resource_name"], + "postgres-primary" + ); + + let deleted_k8s = client + .post(format!("{base_url}/api/v1/rpc/delete_k8s_connection")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .json(&serde_json::json!({"id": k8s_id})) + .send() + .await + .unwrap(); + assert_eq!(deleted_k8s.status(), reqwest::StatusCode::OK); + + let cookie_value = cookie.split_once('=').unwrap().1; + let session_id = session_security + .authenticate(cookie_value) + .unwrap() + .event_scope(); + let query_request_id = "query-request-1"; + let cancellation_slot = format!( + "web-query:{session_id}:{}:connection-1:{query_request_id}", + "connection-1".len() + ); + let query_task = tokio::spawn(std::future::pending::<()>()); + crate::commands::register_abort_handle( + &application_state.query_cancellation.handles, + cancellation_slot, + Arc::new(query_task.abort_handle()), + ); + let cancellation = client + .post(format!("{base_url}/api/v1/rpc/cancel_query")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header(RPC_DEADLINE_HEADER_NAME, "1000") + .header(RPC_CANCELLATION_HEADER_NAME, "query-1") + .json(&serde_json::json!({ + "connectionId": "connection-1", + "queryRequestId": query_request_id + })) + .send() + .await + .unwrap(); + assert_eq!(cancellation.status(), reqwest::StatusCode::OK); + assert_eq!( + cancellation.json::().await.unwrap(), + serde_json::json!({"ok": true, "data": null}) + ); + assert!(query_task.await.is_err()); + + let request_id = "request-http".to_string(); + let cancellation_error = client + .post(format!("{base_url}/api/v1/rpc/cancel_query")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &session.csrf_token) + .header(REQUEST_ID_HEADER, &request_id) + .json(&serde_json::json!({"connectionId": "connection-1"})) + .send() + .await + .unwrap(); + assert_eq!(cancellation_error.status(), reqwest::StatusCode::CONFLICT); + assert_eq!( + cancellation_error.headers().get(REQUEST_ID_HEADER).unwrap(), + request_id.as_str() + ); + let cancellation_error = cancellation_error + .json::() + .await + .unwrap(); + assert_eq!( + cancellation_error["error"]["code"], + "QUERY_CANCELLATION_FAILED" + ); + assert_eq!(cancellation_error["error"]["requestId"], request_id); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn authenticates_websockets_and_delivers_scoped_events_with_heartbeat() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let websocket_url = format!("ws://{address}/api/v1/events"); + let (security, bootstrap_token) = + LocalSessionSecurity::new(base_url.clone(), LocalSessionSecurityConfig::default()).unwrap(); + let issued = security + .consume_bootstrap(bootstrap_token.expose()) + .unwrap(); + let event_scope = security + .authenticate(&issued.cookie_value) + .unwrap() + .event_scope(); + let events = WebEventBus::new(EventBusConfig { + connection_queue_capacity: 4, + session_history_capacity: 4, + max_sessions: 4, + max_connections_per_session: 2, + disconnected_session_ttl: Duration::from_secs(1), + heartbeat_interval: Duration::from_millis(20), + heartbeat_timeout: Duration::from_millis(80), + }); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve_with_events( + listener, + temp.path().to_path_buf(), + temp.path().to_path_buf(), + temp.path().join("plugins"), + security, + test_application(temp.path()), + events.clone(), + Arc::default(), + async move { + let _ = shutdown_rx.await; + }, + )); + + let unauthorized = tokio_tungstenite::connect_async(&websocket_url) + .await + .unwrap_err(); + assert!(matches!( + unauthorized, + WebSocketError::Http(response) + if response.status() == reqwest::StatusCode::UNAUTHORIZED + )); + + let mut request = websocket_url.into_client_request().unwrap(); + request.headers_mut().insert( + "cookie", + format!("tabularis_session={}", issued.cookie_value) + .parse() + .unwrap(), + ); + request + .headers_mut() + .insert("origin", base_url.parse().unwrap()); + let (mut websocket, response) = tokio_tungstenite::connect_async(request).await.unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::SWITCHING_PROTOCOLS); + + websocket + .send(WebSocketMessage::Text( + serde_json::json!({ + "type": "subscribe", + "events": ["connection-health-failed"] + }) + .to_string(), + )) + .await + .unwrap(); + let acknowledgement = websocket.next().await.unwrap().unwrap(); + let WebSocketMessage::Text(acknowledgement) = acknowledgement else { + panic!("expected a subscription acknowledgement"); + }; + assert_eq!( + serde_json::from_str::(&acknowledgement).unwrap()["type"], + "subscribed" + ); + + let heartbeat = websocket.next().await.unwrap().unwrap(); + let WebSocketMessage::Ping(payload) = heartbeat else { + panic!("expected a heartbeat ping"); + }; + websocket + .send(WebSocketMessage::Pong(payload)) + .await + .unwrap(); + + events + .emit_to( + event_scope, + "connection-health-failed", + serde_json::json!({"connectionId": "connection-1", "error": "offline"}), + ) + .unwrap(); + let event = loop { + match websocket.next().await.unwrap().unwrap() { + WebSocketMessage::Text(event) => break event, + WebSocketMessage::Ping(payload) => { + websocket + .send(WebSocketMessage::Pong(payload)) + .await + .unwrap(); + } + message => panic!("expected an event message, received {message:?}"), + } + }; + let event: serde_json::Value = serde_json::from_str(&event).unwrap(); + assert_eq!(event["type"], "event"); + assert_eq!(event["event"], "connection-health-failed"); + assert_eq!(event["payload"]["connectionId"], "connection-1"); + + websocket.close(None).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), async { + while events.connection_count(event_scope) != 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("closed WebSocket must be removed from the event bus"); + + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn expires_healthy_websockets_without_further_http_requests() { + assert_expired_session_cleanup(true).await; +} + +#[tokio::test] +async fn reclaims_expired_session_uploads_without_a_websocket() { + assert_expired_session_cleanup(false).await; +} + +async fn assert_expired_session_cleanup(connect_websocket: bool) { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, bootstrap) = LocalSessionSecurity::new( + base_url.clone(), + LocalSessionSecurityConfig { + session_ttl: Duration::from_millis(500), + ..Default::default() + }, + ) + .unwrap(); + let issued = security.consume_bootstrap(bootstrap.expose()).unwrap(); + let authenticated = security.authenticate(&issued.cookie_value).unwrap(); + let owner = authenticated.event_scope(); + let cookie = format!("tabularis_session={}", issued.cookie_value); + let application_state = Arc::new(ApplicationState::default()); + application_state + .web_active_connections + .lock() + .unwrap() + .insert(owner, Default::default()); + let query = tokio::spawn(std::future::pending::<()>()); + crate::commands::register_abort_handle( + &application_state.query_cancellation.handles, + format!("web-query:{owner}:12:connection-1:request-1"), + Arc::new(query.abort_handle()), + ); + let events = WebEventBus::default(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve_with_events( + listener, + temp.path().to_path_buf(), + temp.path().to_path_buf(), + temp.path().join("plugins"), + security.clone(), + test_application_with_state(temp.path(), application_state.clone()), + events.clone(), + Arc::default(), + async move { + let _ = shutdown_rx.await; + }, + )); + let upload = reqwest::Client::new() + .post(format!("{base_url}/api/v1/uploads/blobs")) + .header(COOKIE, &cookie) + .header(ORIGIN, &base_url) + .header(CSRF_HEADER, &authenticated.csrf_token) + .header(reqwest::header::CONTENT_TYPE, "text/plain") + .body("session-owned upload") + .send() + .await + .unwrap(); + assert_eq!(upload.status(), reqwest::StatusCode::CREATED); + let transfer_dir = temp + .path() + .join("web-file-transfers") + .join(owner.to_string()); + assert!(transfer_dir.is_dir()); + + let mut websocket = if connect_websocket { + let mut request = format!("ws://{address}/api/v1/events") + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("cookie", cookie.parse().unwrap()); + request + .headers_mut() + .insert("origin", base_url.parse().unwrap()); + let (mut websocket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + websocket + .send(WebSocketMessage::Text( + serde_json::json!({ + "type": "subscribe", "events": ["connection-health-failed"] + }) + .to_string(), + )) + .await + .unwrap(); + let acknowledgement = websocket.next().await.unwrap().unwrap(); + assert!(matches!(acknowledgement, WebSocketMessage::Text(text) + if serde_json::from_str::(&text).unwrap()["type"] == "subscribed")); + Some(websocket) + } else { + None + }; + + tokio::time::sleep(Duration::from_millis(600)).await; + // An expired lookup must not discard the ID needed for resource reclamation. + assert!(security.authenticate(&issued.cookie_value).is_none()); + let _ = events.emit_to( + owner, + "connection-health-failed", + serde_json::json!({"error": "offline"}), + ); + if let Some(websocket) = websocket.as_mut() { + tokio::time::timeout(Duration::from_secs(2), async { + loop { + match websocket.next().await { + Some(Ok(WebSocketMessage::Close(_))) | None => break, + Some(Ok(WebSocketMessage::Ping(payload))) => { + websocket + .send(WebSocketMessage::Pong(payload)) + .await + .unwrap(); + } + message => { + panic!("expired WebSocket must close without receiving events: {message:?}") + } + } + } + }) + .await + .expect("expired WebSocket remained connected"); + } + tokio::time::timeout(Duration::from_secs(2), async { + while transfer_dir.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("expired session upload was not reclaimed"); + assert_eq!(events.connection_count(owner), 0); + assert!(!application_state + .web_active_connections + .lock() + .unwrap() + .contains_key(&owner)); + assert!(tokio::time::timeout(Duration::from_secs(2), query) + .await + .unwrap() + .unwrap_err() + .is_cancelled()); + shutdown_tx.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(2), server) + .await + .unwrap() + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn rejects_rpc_body_delayed_until_after_session_cleanup() { + use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; + + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let base_url = format!("http://{address}"); + let (security, bootstrap) = LocalSessionSecurity::new( + base_url.clone(), + LocalSessionSecurityConfig { + session_ttl: Duration::from_millis(500), + ..Default::default() + }, + ) + .unwrap(); + let issued = security.consume_bootstrap(bootstrap.expose()).unwrap(); + let authenticated = security.authenticate(&issued.cookie_value).unwrap(); + let owner = authenticated.event_scope(); + let application_state = Arc::new(ApplicationState::default()); + application_state + .web_active_connections + .lock() + .unwrap() + .insert(owner, Default::default()); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application_with_state(temp.path(), application_state.clone()), + async move { + let _ = shutdown_rx.await; + }, + )); + let body = r#"{"connectionId":"expired-session-connection"}"#; + let mut stream = BufReader::new(tokio::net::TcpStream::connect(address).await.unwrap()); + stream.get_mut().write_all(format!( + "POST /api/v1/rpc/register_active_connection HTTP/1.1\r\nHost: {address}\r\nOrigin: {base_url}\r\nCookie: tabularis_session={}\r\nx-tabularis-csrf: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nExpect: 100-continue\r\nConnection: close\r\n\r\n", + issued.cookie_value, authenticated.csrf_token, body.len(), + ).as_bytes()).await.unwrap(); + // The interim response proves the authorized handler is waiting for the body. + let mut interim = String::new(); + tokio::time::timeout(Duration::from_secs(2), stream.read_line(&mut interim)) + .await + .unwrap() + .unwrap(); + assert!(interim.starts_with("HTTP/1.1 100 Continue"), "{interim}"); + interim.clear(); + stream.read_line(&mut interim).await.unwrap(); + assert_eq!(interim, "\r\n"); + tokio::time::timeout(Duration::from_secs(2), async { + while application_state + .web_active_connections + .lock() + .unwrap() + .contains_key(&owner) + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("session cleanup did not run"); + + // Expiry may already have closed the socket; otherwise submit the late body. + let _ = stream.get_mut().write_all(body.as_bytes()).await; + let mut response = String::new(); + tokio::time::timeout(Duration::from_secs(2), stream.read_to_string(&mut response)) + .await + .unwrap() + .unwrap(); + assert!( + !application_state + .web_active_connections + .lock() + .unwrap() + .contains_key(&owner), + "the delayed RPC recreated state after session cleanup" + ); + assert!( + response.starts_with("HTTP/1.1 401 Unauthorized"), + "{response}" + ); + shutdown_tx.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(2), server) + .await + .unwrap() + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn serves_plugin_assets_from_the_local_plugin_directory_with_custom_data_storage() { + let temp = tempfile::tempdir().unwrap(); + let data_dir = temp.path().join("custom-data"); + let plugins_dir = temp.path().join("local-plugins"); + let plugin = plugins_dir.join("example-plugin"); + std::fs::create_dir_all(&data_dir).unwrap(); + std::fs::create_dir_all(plugin.join("ui")).unwrap(); + std::fs::write(data_dir.join("index.html"), "Tabularis").unwrap(); + std::fs::write(plugin.join(".tabularium"), r#"{ + "id":"example-plugin", "name":"Fixture", "version":"1.0.0", + "description":"Fixture", "ui_extensions":[{ + "slot":"data-grid.toolbar.actions", "module":"ui/index.js" + }] + }"#).unwrap(); + std::fs::write(plugin.join("ui/index.js"), "window.pluginLoaded = true;").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let (security, token) = LocalSessionSecurity::new( + base_url.clone(), LocalSessionSecurityConfig::default(), + ).unwrap(); + let session = security.consume_bootstrap(token.expose()).unwrap(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve_with_events( + listener, data_dir.clone(), data_dir.clone(), plugins_dir, security, + test_application(&data_dir), WebEventBus::default(), Arc::default(), + async move { let _ = shutdown_rx.await; }, + )); + let response = reqwest::Client::new() + .get(format!("{base_url}/api/v1/assets/plugins/example-plugin/ui/index.js")) + .header(COOKIE, format!("tabularis_session={}", session.cookie_value)) + .send().await.unwrap(); + let status = response.status(); + let body = response.text().await.unwrap(); + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); + assert_eq!(status, reqwest::StatusCode::OK); + assert_eq!(body, "window.pluginLoaded = true;"); +} + +#[test] +fn login_attempts_are_counted_per_client_behind_a_proxy() { + use super::auth::login_client; + let public = "203.0.113.7".parse().unwrap(); + let proxy = "172.18.0.3".parse().unwrap(); + let trusted = ["172.18.0.3/32".parse().unwrap(), "::1/128".parse().unwrap()]; + assert_eq!(login_client(Some(public), Some("198.51.100.1"), &trusted), public); + assert_eq!(login_client(Some(proxy), Some("198.51.100.1, 198.51.100.2"), &trusted), "198.51.100.2".parse::().unwrap()); + assert_eq!(login_client(Some(proxy), None, &trusted), proxy); + assert_eq!(login_client(Some(proxy), Some("garbage"), &trusted), proxy); + assert_eq!(login_client(Some("::1".parse().unwrap()), Some("2001:db8::7"), &trusted), "2001:db8::7".parse::().unwrap()); +} + +#[test] +fn private_clients_cannot_spoof_the_login_bucket_without_explicit_proxy_trust() { + for address in ["127.0.0.1", "172.18.0.3", "::1", "fd00::1"] { + let peer = address.parse().unwrap(); + assert_eq!(super::auth::login_client(Some(peer), Some("198.51.100.1"), &[]), peer); + } +} + +#[test] +fn login_client_churn_cannot_clear_an_existing_lockout() { + let security = LocalSessionSecurity::new_remote( + RemoteSessionSecurityConfig { + trusted_proxies: Vec::new(), + public_origin: "https://review.example".into(), + allowed_origins: vec!["https://review.example".into()], + session_ttl: Duration::from_secs(60), + max_body_bytes: 1024, + authorization: AuthorizationLevel::Database, + rate_limit: LoginRateLimitConfig::default(), + }, + RemoteAuthentication::password("correct horse battery staple"), + ) + .unwrap(); + let blocked = "198.51.100.1".parse().unwrap(); + for _ in 0..5 { + let _ = security.authenticate_password("incorrect", blocked); + } + for client in 0..4096_u32 { + let address = std::net::IpAddr::V4(std::net::Ipv4Addr::from(0x0a000000 + client)); + let _ = security.authenticate_password("incorrect", address); + } + assert!(matches!( + security.authenticate_password("correct horse battery staple", blocked), + Err(AuthenticationError::RateLimited) + )); + let overflow = "203.0.113.7".parse().unwrap(); + for _ in 0..10 { + assert!(security + .authenticate_password("incorrect", overflow) + .is_err()); + } + assert!(matches!( + security.authenticate_password("correct horse battery staple", overflow), + Err(AuthenticationError::RateLimited) + )); +} + +#[tokio::test] +async fn rejects_new_proxy_sessions_at_capacity_without_logging_out_existing_clients() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("index.html"), "Tabularis").unwrap(); + let secret = "a-proxy-shared-secret-with-32-bytes"; + let security = LocalSessionSecurity::new_remote( + RemoteSessionSecurityConfig { + trusted_proxies: Vec::new(), + public_origin: "https://review.example".into(), + allowed_origins: vec!["https://review.example".into()], + session_ttl: Duration::from_secs(60), + max_body_bytes: 1024, + authorization: AuthorizationLevel::Database, + rate_limit: LoginRateLimitConfig::default(), + }, + RemoteAuthentication::proxy(secret), + ) + .unwrap(); + let oldest = security.authenticate_proxy(secret, "alice").unwrap(); + for _ in 1..super::auth::MAX_SESSIONS { + security.authenticate_proxy(secret, "alice").unwrap(); + } + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(server::serve( + listener, + temp.path().to_path_buf(), + security, + test_application(temp.path()), + async move { + let _ = shutdown_rx.await; + }, + )); + let client = reqwest::Client::new(); + let response = client + .get(format!("http://{address}/api/v1/session")) + .header(HOST, "review.example") + .header("x-tabularis-proxy-secret", secret) + .header("x-tabularis-user", "bob") + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::SERVICE_UNAVAILABLE); + let existing = client + .get(format!("http://{address}/api/v1/session")) + .header(HOST, "review.example") + .header( + COOKIE, + format!( + "{}={}", + super::auth::SESSION_COOKIE_NAME, + oldest.cookie_value + ), + ) + .send() + .await + .unwrap(); + assert_eq!(existing.status(), reqwest::StatusCode::OK); + let _ = shutdown_tx.send(()); + server.await.unwrap().unwrap(); +} diff --git a/src-tauri/src/ui_state.rs b/src-tauri/src/ui_state.rs new file mode 100644 index 000000000..e3d9da671 --- /dev/null +++ b/src-tauri/src/ui_state.rs @@ -0,0 +1,208 @@ +//! Shared UI state store. +//! +//! Small interface preferences (sidebar widths, dismissed prompts, the last +//! release notes the user saw, ...) used to live in the webview's +//! `localStorage`. That storage is private to one browser origin, so the +//! desktop app and every browser that opens the Web UI kept their own copy. +//! This module keeps those values in a SQLite database next to the other +//! Tabularis data files instead, so every host sees the same state. +//! +//! The database lives in the active config directory, which follows the +//! custom storage location feature. It is opened in WAL mode with a busy +//! timeout because the desktop app and a `tabularis web` server may use it at +//! the same time. + +use once_cell::sync::Lazy; +use serde_json::{Map, Value}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions}; +use sqlx::Row; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::sync::Mutex; + +/// File name of the shared database inside the config directory. +pub const DATABASE_FILE: &str = "tabularis.db"; +/// Longest accepted key. +pub const MAX_KEY_LENGTH: usize = 128; +/// Largest accepted serialized JSON value. +pub const MAX_VALUE_BYTES: usize = 64 * 1024; +/// Most keys a single read may request. +pub const MAX_KEYS_PER_READ: usize = 256; +/// Schema version written to `PRAGMA user_version`. +pub const SCHEMA_VERSION: i64 = 1; + +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +static POOLS: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); + +/// Location of the shared database for a config directory. +pub fn database_path(config_dir: &Path) -> PathBuf { + config_dir.join(DATABASE_FILE) +} + +/// Keys are short identifiers such as `tabularis_sidebar_width` or +/// `tabularis:discord-callout-v2-dismissed`. +pub fn validate_key(key: &str) -> Result<(), String> { + if key.is_empty() || key.len() > MAX_KEY_LENGTH { + return Err(format!( + "UI state keys must be between 1 and {MAX_KEY_LENGTH} characters" + )); + } + if !key + .bytes() + .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b':' | b'-')) + { + return Err(format!("Invalid UI state key: {key}")); + } + Ok(()) +} + +/// Serializes a value and enforces the size cap. +pub fn encode_value(value: &Value) -> Result { + let encoded = serde_json::to_string(value).map_err(|error| error.to_string())?; + if encoded.len() > MAX_VALUE_BYTES { + return Err(format!( + "UI state values must not exceed {MAX_VALUE_BYTES} bytes" + )); + } + Ok(encoded) +} + +fn validate_keys(keys: &[String]) -> Result<(), String> { + if keys.len() > MAX_KEYS_PER_READ { + return Err(format!( + "At most {MAX_KEYS_PER_READ} UI state keys can be read at once" + )); + } + keys.iter().try_for_each(|key| validate_key(key)) +} + +async fn pool(database: &Path) -> Result { + let mut pools = POOLS.lock().await; + if let Some(pool) = pools.get(database) { + return Ok(pool.clone()); + } + if let Some(parent) = database.parent() { + std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let options = SqliteConnectOptions::new() + .filename(database) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal) + .busy_timeout(BUSY_TIMEOUT); + let pool = SqlitePoolOptions::new() + .max_connections(2) + .connect_with(options) + .await + .map_err(|error| format!("Failed to open the UI state database: {error}"))?; + migrate(&pool).await?; + pools.insert(database.to_path_buf(), pool.clone()); + Ok(pool) +} + +async fn migrate(pool: &SqlitePool) -> Result<(), String> { + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(pool) + .await + .map_err(|error| error.to_string())?; + if version > SCHEMA_VERSION { + return Err(format!( + "The UI state database was created by a newer Tabularis (schema {version})" + )); + } + if version < 1 { + sqlx::query( + "CREATE TABLE IF NOT EXISTS ui_state ( + key TEXT PRIMARY KEY NOT NULL, + value TEXT NOT NULL, + updated_at INTEGER NOT NULL + )", + ) + .execute(pool) + .await + .map_err(|error| error.to_string())?; + } + if version != SCHEMA_VERSION { + sqlx::query(&format!("PRAGMA user_version = {SCHEMA_VERSION}")) + .execute(pool) + .await + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +fn now_millis() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis() as i64) + .unwrap_or_default() +} + +/// Reads every stored entry, or only `keys` when given. Missing keys are +/// omitted from the result; rows that no longer parse as JSON are skipped. +pub async fn get_entries( + database: &Path, + keys: Option<&[String]>, +) -> Result, String> { + if let Some(keys) = keys { + validate_keys(keys)?; + } + let pool = pool(database).await?; + let rows = sqlx::query("SELECT key, value FROM ui_state ORDER BY key") + .fetch_all(&pool) + .await + .map_err(|error| error.to_string())?; + let mut entries = Map::new(); + for row in rows { + let key: String = row.try_get("key").map_err(|error| error.to_string())?; + if keys.is_some_and(|keys| !keys.contains(&key)) { + continue; + } + let raw: String = row.try_get("value").map_err(|error| error.to_string())?; + match serde_json::from_str(&raw) { + Ok(value) => { + entries.insert(key, value); + } + Err(error) => log::warn!("Ignoring unreadable UI state entry {key}: {error}"), + } + } + Ok(entries) +} + +/// Inserts or replaces one entry. +pub async fn set_entry(database: &Path, key: &str, value: &Value) -> Result<(), String> { + validate_key(key)?; + let encoded = encode_value(value)?; + let pool = pool(database).await?; + sqlx::query( + "INSERT INTO ui_state (key, value, updated_at) VALUES (?1, ?2, ?3) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + ) + .bind(key) + .bind(encoded) + .bind(now_millis()) + .execute(&pool) + .await + .map_err(|error| error.to_string())?; + Ok(()) +} + +/// Removes one entry. Returns whether it existed. +pub async fn delete_entry(database: &Path, key: &str) -> Result { + validate_key(key)?; + let pool = pool(database).await?; + let result = sqlx::query("DELETE FROM ui_state WHERE key = ?1") + .bind(key) + .execute(&pool) + .await + .map_err(|error| error.to_string())?; + Ok(result.rows_affected() > 0) +} + +/// Closes and forgets a cached pool, so tests can remove temporary folders. +pub async fn close(database: &Path) { + if let Some(pool) = POOLS.lock().await.remove(database) { + pool.close().await; + } +} diff --git a/src-tauri/src/ui_state_tests.rs b/src-tauri/src/ui_state_tests.rs new file mode 100644 index 000000000..5ac602344 --- /dev/null +++ b/src-tauri/src/ui_state_tests.rs @@ -0,0 +1,110 @@ +use crate::ui_state::{ + close, database_path, delete_entry, encode_value, get_entries, set_entry, validate_key, + MAX_KEYS_PER_READ, MAX_KEY_LENGTH, MAX_VALUE_BYTES, +}; +use serde_json::json; + +#[test] +fn accepts_existing_frontend_keys() { + for key in [ + "tabularis_sidebar_width", + "tabularis_row_editor_sidebar_width", + "tabularis_last_seen_version", + "tabularis_support_prompt_dismissed", + "tabularis:discord-callout-v2-dismissed", + "tabularis.format.v1", + ] { + assert!(validate_key(key).is_ok(), "{key}"); + } +} + +#[test] +fn rejects_malformed_keys() { + for key in [ + String::new(), + "Upper".to_string(), + "with space".to_string(), + "../escape".to_string(), + "k".repeat(MAX_KEY_LENGTH + 1), + ] { + assert!(validate_key(&key).is_err(), "{key}"); + } +} + +#[test] +fn caps_value_size() { + assert!(encode_value(&json!("x".repeat(MAX_VALUE_BYTES - 2))).is_ok()); + assert!(encode_value(&json!("x".repeat(MAX_VALUE_BYTES))).is_err()); +} + +#[tokio::test] +async fn stores_reads_and_deletes_entries() { + let temp = tempfile::tempdir().unwrap(); + let database = database_path(temp.path()); + + assert!(get_entries(&database, None).await.unwrap().is_empty()); + set_entry(&database, "tabularis_sidebar_width", &json!(320)) + .await + .unwrap(); + set_entry( + &database, + "tabularis_support_prompt_dismissed", + &json!(true), + ) + .await + .unwrap(); + set_entry(&database, "tabularis_sidebar_width", &json!(280)) + .await + .unwrap(); + + let all = get_entries(&database, None).await.unwrap(); + assert_eq!(all.get("tabularis_sidebar_width"), Some(&json!(280))); + assert_eq!( + all.get("tabularis_support_prompt_dismissed"), + Some(&json!(true)) + ); + + let selected = get_entries( + &database, + Some(&["tabularis_sidebar_width".to_string(), "missing".to_string()]), + ) + .await + .unwrap(); + assert_eq!(selected.len(), 1); + + assert!(delete_entry(&database, "tabularis_sidebar_width") + .await + .unwrap()); + assert!(!delete_entry(&database, "tabularis_sidebar_width") + .await + .unwrap()); + assert_eq!(get_entries(&database, None).await.unwrap().len(), 1); + close(&database).await; +} + +#[tokio::test] +async fn persists_across_reopened_pools() { + let temp = tempfile::tempdir().unwrap(); + let database = database_path(temp.path()); + set_entry(&database, "tabularis_last_seen_version", &json!("0.25.0")) + .await + .unwrap(); + close(&database).await; + + let entries = get_entries(&database, None).await.unwrap(); + assert_eq!( + entries.get("tabularis_last_seen_version"), + Some(&json!("0.25.0")) + ); + close(&database).await; +} + +#[tokio::test] +async fn rejects_invalid_requests_before_touching_the_database() { + let temp = tempfile::tempdir().unwrap(); + let database = database_path(temp.path()); + assert!(set_entry(&database, "Bad Key", &json!(1)).await.is_err()); + let too_many: Vec = (0..=MAX_KEYS_PER_READ).map(|i| format!("k{i}")).collect(); + assert!(get_entries(&database, Some(&too_many)).await.is_err()); + assert!(!database.exists()); +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 22a5184d8..789f41a4e 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -4,10 +4,10 @@ "version": "0.29.0", "identifier": "tabularis", "build": { - "frontendDist": "../dist", + "frontendDist": "../packages/web-ui/dist", "devUrl": "http://localhost:5173", - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build" + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build" }, "app": { "windows": [ @@ -36,6 +36,9 @@ "active": true, "category": "DeveloperTool", "targets": "all", + "resources": { + "../packages/web-ui/dist/": "web-ui/" + }, "icon": [ "icons/32x32.png", "icons/64x64.png", diff --git a/src/contexts/SavedQueriesProvider.tsx b/src/contexts/SavedQueriesProvider.tsx deleted file mode 100644 index a6f5fe973..000000000 --- a/src/contexts/SavedQueriesProvider.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import {useState, useEffect, useCallback, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {useDatabase} from '@/hooks/useDatabase'; -import {SavedQueriesContext, type SavedQuery, type SavedQueryFolder} from './SavedQueriesContext'; - -export const SavedQueriesProvider = ({children}: {children: ReactNode}) => { - const {activeConnectionId} = useDatabase(); - const [queries, setQueries] = useState([]); - const [folders, setFolders] = useState([]); - const [isLoading, setIsLoading] = useState(false); - - const refreshQueries = useCallback(async () => { - if (!activeConnectionId) { - setQueries([]); - setFolders([]); - return; - } - - setIsLoading(true); - try { - const [result, folderResult] = await Promise.all([ - invoke('get_saved_queries', {connectionId: activeConnectionId}), - // Folders are organizational only: if they can't load, queries still show as unfiled. - invoke('get_saved_query_folders', { - connectionId: activeConnectionId, - }).catch((e) => { - console.error('Failed to load saved query folders:', e); - return [] as SavedQueryFolder[]; - }), - ]); - setQueries(result); - setFolders(Array.isArray(folderResult) ? folderResult : []); - } catch (e) { - console.error('Failed to load saved queries:', e); - } finally { - setIsLoading(false); - } - }, [activeConnectionId]); - - useEffect(() => { - refreshQueries(); - }, [refreshQueries]); - - const saveQuery = async (name: string, sql: string, database?: string | null) => { - if (!activeConnectionId) return; - try { - await invoke('save_query', { - connectionId: activeConnectionId, - name, - sql, - database: database ?? null, - }); - await refreshQueries(); - } catch (e) { - console.error('Failed to save query:', e); - throw e; - } - }; - - const updateQuery = async (id: string, name: string, sql: string, database?: string | null) => { - try { - await invoke('update_saved_query', {id, name, sql, database: database ?? null}); - await refreshQueries(); - } catch (e) { - console.error('Failed to update query:', e); - throw e; - } - }; - - const deleteQuery = async (id: string) => { - try { - await invoke('delete_saved_query', {id}); - await refreshQueries(); - } catch (e) { - console.error('Failed to delete query:', e); - throw e; - } - }; - - const createFolder = async (name: string) => { - if (!activeConnectionId) return; - await invoke('create_saved_query_folder', {connectionId: activeConnectionId, name}); - await refreshQueries(); - }; - - const renameFolder = async (id: string, name: string) => { - await invoke('rename_saved_query_folder', {id, name}); - await refreshQueries(); - }; - - const deleteFolder = async (id: string) => { - await invoke('delete_saved_query_folder', {id}); - await refreshQueries(); - }; - - const moveQuery = async (id: string, folderId: string | null) => { - await invoke('move_saved_query', {id, folderId}); - await refreshQueries(); - }; - - return ( - - {children} - - ); -}; diff --git a/src/contexts/UpdateProvider.tsx b/src/contexts/UpdateProvider.tsx deleted file mode 100644 index 7288492a6..000000000 --- a/src/contexts/UpdateProvider.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import {useState, useEffect, type ReactNode} from 'react'; -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; -import {UpdateContext, type UpdateCheckResult} from './UpdateContext'; -import {toErrorMessage} from '@/utils/errors'; - -export const UpdateProvider = ({children}: {children: ReactNode}) => { - const [availableUpdate, setAvailableUpdate] = useState(null); - const [updateInfo, setUpdateInfo] = useState(null); - const [isChecking, setIsChecking] = useState(false); - const [isDownloading, setIsDownloading] = useState(false); - const [downloadProgress, setDownloadProgress] = useState(0); - const [error, setError] = useState(null); - const [isUpToDate, setIsUpToDate] = useState(false); - const [installationSource, setInstallationSource] = useState(null); - - // Listen for download progress events - useEffect(() => { - const unlistenProgress = listen('update-progress', (event) => { - setDownloadProgress(event.payload); - }); - - const unlistenInstalling = listen('update-installing', () => { - setDownloadProgress(100); - }); - - return () => { - unlistenProgress.then((fn) => fn()); - unlistenInstalling.then((fn) => fn()); - }; - }, []); - - const checkForUpdates = async (force = false) => { - setIsChecking(true); - setError(null); - setIsUpToDate(false); - try { - const result = await invoke('check_for_updates', { - force, - }); - setAvailableUpdate(result.hasUpdate ? result : null); - if (result.hasUpdate) { - // A manual check (force) always surfaces an available update. Only a - // background check honours a previous "remind me later" dismissal, - // otherwise the button would keep reporting "up to date" forever once - // a version has been dismissed. - let dismissed = false; - if (!force) { - const config = await invoke<{lastDismissedVersion: string}>('get_config'); - dismissed = config.lastDismissedVersion === result.latestVersion; - } - - if (dismissed) { - setUpdateInfo(null); - setIsUpToDate(false); - } else { - setUpdateInfo(result); - setIsUpToDate(false); - } - } else { - // No update available - setUpdateInfo(null); - setIsUpToDate(true); - } - } catch (err) { - console.error('Failed to check for updates:', err); - setError(toErrorMessage(err)); - setIsUpToDate(false); - } finally { - setIsChecking(false); - } - }; - - const downloadAndInstall = async () => { - setIsDownloading(true); - setDownloadProgress(0); - setError(null); - try { - await invoke('download_and_install_update'); - // L'app si riavvierà automaticamente dopo l'installazione - } catch (err) { - console.error('Failed to download/install update:', err); - setError(toErrorMessage(err)); - setIsDownloading(false); - } - }; - - const dismissUpdate = async () => { - if (updateInfo) { - await invoke('save_config', { - config: {lastDismissedVersion: updateInfo.latestVersion}, - }); - setUpdateInfo(null); - } - }; - - // Check on mount (startup) - useEffect(() => { - const performStartupCheck = async () => { - try { - // Detect installation source first; managed packages skip built-in updates - const source = await invoke('get_installation_source'); - setInstallationSource(source ?? null); - if (source) return; - - const config = await invoke<{autoCheckUpdatesOnStartup: boolean}>('get_config'); - if (config.autoCheckUpdatesOnStartup !== false) { - // Default: check on startup - await checkForUpdates(false); - } - } catch (err) { - console.error('Startup update check failed:', err); - } - }; - - // Delay di 2 secondi per non bloccare l'avvio dell'app - const timer = setTimeout(performStartupCheck, 2000); - return () => clearTimeout(timer); - }, []); - - return ( - - {children} - - ); -}; diff --git a/src/hooks/useJsonEditorActivity.ts b/src/hooks/useJsonEditorActivity.ts deleted file mode 100644 index 5ceeb8ba7..000000000 --- a/src/hooks/useJsonEditorActivity.ts +++ /dev/null @@ -1,80 +0,0 @@ -import {useCallback, useEffect, useRef, useState} from 'react'; -import {WebviewWindow} from '@tauri-apps/api/webviewWindow'; - -/** Tracks editable native windows, including the asynchronous opening phase. */ -export function useJsonEditorActivity() { - const [count, setCount] = useState(0); - const active = useRef(new Set()); - const sessions = useRef(new Map void>()); - const listeners = useRef(new Map void>()); - const mounted = useRef(true); - - useEffect(() => { - mounted.current = true; - const windowListeners = listeners.current; - const windowSessions = sessions.current; - const activeEditors = active.current; - return () => { - mounted.current = false; - windowListeners.forEach((unlisten) => unlisten()); - windowListeners.clear(); - windowSessions.clear(); - activeEditors.clear(); - }; - }, []); - - const begin = useCallback(() => { - const token = Symbol(); - active.current.add(token); - setCount(active.current.size); - return () => { - active.current.delete(token); - if (mounted.current) setCount(active.current.size); - }; - }, []); - - const release = useCallback((sessionId: string) => { - sessions.current.get(sessionId)?.(); - sessions.current.delete(sessionId); - listeners.current.get(sessionId)?.(); - listeners.current.delete(sessionId); - }, []); - - const watch = useCallback( - async (sessionId: string, end: () => void) => { - if (!mounted.current) { - end(); - return; - } - // Reopening the same cell focuses its existing native window. - release(sessionId); - sessions.current.set(sessionId, end); - const ownsSession = () => sessions.current.get(sessionId) === end; - try { - const window = await WebviewWindow.getByLabel(`json-viewer-${sessionId}`); - if (!ownsSession()) return; - if (!window) { - release(sessionId); - return; - } - const unlisten = await window.once('tauri://destroyed', () => { - if (ownsSession()) release(sessionId); - }); - if (!mounted.current || !ownsSession()) unlisten(); - else { - listeners.current.set(sessionId, unlisten); - // The window may have closed between lookup and listener registration. - const stillOpen = await WebviewWindow.getByLabel(`json-viewer-${sessionId}`); - if (!stillOpen && ownsSession()) release(sessionId); - } - } catch (error) { - console.error('Failed to track JSON editor window:', error); - if (ownsSession()) release(sessionId); - } - }, - [release], - ); - - const isEditing = useCallback(() => active.current.size > 0, []); - return {count, begin, watch, release, isEditing}; -} diff --git a/src/hooks/useRightSidebarResize.ts b/src/hooks/useRightSidebarResize.ts deleted file mode 100644 index f5322b9f9..000000000 --- a/src/hooks/useRightSidebarResize.ts +++ /dev/null @@ -1,58 +0,0 @@ -import {useCallback, useEffect, useRef, useState} from 'react'; - -const MIN_WIDTH = 320; -const DEFAULT_WIDTH = 384; -const STORAGE_KEY = 'tabularis_row_editor_sidebar_width'; - -const computeMaxWidth = () => - typeof window === 'undefined' ? 800 : Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.5)); - -export const useRightSidebarResize = () => { - const [width, setWidth] = useState(() => { - if (typeof window === 'undefined') return DEFAULT_WIDTH; - const saved = window.localStorage.getItem(STORAGE_KEY); - if (!saved) return DEFAULT_WIDTH; - const parsed = Number.parseInt(saved, 10); - if (Number.isNaN(parsed)) return DEFAULT_WIDTH; - return Math.max(MIN_WIDTH, Math.min(parsed, computeMaxWidth())); - }); - const isDragging = useRef(false); - - const startResize = useCallback((e: React.MouseEvent) => { - e.preventDefault(); - isDragging.current = true; - document.body.style.cursor = 'col-resize'; - document.body.style.userSelect = 'none'; - - const handleMove = (ev: MouseEvent) => { - if (!isDragging.current) return; - const maxWidth = computeMaxWidth(); - const next = window.innerWidth - ev.clientX; - if (next < MIN_WIDTH) { - setWidth(MIN_WIDTH); - } else if (next > maxWidth) { - setWidth(maxWidth); - } else { - setWidth(next); - } - }; - - const stop = () => { - isDragging.current = false; - document.body.style.cursor = ''; - document.body.style.userSelect = ''; - document.removeEventListener('mousemove', handleMove); - document.removeEventListener('mouseup', stop); - }; - - document.addEventListener('mousemove', handleMove); - document.addEventListener('mouseup', stop); - }, []); - - useEffect(() => { - if (typeof window === 'undefined') return; - window.localStorage.setItem(STORAGE_KEY, String(width)); - }, [width]); - - return {width, startResize}; -}; diff --git a/src/hooks/useRowEditorResize.ts b/src/hooks/useRowEditorResize.ts deleted file mode 100644 index 1fa562176..000000000 --- a/src/hooks/useRowEditorResize.ts +++ /dev/null @@ -1,58 +0,0 @@ -import {useCallback, useEffect, useRef, useState} from 'react'; - -const MIN_WIDTH = 320; -const DEFAULT_WIDTH = 384; -const STORAGE_KEY = 'tabularis_row_editor_sidebar_width'; - -const computeMaxWidth = () => - typeof window === 'undefined' ? 1200 : Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.9)); - -export const useRowEditorResize = () => { - const [width, setWidth] = useState(() => { - if (typeof window === 'undefined') return DEFAULT_WIDTH; - const saved = window.localStorage.getItem(STORAGE_KEY); - if (!saved) return DEFAULT_WIDTH; - const parsed = parseInt(saved, 10); - if (Number.isNaN(parsed)) return DEFAULT_WIDTH; - return Math.max(MIN_WIDTH, parsed); - }); - const isDragging = useRef(false); - - const startResize = useCallback((e: React.MouseEvent) => { - e.preventDefault(); - isDragging.current = true; - document.body.style.cursor = 'col-resize'; - document.body.style.userSelect = 'none'; - - const handleMove = (ev: MouseEvent) => { - if (!isDragging.current) return; - const maxWidth = computeMaxWidth(); - const next = window.innerWidth - ev.clientX; - if (next < MIN_WIDTH) { - setWidth(MIN_WIDTH); - } else if (next > maxWidth) { - setWidth(maxWidth); - } else { - setWidth(next); - } - }; - - const stop = () => { - isDragging.current = false; - document.body.style.cursor = ''; - document.body.style.userSelect = ''; - document.removeEventListener('mousemove', handleMove); - document.removeEventListener('mouseup', stop); - }; - - document.addEventListener('mousemove', handleMove); - document.addEventListener('mouseup', stop); - }, []); - - useEffect(() => { - if (typeof window === 'undefined') return; - window.localStorage.setItem(STORAGE_KEY, String(width)); - }, [width]); - - return {width, startResize}; -}; diff --git a/src/hooks/useSidebarResize.ts b/src/hooks/useSidebarResize.ts deleted file mode 100644 index dcd9b841e..000000000 --- a/src/hooks/useSidebarResize.ts +++ /dev/null @@ -1,63 +0,0 @@ -import {useState, useRef, useEffect, useCallback} from 'react'; - -const MIN_WIDTH = 150; -const MAX_WIDTH = 600; -const DEFAULT_WIDTH = 256; -const COLLAPSE_THRESHOLD = 100; -const STORAGE_KEY = 'tabularis_sidebar_width'; - -export const useSidebarResize = (onCollapse?: () => void) => { - const [sidebarWidth, setSidebarWidth] = useState(() => { - const saved = localStorage.getItem(STORAGE_KEY); - return saved ? parseInt(saved, 10) : DEFAULT_WIDTH; - }); - const isDragging = useRef(false); - const onCollapseRef = useRef(onCollapse); - - useEffect(() => { - onCollapseRef.current = onCollapse; - }, [onCollapse]); - - const startResize = useCallback((e: React.MouseEvent) => { - e.preventDefault(); - isDragging.current = true; - document.body.style.cursor = 'col-resize'; - - const handleResize = (e: MouseEvent) => { - if (!isDragging.current) return; - const newWidth = e.clientX - 64; // Subtract primary sidebar width (w-16 = 64px) - - // Auto-collapse when dragged below threshold - if (newWidth < COLLAPSE_THRESHOLD && onCollapseRef.current) { - isDragging.current = false; - document.body.style.cursor = 'default'; - document.removeEventListener('mousemove', handleResize); - document.removeEventListener('mouseup', stopResize); - onCollapseRef.current(); - return; - } - - if (newWidth > MIN_WIDTH && newWidth < MAX_WIDTH) { - setSidebarWidth(newWidth); - } - }; - - const stopResize = () => { - isDragging.current = false; - document.body.style.cursor = 'default'; - document.removeEventListener('mousemove', handleResize); - document.removeEventListener('mouseup', stopResize); - // localStorage is handled by useEffect - }; - - document.addEventListener('mousemove', handleResize); - document.addEventListener('mouseup', stopResize); - }, []); - - // Persist width on change as well to be safe - useEffect(() => { - localStorage.setItem(STORAGE_KEY, sidebarWidth.toString()); - }, [sidebarWidth]); - - return {sidebarWidth, startResize}; -}; diff --git a/src/main.tsx b/src/main.tsx deleted file mode 100644 index 0bc6843a7..000000000 --- a/src/main.tsx +++ /dev/null @@ -1,43 +0,0 @@ -// Import polyfills first to make Buffer available globally -import './polyfills'; -import React, {Suspense} from 'react'; -import ReactDOM from 'react-dom/client'; -import {App} from './App'; -import './index.css'; -import './i18n/config'; -import {DatabaseProvider} from './contexts/DatabaseProvider'; -import {ToastProvider} from './contexts/ToastProvider'; -import {SettingsProvider} from './contexts/SettingsProvider'; -import {SavedQueriesProvider} from './contexts/SavedQueriesProvider'; -import {QueryHistoryProvider} from './contexts/QueryHistoryProvider'; -import {EditorProvider} from './contexts/EditorProvider'; -import {ThemeProvider} from './contexts/ThemeProvider'; -import {UpdateProvider} from './contexts/UpdateProvider'; -import {ProductionGuardProvider} from './contexts/ProductionGuardContext'; -import {LoadingState} from './components/ui/LoadingState'; - -ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( - - }> - - - - - - - - - - - - - - - - - - - - - , -); diff --git a/src/pages/JsonViewerPage.tsx b/src/pages/JsonViewerPage.tsx deleted file mode 100644 index 07bf5565f..000000000 --- a/src/pages/JsonViewerPage.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import {useState, useEffect, useCallback} from 'react'; -import {useSearchParams} from 'react-router-dom'; -import {useTranslation} from 'react-i18next'; -import {invoke} from '@tauri-apps/api/core'; -import {getCurrentWindow} from '@tauri-apps/api/window'; -import {JsonInput} from '@/components/ui/JsonInput'; - -interface SessionDto { - value: unknown; - original_value: unknown; - col_name: string; - read_only: boolean; -} - -export const JsonViewerPage = () => { - const {t} = useTranslation(); - const [searchParams] = useSearchParams(); - const sessionId = searchParams.get('session') ?? ''; - - const [session, setSession] = useState(null); - const [currentValue, setCurrentValue] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - if (!sessionId) return; - invoke('get_json_viewer_session', {sessionId}) - .then((data) => { - setSession(data); - setCurrentValue(data.value); - }) - .catch((e) => setError(String(e))); - }, [sessionId]); - - const handleClose = useCallback(async () => { - await getCurrentWindow().close(); - }, []); - - const handleSave = useCallback(async () => { - try { - await invoke('complete_json_viewer_session', { - sessionId, - value: currentValue, - }); - } catch (e) { - setError(String(e)); - return; - } - await getCurrentWindow().close(); - }, [sessionId, currentValue]); - - useEffect(() => { - const handler = (e: KeyboardEvent) => { - if (e.key === 'Escape') handleClose(); - }; - window.addEventListener('keydown', handler); - return () => window.removeEventListener('keydown', handler); - }, [handleClose]); - - const showSave = session && !session.read_only; - const displayError = error ?? (!sessionId ? 'No session ID provided' : null); - - return ( -
-
- {displayError ? ( -

{displayError}

- ) : session ? ( - - ) : ( -

{t('common.loading')}

- )} -
- -
- {showSave ? ( - <> - - - - ) : ( - - )} -
-
- ); -}; diff --git a/src/pages/ResultsWindowPage.tsx b/src/pages/ResultsWindowPage.tsx deleted file mode 100644 index 7111c788d..000000000 --- a/src/pages/ResultsWindowPage.tsx +++ /dev/null @@ -1,138 +0,0 @@ -import {useState, useEffect, useCallback} from 'react'; -import {useTranslation} from 'react-i18next'; -import {useSearchParams} from 'react-router-dom'; -import {emit, listen} from '@tauri-apps/api/event'; -import {MultiResultPanel} from '@/components/ui/MultiResultPanel'; -import {ResultEntryContent} from '@/components/ui/ResultEntryContent'; -import {useAlert} from '@/hooks/useAlert'; -import {useToast} from '@/hooks/useToast'; -import {copyTextToClipboard} from '@/utils/clipboard'; -import { - RESULTS_ACTION_EVENT, - RESULTS_READY_EVENT, - resultsCopyEvent, - resultsSyncEvent, - applyCopyResult, - hasMultiResults, - singleResultToEntry, - type ResultsCopyPayload, - type ResultsSyncPayload, - type ResultsWindowAction, -} from '@/utils/resultsWindowSync'; - -/** - * Detached query-results window, bound to a single editor tab (its id comes from - * the `?tab=` query param). It renders that tab's results (pushed from the main - * window via {@link resultsSyncEvent}) and forwards user - * actions back, tagged with its `tabId`. The main window owns all query/DB - * logic; this window holds no query state of its own. - */ -export const ResultsWindowPage = () => { - const {t} = useTranslation(); - const {showAlert} = useAlert(); - const {showToast} = useToast(); - const [searchParams] = useSearchParams(); - const tabId = searchParams.get('tab') ?? ''; - const [payload, setPayload] = useState(null); - - // Receive result snapshots for this tab from the main window. - useEffect(() => { - if (!tabId) return; - const unlistenPromise = listen(resultsSyncEvent(tabId), (event) => - setPayload(event.payload), - ); - // Ask the main window to send this tab's current state now that we're mounted. - emit(RESULTS_READY_EVENT, {tabId}); - return () => { - unlistenPromise.then((unlisten) => unlisten()); - }; - }, [tabId]); - - // Copy-all runs in the main window; the clipboard write and its feedback - // happen here, in the window the user clicked. - useEffect(() => { - if (!tabId) return; - const showError = (error: unknown) => - showAlert(t('common.error') + ': ' + error, { - title: t('common.error'), - kind: 'error', - }); - const unlistenPromise = listen(resultsCopyEvent(tabId), (event) => - applyCopyResult(event.payload, { - onCopied: ({text, count}) => - copyTextToClipboard(text) - .then(() => - showToast(t('dataGrid.copiedRows', {count}), { - kind: 'success', - }), - ) - .catch(showError), - onError: showError, - }), - ); - return () => { - unlistenPromise.then((unlisten) => unlisten()); - }; - }, [tabId, showAlert, showToast, t]); - - const send = useCallback( - (action: ResultsWindowAction) => { - emit(RESULTS_ACTION_EVENT, {tabId, action}); - }, - [tabId], - ); - - if (!payload) { - return ( -
- {t('common.loading')} -
- ); - } - - return ( -
- {hasMultiResults(payload) ? ( - send({type: 'select-result', entryId})} - onRerunEntry={(entryId) => send({type: 'rerun-entry', entryId})} - onPageChange={(entryId, page) => send({type: 'page-change', entryId, page})} - onCloseEntry={(entryId) => send({type: 'close-entry', entryId})} - onCloseOtherEntries={(entryId) => send({type: 'close-other-entries', entryId})} - onCloseEntriesToRight={(entryId) => - send({type: 'close-entries-to-right', entryId}) - } - onCloseEntriesToLeft={(entryId) => - send({type: 'close-entries-to-left', entryId}) - } - onCloseAllEntries={() => send({type: 'close-all-entries'})} - onRenameEntry={(entryId, label) => send({type: 'rename-entry', entryId, label})} - onCopyAllRows={(entryId) => send({type: 'copy-entry-all-rows', entryId})} - /> - ) : payload.result || payload.error || payload.isLoading ? ( - - send({type: 'run-query-page', query: payload.query, page}) - } - onCopyAllRows={() => send({type: 'copy-all-rows'})} - /> - ) : ( -
- {t('editor.executePrompt')} -
- )} -
- ); -}; diff --git a/src/utils/dataImportFile.ts b/src/utils/dataImportFile.ts deleted file mode 100644 index 74ec62a16..000000000 --- a/src/utils/dataImportFile.ts +++ /dev/null @@ -1,30 +0,0 @@ -import {readTextFile, stat} from '@tauri-apps/plugin-fs'; - -export const DATA_IMPORT_FILE_LIMIT = 20 * 1024 * 1024; -export const DATA_IMPORT_EXTENSIONS = ['csv', 'tsv', 'json', 'md']; - -export class DataImportFileError extends Error { - readonly code: 'tooLarge' | 'unsupported' | 'notFile'; - - constructor(code: DataImportFileError['code']) { - super(code); - this.code = code; - } -} - -/** Read only a supported, bounded text file selected by the native dialog. */ -export async function readDataImportFile(path: string): Promise { - const extension = path.split('.').pop()?.toLowerCase(); - if (!extension || !DATA_IMPORT_EXTENSIONS.includes(extension)) { - throw new DataImportFileError('unsupported'); - } - const info = await stat(path); - if (!info.isFile) throw new DataImportFileError('notFile'); - if (info.size > DATA_IMPORT_FILE_LIMIT) throw new DataImportFileError('tooLarge'); - const text = await readTextFile(path); - // Recheck in case the file changed between the metadata check and the read. - if (new TextEncoder().encode(text).byteLength > DATA_IMPORT_FILE_LIMIT) { - throw new DataImportFileError('tooLarge'); - } - return text; -} diff --git a/src/utils/supportPrompt.ts b/src/utils/supportPrompt.ts deleted file mode 100644 index 449a526a9..000000000 --- a/src/utils/supportPrompt.ts +++ /dev/null @@ -1,31 +0,0 @@ -export const SUPPORT_PROMPT_DISMISSED_KEY = 'tabularis_support_prompt_dismissed'; -const SUPPORT_PROMPT_CHANGED_EVENT = 'tabularis-support-prompt-changed'; - -export function isSupportPromptDismissed(): boolean { - try { - return localStorage.getItem(SUPPORT_PROMPT_DISMISSED_KEY) === 'true'; - } catch { - return false; - } -} - -/** Persist before notifying subscribers, so a failed write does not hide the prompt. */ -export function dismissSupportPrompt(): void { - localStorage.setItem(SUPPORT_PROMPT_DISMISSED_KEY, 'true'); - window.dispatchEvent(new Event(SUPPORT_PROMPT_CHANGED_EVENT)); -} - -/** Keep both modal instances and other app windows in sync. */ -export function subscribeToSupportPrompt(onChange: () => void): () => void { - const onStorage = (event: StorageEvent) => { - if (event.key === null || event.key === SUPPORT_PROMPT_DISMISSED_KEY) { - onChange(); - } - }; - window.addEventListener(SUPPORT_PROMPT_CHANGED_EVENT, onChange); - window.addEventListener('storage', onStorage); - return () => { - window.removeEventListener(SUPPORT_PROMPT_CHANGED_EVENT, onChange); - window.removeEventListener('storage', onStorage); - }; -} diff --git a/src/utils/themeSystemEvents.ts b/src/utils/themeSystemEvents.ts deleted file mode 100644 index 53d373612..000000000 --- a/src/utils/themeSystemEvents.ts +++ /dev/null @@ -1,85 +0,0 @@ -import {invoke} from '@tauri-apps/api/core'; -import {listen} from '@tauri-apps/api/event'; -import {getCurrentWindow} from '@tauri-apps/api/window'; -import {isLinuxDesktop} from './systemTheme'; - -export const getSystemIsDark = async (): Promise => { - if (isLinuxDesktop()) { - try { - const portalTheme = await invoke<'dark' | 'light' | null>('get_linux_system_theme'); - if (portalTheme) return portalTheme === 'dark'; - } catch { - /* Browser previews and desktops without a portal use fallbacks. */ - } - } - try { - const nativeTheme = await getCurrentWindow().theme(); - if (nativeTheme) return nativeTheme === 'dark'; - } catch { - /* Browser previews do not expose the native window API. */ - } - return window.matchMedia('(prefers-color-scheme: dark)').matches; -}; - -export const listenForSystemThemeChanges = async ( - onChange: (isDark: boolean) => void, -): Promise<() => void> => { - if (isLinuxDesktop()) { - let disposed = false; - let revision = 0; - const refresh = async () => { - const request = ++revision; - const isDark = await getSystemIsDark(); - if (!disposed && request === revision) onChange(isDark); - }; - const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); - const handleChange = () => { - void refresh(); - }; - mediaQuery.addEventListener('change', handleChange); - let stopPortal: (() => void) | undefined; - try { - stopPortal = await listen('linux-system-theme-changed', handleChange); - } catch { - /* Keep the media-query fallback. */ - } - await refresh(); - return () => { - disposed = true; - stopPortal?.(); - mediaQuery.removeEventListener('change', handleChange); - }; - } - try { - let disposed = false; - let revision = 0; - const stopNative = await getCurrentWindow().onThemeChanged(({payload}) => { - const request = ++revision; - if (payload === null) { - void getSystemIsDark().then((isDark) => { - if (!disposed && request === revision) onChange(isDark); - }); - } else { - onChange(payload === 'dark'); - } - }); - // A user may enable follow-system after the OS changed in static mode. - // Subscribe before reading and never let a stale read override an event. - const request = ++revision; - const isDark = await getSystemIsDark(); - if (!disposed && request === revision) onChange(isDark); - return () => { - disposed = true; - stopNative(); - }; - } catch { - const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); - const handleChange = (event: MediaQueryListEvent) => { - onChange(event.matches); - }; - mediaQuery.addEventListener('change', handleChange); - await Promise.resolve(); - onChange(mediaQuery.matches); - return () => mediaQuery.removeEventListener('change', handleChange); - } -}; diff --git a/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx b/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx deleted file mode 100644 index 4c91d7722..000000000 --- a/tests/components/layout/sidebar/DiscordCommunityCallout.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import {render, screen, fireEvent} from '@testing-library/react'; -import {describe, it, expect, vi, beforeEach} from 'vitest'; -import { - DiscordCommunityCallout, - DISCORD_CALLOUT_STORAGE_KEY, -} from '@/components/layout/sidebar/DiscordCommunityCallout'; -import {openUrl} from '@tauri-apps/plugin-opener'; - -const createMemoryStorage = (initial: Record = {}) => { - const store: Record = {...initial}; - return { - getItem: vi.fn((key: string) => (key in store ? store[key] : null)), - setItem: vi.fn((key: string, value: string) => { - store[key] = value; - }), - snapshot: () => ({...store}), - }; -}; - -describe('DiscordCommunityCallout', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it('renders on first run when storage flag is missing', () => { - const storage = createMemoryStorage(); - render(); - - expect(screen.getByTestId('discord-callout')).toBeInTheDocument(); - expect(screen.getByTestId('discord-callout-pulse')).toBeInTheDocument(); - expect(screen.getByText('discordCallout.title')).toBeInTheDocument(); - expect(screen.getByText('discordCallout.body')).toBeInTheDocument(); - expect(storage.getItem).toHaveBeenCalledWith(DISCORD_CALLOUT_STORAGE_KEY); - }); - - it('stays hidden when storage flag is already set', () => { - const storage = createMemoryStorage({[DISCORD_CALLOUT_STORAGE_KEY]: 'true'}); - render(); - - expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); - expect(screen.queryByTestId('discord-callout-pulse')).not.toBeInTheDocument(); - }); - - it('persists dismissal and hides itself when the close button is clicked', () => { - const storage = createMemoryStorage(); - render(); - - fireEvent.click(screen.getByLabelText('discordCallout.dismiss')); - - expect(storage.setItem).toHaveBeenCalledWith(DISCORD_CALLOUT_STORAGE_KEY, 'true'); - expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); - }); - - it('opens Discord and dismisses when the CTA is clicked', () => { - const storage = createMemoryStorage(); - render(); - - fireEvent.click(screen.getByText('discordCallout.cta')); - - expect(openUrl).toHaveBeenCalledWith('https://discord.com/invite/K2hmhfHRSt'); - expect(storage.setItem).toHaveBeenCalledWith(DISCORD_CALLOUT_STORAGE_KEY, 'true'); - expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); - }); - - it('still hides for the session if storage writes throw', () => { - const storage = { - getItem: vi.fn(() => null), - setItem: vi.fn(() => { - throw new Error('quota exceeded'); - }), - }; - render(); - - fireEvent.click(screen.getByLabelText('discordCallout.dismiss')); - - expect(screen.queryByTestId('discord-callout')).not.toBeInTheDocument(); - }); - - it('falls back to visible when getItem throws (e.g. privacy mode)', () => { - const storage = { - getItem: vi.fn(() => { - throw new Error('blocked'); - }), - setItem: vi.fn(), - }; - render(); - - expect(screen.getByTestId('discord-callout')).toBeInTheDocument(); - }); -}); diff --git a/tests/fixtures/sql-syntax/googlesql.json b/tests/fixtures/sql-syntax/googlesql.json index 1bd77b25c..420be0c56 100644 --- a/tests/fixtures/sql-syntax/googlesql.json +++ b/tests/fixtures/sql-syntax/googlesql.json @@ -17,44 +17,170 @@ "boolean_literals": "keywords", "formatter": "bigquery", "keywords": [ - "QUALIFY", "PIVOT", "UNPIVOT", "TABLESAMPLE SYSTEM", "UNNEST", - "WITH OFFSET", "EXCEPT", "REPLACE", "WINDOW", "OVER", "PARTITION BY", - "CLUSTER BY", "OPTIONS", "FOR SYSTEM_TIME AS OF", "IGNORE NULLS", - "RESPECT NULLS", "UNION ALL", "UNION DISTINCT", "INTERSECT DISTINCT", - "EXCEPT DISTINCT", "MERGE", "WHEN MATCHED", "WHEN NOT MATCHED", - "WHEN NOT MATCHED BY SOURCE", "CREATE OR REPLACE TABLE", - "CREATE TEMP TABLE", "CREATE TEMP FUNCTION", - "CREATE OR REPLACE PROCEDURE", "CREATE SCHEMA", "RETURNS", "LANGUAGE js", - "EXPORT DATA", "LOAD DATA", "ASSERT", "DECLARE", "BEGIN", - "BEGIN TRANSACTION", "COMMIT TRANSACTION", "ROLLBACK TRANSACTION", - "EXCEPTION WHEN ERROR THEN", "ELSEIF", "END IF", "LOOP", "END LOOP", - "WHILE", "END WHILE", "REPEAT", "UNTIL", "END REPEAT", "FOR", "DO", - "END FOR", "END CASE", "LEAVE", "BREAK", "CONTINUE", "ITERATE", "RETURN", - "CALL", "EXECUTE IMMEDIATE", "RAISE USING MESSAGE", "INT64", "FLOAT64", - "NUMERIC", "BIGNUMERIC", "BOOL", "STRING", "BYTES", "DATE", "DATETIME", - "TIME", "TIMESTAMP", "INTERVAL", "GEOGRAPHY", "JSON", "STRUCT", "ARRAY", + "QUALIFY", + "PIVOT", + "UNPIVOT", + "TABLESAMPLE SYSTEM", + "UNNEST", + "WITH OFFSET", + "EXCEPT", + "REPLACE", + "WINDOW", + "OVER", + "PARTITION BY", + "CLUSTER BY", + "OPTIONS", + "FOR SYSTEM_TIME AS OF", + "IGNORE NULLS", + "RESPECT NULLS", + "UNION ALL", + "UNION DISTINCT", + "INTERSECT DISTINCT", + "EXCEPT DISTINCT", + "MERGE", + "WHEN MATCHED", + "WHEN NOT MATCHED", + "WHEN NOT MATCHED BY SOURCE", + "CREATE OR REPLACE TABLE", + "CREATE TEMP TABLE", + "CREATE TEMP FUNCTION", + "CREATE OR REPLACE PROCEDURE", + "CREATE SCHEMA", + "RETURNS", + "LANGUAGE js", + "EXPORT DATA", + "LOAD DATA", + "ASSERT", + "DECLARE", + "BEGIN", + "BEGIN TRANSACTION", + "COMMIT TRANSACTION", + "ROLLBACK TRANSACTION", + "EXCEPTION WHEN ERROR THEN", + "ELSEIF", + "END IF", + "LOOP", + "END LOOP", + "WHILE", + "END WHILE", + "REPEAT", + "UNTIL", + "END REPEAT", + "FOR", + "DO", + "END FOR", + "END CASE", + "LEAVE", + "BREAK", + "CONTINUE", + "ITERATE", + "RETURN", + "CALL", + "EXECUTE IMMEDIATE", + "RAISE USING MESSAGE", + "INT64", + "FLOAT64", + "NUMERIC", + "BIGNUMERIC", + "BOOL", + "STRING", + "BYTES", + "DATE", + "DATETIME", + "TIME", + "TIMESTAMP", + "INTERVAL", + "GEOGRAPHY", + "JSON", + "STRUCT", + "ARRAY", "RANGE" ], "functions": [ - "SAFE_CAST", "SAFE.", "SAFE_DIVIDE", "IF", "IFNULL", "COALESCE", - "NULLIF", "COUNTIF", "ARRAY_AGG", "STRING_AGG", "LOGICAL_AND", - "LOGICAL_OR", "ANY_VALUE", "APPROX_COUNT_DISTINCT", "APPROX_QUANTILES", - "APPROX_TOP_COUNT", "APPROX_TOP_SUM", "ROW_NUMBER", "RANK", "DENSE_RANK", - "LAG", "LEAD", "FIRST_VALUE", "LAST_VALUE", "NTILE", "PERCENTILE_CONT", - "ARRAY_LENGTH", "ARRAY_CONCAT", "ARRAY_TO_STRING", "GENERATE_ARRAY", - "GENERATE_DATE_ARRAY", "SPLIT", "FORMAT", "STARTS_WITH", "ENDS_WITH", - "CONTAINS_SUBSTR", "REGEXP_CONTAINS", "REGEXP_EXTRACT", - "REGEXP_EXTRACT_ALL", "REGEXP_REPLACE", "REGEXP_INSTR", - "FARM_FINGERPRINT", "GENERATE_UUID", "JSON_VALUE", "JSON_QUERY", - "JSON_VALUE_ARRAY", "JSON_QUERY_ARRAY", "JSON_EXTRACT", - "JSON_EXTRACT_SCALAR", "PARSE_JSON", "TO_JSON", "TO_JSON_STRING", - "CURRENT_DATE", "CURRENT_DATETIME", "CURRENT_TIMESTAMP", "EXTRACT", - "DATE_TRUNC", "DATE_ADD", "DATE_SUB", "DATE_DIFF", "DATETIME_TRUNC", - "DATETIME_DIFF", "TIMESTAMP_TRUNC", "TIMESTAMP_ADD", "TIMESTAMP_SUB", - "TIMESTAMP_DIFF", "FORMAT_DATE", "FORMAT_TIMESTAMP", "PARSE_DATE", - "PARSE_TIMESTAMP", "UNIX_SECONDS", "UNIX_MILLIS", "TIMESTAMP_SECONDS", - "TIMESTAMP_MILLIS", "LAST_DAY", "ST_GEOGPOINT", "ST_GEOGFROMTEXT", - "ST_ASTEXT", "ST_DISTANCE", "ST_DWITHIN", "ST_CONTAINS", "ST_INTERSECTS", - "ST_AREA", "ST_LENGTH", "ST_BUFFER" + "SAFE_CAST", + "SAFE.", + "SAFE_DIVIDE", + "IF", + "IFNULL", + "COALESCE", + "NULLIF", + "COUNTIF", + "ARRAY_AGG", + "STRING_AGG", + "LOGICAL_AND", + "LOGICAL_OR", + "ANY_VALUE", + "APPROX_COUNT_DISTINCT", + "APPROX_QUANTILES", + "APPROX_TOP_COUNT", + "APPROX_TOP_SUM", + "ROW_NUMBER", + "RANK", + "DENSE_RANK", + "LAG", + "LEAD", + "FIRST_VALUE", + "LAST_VALUE", + "NTILE", + "PERCENTILE_CONT", + "ARRAY_LENGTH", + "ARRAY_CONCAT", + "ARRAY_TO_STRING", + "GENERATE_ARRAY", + "GENERATE_DATE_ARRAY", + "SPLIT", + "FORMAT", + "STARTS_WITH", + "ENDS_WITH", + "CONTAINS_SUBSTR", + "REGEXP_CONTAINS", + "REGEXP_EXTRACT", + "REGEXP_EXTRACT_ALL", + "REGEXP_REPLACE", + "REGEXP_INSTR", + "FARM_FINGERPRINT", + "GENERATE_UUID", + "JSON_VALUE", + "JSON_QUERY", + "JSON_VALUE_ARRAY", + "JSON_QUERY_ARRAY", + "JSON_EXTRACT", + "JSON_EXTRACT_SCALAR", + "PARSE_JSON", + "TO_JSON", + "TO_JSON_STRING", + "CURRENT_DATE", + "CURRENT_DATETIME", + "CURRENT_TIMESTAMP", + "EXTRACT", + "DATE_TRUNC", + "DATE_ADD", + "DATE_SUB", + "DATE_DIFF", + "DATETIME_TRUNC", + "DATETIME_DIFF", + "TIMESTAMP_TRUNC", + "TIMESTAMP_ADD", + "TIMESTAMP_SUB", + "TIMESTAMP_DIFF", + "FORMAT_DATE", + "FORMAT_TIMESTAMP", + "PARSE_DATE", + "PARSE_TIMESTAMP", + "UNIX_SECONDS", + "UNIX_MILLIS", + "TIMESTAMP_SECONDS", + "TIMESTAMP_MILLIS", + "LAST_DAY", + "ST_GEOGPOINT", + "ST_GEOGFROMTEXT", + "ST_ASTEXT", + "ST_DISTANCE", + "ST_DWITHIN", + "ST_CONTAINS", + "ST_INTERSECTS", + "ST_AREA", + "ST_LENGTH", + "ST_BUFFER" ] } diff --git a/tests/fixtures/sql-syntax/googlesql.ts b/tests/fixtures/sql-syntax/googlesql.ts index e29e74a52..f0016f4a8 100644 --- a/tests/fixtures/sql-syntax/googlesql.ts +++ b/tests/fixtures/sql-syntax/googlesql.ts @@ -1,6 +1,9 @@ -import descriptor from "./googlesql.json"; -import type { DriverCapabilities, SqlSyntaxDescriptor } from "../../../src/types/plugins"; -import { resolveSqlSyntax } from "../../../src/utils/sqlSyntax"; +import descriptor from './googlesql.json'; +import type { + DriverCapabilities, + SqlSyntaxDescriptor, +} from '../../../packages/web-ui/src/types/plugins'; +import {resolveSqlSyntax} from '../../../packages/web-ui/src/utils/sqlSyntax'; /** The GoogleSQL `sql_syntax` descriptor the BigQuery plugin ships. */ export const GOOGLESQL_DESCRIPTOR = descriptor as SqlSyntaxDescriptor; @@ -10,9 +13,9 @@ export const GOOGLESQL_DESCRIPTOR = descriptor as SqlSyntaxDescriptor; * hosts without `sql_syntax`, plus the GoogleSQL descriptor. */ export const GOOGLESQL_CAPS = { - identifier_quote: "`", - sql_dialect: "mysql", - sql_syntax: GOOGLESQL_DESCRIPTOR, + identifier_quote: '`', + sql_dialect: 'mysql', + sql_syntax: GOOGLESQL_DESCRIPTOR, } as DriverCapabilities; /** The resolved GoogleSQL syntax, accepted wherever a dialect is. */ diff --git a/tests/fixtures/themes/author/import-example.jsonc b/tests/fixtures/themes/author/import-example.jsonc index 9a4401ed0..1ab53e35d 100644 --- a/tests/fixtures/themes/author/import-example.jsonc +++ b/tests/fixtures/themes/author/import-example.jsonc @@ -1,19 +1,19 @@ // Invented local test data. Not a third-party theme or redistribution license. { - "name": "Manual SQL import", - "author": "Fixture author — review rights separately", - "type": "dark", - "include": "./must-not-be-read.json", - "colors": { - "editor.background": "#101820", - "editor.foreground": "#ddeeff", - "editor.selectionBackground": "#33557780", - }, - "tokenColors": [ - { - "scope": "keyword.control.sql", - "settings": { "foreground": "#91b6ff", "fontStyle": "italic" }, + "name": "Manual SQL import", + "author": "Fixture author — review rights separately", + "type": "dark", + "include": "./must-not-be-read.json", + "colors": { + "editor.background": "#101820", + "editor.foreground": "#ddeeff", + "editor.selectionBackground": "#33557780", }, - ], - "semanticTokenColors": { "*.readonly": "#ff00ff" }, + "tokenColors": [ + { + "scope": "keyword.control.sql", + "settings": {"foreground": "#91b6ff", "fontStyle": "italic"}, + }, + ], + "semanticTokenColors": {"*.readonly": "#ff00ff"}, } diff --git a/tests/fixtures/themes/manual-registry.mjs b/tests/fixtures/themes/manual-registry.mjs index 9c2029ab6..fc645d82b 100644 --- a/tests/fixtures/themes/manual-registry.mjs +++ b/tests/fixtures/themes/manual-registry.mjs @@ -1,77 +1,182 @@ #!/usr/bin/env node // Isolated manual-test data only. No upstream requests, database or disk writes. -import { createServer } from "node:http"; -import { readFileSync } from "node:fs"; -import { createHash } from "node:crypto"; -import { createInterface } from "node:readline"; +import {createServer} from 'node:http'; +import {readFileSync} from 'node:fs'; +import {createHash} from 'node:crypto'; +import {createInterface} from 'node:readline'; -const family = process.argv[2] ?? "original"; -const port = Number(process.argv[3] ?? "49179"); -if (!["original", "imported"].includes(family) || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Usage: node manual-registry.mjs [original|imported] [loopback-port]"); -const artifacts = new Map(["1.0.0", "2.0.0"].map((version, index) => { - const bytes = readFileSync(new URL(`./author/${family}-v${index + 1}.zip`, import.meta.url)); - return [version, { bytes, sha256: createHash("sha256").update(bytes).digest("hex") }]; -})); -let latest = "1.0.0"; +const family = process.argv[2] ?? 'original'; +const port = Number(process.argv[3] ?? '49179'); +if ( + !['original', 'imported'].includes(family) || + !Number.isInteger(port) || + port < 0 || + port > 65535 +) + throw new Error('Usage: node manual-registry.mjs [original|imported] [loopback-port]'); +const artifacts = new Map( + ['1.0.0', '2.0.0'].map((version, index) => { + const bytes = readFileSync( + new URL(`./author/${family}-v${index + 1}.zip`, import.meta.url), + ); + return [version, {bytes, sha256: createHash('sha256').update(bytes).digest('hex')}]; + }), +); +let latest = '1.0.0'; let tamper = false; let slow = false; -const counts = { "1.0.0": 0, "2.0.0": 0 }; +const counts = {'1.0.0': 0, '2.0.0': 0}; let base; -const total = () => counts["1.0.0"] + counts["2.0.0"]; +const total = () => counts['1.0.0'] + counts['2.0.0']; const detail = () => ({ - id: "fixture-theme", ownerId: "fixture-owner", name: `${family} fixture theme`, description: "Local-only author fixture; not a release or safe published minimum.", author: "Fixture author", repoUrl: "https://example.invalid/theme", homepage: base, - latestVersion: latest, status: "approved", tags: ["blue", "theme"], screenshots: [], featured: false, verified: false, downloads: total(), readmeAvailableLocales: ["en"], readmeLocale: "en", readmeHtml: "

Offline theme fixture

This README request does not increment downloads.

", documentationUrl: null, createdAt: 0, updatedAt: 0, - releases: [...artifacts].map(([version, artifact]) => ({ id: `fixture-${version}`, pluginId: "fixture-theme", version, minRuntimeVersion: "0.24.0", assets: { universal: { url: `${base}/assets/${version}.zip`, sha256: tamper ? "0".repeat(64) : artifact.sha256, size: artifact.bytes.length } }, createdAt: 0, integrity: null })), + id: 'fixture-theme', + ownerId: 'fixture-owner', + name: `${family} fixture theme`, + description: 'Local-only author fixture; not a release or safe published minimum.', + author: 'Fixture author', + repoUrl: 'https://example.invalid/theme', + homepage: base, + latestVersion: latest, + status: 'approved', + tags: ['blue', 'theme'], + screenshots: [], + featured: false, + verified: false, + downloads: total(), + readmeAvailableLocales: ['en'], + readmeLocale: 'en', + readmeHtml: + '

Offline theme fixture

This README request does not increment downloads.

', + documentationUrl: null, + createdAt: 0, + updatedAt: 0, + releases: [...artifacts].map(([version, artifact]) => ({ + id: `fixture-${version}`, + pluginId: 'fixture-theme', + version, + minRuntimeVersion: '0.24.0', + assets: { + universal: { + url: `${base}/assets/${version}.zip`, + sha256: tamper ? '0'.repeat(64) : artifact.sha256, + size: artifact.bytes.length, + }, + }, + createdAt: 0, + integrity: null, + })), }); const server = createServer((request, response) => { - const url = new URL(request.url ?? "/", base); - const path = url.pathname.replace(/\/+$/, ""); - response.setHeader("X-Tabularis-Theme-Fixture", "791"); - const json = (value, status = 200) => { response.writeHead(status, { "Content-Type": "application/json" }); response.end(JSON.stringify(value)); }; - if (request.method !== "GET") return json({ error: "Read-only fixture API; use terminal commands" }, 405); - if (path === "/__fixture/status") return json({ family, latest, counts, total: total(), tamper, slow, pid: process.pid }); - if (path === "/api/kinds") return json({ kinds: [{ key: "driver", label: "Driver", description: null }, { key: "theme", label: "Theme", description: null }] }); - if (path === "/api/plugins") { - const plugins = !url.searchParams.has("kind") || url.searchParams.get("kind") === "theme" ? [detail()] : []; - return json({ total: plugins.length, page: 1, limit: 100, plugins, facets: { categories: [], kinds: [] } }); - } - if (path === "/api/plugins/fixture-theme") return json(detail()); - const integrity = path.match(/^\/api\/plugins\/fixture-theme\/releases\/([^/]+)\/integrity$/); - if (integrity && artifacts.has(integrity[1])) return json({ slug: "fixture-theme", version: integrity[1], assets: {} }); - const pinned = path.match(/^\/api\/plugins\/fixture-theme\/releases\/([^/]+)$/); - if (path === "/api/plugins/fixture-theme/latest" || pinned) { - const version = pinned?.[1] ?? latest; - if (!artifacts.has(version)) return json({ error: "Unknown fixture release" }, 404); - counts[version]++; // Same request-count rule, with or without redirect=1. - console.log(JSON.stringify({ tracked: request.url, counts, total: total() })); - if (url.searchParams.get("redirect") === "1") { response.writeHead(302, { Location: `${base}/assets/${version}.zip` }); return response.end(); } - return json({ version, url: `${base}/assets/${version}.zip` }); - } - const asset = path.match(/^\/assets\/([^/]+)\.zip$/); - if (asset && artifacts.has(asset[1])) { - const { bytes } = artifacts.get(asset[1]); response.writeHead(200, { "Content-Type": "application/zip", "Content-Length": bytes.length }); - if (!slow) return response.end(bytes); - let offset = 0; - const timer = setInterval(() => { const end = Math.min(offset + 64, bytes.length); response.write(bytes.subarray(offset, end)); offset = end; if (offset === bytes.length) { clearInterval(timer); response.end(); } }, 100); - response.on("close", () => clearInterval(timer)); return; - } - return json({ error: "Unknown local fixture route" }, 404); + const url = new URL(request.url ?? '/', base); + const path = url.pathname.replace(/\/+$/, ''); + response.setHeader('X-Tabularis-Theme-Fixture', '791'); + const json = (value, status = 200) => { + response.writeHead(status, {'Content-Type': 'application/json'}); + response.end(JSON.stringify(value)); + }; + if (request.method !== 'GET') + return json({error: 'Read-only fixture API; use terminal commands'}, 405); + if (path === '/__fixture/status') + return json({family, latest, counts, total: total(), tamper, slow, pid: process.pid}); + if (path === '/api/kinds') + return json({ + kinds: [ + {key: 'driver', label: 'Driver', description: null}, + {key: 'theme', label: 'Theme', description: null}, + ], + }); + if (path === '/api/plugins') { + const plugins = + !url.searchParams.has('kind') || url.searchParams.get('kind') === 'theme' + ? [detail()] + : []; + return json({ + total: plugins.length, + page: 1, + limit: 100, + plugins, + facets: {categories: [], kinds: []}, + }); + } + if (path === '/api/plugins/fixture-theme') return json(detail()); + const integrity = path.match(/^\/api\/plugins\/fixture-theme\/releases\/([^/]+)\/integrity$/); + if (integrity && artifacts.has(integrity[1])) + return json({slug: 'fixture-theme', version: integrity[1], assets: {}}); + const pinned = path.match(/^\/api\/plugins\/fixture-theme\/releases\/([^/]+)$/); + if (path === '/api/plugins/fixture-theme/latest' || pinned) { + const version = pinned?.[1] ?? latest; + if (!artifacts.has(version)) return json({error: 'Unknown fixture release'}, 404); + counts[version]++; // Same request-count rule, with or without redirect=1. + console.log(JSON.stringify({tracked: request.url, counts, total: total()})); + if (url.searchParams.get('redirect') === '1') { + response.writeHead(302, {Location: `${base}/assets/${version}.zip`}); + return response.end(); + } + return json({version, url: `${base}/assets/${version}.zip`}); + } + const asset = path.match(/^\/assets\/([^/]+)\.zip$/); + if (asset && artifacts.has(asset[1])) { + const {bytes} = artifacts.get(asset[1]); + response.writeHead(200, { + 'Content-Type': 'application/zip', + 'Content-Length': bytes.length, + }); + if (!slow) return response.end(bytes); + let offset = 0; + const timer = setInterval(() => { + const end = Math.min(offset + 64, bytes.length); + response.write(bytes.subarray(offset, end)); + offset = end; + if (offset === bytes.length) { + clearInterval(timer); + response.end(); + } + }, 100); + response.on('close', () => clearInterval(timer)); + return; + } + return json({error: 'Unknown local fixture route'}, 404); }); -server.listen(port, "127.0.0.1", () => { - base = `http://127.0.0.1:${server.address().port}`; - console.log(JSON.stringify({ fixture: 791, base, family, pid: process.pid, commands: "next | first | tamper | slow | counts | quit" })); +server.listen(port, '127.0.0.1', () => { + base = `http://127.0.0.1:${server.address().port}`; + console.log( + JSON.stringify({ + fixture: 791, + base, + family, + pid: process.pid, + commands: 'next | first | tamper | slow | counts | quit', + }), + ); }); -const input = createInterface({ input: process.stdin }); -input.on("line", (line) => { - switch (line.trim()) { - case "next": latest = "2.0.0"; break; - case "first": latest = "1.0.0"; break; - case "tamper": tamper = !tamper; break; - case "slow": slow = !slow; break; - case "counts": break; - case "quit": server.close(); input.close(); return; - default: console.log("Commands: next | first | tamper | slow | counts | quit"); return; - } - console.log(JSON.stringify({ family, latest, counts, tamper, slow })); +const input = createInterface({input: process.stdin}); +input.on('line', (line) => { + switch (line.trim()) { + case 'next': + latest = '2.0.0'; + break; + case 'first': + latest = '1.0.0'; + break; + case 'tamper': + tamper = !tamper; + break; + case 'slow': + slow = !slow; + break; + case 'counts': + break; + case 'quit': + server.close(); + input.close(); + return; + default: + console.log('Commands: next | first | tamper | slow | counts | quit'); + return; + } + console.log(JSON.stringify({family, latest, counts, tamper, slow})); +}); +process.on('SIGTERM', () => { + server.close(); + input.close(); }); -process.on("SIGTERM", () => { server.close(); input.close(); }); diff --git a/tests/fixtures/themes/pre-feature/README.md b/tests/fixtures/themes/pre-feature/README.md index 6e448be6b..8a3695b08 100644 --- a/tests/fixtures/themes/pre-feature/README.md +++ b/tests/fixtures/themes/pre-feature/README.md @@ -16,7 +16,7 @@ is not an old packaged application or platform GUI test. Run from the repository root: ```sh -pnpm exec vitest run tests/contexts/ThemeDowngrade.test.tsx +pnpm exec vitest --config packages/web-ui/vitest.config.ts run packages/web-ui/tests/contexts/ThemeDowngrade.test.tsx ``` ## Result and release implication @@ -27,7 +27,7 @@ its offline fallback, and then its save effect writes that fallback to The tests deliberately assert this **hazard**. A green test is not a successful downgrade-compatibility claim. The known builtin `monokai` retains its identity. The new provider's no-write fallback/restore behavior is separately tested in -`tests/contexts/ThemeProvider.test.tsx`. +`packages/web-ui/tests/contexts/ThemeProvider.test.tsx`. The new standalone snapshot container also fails the old native `Theme` shape, rather than silently replaying different editor rules. Historical standalone diff --git a/tests/fixtures/themes/pre-feature/themes/themeRegistry.ts b/tests/fixtures/themes/pre-feature/themes/themeRegistry.ts index e38398acc..2d4b125c7 100644 --- a/tests/fixtures/themes/pre-feature/themes/themeRegistry.ts +++ b/tests/fixtures/themes/pre-feature/themes/themeRegistry.ts @@ -1,2 +1,2 @@ // Golden-checked legacy/builtin dependency; the provider fixture itself is frozen. -export { themeRegistry } from "../../../../../src/themes/themeRegistry"; +export { themeRegistry } from "../../../../../packages/web-ui/src/themes/themeRegistry"; diff --git a/tests/fixtures/themes/pre-feature/themes/themeUtils.ts b/tests/fixtures/themes/pre-feature/themes/themeUtils.ts index d8156e4bc..17d477682 100644 --- a/tests/fixtures/themes/pre-feature/themes/themeUtils.ts +++ b/tests/fixtures/themes/pre-feature/themes/themeUtils.ts @@ -1 +1 @@ -export { applyThemeToCSS } from "../../../../../src/themes/themeUtils"; +export { applyThemeToCSS } from "../../../../../packages/web-ui/src/themes/themeUtils"; diff --git a/tests/fixtures/themes/pre-feature/types/theme.ts b/tests/fixtures/themes/pre-feature/types/theme.ts index 9752604f7..9b8f43cb5 100644 --- a/tests/fixtures/themes/pre-feature/types/theme.ts +++ b/tests/fixtures/themes/pre-feature/types/theme.ts @@ -1 +1 @@ -export type { Theme, ThemeSettings } from "../../../../../src/types/theme"; +export type { Theme, ThemeSettings } from "../../../../../packages/web-ui/src/types/theme"; diff --git a/tests/fixtures/themes/pre-feature/utils/systemTheme.ts b/tests/fixtures/themes/pre-feature/utils/systemTheme.ts index 0bffd318b..87205f1e7 100644 --- a/tests/fixtures/themes/pre-feature/utils/systemTheme.ts +++ b/tests/fixtures/themes/pre-feature/utils/systemTheme.ts @@ -1 +1 @@ -export { isLinuxDesktop } from "../../../../../src/utils/systemTheme"; +export { isLinuxDesktop } from "../../../../../packages/web-ui/src/utils/systemTheme"; diff --git a/tests/fixtures/themes/pre-feature/utils/themeManagement.ts b/tests/fixtures/themes/pre-feature/utils/themeManagement.ts index 8cdf67306..56e5a6898 100644 --- a/tests/fixtures/themes/pre-feature/utils/themeManagement.ts +++ b/tests/fixtures/themes/pre-feature/utils/themeManagement.ts @@ -1 +1 @@ -export { getSystemThemeId, resolveActiveThemeId } from "../../../../../src/utils/themeManagement"; +export { getSystemThemeId, resolveActiveThemeId } from "../../../../../packages/web-ui/src/utils/themeManagement"; diff --git a/tests/fixtures/themes/selection-shapes.json b/tests/fixtures/themes/selection-shapes.json index c4384927a..99dd36bc4 100644 --- a/tests/fixtures/themes/selection-shapes.json +++ b/tests/fixtures/themes/selection-shapes.json @@ -1,7 +1,7 @@ [ { "name": "static builtin with inherited editor", - "config": { "theme": "tabularis-dark", "editorTheme": null } + "config": {"theme": "tabularis-dark", "editorTheme": null} }, { "name": "system appearance with independent editor", @@ -23,7 +23,7 @@ }, { "name": "partial non-theme save", - "config": { "fontFamily": "System", "fontSize": 14 } + "config": {"fontFamily": "System", "fontSize": 14} }, { "name": "old configuration without theme settings", diff --git a/tests/fixtures/themes/snapshot-editor-vectors.json b/tests/fixtures/themes/snapshot-editor-vectors.json index 359812bd3..bb5d69cbe 100644 --- a/tests/fixtures/themes/snapshot-editor-vectors.json +++ b/tests/fixtures/themes/snapshot-editor-vectors.json @@ -1,18 +1,101 @@ [ - {"name":"minimal","valid":true,"editor":{"base":"vs-dark","inherit":true}}, - {"name":"nullable legacy fields","valid":true,"editor":{"base":"hc-black","inherit":false,"themeName":null,"rules":null,"colors":null}}, - {"name":"empty reset and aliases","valid":true,"editor":{"base":"vs","inherit":true,"themeName":"","rules":[{"token":"string.sql","foreground":"","background":null,"fontStyle":"","font_style":null}]}}, - {"name":"hex alpha","valid":true,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":"string.sql","foreground":"#1234","background":"12345678"}]}}, - {"name":"opaque editor metadata","valid":true,"editor":{"base":"vs","inherit":true,"opaque":{"kept":true}}}, - {"name":"missing base","valid":false,"editor":{"inherit":true}}, - {"name":"missing inherit","valid":false,"editor":{"base":"vs-dark"}}, - {"name":"wrong inherit type","valid":false,"editor":{"base":"vs-dark","inherit":"true"}}, - {"name":"unsupported base","valid":false,"editor":{"base":"hc-light","inherit":true}}, - {"name":"named asset","valid":false,"editor":{"base":"vs-dark","inherit":true,"themeName":"nord"}}, - {"name":"malformed foreground","valid":false,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":"string.sql","foreground":"red"}]}}, - {"name":"malformed background","valid":false,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":"string.sql","background":"12345"}]}}, - {"name":"wrong token type","valid":false,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":3}]}}, - {"name":"wrong color type","valid":false,"editor":{"base":"vs-dark","inherit":true,"colors":{"editor.background":false}}}, - {"name":"wrong camel style type","valid":false,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":"string.sql","fontStyle":true}]}}, - {"name":"wrong native style type","valid":false,"editor":{"base":"vs-dark","inherit":true,"rules":[{"token":"string.sql","font_style":true}]}} + {"name": "minimal", "valid": true, "editor": {"base": "vs-dark", "inherit": true}}, + { + "name": "nullable legacy fields", + "valid": true, + "editor": { + "base": "hc-black", + "inherit": false, + "themeName": null, + "rules": null, + "colors": null + } + }, + { + "name": "empty reset and aliases", + "valid": true, + "editor": { + "base": "vs", + "inherit": true, + "themeName": "", + "rules": [ + { + "token": "string.sql", + "foreground": "", + "background": null, + "fontStyle": "", + "font_style": null + } + ] + } + }, + { + "name": "hex alpha", + "valid": true, + "editor": { + "base": "vs-dark", + "inherit": true, + "rules": [{"token": "string.sql", "foreground": "#1234", "background": "12345678"}] + } + }, + { + "name": "opaque editor metadata", + "valid": true, + "editor": {"base": "vs", "inherit": true, "opaque": {"kept": true}} + }, + {"name": "missing base", "valid": false, "editor": {"inherit": true}}, + {"name": "missing inherit", "valid": false, "editor": {"base": "vs-dark"}}, + {"name": "wrong inherit type", "valid": false, "editor": {"base": "vs-dark", "inherit": "true"}}, + {"name": "unsupported base", "valid": false, "editor": {"base": "hc-light", "inherit": true}}, + { + "name": "named asset", + "valid": false, + "editor": {"base": "vs-dark", "inherit": true, "themeName": "nord"} + }, + { + "name": "malformed foreground", + "valid": false, + "editor": { + "base": "vs-dark", + "inherit": true, + "rules": [{"token": "string.sql", "foreground": "red"}] + } + }, + { + "name": "malformed background", + "valid": false, + "editor": { + "base": "vs-dark", + "inherit": true, + "rules": [{"token": "string.sql", "background": "12345"}] + } + }, + { + "name": "wrong token type", + "valid": false, + "editor": {"base": "vs-dark", "inherit": true, "rules": [{"token": 3}]} + }, + { + "name": "wrong color type", + "valid": false, + "editor": {"base": "vs-dark", "inherit": true, "colors": {"editor.background": false}} + }, + { + "name": "wrong camel style type", + "valid": false, + "editor": { + "base": "vs-dark", + "inherit": true, + "rules": [{"token": "string.sql", "fontStyle": true}] + } + }, + { + "name": "wrong native style type", + "valid": false, + "editor": { + "base": "vs-dark", + "inherit": true, + "rules": [{"token": "string.sql", "font_style": true}] + } + } ] diff --git a/tests/hooks/useJsonEditorActivity.test.ts b/tests/hooks/useJsonEditorActivity.test.ts deleted file mode 100644 index 9ba4a2df4..000000000 --- a/tests/hooks/useJsonEditorActivity.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import {act, renderHook} from '@testing-library/react'; -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {WebviewWindow} from '@tauri-apps/api/webviewWindow'; -import {useJsonEditorActivity} from '@/hooks/useJsonEditorActivity'; - -vi.mock('@tauri-apps/api/webviewWindow', () => ({WebviewWindow: {getByLabel: vi.fn()}})); - -describe('editable JSON window activity', () => { - beforeEach(() => { - vi.mocked(WebviewWindow.getByLabel).mockReset(); - }); - - it('blocks while opening and releases on save, close and unmount', async () => { - const unlisten = vi.fn(); - let close!: () => void; - vi.mocked(WebviewWindow.getByLabel).mockResolvedValue({ - once: vi.fn((_event, handler) => { - close = handler; - return Promise.resolve(unlisten); - }), - } as unknown as WebviewWindow); - const {result, unmount} = renderHook(useJsonEditorActivity); - let end!: () => void; - act(() => { - end = result.current.begin(); - }); - expect(result.current.isEditing()).toBe(true); - await act(async () => { - await result.current.watch('first', end); - }); - expect(WebviewWindow.getByLabel).toHaveBeenCalledWith('json-viewer-first'); - act(() => result.current.release('first')); - expect(result.current.count).toBe(0); - expect(unlisten).toHaveBeenCalledOnce(); - act(() => { - end = result.current.begin(); - }); - await act(async () => { - await result.current.watch('second', end); - }); - act(() => close()); - expect(result.current.isEditing()).toBe(false); - act(() => { - end = result.current.begin(); - }); - await act(async () => { - await result.current.watch('third', end); - }); - unmount(); - expect(unlisten).toHaveBeenCalledTimes(3); - expect(result.current.isEditing()).toBe(false); - }); - - it('unsubscribes a listener that resolves after unmount', async () => { - let finish!: (unlisten: () => void) => void; - const unlisten = vi.fn(); - vi.mocked(WebviewWindow.getByLabel).mockResolvedValue({ - once: () => - new Promise<() => void>((resolve) => { - finish = resolve; - }), - } as unknown as WebviewWindow); - const {result, unmount} = renderHook(useJsonEditorActivity); - let end!: () => void; - act(() => { - end = result.current.begin(); - }); - let watching!: Promise; - await act(async () => { - watching = result.current.watch('late', end); - }); - unmount(); - await act(async () => { - finish(unlisten); - await watching; - }); - expect(unlisten).toHaveBeenCalledOnce(); - }); - - it('releases a window that closed during opening', async () => { - vi.mocked(WebviewWindow.getByLabel).mockResolvedValue(null); - const {result} = renderHook(useJsonEditorActivity); - let end!: () => void; - act(() => { - end = result.current.begin(); - }); - await act(async () => { - await result.current.watch('closed', end); - }); - expect(result.current.count).toBe(0); - }); - - it('releases a window that closes before its listener is registered', async () => { - const unlisten = vi.fn(); - vi.mocked(WebviewWindow.getByLabel) - .mockResolvedValueOnce({ - once: vi.fn().mockResolvedValue(unlisten), - } as unknown as WebviewWindow) - .mockResolvedValueOnce(null); - const {result} = renderHook(useJsonEditorActivity); - let end!: () => void; - act(() => { - end = result.current.begin(); - }); - await act(async () => { - await result.current.watch('closing', end); - }); - expect(result.current.isEditing()).toBe(false); - expect(unlisten).toHaveBeenCalledOnce(); - }); - - it('cleans up a stale listener after the same window is reopened', async () => { - let registerFirst!: (unlisten: () => void) => void; - let staleClose!: () => void; - const staleUnlisten = vi.fn(); - const currentUnlisten = vi.fn(); - const once = vi - .fn() - .mockImplementationOnce((_event, handler) => { - staleClose = handler; - return new Promise<() => void>((resolve) => { - registerFirst = resolve; - }); - }) - .mockResolvedValue(currentUnlisten); - vi.mocked(WebviewWindow.getByLabel).mockResolvedValue({once} as unknown as WebviewWindow); - const {result, unmount} = renderHook(useJsonEditorActivity); - let end!: () => void; - act(() => { - end = result.current.begin(); - }); - let first!: Promise; - await act(async () => { - first = result.current.watch('same', end); - }); - act(() => { - end = result.current.begin(); - }); - await act(async () => { - await result.current.watch('same', end); - }); - act(() => staleClose()); - expect(result.current.count).toBe(1); - await act(async () => { - registerFirst(staleUnlisten); - await first; - }); - expect(staleUnlisten).toHaveBeenCalledOnce(); - expect(result.current.count).toBe(1); - unmount(); - expect(currentUnlisten).toHaveBeenCalledOnce(); - }); -}); diff --git a/tests/hooks/useReferencedRecord.test.ts b/tests/hooks/useReferencedRecord.test.ts deleted file mode 100644 index 4990c9025..000000000 --- a/tests/hooks/useReferencedRecord.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import {describe, expect, it, vi, beforeEach} from 'vitest'; - -const invokeMock = vi.hoisted(() => vi.fn()); -vi.mock('@tauri-apps/api/core', () => ({ - invoke: invokeMock, -})); - -// quoteTableRef and the FK helpers are pure string utils — no mocks needed. -import {fetchReferencedRecord, type FetchReferencedRecordParams} from '@/hooks/useReferencedRecord'; -import type {ForeignKey} from '@/types/schema'; - -const fk: ForeignKey = { - name: 'fk_users', - column_name: 'user_id', - ref_table: 'users', - ref_column: 'id', -}; - -const baseParams: Omit = { - connectionId: 'conn-1', - fk, - value: 42, - driver: 'postgres', - schema: 'public', - sourceColumnType: 'integer', -}; - -describe('fetchReferencedRecord database threading', () => { - beforeEach(() => { - vi.clearAllMocks(); - invokeMock.mockResolvedValue({columns: [], rows: [], affected_rows: 0}); - }); - - it('passes the database override to execute_query when set', async () => { - await fetchReferencedRecord({...baseParams, database: 'analytics'}); - - expect(invokeMock).toHaveBeenCalledWith( - 'execute_query', - expect.objectContaining({database: 'analytics'}), - ); - }); - - it('omits database from execute_query when not set (backward-compatible)', async () => { - await fetchReferencedRecord({...baseParams}); - - const callArgs = invokeMock.mock.calls[0][1] as Record; - expect(callArgs).not.toHaveProperty('database'); - }); - - it('omits database when set to null', async () => { - await fetchReferencedRecord({...baseParams, database: null}); - - const callArgs = invokeMock.mock.calls[0][1] as Record; - expect(callArgs).not.toHaveProperty('database'); - }); - - it('omits database when set to empty string', async () => { - await fetchReferencedRecord({...baseParams, database: ''}); - - const callArgs = invokeMock.mock.calls[0][1] as Record; - expect(callArgs).not.toHaveProperty('database'); - }); -}); diff --git a/tests/utils/credentials.test.ts b/tests/utils/credentials.test.ts deleted file mode 100644 index 6aa349a9e..000000000 --- a/tests/utils/credentials.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import {describe, it, expect, vi, beforeEach} from 'vitest'; -import {invoke} from '@tauri-apps/api/core'; -import {fetchConnectionWithCredentials} from '@/utils/credentials'; - -vi.mock('@tauri-apps/api/core', () => ({ - invoke: vi.fn(), -})); - -describe('credentials', () => { - beforeEach(() => { - vi.mocked(invoke).mockReset(); - }); - - describe('fetchConnectionWithCredentials', () => { - it("invoca find_connection_by_id con l'id fornito", async () => { - const mockConn = { - id: 'abc', - name: 'Test', - params: {driver: 'mysql', password: 'secret', database: 'mydb'}, - }; - vi.mocked(invoke).mockResolvedValueOnce(mockConn); - - const result = await fetchConnectionWithCredentials('abc'); - - expect(invoke).toHaveBeenCalledWith('get_connection_by_id', {id: 'abc'}); - expect(result).toEqual(mockConn); - }); - - it('propaga gli errori del backend', async () => { - vi.mocked(invoke).mockRejectedValueOnce('Connection not found'); - - await expect(fetchConnectionWithCredentials('unknown')).rejects.toBe( - 'Connection not found', - ); - }); - }); -}); diff --git a/tests/utils/dataImportFile.test.ts b/tests/utils/dataImportFile.test.ts deleted file mode 100644 index 701cec94d..000000000 --- a/tests/utils/dataImportFile.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {stat, readTextFile} from '@tauri-apps/plugin-fs'; -import {DATA_IMPORT_FILE_LIMIT, readDataImportFile} from '@/utils/dataImportFile'; -vi.mock('@tauri-apps/plugin-fs', () => ({stat: vi.fn(), readTextFile: vi.fn()})); -const info = (size: number, isFile = true) => ({size, isFile}) as Awaited>; -describe('readDataImportFile', () => { - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(stat).mockResolvedValue(info(10)); - vi.mocked(readTextFile).mockResolvedValue('a,b\n1,2'); - }); - it.each(['csv', 'tsv', 'json', 'md', 'CSV'])('reads supported %s files', async (ext) => { - expect(await readDataImportFile(`/tmp/data.${ext}`)).toBe('a,b\n1,2'); - }); - it('rejects oversized files before reading them', async () => { - vi.mocked(stat).mockResolvedValue(info(DATA_IMPORT_FILE_LIMIT + 1)); - await expect(readDataImportFile('/tmp/data.csv')).rejects.toMatchObject({code: 'tooLarge'}); - expect(readTextFile).not.toHaveBeenCalled(); - }); - it('accepts the exact size boundary', async () => { - vi.mocked(stat).mockResolvedValue(info(DATA_IMPORT_FILE_LIMIT)); - await expect(readDataImportFile('/tmp/data.csv')).resolves.toBe('a,b\n1,2'); - }); - it('rechecks UTF-8 bytes if the file grows during the read', async () => { - vi.mocked(readTextFile).mockResolvedValue( - '界'.repeat(Math.floor(DATA_IMPORT_FILE_LIMIT / 3) + 1), - ); - await expect(readDataImportFile('/tmp/data.csv')).rejects.toMatchObject({code: 'tooLarge'}); - }); - it('rejects unsupported extensions without filesystem access', async () => { - await expect(readDataImportFile('/tmp/data.exe')).rejects.toMatchObject({ - code: 'unsupported', - }); - expect(stat).not.toHaveBeenCalled(); - }); - it('rejects directories', async () => { - vi.mocked(stat).mockResolvedValue(info(1, false)); - await expect(readDataImportFile('/tmp/directory.csv')).rejects.toMatchObject({ - code: 'notFile', - }); - expect(readTextFile).not.toHaveBeenCalled(); - }); - it.each(['stat', 'read'])('propagates %s errors', async (operation) => { - vi.mocked(operation === 'stat' ? stat : readTextFile).mockRejectedValue( - new Error('Permission denied'), - ); - await expect(readDataImportFile('/tmp/data.csv')).rejects.toThrow('Permission denied'); - }); -}); diff --git a/tests/utils/queryNotification.test.ts b/tests/utils/queryNotification.test.ts deleted file mode 100644 index cef564efc..000000000 --- a/tests/utils/queryNotification.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import { - isPermissionGranted, - requestPermission, - sendNotification, -} from '@tauri-apps/plugin-notification'; - -const getCurrentWindow = vi.fn(); - -vi.mock('@tauri-apps/api/window', () => ({ - getCurrentWindow, -})); - -const CONTENT = {title: 'Query finished', body: 'tab · 25.00 s'}; - -async function importQueryNotification() { - return await import('@/utils/queryNotification'); -} - -describe('queryNotification', () => { - beforeEach(() => { - vi.resetAllMocks(); - vi.resetModules(); - }); - - describe('shouldNotifyQueryFinished', () => { - it('does not notify when the window is focused', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 30000, - windowFocused: true, - }), - ).toBe(false); - }); - - it('does not notify when the setting is disabled', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: false, - thresholdSec: 20, - durationMs: 30000, - windowFocused: false, - }), - ).toBe(false); - }); - - it('does not notify below the threshold', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 19999, - windowFocused: false, - }), - ).toBe(false); - }); - - it('notifies at the threshold', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 20000, - windowFocused: false, - }), - ).toBe(true); - }); - - it('notifies above the threshold', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 60000, - windowFocused: false, - }), - ).toBe(true); - }); - - it('treats an undefined enabled setting as on', async () => { - const {shouldNotifyQueryFinished} = await importQueryNotification(); - expect( - shouldNotifyQueryFinished({ - enabled: undefined, - thresholdSec: 20, - durationMs: 30000, - windowFocused: false, - }), - ).toBe(true); - }); - - it.each([undefined, 0, -5, Number.NaN])( - 'falls back to the default 20s threshold when thresholdSec is %s', - async (thresholdSec) => { - const {shouldNotifyQueryFinished, DEFAULT_NOTIFY_THRESHOLD_SEC} = - await importQueryNotification(); - - expect(DEFAULT_NOTIFY_THRESHOLD_SEC).toBe(20); - // Below 20s: no notification even with a broken threshold value. - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec, - durationMs: 19999, - windowFocused: false, - }), - ).toBe(false); - // At 20s the default threshold applies. - expect( - shouldNotifyQueryFinished({ - enabled: true, - thresholdSec, - durationMs: 20000, - windowFocused: false, - }), - ).toBe(true); - }, - ); - }); - - describe('notifyQueryFinished', () => { - it('sends a notification when the window is unfocused and the query ran long', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockResolvedValue(false), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(true); - vi.mocked(sendNotification).mockResolvedValue(undefined); - - const {notifyQueryFinished} = await importQueryNotification(); - - await notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 25000, - content: CONTENT, - }); - - expect(getCurrentWindow).toHaveBeenCalledTimes(1); - expect(sendNotification).toHaveBeenCalledTimes(1); - expect(sendNotification).toHaveBeenCalledWith({ - title: 'Query finished', - body: 'tab · 25.00 s', - }); - expect(requestPermission).not.toHaveBeenCalled(); - }); - - it('does not send when the window is focused', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockResolvedValue(true), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(true); - - const {notifyQueryFinished} = await importQueryNotification(); - - await notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 25000, - content: CONTENT, - }); - - expect(sendNotification).not.toHaveBeenCalled(); - expect(requestPermission).not.toHaveBeenCalled(); - }); - - it('does not send when the query finished below the threshold', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockResolvedValue(false), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(true); - - const {notifyQueryFinished} = await importQueryNotification(); - - await notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 2000, - content: CONTENT, - }); - - expect(sendNotification).not.toHaveBeenCalled(); - expect(requestPermission).not.toHaveBeenCalled(); - }); - - it('requests permission when not granted and does not send when denied', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockResolvedValue(false), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(false); - vi.mocked(requestPermission).mockResolvedValue('denied'); - - const {notifyQueryFinished} = await importQueryNotification(); - - await notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 25000, - content: CONTENT, - }); - - expect(requestPermission).toHaveBeenCalledTimes(1); - expect(sendNotification).not.toHaveBeenCalled(); - }); - - it('sends after permission is granted on request', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockResolvedValue(false), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(false); - vi.mocked(requestPermission).mockResolvedValue('granted'); - vi.mocked(sendNotification).mockResolvedValue(undefined); - - const {notifyQueryFinished} = await importQueryNotification(); - - await notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 25000, - content: CONTENT, - }); - - expect(requestPermission).toHaveBeenCalledTimes(1); - expect(sendNotification).toHaveBeenCalledTimes(1); - }); - - it('treats a rejecting focus probe as unfocused and never throws', async () => { - getCurrentWindow.mockReturnValue({ - isFocused: vi.fn().mockRejectedValue(new Error('boom')), - }); - vi.mocked(isPermissionGranted).mockResolvedValue(true); - vi.mocked(sendNotification).mockResolvedValue(undefined); - - const {notifyQueryFinished} = await importQueryNotification(); - - await expect( - notifyQueryFinished({ - enabled: true, - thresholdSec: 20, - durationMs: 25000, - content: CONTENT, - }), - ).resolves.toBeUndefined(); - - expect(sendNotification).toHaveBeenCalledTimes(1); - }); - }); -}); diff --git a/tests/utils/startupConfig.test.ts b/tests/utils/startupConfig.test.ts deleted file mode 100644 index 44cc1add2..000000000 --- a/tests/utils/startupConfig.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {describe, expect, it, vi} from 'vitest'; -import {invoke} from '@tauri-apps/api/core'; -import {loadStartupConfig} from '@/utils/startupConfig'; - -describe('loadStartupConfig', () => { - it('coalesces bootstrap readers without caching subsequent settings edits', async () => { - vi.mocked(invoke) - .mockResolvedValueOnce({language: 'it'}) - .mockResolvedValueOnce({language: 'en'}); - const first = loadStartupConfig(); - expect(loadStartupConfig()).toBe(first); - expect(await first).toEqual({language: 'it'}); - expect(await loadStartupConfig()).toEqual({language: 'en'}); - expect(invoke).toHaveBeenCalledTimes(2); - }); - - it('allows retry after a failed read', async () => { - vi.mocked(invoke).mockRejectedValueOnce(new Error('unavailable')).mockResolvedValueOnce({}); - await expect(loadStartupConfig()).rejects.toThrow('unavailable'); - await expect(loadStartupConfig()).resolves.toEqual({}); - }); -}); diff --git a/tests/utils/supportPrompt.test.ts b/tests/utils/supportPrompt.test.ts deleted file mode 100644 index a87b87790..000000000 --- a/tests/utils/supportPrompt.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import { - SUPPORT_PROMPT_DISMISSED_KEY, - dismissSupportPrompt, - isSupportPromptDismissed, - subscribeToSupportPrompt, -} from '@/utils/supportPrompt'; - -describe('supportPrompt', () => { - beforeEach(() => localStorage.clear()); - afterEach(() => vi.restoreAllMocks()); - - it('defaults to visible and only treats true as dismissed', () => { - expect(isSupportPromptDismissed()).toBe(false); - for (const value of ['false', '', 'invalid']) { - localStorage.setItem(SUPPORT_PROMPT_DISMISSED_KEY, value); - expect(isSupportPromptDismissed()).toBe(false); - } - dismissSupportPrompt(); - expect(isSupportPromptDismissed()).toBe(true); - }); - - it('handles unavailable storage reads without breaking the changelog', () => { - vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { - throw new Error('Storage unavailable'); - }); - expect(isSupportPromptDismissed()).toBe(false); - }); - - it('persists dismissal before notifying local subscribers and unsubscribes', () => { - const listener = vi.fn(() => expect(isSupportPromptDismissed()).toBe(true)); - const unsubscribe = subscribeToSupportPrompt(listener); - try { - dismissSupportPrompt(); - expect(listener).toHaveBeenCalledOnce(); - } finally { - unsubscribe(); - } - dismissSupportPrompt(); - expect(listener).toHaveBeenCalledOnce(); - }); - - it('notifies on relevant cross-window changes and clearing storage only', () => { - const listener = vi.fn(); - const unsubscribe = subscribeToSupportPrompt(listener); - try { - window.dispatchEvent(new StorageEvent('storage', {key: 'unrelated'})); - expect(listener).not.toHaveBeenCalled(); - window.dispatchEvent(new StorageEvent('storage', {key: SUPPORT_PROMPT_DISMISSED_KEY})); - window.dispatchEvent(new StorageEvent('storage', {key: null})); - expect(listener).toHaveBeenCalledTimes(2); - } finally { - unsubscribe(); - } - window.dispatchEvent(new StorageEvent('storage', {key: SUPPORT_PROMPT_DISMISSED_KEY})); - expect(listener).toHaveBeenCalledTimes(2); - }); - - it('propagates write failures without notifying subscribers', () => { - vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { - throw new Error('Storage unavailable'); - }); - const listener = vi.fn(); - const unsubscribe = subscribeToSupportPrompt(listener); - try { - expect(dismissSupportPrompt).toThrow('Storage unavailable'); - expect(listener).not.toHaveBeenCalled(); - } finally { - unsubscribe(); - } - }); -}); diff --git a/vitest.config.ts b/vitest.config.ts deleted file mode 100644 index 18aa5c6e4..000000000 --- a/vitest.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -import {defineConfig} from 'vitest/config'; -import react from '@vitejs/plugin-react'; -import path from 'path'; - -export default defineConfig({ - plugins: [react()], - resolve: { - alias: { - '@': path.resolve(__dirname, './src'), - }, - }, - test: { - globals: true, - environment: 'jsdom', - setupFiles: ['./tests/setup.ts'], - include: [ - 'tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', - // Workspace packages (packages/*) run their own vitest with a node - // environment via `pnpm --filter test` (see packages.yml). They are - // deliberately not included here: the jsdom environment breaks Node-only - // tests (Vite rewrites `new URL(x, import.meta.url)` against location). - ], - coverage: { - provider: 'v8', - reporter: ['text', 'json', 'html'], - include: ['src/**/*.ts', 'src/**/*.tsx'], - exclude: ['src/**/*.d.ts'], - }, - }, -}); diff --git a/web-ui-project/.gitignore b/web-ui-project/.gitignore new file mode 100644 index 000000000..cc1773947 --- /dev/null +++ b/web-ui-project/.gitignore @@ -0,0 +1 @@ +.runtime/ diff --git a/web-ui-project/README.md b/web-ui-project/README.md new file mode 100644 index 000000000..0e940c05e --- /dev/null +++ b/web-ui-project/README.md @@ -0,0 +1,42 @@ +# Web UI project process + +This directory is the single tracked home for the Web UI parity project. + +## Layout + +- `docs/WEB_UI_PLAN.md`: architecture, milestones, parity matrix, and task loop. +- `docs/WEB_MODE_OPERATIONS.md`: Web CLI, local and remote operation, storage, limitations, plugins, troubleshooting, and upgrades. +- `docs/architecture/decisions/`: accepted Web UI ADRs. +- `docs/WEB_REMOTE_SECURITY.md`: remote threat model and reverse-proxy deployment guide. +- `docs/WEB_MODE_CONTAINERS.md`: Docker images, Docker Compose, Helm chart, and the encrypted container secret store. +- `docs/WEB_MANUAL_PARITY_AUDIT.md`: signed desktop and browser evidence for every feature-matrix row. +- `docs/web-ui-parity.json`: generated command and transport parity inventory. +- `tasks/`: task specifications and the authoritative `PROGRESS.md` ledger. +- `scripts/`: task runner, inventory generator, boundary checker, and allowlist. +- `tests/`: tests for the project tooling. +- `.runtime/`: ignored runner locks, state, and logs created on first execution. + +All durable project files are version-controlled. Runtime logs are intentionally +excluded because they may be large or contain local diagnostic data. + +## Run tasks + +```bash +pnpm web:tasks +``` + +On startup, the runner creates any missing runtime subdirectories. With no task +IDs, it reads the tracked ledger and starts at the first `PENDING` task, then +continues in lexical order. Explicit task IDs remain supported: + +```bash +pnpm web:tasks WEB-091 WEB-092 +``` + +The runner watches the CI run for each pushed task. A failed run starts a +focused Pi repair session, amends the same task commit, pushes with +`--force-with-lease`, and watches the replacement run. The repair limit is +configured with `PI_WEB_UI_CI_REPAIR_ATTEMPTS` and defaults to three. + +Telegram start and finish notifications include the global completed-task +percentage and the completed/total counts from `tasks/PROGRESS.md`. diff --git a/web-ui-project/docs/WEB_E2E_MATRIX.md b/web-ui-project/docs/WEB_E2E_MATRIX.md new file mode 100644 index 000000000..a0f48fb71 --- /dev/null +++ b/web-ui-project/docs/WEB_E2E_MATRIX.md @@ -0,0 +1,41 @@ +# Web UI automated E2E matrix + +WEB-100 runs the built browser application against the real headless Rust server. The suite captures the one-time local bootstrap URL through a fake browser opener, exchanges it for the production HttpOnly session cookie, and uses the same authenticated HTTP RPC and plugin asset paths as the UI. + +## Required matrix + +| Fixture | Browser workflow | Chromium | Firefox | WebKit | +|---|---|---:|---:|---:| +| SQLite | Save and test a real file connection, identify the engine, create/write/read a table | Required | Required | Required | +| PostgreSQL 16 | Save and test a real TCP connection, identify the database, create/write/read a table | Required | Required | Required | +| MySQL 8.4 | Save and test a real TCP connection, identify the database, create/write/read a table | Required | Required | Required | +| External driver plugin | Start a JSON-RPC subprocess, register its manifest, test its connection, execute a query | Required | Required | Required | +| UI extension plugin | Serve an authenticated allowlisted bundle and render its sidebar slot contribution | Required | Required | Required | + +The workflows in this matrix do not depend on browser-specific clipboard, notification, or filesystem permission APIs, so all three engines run equivalent assertions. Chromium is the focused local and pull-request entry point; the CI parity gate runs all projects. + +SSH and Kubernetes tunnel fixtures remain optional because they require deployment-specific credentials and infrastructure. Their tunnel services and event paths retain focused Rust and frontend coverage; they are not silently simulated in this real-database gate. + +## Commands + +Run the required local Chromium gate. The script starts isolated PostgreSQL and MySQL containers, builds the shared UI and Rust binary, and removes the containers and volumes when done: + +```bash +pnpm test:web-e2e +``` + +Install Playwright's browser binaries, then run the full release-browser gate: + +```bash +pnpm exec playwright install chromium firefox webkit +pnpm test:web-e2e:browsers +``` + +CI provides database service containers and sets `TABULARIS_E2E_MANAGED_DATABASES=1`. External fixtures can use the `TABULARIS_E2E_POSTGRES_*`, `TABULARIS_E2E_MYSQL_*`, `TABULARIS_E2E_DATABASE_PASSWORD`, and `TABULARIS_E2E_SQLITE_PATH` environment variables. + +## Isolation and artifacts + +- Runtime configuration, connection persistence, the SQLite database, cookies, traces, screenshots, videos, and HTML reports live under ignored `web-ui-project/.runtime/e2e`. +- Fixture credentials are local disposable values and are never used outside the isolated databases. +- Driver and UI-extension fixtures are copied into the isolated application data directory before the server starts. +- The suite uses one worker so the local session, plugin process, and deterministic database rows cannot race each other. diff --git a/web-ui-project/docs/WEB_MANUAL_PARITY_AUDIT.md b/web-ui-project/docs/WEB_MANUAL_PARITY_AUDIT.md new file mode 100644 index 000000000..9974f5d05 --- /dev/null +++ b/web-ui-project/docs/WEB_MANUAL_PARITY_AUDIT.md @@ -0,0 +1,51 @@ +# Web UI manual parity audit + +- **Task:** WEB-101 +- **Audit date:** 2026-08-22 +- **Reviewed baseline:** `feat/web-ui` at `43eee49f` plus this audit record +- **Reviewer:** Web UI parity reviewer operating in the repository task workflow +- **Result:** PASS + +## Method + +The reviewer traced every row from the feature-parity matrix through the shared React UI, the Tauri and browser adapters, shared Rust application services, and the focused test evidence listed below. The review also exercised the desktop launch smoke, authenticated headless Web startup, the dual-transport contract, browser capability adaptations, packaging checks, resilience checks, and the real-database Chromium matrix. Adapted behavior is accepted only when it preserves the user outcome without granting the browser native host paths or lifecycle authority. + +The sign-off applies to the implementation and documented limitations at this baseline. Environment-dependent SSH and Kubernetes infrastructure is covered by focused adapter and failure-path tests rather than live credentials. Remote TLS termination remains a deployment responsibility as explicitly documented. + +## Signed feature matrix + +| Area | Desktop evidence | Web evidence | Adaptation rationale | Known limitation | Test reference | Reviewer sign-off | +|---|---|---|---|---|---|---| +| Application startup | Default CLI launch still enters the Tauri runtime and loads the shared packaged UI; the isolated desktop smoke reached the application event loop. | `web` bootstraps the same runtime without a WebView, serves the SPA, exposes liveness, negotiates a session, and shuts down cleanly. | A browser process and HTTP server replace the native window while application services and UI assets remain shared. | Automatic browser opening depends on an available system opener; when it fails, the one-time sign-in URL is printed to the terminal. `--no-open` never prints it. | `src-tauri/src/cli.rs`
`src-tauri/src/runtime/tests.rs`
`src-tauri/src/transport/web/tests.rs`
`web-ui-project/scripts/check-web-ui-packaging.test.mjs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Remote access | Desktop remains a local trusted application and does not expose an HTTP listener by default. | Non-loopback access requires password or trusted-proxy authentication, HTTPS public origins, an explicit origin allowlist, secure cookies, rate limits, audit records, and restricted default authorization. | Remote browser access has a larger trust boundary, so equivalent administration is security-scoped rather than implicitly local-admin. | Tabularis does not terminate TLS; a protected reverse proxy and firewall isolation are required. MCP remains denied remotely. | `src-tauri/src/transport/web/tests.rs`
`src-tauri/src/transport/web/rpc_tests.rs`
`web-ui-project/docs/WEB_REMOTE_SECURITY.md` | Approved by Web UI parity reviewer on 2026-08-22 | +| Connections and groups | The shared connections UI uses the typed client over Tauri for CRUD, grouping, tags, ordering, duplication, icons, and encrypted import/export. | The same UI and services run over authenticated RPC; browser files and icons use purpose-bound upload/download tokens. | File pickers are transport-specific, but connection semantics and persisted records are shared. | Browser clients cannot submit arbitrary server paths; plaintext secret export is intentionally rejected. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/connections_tests.rs`
`src-tauri/src/application/connection_files_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| MySQL/PostgreSQL/SQLite | Desktop continues to use the built-in drivers and shared pools through Tauri commands. | The authenticated browser matrix saved, tested, identified, created, wrote, and read real SQLite, PostgreSQL 16, and MySQL 8.4 connections. | Driver and pool implementations stay backend-side; only command transport changes. | The release matrix uses disposable databases and does not certify every server version, extension, or authentication plugin. | `web-ui-project/e2e/tests/web-ui-matrix.spec.ts`
`web-ui-project/docs/WEB_E2E_MATRIX.md`
`packages/web-ui/tests/api/dualTransportContract.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| SSH tunnels and askpass | Native SSH profile management, tunnel startup, progress, and askpass continue through the shared tunnel service and Tauri events. | Authorized loopback sessions receive session-owned prompts and correlated progress over WebSocket and submit answers over RPC. | Browser sessions replace native prompt windows, with ownership and timeout boundaries preventing cross-session answers. | No live SSH host is part of the portable E2E gate; deployment credentials and host-key policy must be validated in the target environment. Remote sessions require the explicit high-risk policy. | `src-tauri/src/application/tunnels_tests.rs`
`packages/web-ui/tests/hooks/useSshAskpass.test.ts`
`src-tauri/src/transport/web/events_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| K8s tunnels | Existing Kubernetes profiles, binary path validation, discovery, tunnel lifecycle, and progress remain available through Tauri. | The same backend operations are exposed to authorized Web sessions with typed RPC and scoped events. | Only progress delivery changes from native events to the session event bus. | Live cluster credentials are not in the portable E2E gate; configured executable and failure diagnostics have deterministic coverage. Remote sessions require the explicit high-risk policy. | `packages/web-ui/tests/components/modals/K8sConnectionsModal.test.tsx`
`src-tauri/src/k8s_tunnel/tests.rs`
`src-tauri/src/application/connections_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Schema explorer | The shared explorer loads databases, schemas, tables, columns, views, materialized views, routines, triggers, keys, and indexes through Tauri. | Identical typed metadata commands run over database-authorized RPC and preserve per-connection selected schemas. | Metadata discovery has no browser-specific semantics, so the UI and application service are identical. | Engine-specific metadata remains bounded by each driver capability and server permissions. | `packages/web-ui/tests/contexts/DatabaseProvider.test.tsx`
`packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| SQL editor | Desktop execution, batch execution, count, explain, cancellation, history, saved queries, and progress use the typed Tauri transport. | The same contracts run over RPC and WebSocket with request-scoped cancellation and session-isolated active connections. | Query behavior is shared; only request and progress transport differ. | Web pages are capped at 10,000 rows and 16 MiB per response and require pagination beyond those limits. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/src/application/queries_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Results/data grid | Shared grid editing, insertion, deletion, referenced records, and BLOB display/save continue through Tauri and native file selection. | The same record service is used over RPC; BLOB uploads, previews, and single-use downloads avoid exposing host paths. | Browser sandbox file semantics require opaque transfer tokens while database mutations remain identical. | Browser BLOB and result transfers retain explicit size limits and downloads depend on browser download handling. | `packages/web-ui/tests/components/ui/DataGrid.test.tsx`
`packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/records_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Multiple result windows | Desktop keeps native secondary windows and Tauri route/event adapters for detached results and JSON views. | Browser mode opens an opaque session route in a tab and synchronizes through the shared route-session host. | A browser tab is the platform-equivalent independent surface and avoids reproducing native window management. | An in-memory detached session shows an explicit expired state after its owner is gone; popup blockers can require user action. | `packages/web-ui/tests/pages/SecondaryWindowPages.test.tsx`
`packages/web-ui/tests/platform/secondaryWindowSessions.test.ts`
`packages/web-ui/tests/platform/tauriCapabilities.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| ER/schema diagram | Desktop opens schema and ER diagrams in native secondary windows and saves through the native dialog. | Browser mode opens the same diagram component at an opaque route and downloads through a token or browser save. | Routes and downloads replace native window and filesystem primitives without changing diagram generation. | Browser tab and download behavior is subject to popup and download policies; no native always-on-top behavior is reproduced. | `packages/web-ui/tests/platform/secondaryWindowSessions.test.ts`
`packages/web-ui/tests/utils/schemaDiagram.test.ts`
`src-tauri/src/application/generic_exports_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Views/routines/triggers | Existing create, inspect, edit, refresh, and drop flows remain in the shared UI over Tauri commands. | Database-authorized RPC routes the same object commands to shared services. | Object DDL and metadata semantics are transport-independent. | Availability and exact DDL support remain driver-capability and database-version dependent, matching desktop behavior. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/tests/postgres_integration/parity_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| User management | Desktop user, grant, privilege, lock, password, create, and drop operations remain available for supporting drivers. | Sensitive database-authorized RPC exposes the same operations and shared validation. | There is no browser-specific workflow change, but authorization remains explicit because these operations are sensitive. | Feature availability follows driver support; current rich user-management behavior is primarily MySQL-oriented. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/src/drivers/mysql/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Notebooks | Desktop notebook CRUD, execution, outline, charts, history, parameters, and import/export remain in the shared React implementation. | The same notebook format and services run over RPC; browser imports and exports use opaque transfers and downloads. | Browser file exchange is adapted while notebook content and execution stay identical. | Download location is browser-controlled and server-side notebook storage remains scoped to the Tabularis data directory. | `packages/web-ui/tests/api/contract/transportContract.ts`
`packages/web-ui/tests/utils/notebookTransfer.test.ts`
`src-tauri/src/application/notebooks/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Dump/import | Desktop jobs keep native file targets, cancellation, and progress through existing commands and events. | Browser uploads source SQL or archives, runs the same server-side jobs, receives scoped progress, and downloads generated dumps. | Opaque streaming transfers replace trusted native paths and preserve long-running job semantics. | Tool availability and database-specific dump fidelity depend on installed drivers or external utilities; transfer limits remain enforced. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/database_transfers_tests.rs`
`packages/web-ui/tests/utils/dumpUtils.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| Clipboard import | Desktop reads clipboard content through the Tauri clipboard plugin and uses the shared parser and import UI. | Browser mode requests Clipboard API permission, then feeds the same parser and backend workflow. | Browser permission is mandatory and cannot be bypassed safely; the parsed data outcome is shared. | Denied or unavailable browser clipboard permission produces an explicit fallback instead of silent access. | `packages/web-ui/tests/platform/tauriCapabilities.test.ts`
`packages/web-ui/tests/platform/browserCapabilities.test.ts`
`packages/web-ui/tests/utils/clipboardParser.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| AI features | Desktop AI providers, generation, explanations, plans, naming, activity, notifications, and approvals remain over Tauri. | The same services run through authorized RPC and session-owned approval events; provider keys are write-only. | Browser approval and attention use semantic platform capabilities while AI business logic remains shared. | Provider network availability and model behavior are external; remote use requires explicit high-risk authorization and notification permission may be denied. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/ai/tests.rs`
`packages/web-ui/tests/components/modals/AiApprovalGate.test.tsx` | Approved by Web UI parity reviewer on 2026-08-22 | +| Settings/keybindings/themes | Desktop reads and writes the existing config locations and applies shared settings, keybindings, editor preferences, prompts, and themes. | Web uses the same global persistence service while isolating session restore state and preserving the shared UI application logic. | Global preferences stay shared; browser connection and editor restore state is session-scoped to avoid cross-session interference. | Concurrent users share server-global settings and custom themes by design; deployments needing per-user global profiles require future product policy. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/persistence_tests.rs`
`packages/web-ui/tests/contexts/SettingsProvider.test.tsx` | Approved by Web UI parity reviewer on 2026-08-22 | +| Credentials/keychain | Desktop stores secrets through the existing backend secret service and only returns redacted connection values to the UI. | Browser responses remain write-only for database, SSH, backup, and AI secrets; no raw keychain material is sent over RPC. | The security outcome is identical because secret access never moves into frontend code. | Headless hosts need a functioning OS secret service or deployment-specific keychain setup before relying on saved credentials. | `src-tauri/src/application/connections_tests.rs`
`src-tauri/src/application/tunnels_tests.rs`
`src-tauri/src/application/ai/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Plugin drivers | Desktop starts existing subprocess JSON-RPC drivers from the shared plugin runtime. | Headless Web starts the same runtime; the real browser matrix registers an external driver, tests it, and executes a query through its subprocess. | Drivers remain backend plugins and are independent of frontend transport. | Installed plugin binaries must match the host platform and remain trusted code with host-level database access. | `web-ui-project/e2e/tests/web-ui-matrix.spec.ts`
`src-tauri/src/plugins/driver_resilience_tests.rs`
`packages/web-ui/tests/api/contract/transportContract.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| Plugin registry/install | Desktop registry browsing, preview, README, install, update, enable, disable, restart, and uninstall use Tauri. | Authorized Web sessions invoke the same lifecycle service and receive progress events. | Only transport and browser confirmation differ; installation still occurs in the backend plugin directory. | Remote installation and process control are denied unless high-risk authorization is explicitly enabled; registry trust remains an administrator decision. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/plugins/tests.rs`
`packages/web-ui/tests/components/modals/PluginInstallConfirmModal.test.tsx` | Approved by Web UI parity reviewer on 2026-08-22 | +| Plugin UI extensions | Desktop loads declared plugin UI bundles through the Tauri asset adapter into the shared slot host. | Web serves authenticated allowlisted assets with strict CSP and the real browser matrix renders a sidebar contribution. | The loader changes to authenticated HTTP, while API compatibility, slots, and error isolation are shared. | UI extensions execute trusted plugin JavaScript in the application origin; install only reviewed plugins despite CSP and allowlisting. | `web-ui-project/e2e/tests/web-ui-matrix.spec.ts`
`packages/web-ui/tests/types/pluginSlotsParity.test.ts`
`src-tauri/src/application/plugin_assets/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Logs/task manager | Desktop log controls, exports, process snapshots, and task actions continue through the shared client and Tauri adapter. | Web exposes browser-safe views and actions over typed RPC, with local-admin guards on destructive process operations. | Operational information is identical; host-affecting actions are authorization-scoped for browser sessions. | Process metrics are host snapshots and platform dependent; remote default sessions cannot clear logs or control processes. | `packages/web-ui/tests/components/settings/LogsTab.test.tsx`
`packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/operations/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Backups | Desktop keeps scheduled and manual encrypted connection backups with native save targets. | Web supports the same scheduler and server target plus browser download of manual backup copies. | Browser downloads replace direct client filesystem paths; server-directory targets stay explicit administration choices. | Browser clients cannot schedule writes to arbitrary client paths, and server targets require filesystem permissions and local-admin authority. | `packages/web-ui/tests/components/settings/BackupTab.test.tsx`
`src-tauri/src/application/connection_files_tests.rs`
`packages/web-ui/tests/api/contract/transportContract.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| MCP configuration | Desktop continues to list supported MCP hosts and install local host configuration. | Loopback Web local-admin sessions can use the same typed commands; remote policy hides the capability and rejects direct RPC attempts. | MCP edits files on the Tabularis host, so it is valid only when the browser controls the same local machine. | MCP configuration is intentionally unavailable in every remote session, including deployments with high-risk capabilities enabled. | `packages/web-ui/tests/pages/McpPage.test.tsx`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/src/application/mcp_host/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Deep links | Desktop retains native deep-link handling and explicit plugin-install confirmation. | Browser URLs route to the same validated install page, preserve selected registry/version data, and require confirmation. | An HTTPS route is the browser-native deep-link equivalent and avoids requiring an OS protocol handler. | Browser mode does not register the native `tabularis://` protocol; users or websites must open the server's HTTPS install route. | `packages/web-ui/tests/pages/PluginInstallRoutePage.test.tsx`
`packages/web-ui/tests/utils/pluginInstallRoute.test.ts`
`packages/web-ui/tests/routing.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| Updater | Desktop retains native update checks, dismissal, download, installation, and restart behavior. | Web negotiates that native updates are disabled and shows server version, build metadata, and administrator upgrade guidance. | A browser must not replace or restart the serving binary; server upgrade ownership belongs to the deployment administrator. | Web upgrades are not self-service and require service downtime plus the original package or deployment mechanism. | `packages/web-ui/tests/contexts/UpdateProvider.test.tsx`
`packages/web-ui/tests/api/transports/httpTransport.test.ts`
`web-ui-project/docs/WEB_MODE_UPGRADES.md` | Approved by Web UI parity reviewer on 2026-08-22 | +| DevTools/window title | Desktop continues to use native WebView DevTools behavior and updates native window titles from connection state. | Browser mode uses browser developer tools, document titles, routes, and tabs without exposing native window controls. | These are host lifecycle features, so browser-native behavior is the correct replacement rather than a simulated desktop API. | Browser DevTools policy and tab title presentation are controlled by the browser and deployment; native request-attention behavior is not available. | `packages/web-ui/tests/contexts/DatabaseProvider.test.tsx`
`packages/web-ui/tests/platform/tauriCapabilities.test.ts`
`packages/web-ui/tests/platform/browserCapabilities.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | +| Performance and resilience | Desktop retains shared query, driver, pool, transfer, and shutdown services without Web admission changing Tauri command behavior. | Web bounds rows, response bytes, global and per-session RPC concurrency, events, transfers, jobs, and session state; reconnect and cleanup paths are deterministic. | Browser sessions add lifecycle and concurrency boundaries while reusing the same cancellable application jobs. | The gate validates deterministic limits rather than target-hardware latency, CPU, or RSS; release profiling is still required for representative deployments. | `web-ui-project/scripts/run-web-ui-resilience-tests.sh`
`web-ui-project/docs/WEB_PERFORMANCE_RESILIENCE.md`
`src-tauri/src/transport/web/events_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | + +## Audit conclusion + +All 29 planned feature areas have desktop evidence, Web evidence, an explicit parity or adaptation rationale, a known-limitation statement, test references, and dated reviewer approval. No feature remains unclassified. The accepted limitations are platform or deployment boundaries rather than silent parity gaps; they must remain visible in release documentation and the final merge-readiness review. diff --git a/web-ui-project/docs/WEB_MODE_CONTAINERS.md b/web-ui-project/docs/WEB_MODE_CONTAINERS.md new file mode 100644 index 000000000..29a0e4877 --- /dev/null +++ b/web-ui-project/docs/WEB_MODE_CONTAINERS.md @@ -0,0 +1,87 @@ +# Running Tabularis Web in containers + +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, 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 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 + +```bash +docker run -d --name tabularis \ + -p 127.0.0.1:8080:8080 \ + -v tabularis-data:/data \ + ghcr.io/tabularisdb/tabularis +docker logs tabularis # prints the generated login password +``` + +Open . Publishing on `127.0.0.1` matters: plain HTTP is accepted only for a `localhost`, `127.0.0.0/8`, or `[::1]` public URL, and the server rejects any other `Host` header. To use another host port, publish it and tell the server the URL the browser sees: + +```bash +docker run -d -p 127.0.0.1:9000:8080 -e TABULARIS_PUBLIC_URL=http://localhost:9000 ... +``` + +## Docker Compose + +[`docker/compose.yaml`](../../docker/compose.yaml) runs the same local setup. [`docker/compose.tls.yaml`](../../docker/compose.tls.yaml) adds Caddy for a public HTTPS deployment with automatic certificates: + +```bash +cd docker +cp .env.example .env # set TABULARIS_DOMAIN, a password and a secret key +docker compose -f compose.yaml -f compose.tls.yaml up -d +``` + +Caddy keeps the original `Host` header and upgrades WebSockets, which Tabularis requires. Any other reverse proxy must do the same; see [Remote Web UI security](./WEB_REMOTE_SECURITY.md). + +## Kubernetes with Helm + +```bash +helm install tabularis oci://ghcr.io/tabularisdb/charts/tabularis \ + --set publicUrl=https://tabularis.example.com \ + --set ingress.enabled=true --set ingress.className=nginx +``` + +The chart runs one replica with a `Recreate` strategy, because sessions and the data volume belong to one process. Values you set (`auth.password`, `auth.proxySecret`, `secretStore.key`) go into a Secret that is mounted as files. A missing login password or secret-store key is generated by the container on the data volume, exactly as with plain Docker, so the chart renders the same output every time and works with `helm template` based GitOps tools such as Argo CD and Flux. Proxy mode needs `auth.proxySecret`, because the proxy must send the same value. Use `auth.existingSecret` to bring your own Secret with the keys `web-password` or `proxy-secret`, and `secret-key`. The pod runs read-only as non-root and sends the public `Host` header in its probes. See `charts/tabularis/values.yaml` for every option. + +## Environment variables + +The entrypoint translates these into `tabularis web` flags. Arguments after the image name are appended, so `docker run ghcr.io/tabularisdb/tabularis --debug` works; any other command (for example `sh`) runs instead of the server. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `TABULARIS_PUBLIC_URL` | `http://localhost:8080` | URL the browser uses. HTTPS, or HTTP on a loopback host. Becomes `--public-url` and the first `--allowed-origin`. | +| `TABULARIS_TRUSTED_PROXIES` | | Trusted proxy source CIDRs, comma separated (`--trusted-proxy`); Helm: `trustedProxies`. Headers are ignored by default. | +| `TABULARIS_ALLOWED_ORIGINS` | | Further origins, comma separated. | +| `TABULARIS_AUTH` | `password` | `password` or `proxy` (an authenticating reverse proxy). | +| `TABULARIS_WEB_PASSWORD` | generated | Login password, at least 12 characters. When unset, a password is generated on first start, stored in `/data/web-password`, and printed once. | +| `TABULARIS_WEB_PROXY_SECRET` | | Required for `proxy` mode, at least 32 characters. | +| `TABULARIS_SECRET_KEY` | generated | Encrypts stored credentials, at least 16 characters. See below. | +| `TABULARIS_ALLOW_HIGH_RISK` | `false` | Grants every session host-level operations. Only for a single trusted user. | +| `TABULARIS_SERVER_FILE_ROOTS` | | Server directories the browser may pick files from, comma separated. | +| `TABULARIS_PORT` | `8080` | Port inside the container. | +| `TABULARIS_HOST` | `0.0.0.0` | Bind address inside the container. | +| `TABULARIS_DEBUG` | `false` | Debug logging. | + +`TABULARIS_WEB_PASSWORD`, `TABULARIS_WEB_PROXY_SECRET` and `TABULARIS_SECRET_KEY` also accept a `_FILE` variant pointing at a Docker or Kubernetes secret file. + +## Stored credentials + +Containers have no OS keychain. The image sets `TABULARIS_SECRET_STORE=file`, which keeps every secret the desktop app would put in the keychain (database and SSH passwords, connection URIs, plugin secrets, AI keys) in `/data/secrets.enc.json`, encrypted with AES-256-GCM under a key derived from `TABULARIS_SECRET_KEY` with Argon2id. + +Without `TABULARIS_SECRET_KEY`, a random key is generated in `/data/secrets.key`. Secrets then survive restarts and upgrades, but anyone who can read the volume can read them. Generated keys are published atomically under a startup lock. An incomplete key is regenerated only before a secret store exists; otherwise startup names the damaged or missing key file and requires restoring the original key, without changing the encrypted store. Set your own key in production and back it up separately from the volume: a lost key makes the stored credentials unrecoverable, and a wrong key stops the container at startup instead of silently starting empty. + +`TABULARIS_SECRET_STORE=file` also works outside containers, for example on a headless server without a Secret Service. `TABULARIS_SECRET_STORE_PATH` moves the store file. + +## Health, logs and shutdown + +`GET /healthz` is a liveness check. It still enforces the `Host` allowlist, so the image's `HEALTHCHECK` sends the public host. Logs go to stderr (`docker logs`), and audit events use the `tabularis::web_audit` target. `docker stop` sends `SIGTERM`; the server finishes requests, closes pools and tunnels, and stops driver plugins before exiting. + +## Building the image yourself + +```bash +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, 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_MODE_OPERATIONS.md b/web-ui-project/docs/WEB_MODE_OPERATIONS.md new file mode 100644 index 000000000..569c00687 --- /dev/null +++ b/web-ui-project/docs/WEB_MODE_OPERATIONS.md @@ -0,0 +1,204 @@ +# Tabularis Web operator guide + +This guide covers day-to-day use and operation of the browser UI started by `tabularis web`. Running `tabularis` without the `web` subcommand still starts the desktop application. + +## CLI options + +Start an interactive loopback server with the secure defaults: + +```bash +tabularis web +# Tabularis Web is available at http://127.0.0.1:8080 +``` + +The Web-specific options are: + +| Option | Purpose and constraints | +|---|---| +| `web` | Start the HTTP and WebSocket server without creating a desktop window. It conflicts with `--mcp` and `--explain`. | +| `--host` | Bind address. The default is `127.0.0.1`. A non-loopback address is rejected unless remote authentication is fully configured. | +| `--port` | Bind port. The default is `8080`; there is no automatic port fallback, so choose another port if it is occupied. | +| `--no-open` | Do not launch a browser. Use this for services, remote deployments, and liveness-only automation. For an interactive local session, let Tabularis open the one-time bootstrap URL. | +| `--web-root` | Development or test override for a directory containing a built `index.html`. Packaged installations locate their matching Web UI resources automatically. | +| `--auth` | Remote authentication mode: `password` or `proxy`. It requires `--public-url` and at least one `--allowed-origin`. | +| `--public-url` | Public HTTPS origin seen by browsers, for example `https://tabularis.example.com`. Plain HTTP is accepted only for a loopback host such as `http://localhost:8080` (a container published on `127.0.0.1`). It must not contain a path, query, fragment, or credentials. | +| `--trusted-proxy` | Proxy source CIDR allowed to supply `X-Forwarded-For`; repeat as needed. Empty by default. | +| `--allowed-origin` | Allowed HTTPS (or loopback HTTP) browser origin. Repeat the option for additional origins; the public URL must be included. | +| `--allow-high-risk` | Give remote sessions `local-admin` authority. Without it, remote sessions are restricted to database operations. Do not enable it for shared deployments. | +| `--server-file-browser-root` | Allow the Web UI to browse one server directory. Repeat it to expose additional roots. Paths outside these roots remain inaccessible; remote sessions also require `--allow-high-risk`. | + +`--debug` enables additional logging, including SQLx query logging, in desktop and Web modes. Treat debug output as sensitive and disable it after diagnosis. Use `tabularis --help` for the complete process-mode CLI. + +Development example: + +```bash +pnpm --filter @tabularis/web-ui build +tabularis web --port 8081 --web-root packages/web-ui/dist +``` + +`--web-root` must point to assets from the same source revision as the server. Do not combine a server binary and UI bundle from different releases. + +Server file browsing is disabled by default. Enable only the directories required by the Web UI: + +```bash +tabularis web \ + --server-file-browser-root /srv/databases \ + --server-file-browser-root /var/backups +``` + +The picker canonicalizes configured roots and directory entries, rejects traversal outside them, and skips symlinks whose targets leave the allowed root. It also provides a save mode for operations such as **New SQLite Database**, allowing a new file name only inside the selected root. Without this option, browse and save actions show the standard in-app unavailable dialog. + +## Local security behavior + +Local mode is authenticated even though it listens only on loopback: + +1. Tabularis binds to `127.0.0.1` by default and refuses a non-loopback bind without remote authentication. +2. Startup creates a high-entropy, single-use bootstrap token that expires after 60 seconds. +3. The default browser opens the bootstrap URL. The server exchanges the token for an opaque eight-hour `HttpOnly`, `SameSite=Strict` session cookie and removes the token from normal navigation. +4. The server validates the request `Host` and `Origin`. State-changing requests also require the session CSRF token. +5. Bootstrap tokens, session credentials, request bodies, SQL text, and result payloads are not written to Web audit records. `/healthz` reports liveness only. + +The local cookie is sent over loopback HTTP and is not marked `Secure`; remote cookies are `Secure` whenever their public origin is HTTPS, which it must be except on a loopback host. Closing a browser tab does not stop the server. Stop the foreground process with `Ctrl+C`, or stop its service unit. Sessions, active jobs, pools, tunnels, and temporary transfer state are cleaned up on logout, expiry, disconnect where applicable, or process shutdown. + +`--no-open` intentionally does not print the secret bootstrap URL, so it never ends up in a service log. It is therefore unsuitable for creating a new interactive loopback session by hand. If the browser launch fails, for example on a headless machine or over SSH, Tabularis prints the one-time URL to the terminal instead. It is valid once, for one minute; restart `tabularis web` for a fresh one. + +## Remote deployment and reverse proxy + +Tabularis does not terminate TLS. A remote deployment must place the plain-HTTP listener behind a trusted TLS reverse proxy, prevent clients from reaching the listener directly, preserve the public `Host`, and proxy WebSocket upgrades. + +Choose one authentication mode: + +- Password mode reads a password of at least 12 characters from `TABULARIS_WEB_PASSWORD`. +- Trusted-proxy mode reads a shared secret of at least 32 characters from `TABULARIS_WEB_PROXY_SECRET`. After authenticating the user, the proxy must replace the `X-Tabularis-User` and `X-Tabularis-Proxy-Secret` headers. + +Minimal password-mode service command: + +```bash +export TABULARIS_WEB_PASSWORD='replace-with-a-long-unique-password' + +tabularis web \ + --host 127.0.0.1 \ + --port 8080 \ + --no-open \ + --auth password \ + --public-url https://tabularis.example.com \ + --allowed-origin https://tabularis.example.com +``` + +Minimal trusted-proxy command: + +```bash +export TABULARIS_WEB_PROXY_SECRET="$(openssl rand -base64 48)" + +tabularis web \ + --host 127.0.0.1 \ + --port 8080 \ + --no-open \ + --auth proxy \ + --public-url https://tabularis.example.com \ + --allowed-origin https://tabularis.example.com +``` + +Remote login attempts are rate-limited. Remote sessions receive database-only authorization by default; SSH, Kubernetes, AI secrets and approvals, imports and exports, backups and dumps, plugin lifecycle, host logs and tasks, global settings, and other local-administrator operations remain denied unless `--allow-high-risk` is explicitly accepted. MCP host operations remain unavailable remotely even with that opt-in. + +See [Remote Web UI security and reverse-proxy deployment](./WEB_REMOTE_SECURITY.md) for Nginx, systemd, firewall, origin, audit, rate-limit, and verification examples. That guide is the normative remote threat model. For the official Docker image, Docker Compose, and the Helm chart, see [Running Tabularis Web in containers](./WEB_MODE_CONTAINERS.md). + +## Data, configuration, and credential locations + +Desktop and Web modes use the same runtime paths. The process account and its home/XDG environment determine the locations: + +| Platform | Configuration directory | Data directory | +|---|---|---| +| Linux | `${XDG_CONFIG_HOME:-~/.config}/tabularis`, normally `~/.config/tabularis` | `${XDG_DATA_HOME:-~/.local/share}/tabularis`, normally `~/.local/share/tabularis` | +| macOS | `~/Library/Application Support/tabularis` | `~/Library/Application Support/tabularis` | +| Windows | `%APPDATA%\tabularis` | `%APPDATA%\tabularis` | + +Important configuration content includes: + +- `config.json`: settings, UI preferences, registry configuration, and non-secret backup settings; +- `connections.json`: connection metadata; debug builds may prefer an existing `connections.dev.json`; +- `ssh_connections.json` and `k8s_connections.json`: tunnel profile metadata; +- `notebooks/`, `saved_queries/`, `query_history/`, and `themes/`: user-created content; +- `ai_activity.jsonl` and rotated files: AI and MCP activity records when enabled. + +Important data content includes `plugins/`, `connection-icons/`, and session-owned Web transfer/job directories. `web-file-transfers/`, `web-uploads/`, and export/import job directories are temporary operational state, not durable backup inputs. + +Passwords, connection URIs, SSH passphrases, AI provider keys, backup encryption passwords, and backup-target credentials are stored under the `tabularis` service in the OS credential store. They are not recoverable by copying `config.json` or `connections.json`, and the browser never receives raw stored credentials. A headless service must run as the same dedicated account on every start and must have a functioning keyring backend, or set `TABULARIS_SECRET_STORE=file` to keep them in an encrypted file instead (the default in the container image; see [Running Tabularis Web in containers](./WEB_MODE_CONTAINERS.md#stored-credentials)). + +For backup or migration: + +1. Stop Tabularis so the configuration and data trees are consistent. +2. Back up both directories with owner-only permissions. +3. Handle OS credential-store migration separately, or use Tabularis encrypted connection export and backup workflows. +4. Restore to the same service account and verify keyring access before enabling scheduled or unattended operation. + +Do not edit persisted JSON while Tabularis is running. Files can contain hostnames, usernames, paths, SQL history, plugin settings, and other operationally sensitive metadata even when passwords are absent. + +## Browser limitations and adaptations + +The browser uses the same React UI and Rust services as desktop, but native operating-system workflows are adapted: + +- File import uses authenticated, purpose-bound uploads. Export and BLOB workflows use expiring, usually single-use downloads. A browser-supplied path is never treated as a server path. +- Clipboard reads and notifications depend on browser permission and secure-context policy. Denial produces an explicit fallback rather than silently invoking a desktop API. +- Save dialogs become browser downloads. File placement and overwrite behavior are controlled by the browser. +- Secondary result, diagram, explain, task, and connection windows become routes or browser tabs. Popup blockers can prevent opening a new tab. +- External links are validated before opening and may still be blocked by browser popup policy. +- Deep-link plugin installation becomes a validated `/install-plugin` route with explicit confirmation. +- The desktop updater, native restart, window attention, title-bar controls, and native DevTools lifecycle do not apply. The Info page reports server build data and directs the user to an administrator for upgrades. +- MCP configuration is a local-host operation and is unavailable to remote browser sessions. +- A Web query page is capped at 10,000 rows and a serialized query response at 16 MiB. Paginate or export large results. Uploads and event queues also have explicit limits. +- Refreshing reconnects event subscriptions, but an abandoned in-flight request can be cancelled and cleaned up. In-memory sessions and jobs do not survive a server restart. + +Use a current Chromium, Firefox, or WebKit-based browser with cookies, JavaScript, Fetch, and WebSocket enabled. For resource and recovery details, see the [Web UI performance and resilience contract](./WEB_PERFORMANCE_RESILIENCE.md). The [manual parity audit](./WEB_MANUAL_PARITY_AUDIT.md) records every intentional desktop-to-browser adaptation. + +## Plugin compatibility + +Database driver plugins still run as backend subprocesses over the existing JSON-RPC protocol. The browser does not load driver binaries or database credentials. Existing drivers remain compatible when their manifest and executable support the server's operating system and architecture and the service account can execute them. + +Plugin installation and lifecycle run on the Tabularis server. In remote mode they require the explicit high-risk authorization policy. Install only trusted, correctly signed releases and inspect startup errors after moving an installation between platforms. + +UI extensions use the same slots and `@tabularis/plugin-api` host API in desktop and Web modes. Each extension should declare the API version used to build it. Incompatible or newer declarations are skipped; legacy entries without a declaration remain supported. Extension JavaScript and locale files must be declared in the installed manifest and bundled locally rather than fetched as remote executable code. + +An enabled UI extension is trusted application code running in the shared page, not a sandbox. Authenticated, allowlisted asset delivery and CSP headers constrain asset exposure but do not make evaluated third-party JavaScript safe. Read the [Plugin UI extension trust model](../../docs/security/plugin-ui-extensions.md) and the [`@tabularis/plugin-api` compatibility guide](../../packages/plugin-api/README.md) before deployment. + +## Troubleshooting + +### Server does not start + +- **Address already in use:** choose an unused explicit port, for example `--port 8081`. Tabularis does not scan for a free port. +- **Web UI assets were not found:** reinstall the complete package. Developers must build `@tabularis/web-ui` or pass a valid `--web-root` containing `index.html`. +- **Non-loopback bind rejected:** configure `--auth`, `--public-url`, and `--allowed-origin`; do not bypass the remote security boundary. +- **Password or proxy secret rejected:** set the required environment variable in the service account's environment and satisfy the minimum length. Do not pass secrets on the command line. + +### Browser cannot establish or keep a session + +- **Local 401 after launch:** the bootstrap token is expired or was already consumed. Restart the process and let it open a fresh URL; do not bookmark bootstrap URLs. +- **Remote 401:** verify the password or that the trusted proxy replaces both required identity headers. +- **HTTP 403:** check the public `Host`, exact HTTPS origin allowlist, proxy header handling, CSRF/session state, and the command's authorization level. +- **HTTP 429:** this client is locked out after repeated failed logins. Wait for the five-minute lockout and correct the credentials before retrying. Other clients are not affected. +- **WebSocket disconnects or missing progress:** enable HTTP/1.1 WebSocket upgrades and suitable idle timeouts on the reverse proxy. Confirm the public origin and session cookie are preserved. +- **Browser did not open locally:** `--no-open` suppresses bootstrap launch. Otherwise configure the OS default-browser opener and restart the process. + +### Features fail after login + +- **Saved credentials are missing:** verify that the process uses the expected home directory and service account and can unlock the OS credential store. Copying configuration files does not copy secrets. +- **Import, export, dump, or BLOB transfer expired:** retry from the UI. Transfer tokens are session-owned, purpose-bound, size-limited, and short-lived; downloads can be single-use. +- **Large query fails or truncates:** paginate below the row and response-size limits, select fewer columns, or use a streamed export. +- **Plugin will not start:** check server OS/architecture compatibility, executable permissions and interpreter settings, the installed manifest, plugin startup errors, and server logs. +- **Clipboard, notification, new tab, or external link is blocked:** grant the relevant browser permission or allow the popup. The UI reports unsupported or denied capabilities. +- **Remote command receives 403:** the database-only policy is working. Reassess the threat model before restarting with `--allow-high-risk`; MCP remains remote-disabled. + +`/healthz` is suitable for process liveness but does not prove authentication, database connectivity, plugin health, or WebSocket operation. Runtime and Web audit logs are written to stderr and retained in a bounded in-memory UI buffer; under systemd, inspect the service journal. Web audit entries use the `tabularis::web_audit` target and omit secrets, SQL text, request bodies, and result payloads. + +## Upgrade and rollback + +The browser cannot replace or restart its server. Upgrade with the same package manager, release artifact, container image, or service deployment method that installed Tabularis: + +1. Record the current server/build information and launch configuration. +2. Back up the configuration and data directories and account for the separate OS credential store. +3. Stop the Web process, install the complete target release, and restart it with the same account, environment, paths, and arguments. +4. Verify the reported server build, authentication, one connection, a read-only query, WebSocket progress, and any required plugins before restoring access. + +The server ships its matching browser assets; never deploy only a new UI bundle. If verification fails, stop the service, restore the previous complete installation and deployment files, restore data only when required by the release notes, and restart with the original configuration. Preserve failed-version logs for diagnosis. + +See [Upgrading a Tabularis Web server](./WEB_MODE_UPGRADES.md) for the release checklist, rollback sequence, and build identifier behavior. Release-specific migration or rollback constraints take precedence over this general guide. diff --git a/web-ui-project/docs/WEB_MODE_UPGRADES.md b/web-ui-project/docs/WEB_MODE_UPGRADES.md new file mode 100644 index 000000000..3a00b8354 --- /dev/null +++ b/web-ui-project/docs/WEB_MODE_UPGRADES.md @@ -0,0 +1,29 @@ +# Upgrading a Tabularis Web server + +Tabularis Web deliberately does not let a browser replace or restart the server binary. Server upgrades are an administrator operation and must use the same installation or deployment method that installed Tabularis. + +## Before upgrading + +1. Open **Settings → Info → Updates** and record the displayed server version and build information. +2. Review the target release and its notes on the [Tabularis Releases page](https://github.com/TabularisDB/tabularis/releases). +3. Back up the Tabularis configuration and data directories according to your deployment policy. +4. Record the server's launch arguments, service configuration, user account, and data-directory overrides. + +## Upgrade procedure + +1. Stop accepting new browser sessions. +2. Stop the `tabularis web` process or its service manager unit. +3. Upgrade Tabularis through the original installation method. For a package-managed installation, use that package manager. For a directly installed release, replace it with the matching release artifact. +4. Start `tabularis web` with the same service account, data locations, and arguments. +5. Reopen the Web UI and verify that **Settings → Info → Updates** reports the expected server version and build. +6. Run a connection and read-only query smoke test before restoring normal access. + +The browser UI bundle is served by the Tabularis process, so restarting the upgraded server also serves the matching UI. Do not copy a frontend bundle from a different release onto the server. + +## Rollback + +If verification fails, stop the server, restore the previous Tabularis installation and any deployment files changed during the upgrade, then restart it with the original configuration. Preserve the failed server logs for diagnosis. Data migrations and release-specific rollback notes, when applicable, are documented in the corresponding release notes. + +## Build identifiers + +The Web UI reports the server version, target platform, build profile, and an optional source commit. Release automation can set `TABULARIS_BUILD_COMMIT` while compiling to include the source commit in session negotiation and the Info screen. diff --git a/web-ui-project/docs/WEB_PERFORMANCE_RESILIENCE.md b/web-ui-project/docs/WEB_PERFORMANCE_RESILIENCE.md new file mode 100644 index 000000000..793c71222 --- /dev/null +++ b/web-ui-project/docs/WEB_PERFORMANCE_RESILIENCE.md @@ -0,0 +1,32 @@ +# Web UI performance and resilience contract + +WEB-095 establishes deterministic resource limits and a focused CI gate for failure and recovery paths. Run it with: + +```bash +pnpm test:web-resilience +``` + +## Resource bounds + +- Web query pages are capped at 10,000 rows and serialized query responses at 16 MiB. Clients must paginate when either limit is reached. +- Web RPC execution is capped at 64 active requests process-wide and 16 active requests per authenticated session. Excess work fails immediately through the shared error envelope with `SERVER_BUSY` or `SESSION_BUSY`; requests are not queued without a bound. +- WebSocket sessions, connections, replay history, and per-connection queues remain bounded. Slow consumers are disconnected instead of accumulating events. +- Uploads, downloads, BLOBs, request bodies, event control messages, pending file tokens, deadlines, and cancellation identifiers retain their existing explicit limits. +- Query, export, dump, and import registrations abort their worker when the owning request is dropped. Explicit logout additionally clears all jobs and temporary state owned by that session. + +## Resilience matrix + +| Scenario | Expected behavior | Automated evidence | +|---|---|---| +| Large query result | Clamp row count and reject responses above 16 MiB with pagination guidance | `web_policy_caps_rows_and_rejects_oversized_payloads` | +| Slow client | Disconnect a full WebSocket consumer and retain only bounded replay history | `disconnects_slow_consumers_and_bounds_reconnect_history` | +| Multiple sessions | Isolate active connections, cancellation identifiers, queues, and per-session RPC admission | `browser_active_connections_are_isolated_by_session` and `bounds_slow_rpc_work_per_session_and_across_the_server` | +| Reconnect | Replay missed scoped events from the bounded session history | `replays_only_missed_events_for_the_same_session` and the HTTP transport reconnect test | +| Abandoned job | Abort and unregister query, export, dump, and import workers without affecting another session | query and transfer `session_cleanup` tests plus registration-drop tests | +| Plugin crash | Release pending callers promptly when the plugin process channel exits | `crashed_plugin_process_fails_pending_calls_without_hanging` | +| Tunnel failure | Return correlated progress errors and preserve configured executable diagnostics | `connection_test_failures_emit_correlated_progress` and `test_spawn_error_identifies_configured_program` | +| Graceful shutdown | Abort background jobs, close pools, stop tunnels, and shut down external drivers | `runtime::tests` and the headless server shutdown fixtures | +| Memory and CPU bounds | Reject excess concurrent RPC work and bound response, transfer, event, and session-owned state | RPC admission, query policy, event bus, and file transfer tests | +| Browser refresh during work | Re-establish event subscriptions; dropped request workers clean themselves up and session-scoped events continue after reconnect | HTTP transport refresh test and registration-drop tests | + +The deterministic CI suite validates limits and lifecycle behavior rather than asserting host-specific timing or RSS values. Release profiling should still exercise representative databases and plugin binaries on target hardware. diff --git a/web-ui-project/docs/WEB_REMOTE_SECURITY.md b/web-ui-project/docs/WEB_REMOTE_SECURITY.md new file mode 100644 index 000000000..3ef676602 --- /dev/null +++ b/web-ui-project/docs/WEB_REMOTE_SECURITY.md @@ -0,0 +1,193 @@ +# Remote Web UI security and reverse-proxy deployment + +Remote Tabularis Web access exposes database administration, credentials, tunnels, plugins, AI providers, imports, exports, and host operations. It is therefore disabled unless an authentication mode, a public HTTPS origin, and an explicit origin allowlist are configured. + +## Supported deployment boundary + +Tabularis currently serves plain HTTP. Remote deployments must terminate TLS at a trusted reverse proxy and keep the Tabularis listener unreachable from untrusted networks. Direct TLS termination in the Tabularis process is not supported. + +Use a dedicated service account, restrict the data directory, and place firewall rules between clients and the Tabularis listener. The reverse proxy must preserve the public `Host` header and must support WebSocket upgrades. + +## Password mode + +Set the password through the process environment rather than the command line so it is not exposed in process listings: + +```bash +export TABULARIS_WEB_PASSWORD='replace-with-a-long-unique-password' + +tabularis web \ + --host 127.0.0.1 \ + --port 8080 \ + --no-open \ + --auth password \ + --public-url https://tabularis.example.com \ + --allowed-origin https://tabularis.example.com +``` + +Passwords must contain at least 12 characters. The server provides a minimal, same-origin `/login` form, stores only a SHA-256 verifier in runtime memory, and exchanges valid credentials for an `HttpOnly`, `SameSite=Strict`, `Secure` session cookie. Five failed attempts from one client within one minute lock that client out for five minutes; other clients can still log in. `X-Forwarded-For` is ignored by default, including from private and loopback peers. Configure each trusted proxy source network explicitly, for example `--trusted-proxy 127.0.0.1/32` for a local proxy, or repeat the flag for IPv4/IPv6 CIDRs. Only requests from those networks use the last header entry, which the proxy must append (Nginx `$proxy_add_x_forwarded_for`). Trust only proxy addresses, not client networks. Restrict direct access to the upstream listener with firewall rules or a Kubernetes NetworkPolicy; a configured HTTPS public URL does not enable TLS or prevent direct HTTP access to that listener. + +The server admits at most 1,024 live sessions. At capacity, new logins and cookieless proxy requests receive HTTP 503; existing sessions remain active. Logout or expiry frees capacity. Password-login tracking is also bounded: when full, all untracked clients are temporarily rejected without discarding active lockouts or bypassing them with an untracked password guess. Existing tracked clients retain their normal per-client policy; expiry frees tracking slots. + +## Authenticated reverse-proxy mode + +Proxy mode trusts an authenticated identity only when the proxy also supplies a deployment secret. Generate a random secret of at least 32 characters and provide the same value to Tabularis and the proxy: + +```bash +export TABULARIS_WEB_PROXY_SECRET="$(openssl rand -base64 48)" + +tabularis web \ + --host 127.0.0.1 \ + --port 8080 \ + --no-open \ + --auth proxy \ + --public-url https://tabularis.example.com \ + --allowed-origin https://tabularis.example.com +``` + +After authenticating the user, the proxy must replace—not append—the following request headers: + +- `X-Tabularis-User`: the authenticated, non-empty user identifier; +- `X-Tabularis-Proxy-Secret`: the shared deployment secret. + +Tabularis removes both headers before dispatching application requests. Missing or invalid proxy credentials are rejected. Secret checks are not rate-limited: a secret of 32 or more random characters cannot be guessed online, and a lockout would let anyone who reaches the port deny every proxied user. + +Example Nginx location after the deployment's own `auth_request`, OIDC, or basic-auth configuration: + +```nginx +location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + + proxy_set_header Host $http_host; + proxy_set_header X-Tabularis-User $remote_user; + proxy_set_header X-Tabularis-Proxy-Secret "replace-with-the-environment-secret"; + + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; +} +``` + +Store the proxy secret in the reverse proxy's protected secret store rather than directly in a world-readable configuration file. Never expose the upstream listener directly: a client that can bypass the trusted proxy can submit proxy headers itself. + +## Origin and cookie policy + +`--public-url` and every repeated `--allowed-origin` value must be an HTTPS origin with no path, query, fragment, or embedded credentials. The only exception is a loopback host (`localhost`, `127.0.0.0/8`, `[::1]`), which may use plain HTTP because the traffic never leaves the browser's machine; its session cookie is then not marked `Secure`. The public URL must also appear in the allowlist. Requests with an unexpected `Host` or `Origin` are rejected. State-changing requests additionally require the session's CSRF token. + +Examples with an additional explicitly trusted administration origin: + +```bash +--public-url https://tabularis.example.com \ +--allowed-origin https://tabularis.example.com \ +--allowed-origin https://admin.example.com +``` + +Only add origins that are controlled by the same deployment owner. Browser session cookies are always marked `Secure` in remote mode. + +## High-risk capability policy + +Remote sessions are restricted to the `database` authorization level by default. This permits core connection, metadata, query, data-editing, and notebook workflows while denying commands classified as `sensitive` or `local-admin`. Denied operations return HTTP 403 with the shared RPC error envelope. + +Database-only sessions may create network connections and use their existing targets. +Changing a saved connection's driver, destination, or transport/authentication settings +requires `local-admin`, including when a new password is supplied. This keeps stored +credentials bound to the administrator-approved target; editing connection metadata +or credentials for that same target remains available. + +File- and folder-based drivers (including SQLite) require `local-admin` for connection +access. This applies to saved connections and per-request database overrides as well +as new connections. A directory-browser allowlist alone cannot confine database SQL: +for example, SQLite can open additional files through `ATTACH`. Use a dedicated +service account and filesystem isolation when enabling these drivers remotely. + + +The following groups require an explicit high-risk opt-in because they can disclose secrets, modify the host, start tunnels or subprocesses, install code, or alter server-wide state: + +- SSH and Kubernetes tunnel lifecycle and askpass responses; +- AI provider keys, generation, approvals, and activity exports; +- connection credential import/export, backups, dumps, and sensitive file operations; +- plugin registry, installation, lifecycle, and process control; +- logs, process/task management, global configuration, and host filesystem actions; +- MCP host configuration, which remains disabled for all remote sessions. + +A trusted single-administrator deployment may grant the complete `local-admin` policy explicitly: + +```bash +--allow-high-risk +``` + +The negotiated session contract reports `remote`, `authorizationLevel`, and `highRiskCapabilities`. Do not enable high-risk capabilities for shared or weakly authenticated deployments. + +## Audit events and secret handling + +Security events are emitted through the existing logger with target `tabularis::web_audit`. Authentication success, denial, rate limiting, CSRF or host rejection, RPC completion, and logout events include a request ID and, when a session exists, an opaque session ID. RPC audit records include command names and response status only. They never include passwords, proxy secrets, bootstrap tokens, request bodies, SQL text, or result payloads. + +Protect and retain logs according to the deployment's incident-response policy. Debug logging does not relax audit redaction. + +## Threat model + +| Threat | Security objective | Control | Residual deployment responsibility | +|---|---|---|---| +| Accidental LAN or internet exposure | Remote binding is intentional | Non-loopback binds fail without configured remote authentication | Firewall the upstream listener | +| Credential theft in transit | Credentials and cookies remain confidential | HTTPS public origins and `Secure` cookies | Configure valid TLS and secure proxy-to-client ciphers | +| Password guessing | Bound online attempts | Five-failure window and timed lockout per client | Use a unique password and monitor audit events | +| Proxy-header spoofing | Only the trusted proxy can assert identity | Shared proxy secret and stripped headers | Prevent direct access and protect the proxy secret | +| Cross-site request forgery | State changes originate from an allowed UI | Strict SameSite cookie, explicit origins, CSRF token | Keep the allowlist minimal | +| DNS rebinding or Host confusion | Requests reach only configured virtual hosts | Explicit host allowlist | Preserve the original public Host header | +| Session theft | Limit credential exposure and lifetime | Opaque eight-hour in-memory sessions, HttpOnly cookies, logout invalidation | Protect administrator browsers and TLS endpoints | +| Excessive authenticated authority | Compromise has a bounded blast radius | Database-only default and explicit high-risk opt-in | Do not enable `--allow-high-risk` unnecessarily | +| Secret or SQL leakage through logs | Audit data is safe to retain | Structured identifiers and command/status metadata only | Restrict log access and retention | +| Malicious plugin or imported file | Untrusted content cannot silently gain host authority | Existing plugin trust, CSP, opaque upload/download tokens, authorization levels | Install only trusted plugins and validate backups/imports | +| Denial of service | Authentication and request resources are bounded | Login lockout, body limits, event queues, session expiry | Add proxy connection and request-rate limits | + +## systemd example + +Run the packaged binary as a dedicated account and keep its listener on loopback behind the TLS reverse proxy. Create `/etc/tabularis/web.env`, owned by `root:tabularis` with mode `0640`: + +```ini +TABULARIS_WEB_PASSWORD=replace-with-a-long-unique-password +``` + +Example `/etc/systemd/system/tabularis-web.service`: + +```ini +[Unit] +Description=Tabularis Web +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=tabularis +Group=tabularis +EnvironmentFile=/etc/tabularis/web.env +Environment=HOME=/var/lib/tabularis +StateDirectory=tabularis +UMask=0077 +ExecStart=/usr/bin/tabularis web --host 127.0.0.1 --port 8080 --no-open --auth password --public-url https://tabularis.example.com --allowed-origin https://tabularis.example.com +Restart=on-failure +RestartSec=5 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 + +[Install] +WantedBy=multi-user.target +``` + +Create the service account before enabling the unit, replace the public origin, and configure the reverse proxy as described above. Do not place `--allow-high-risk` in a shared deployment. The packaged binary resolves its Web UI resources independently of the service working directory. + +## Container example + +Use the official images and their Compose and Helm setups described in [Running Tabularis Web in containers](./WEB_MODE_CONTAINERS.md). Containers do not remove the remote-mode requirements: attach the container only to an internal reverse-proxy network, do not publish port 8080 beyond `127.0.0.1`, and pass `TABULARIS_WEB_PASSWORD` and `TABULARIS_SECRET_KEY` through a secret manager rather than the image or a committed file. + +## Verification checklist + +1. Confirm the upstream port is unreachable from a client network. +2. Confirm HTTP redirects to HTTPS at the proxy and the browser receives a `Secure` session cookie. +3. Confirm an unlisted `Origin` and incorrect `Host` receive HTTP 403. +4. Confirm invalid credentials eventually receive HTTP 429. +5. Confirm a default remote session receives HTTP 403 for a local-administrator RPC. +6. Confirm WebSocket events reconnect through the proxy. +7. Confirm audit logs contain request and opaque session IDs but no configured secrets or SQL payloads. diff --git a/web-ui-project/docs/WEB_UI_PLAN.md b/web-ui-project/docs/WEB_UI_PLAN.md new file mode 100644 index 000000000..ab892e5dd --- /dev/null +++ b/web-ui-project/docs/WEB_UI_PLAN.md @@ -0,0 +1,573 @@ +# Plan — Web UI feature parity via `tabularis web` + +## 1. Goal + +Deliver a browser-based Tabularis UI with functional parity with the desktop application while preserving one implementation of business logic. + +Target user experience: + +```bash +tabularis web +# Tabularis Web is available at http://127.0.0.1:8080 +``` + +The implementation will live on the long-running branch `feat/web-ui`. The existing React application will ultimately become the workspace package `packages/web-ui`; it will remain the single UI used by both Tauri and browsers. + +### Success criteria + +- `tabularis` continues to launch the desktop application. +- `tabularis web` starts an HTTP server and serves `packages/web-ui/dist` without creating a desktop window. +- Desktop and web use the same React components, contexts, hooks, types, translations, and styles. +- Tauri IPC and HTTP/WebSocket are transport adapters over the same Rust application services. +- Database drivers, connection management, persistence, credentials, plugins, AI, imports, exports, and query logic are not duplicated. +- Every desktop capability is classified as: + - **identical**: same behavior in desktop and web; + - **web-adapted**: equivalent browser workflow; + - **not applicable**: desktop-only lifecycle behavior with a documented web replacement. +- Tests verify the same API contract through both transports. +- Remote network exposure is opt-in and protected by authentication. + +## 2. Verified baseline + +Current repository facts relevant to this plan: + +- React 19, TypeScript, Vite, and Tauri 2 are already used. +- The pnpm workspace already includes `packages/*`. +- The frontend currently lives in root `src/` and builds to root `dist/`. +- The Tauri application registers approximately 255 Rust commands. +- The frontend references 224 distinct `invoke()` command names across approximately 362 call sites. +- 85 frontend files import `@tauri-apps/api/core` directly. +- 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/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. + +## 3. Non-goals and constraints + +### Non-goals + +- Do not create a second React implementation. +- Do not maintain separate desktop and web business rules. +- Do not expose raw database credentials to the browser. +- Do not make internet-facing access the default. +- Do not reproduce desktop-only window chrome in a browser when a route or browser tab is equivalent. +- Do not convert all command APIs to REST resources. A command/RPC contract is a better fit for existing semantics and avoids duplicate endpoint modeling. + +### Constraints + +- Code, comments, and repository documentation remain in English. +- `pnpm` remains the only JavaScript package manager. +- No explicit TypeScript `any`. +- Existing React hook and Fast Refresh rules remain mandatory. +- Desktop compatibility must remain green after every task. +- Existing data locations and migrations must be preserved. + +## 4. Target architecture + +```text + packages/web-ui + ┌────────────────────────┐ + │ Shared React UI │ + │ │ + │ TabularisClient │ + │ PlatformCapabilities │ + └───────────┬────────────┘ + │ + ┌──────────────┴──────────────┐ + │ │ + TauriTransport HttpWsTransport + TauriCapabilities BrowserCapabilities + │ │ + └──────────────┬──────────────┘ + │ + Shared command contract + │ + ┌───────────┴───────────┐ + │ Rust application API │ + │ services + domain │ + └───────────┬───────────┘ + │ + drivers / pools / persistence / keychain / plugins / AI +``` + +### 4.1 `packages/web-ui` + +`packages/web-ui` is not a second UI. The current root frontend is moved there after transport boundaries are established. + +Proposed structure: + +```text +packages/web-ui/ +├── package.json +├── index.html +├── vite.config.ts +├── vitest.config.ts +├── tsconfig*.json +├── public/ +└── src/ + ├── api/ + │ ├── client.ts + │ ├── contract.ts + │ ├── errors.ts + │ ├── events.ts + │ └── transports/ + │ ├── tauriTransport.ts + │ └── httpTransport.ts + ├── platform/ + │ ├── capabilities.ts + │ ├── tauriCapabilities.ts + │ └── browserCapabilities.ts + ├── components/ + ├── contexts/ + ├── hooks/ + ├── i18n/ + ├── pages/ + ├── themes/ + ├── types/ + └── utils/ +``` + +The root package remains a workspace orchestrator. Root scripts delegate to `@tabularis/web-ui` and `src-tauri`. + +### 4.2 Frontend API boundary + +Replace direct calls such as: + +```ts +invoke("execute_query", payload) +``` + +with one typed client: + +```ts +client.call("execute_query", payload) +``` + +The command name and request/result types are defined once in a `CommandMap`. Both transports implement the same interface: + +```ts +interface TabularisTransport { + call( + command: K, + payload: CommandMap[K]["request"], + ): Promise; + + subscribe( + event: K, + handler: (payload: EventMap[K]) => void, + ): Promise; +} +``` + +Temporary compatibility is allowed: `TauriTransport.call()` may delegate directly to `invoke()` while callers are migrated. No component should select a transport itself. + +### 4.3 Rust application boundary + +Tauri commands currently contain a mix of transport concerns and business logic. Migrate incrementally to: + +```text +transport/tauri -> application service <- transport/web +``` + +Proposed backend modules: + +```text +src-tauri/src/ +├── application/ +│ ├── context.rs +│ ├── connections.rs +│ ├── queries.rs +│ ├── metadata.rs +│ ├── persistence.rs +│ ├── plugins.rs +│ ├── ai.rs +│ └── ... +├── runtime/ +│ ├── bootstrap.rs +│ ├── events.rs +│ ├── paths.rs +│ ├── secrets.rs +│ └── state.rs +└── transport/ + ├── tauri/ + └── web/ + ├── auth.rs + ├── events.rs + ├── rpc.rs + ├── static_assets.rs + └── server.rs +``` + +Do not perform a big-bang move. Extract one capability group at a time. Existing public Tauri command names remain stable and become thin wrappers. + +### 4.4 Web protocol + +Use a versioned command RPC instead of creating hundreds of unrelated REST routes: + +```http +POST /api/v1/rpc/execute_query +Content-Type: application/json +Authorization: Bearer +``` + +Response envelope: + +```json +{ + "ok": true, + "data": {} +} +``` + +Error envelope: + +```json +{ + "ok": false, + "error": { + "code": "QUERY_FAILED", + "message": "...", + "details": null, + "requestId": "..." + } +} +``` + +Additional endpoints: + +- `GET /healthz`: process liveness only, no sensitive data. +- `GET /api/v1/session`: session and capability negotiation. +- `GET /api/v1/events`: WebSocket connection for events and progress. +- `POST /api/v1/uploads`: browser upload to an opaque temporary file token. +- `GET /api/v1/downloads/:token`: single-use or expiring download. +- `GET /assets/plugins/...`: authenticated plugin UI assets with strict CSP. +- `GET /*`: static UI assets with SPA fallback to `index.html`. + +### 4.5 Platform capabilities + +Native operations must be represented by semantic capabilities rather than imported directly in components: + +- `chooseInputFile()` +- `chooseSaveTarget()` +- `readClipboard()` / `writeClipboard()` +- `downloadFile()` +- `openExternalUrl()` +- `notify()` +- `openRoute()` / `closeRoute()` +- `requestAttention()` +- `restartApplication()` + +Desktop implementations use Tauri plugins. Browser implementations use browser APIs, upload/download tokens, routes, and tabs. Unsupported capabilities are explicitly reported by session negotiation; they must not fail through missing globals. + +## 5. Security model + +### 5.1 Defaults + +```bash +tabularis web +``` + +means: + +- bind to `127.0.0.1`; +- choose port `8080`, or the next free port if explicitly configured to allow fallback; +- generate an ephemeral high-entropy session token; +- open a URL containing a one-time bootstrap token; +- exchange the bootstrap token for an HttpOnly, SameSite=Strict session cookie; +- redact tokens from logs; +- reject cross-origin requests. + +### 5.2 Remote mode + +Binding to a non-loopback interface must require an explicit option: + +```bash +tabularis web --host 0.0.0.0 --auth password +``` + +Remote mode acceptance requirements: + +- password or external reverse-proxy authentication is mandatory; +- TLS is required directly or documented as a reverse-proxy requirement; +- allowed origins are explicit; +- secure cookies are enabled under TLS; +- login attempts are rate-limited; +- database, SSH, K8s, plugin, filesystem, MCP, and AI operations are authorization-scoped; +- audit logs identify session and request IDs without recording secrets or full SQL result payloads. + +Remote mode should be implemented after local parity, not as part of the first MVP. + +### 5.3 Filesystem safety + +Browser-provided paths are never trusted as server paths. Import flows use uploaded temporary files. Export flows use generated download tokens. Any optional server-side path access requires a separate local/admin capability and canonical path validation. + +## 6. Feature-parity matrix + +The matrix is a tracked artifact in the branch. Every row must end with automated tests and a manual check. + +| Area | Web behavior | Parity type | Primary transport needs | +|---|---|---|---| +| Application startup | `tabularis web`, static serving, browser open | Adapted | CLI/HTTP | +| Remote access | Password or trusted-proxy authentication, HTTPS origin allowlist, restricted-by-default capability policy | Adapted/security-scoped | CLI/HTTP/audit | +| Connections and groups | Full CRUD, tags, icons, duplicate/import/export | Identical/adapted files | RPC/upload/download | +| MySQL/PostgreSQL/SQLite | Existing drivers and pools | Identical | Shared services | +| SSH tunnels and askpass | Prompt delivered to active authorized web session | Adapted | RPC/WebSocket | +| K8s tunnels | Existing backend commands and progress | Identical | RPC/WebSocket | +| Schema explorer | Databases, schemas, tables, views, routines, triggers | Identical | RPC | +| SQL editor | Execute, batch, count, cancel, history, saved queries | Identical | RPC/WebSocket | +| Results/data grid | Edit, insert, delete, blobs, referenced records | Identical/adapted files | RPC/upload/download | +| Multiple result windows | Browser route/tab with session ID | Adapted | Routes/RPC/events | +| ER/schema diagram | Browser route/tab and download | Adapted | RPC/download | +| Views/routines/triggers | Existing create/edit/drop behavior | Identical | RPC | +| User management | Existing users/grants/privileges behavior | Identical | RPC | +| Notebooks | CRUD, execution, import/export, charts | Identical/adapted files | RPC/upload/download | +| Dump/import | Server-side jobs, browser upload/download, progress | Adapted | RPC/events/streaming | +| Clipboard import | Browser clipboard permission and shared parser/backend | Adapted | Browser capability/RPC | +| AI features | Queries, explanations, plans, names, approvals/activity | Identical | RPC/WebSocket | +| Settings/keybindings/themes | Same persisted settings and custom themes | Identical | RPC | +| Credentials/keychain | Secrets remain backend-side | Identical security outcome | Shared secret service | +| Plugin drivers | Existing subprocess/JSON-RPC backend | Identical | Shared services | +| Plugin registry/install | Existing registry and installer with progress | Identical | RPC/WebSocket | +| Plugin UI extensions | Authenticated asset loading and same host API | Adapted loader | Static assets/CSP | +| Logs/task manager | Same backend information and actions | Identical | RPC/events | +| Backups | Same scheduler and manual execution | Identical/adapted files | RPC/download | +| MCP configuration | Local host operation only; hidden/blocked remotely by default | Adapted/security-scoped | RPC | +| Deep links | Browser URL or explicit install route | Adapted | Routing | +| Updater | Desktop updater; web shows server version/upgrade guidance | Not applicable/adapted | Capability flag | +| DevTools/window title | Browser-native behavior | Not applicable | Capability flag | +| Performance and resilience | Bounded RPC, results, events, transfers, jobs, sessions, and recovery paths | Identical/adapted lifecycle | RPC/events/runtime/CI | + +## 7. Standard task loop + +Run this loop for **every task**, including migration tasks. A task is not complete until the loop closes. + +### LOOP-01 — Select and baseline + +1. Select exactly one task ID from this plan. +2. Confirm `git status` and do not include unrelated changes. +3. Pull/rebase `feat/web-ui` on the agreed base. +4. Re-run GitNexus analysis if stale. +5. Record affected symbols and current behavior. +6. Run focused baseline tests before changing code. + +### LOOP-02 — Impact and contract + +1. Run upstream impact analysis for every existing symbol to be edited. +2. Report HIGH or CRITICAL risk before editing. +3. Write or update the command/capability contract first. +4. Add a failing test for the desired behavior. +5. Define desktop and web acceptance criteria. + +### LOOP-03 — Implement minimally + +1. Implement the smallest vertical change. +2. Keep the Tauri command name and payload backward compatible unless the task explicitly versions the contract. +3. Extract shared logic before adding the web adapter. +4. Do not copy existing business logic into the HTTP handler. +5. Keep feature flags or capability checks explicit. + +### LOOP-04 — Verify + +Run, as applicable: + +```bash +pnpm typecheck +pnpm lint +pnpm test --run +pnpm --filter @tabularis/web-ui build +pnpm test:rust +pnpm build +``` + +For transport tasks, run the same contract test against Tauri mocks and the real HTTP test server. + +### LOOP-05 — Inspect and commit + +1. Run GitNexus change detection against `main` and inspect affected flows. +2. Review `git diff --check` and the complete task diff. +3. Update the parity matrix and task status. +4. Add manual-test evidence where required. +5. Create one conventional commit for the task. +6. Push `feat/web-ui` and continue only from a green state. + +Suggested commit format: + +```text +feat(web): add typed RPC transport +refactor(api): extract shared query service +feat(web): adapt notebook downloads +``` + +### Definition of done for each migrated command group + +- No direct business logic exists in the HTTP transport. +- Desktop tests still pass. +- Web contract tests pass. +- Request and response types are explicit. +- Errors use the shared error envelope. +- Events are tested where relevant. +- Authorization requirements are declared. +- Feature matrix status is updated. +- No new direct Tauri import is introduced outside Tauri adapters. + +## 8. Branch and delivery strategy + +### Initial branch setup + +Do not create the branch from a dirty working tree. The current checkout has an unrelated modification to `AGENTS.md`; preserve it outside this feature branch before starting. + +```bash +git status --short +git switch main +git pull --ff-only +git switch -c feat/web-ui +``` + +If the existing local change belongs elsewhere, commit it on its own branch or stash it before creating `feat/web-ui`. + +### Integration strategy + +- Keep `feat/web-ui` buildable after every commit. +- Use small vertical commits instead of one final migration commit. +- Merge/rebase `main` regularly because the branch is expected to be long-lived. +- Hide incomplete web functionality behind capability negotiation, not scattered environment checks. +- Do not merge until desktop CI, web CI, Rust tests, security tests, and the agreed parity gate pass. +- If the branch becomes too large for review, open stacked PRs from milestone branches into `feat/web-ui`, then one final PR from `feat/web-ui` into `main`. + +## 9. Execution backlog + +Each backlog item lives in a separate file under `../tasks/`. The task runner +uses `../tasks/PROGRESS.md` as the completion ledger and skips validated +`COMPLETED` tasks unless `--force` is supplied. + +| Phase | Task | +|---|---| +| Phase 0 — Governance and measurable baseline (3–5 days) | [WEB-000 — Create `feat/web-ui`](../tasks/WEB-000.md) | +| Phase 0 — Governance and measurable baseline (3–5 days) | [WEB-001 — Generate the API inventory](../tasks/WEB-001.md) | +| Phase 0 — Governance and measurable baseline (3–5 days) | [WEB-002 — Add architecture decision records](../tasks/WEB-002.md) | +| Phase 1 — Frontend transport seam (8–12 days) | [WEB-010 — Define typed command and event contracts](../tasks/WEB-010.md) | +| Phase 1 — Frontend transport seam (8–12 days) | [WEB-011 — Add `TabularisClientProvider`](../tasks/WEB-011.md) | +| Phase 1 — Frontend transport seam (8–12 days) | [WEB-012 — Define platform capabilities](../tasks/WEB-012.md) | +| Phase 1 — Frontend transport seam (8–12 days) | [WEB-013 — Migrate a representative vertical slice](../tasks/WEB-013.md) | +| Phase 1 — Frontend transport seam (8–12 days) | [WEB-014 — Enforce frontend boundaries](../tasks/WEB-014.md) | +| Phase 2 — Create `packages/web-ui` without duplication (5–8 days) | [WEB-020 — Scaffold workspace package](../tasks/WEB-020.md) | +| Phase 2 — Create `packages/web-ui` without duplication (5–8 days) | [WEB-021 — Move frontend source and assets](../tasks/WEB-021.md) | +| Phase 2 — Create `packages/web-ui` without duplication (5–8 days) | [WEB-022 — Make routing server-safe](../tasks/WEB-022.md) | +| Phase 3 — Headless backend bootstrap (8–12 days) | [WEB-030 — Extend CLI](../tasks/WEB-030.md) | +| Phase 3 — Headless backend bootstrap (8–12 days) | [WEB-031 — Extract shared bootstrap](../tasks/WEB-031.md) | +| Phase 3 — Headless backend bootstrap (8–12 days) | [WEB-032 — Add HTTP server skeleton](../tasks/WEB-032.md) | +| Phase 3 — Headless backend bootstrap (8–12 days) | [WEB-033 — Local session security](../tasks/WEB-033.md) | +| Phase 4 — RPC and event infrastructure (8–12 days) | [WEB-040 — Implement versioned RPC dispatcher](../tasks/WEB-040.md) | +| Phase 4 — RPC and event infrastructure (8–12 days) | [WEB-041 — Implement WebSocket event bus](../tasks/WEB-041.md) | +| Phase 4 — RPC and event infrastructure (8–12 days) | [WEB-042 — Implement browser HTTP transport](../tasks/WEB-042.md) | +| Phase 4 — RPC and event infrastructure (8–12 days) | [WEB-043 — Add dual-transport contract harness](../tasks/WEB-043.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-050 — Connections, groups, tags, and appearance](../tasks/WEB-050.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-051 — SSH and K8s connections](../tasks/WEB-051.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-052 — Metadata explorer](../tasks/WEB-052.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-053 — Query execution](../tasks/WEB-053.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-054 — Data editing and blobs](../tasks/WEB-054.md) | +| Phase 5 — Core database parity (15–22 days) | [WEB-055 — Database objects and user management](../tasks/WEB-055.md) | +| Phase 6 — Persistence and productivity parity (10–15 days) | [WEB-060 — Settings, keybindings, and themes](../tasks/WEB-060.md) | +| Phase 6 — Persistence and productivity parity (10–15 days) | [WEB-061 — Saved queries and query history](../tasks/WEB-061.md) | +| Phase 6 — Persistence and productivity parity (10–15 days) | [WEB-062 — Notebooks](../tasks/WEB-062.md) | +| Phase 6 — Persistence and productivity parity (10–15 days) | [WEB-063 — Secondary windows](../tasks/WEB-063.md) | +| Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) | [WEB-070 — Upload/download token service](../tasks/WEB-070.md) | +| Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) | [WEB-071 — Connection import/export and backup](../tasks/WEB-071.md) | +| Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) | [WEB-072 — Database dump/import](../tasks/WEB-072.md) | +| Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) | [WEB-073 — Generic exports and logs](../tasks/WEB-073.md) | +| Phase 8 — AI, plugins, and operational parity (15–22 days) | [WEB-080 — AI and approval flows](../tasks/WEB-080.md) | +| Phase 8 — AI, plugins, and operational parity (15–22 days) | [WEB-081 — Plugin driver lifecycle](../tasks/WEB-081.md) | +| Phase 8 — AI, plugins, and operational parity (15–22 days) | [WEB-082 — Plugin UI extensions](../tasks/WEB-082.md) | +| Phase 8 — AI, plugins, and operational parity (15–22 days) | [WEB-083 — Logs and task manager](../tasks/WEB-083.md) | +| Phase 8 — AI, plugins, and operational parity (15–22 days) | [WEB-084 — MCP behavior](../tasks/WEB-084.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-090 — Clipboard, dialogs, notifications, and external URLs](../tasks/WEB-090.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-091 — Deep links and install links](../tasks/WEB-091.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-092 — Updater adaptation](../tasks/WEB-092.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-093 — Remote authenticated mode](../tasks/WEB-093.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-094 — Packaging](../tasks/WEB-094.md) | +| Phase 9 — Browser adaptations and release hardening (12–18 days) | [WEB-095 — Performance and resilience](../tasks/WEB-095.md) | +| Phase 10 — Final parity gate (8–12 days) | [WEB-100 — Automated E2E matrix](../tasks/WEB-100.md) | +| Phase 10 — Final parity gate (8–12 days) | [WEB-101 — Manual parity audit](../tasks/WEB-101.md) | +| Phase 10 — Final parity gate (8–12 days) | [WEB-102 — Documentation](../tasks/WEB-102.md) | +| Phase 10 — Final parity gate (8–12 days) | [WEB-103 — Merge readiness](../tasks/WEB-103.md) | + + +## 10. Recommended milestone cuts + +### Milestone A — Architecture proof + +Includes WEB-000 through WEB-043. + +Demo: + +```bash +tabularis web +``` + +loads `packages/web-ui` and executes a representative connection/query flow over HTTP/WebSocket. Desktop remains green. + +Expected effort: 6–9 weeks. + +### Milestone B — Database-manager MVP + +Includes Phase 5 and core portions of Phase 6. + +Demo: + +- connection management; +- schema navigation; +- SQL execution/cancellation; +- editable results; +- database object management; +- saved queries/history. + +Expected cumulative effort: 10–14 weeks. + +### Milestone C — Broad parity + +Includes Phases 6–8. + +Demo includes notebooks, imports/exports, dumps, backups, AI, plugins, logs, and task manager. + +Expected cumulative effort: 17–23 weeks. + +### Milestone D — Release parity + +Includes Phases 9–10, security audit, packaging, E2E, and documentation. + +Expected cumulative effort: 22–30 engineering weeks for one experienced full-time contributor. + +Two contributors can reduce calendar time, but not linearly. A realistic target is 14–20 calendar weeks if one contributor owns Rust/runtime/transport and the other owns frontend adapters/E2E, with shared review of contracts and security. + +## 11. Risk register + +| Risk | Impact | Mitigation | +|---|---|---| +| `AppHandle` coupling prevents headless startup | Critical | Extract runtime context incrementally before HTTP parity work | +| Hundreds of untyped string command calls drift | High | `CommandMap`, inventory script, dual-transport contract tests | +| Browser filesystem semantics differ | High | Upload/download tokens and semantic capability adapters | +| Remote access exposes database administration | Critical | Loopback default, explicit remote mode, auth/TLS/origin/audit controls | +| Large query results exhaust memory | High | Limits, pagination/streaming design, bounded WebSocket queues | +| SSH askpass reaches wrong browser session | Critical | Session ownership, timeout, explicit approval, audit trail | +| Plugin UI executes untrusted JavaScript | High | Existing trust model review, CSP, authenticated assets, version checks | +| Shared settings conflict across sessions | Medium | Separate global, user, and session state explicitly | +| Long-running branch diverges from `main` | High | Small commits, regular rebases, milestone/stacked PRs | +| Moving the frontend breaks release tooling | High | Establish transport seam first, move files in one mechanical task, preserve root delegator scripts | +| “Parity” becomes subjective | High | Machine-readable matrix with explicit adaptation and sign-off | + +## 12. Immediate next actions + +Execute only these tasks first: + +1. Resolve the unrelated `AGENTS.md` working-tree modification outside this feature. +2. Create and push `feat/web-ui` from current `main`. +3. Complete WEB-001 and commit the generated command/parity inventory. +4. Review and approve the ADRs in WEB-002 before choosing the HTTP framework or changing startup. +5. Implement WEB-010 through WEB-013 as a desktop-compatible transport seam. +6. Move the existing frontend to `packages/web-ui` only after the representative slice is green. +7. Stop after Milestone A for architecture and security review before bulk-migrating the remaining command groups. + +This ordering avoids a second UI, avoids a second backend API implementation, and validates the hardest assumptions before committing to the full parity migration. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0001-command-rpc.md b/web-ui-project/docs/architecture/decisions/ADR-0001-command-rpc.md new file mode 100644 index 000000000..e7e6af901 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0001-command-rpc.md @@ -0,0 +1,41 @@ +# ADR-0001: Preserve command semantics through versioned RPC + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +The desktop frontend invokes a large Tauri command surface. Modeling the same operations as individually designed REST resources would create a second public contract, duplicate transport code, and allow desktop and web behavior to drift. Many operations are commands, jobs, or queries that do not map naturally to resource-oriented CRUD. + +## Decision + +Expose browser-callable application operations through a versioned command RPC contract. Command names, request types, response types, authorization requirements, and errors are defined once and shared by both transports. + +The initial HTTP shape is `POST /api/v1/rpc/{command}`. Responses use one success or error envelope and include a request ID on errors. Existing Tauri command names and payloads remain backward compatible while their business logic is extracted into shared Rust application services. + +RPC dispatchers perform only transport duties: authentication, authorization, deserialization, validation at the transport boundary, service invocation, and response mapping. They must not contain copied business logic. + +## Consequences + +- Contract tests can exercise the same operation through Tauri and HTTP adapters. +- Existing commands can migrate incrementally without a big-bang API rewrite. +- RPC versioning and authorization metadata must be explicit. +- Resource caching and standard REST tooling are less automatic and must be added only where justified. + +## Rejected alternatives + +### Duplicate REST API + +Rejected because hundreds of separately modeled endpoints would duplicate semantics and increase parity drift. Purpose-built non-RPC endpoints remain appropriate for health, session negotiation, uploads, downloads, events, static assets, and authentication. + +### Expose Tauri IPC directly to browsers + +Rejected because Tauri IPC is unavailable in a normal browser and does not provide the required network security boundary. + +### GraphQL + +Rejected because it adds a second schema and resolver model without removing the need to support command and job semantics. + +### gRPC or gRPC-Web + +Rejected for the initial implementation because it adds code generation and browser proxy complexity while the current JSON command payloads map directly to JSON RPC over HTTP. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0002-shared-ui-package.md b/web-ui-project/docs/architecture/decisions/ADR-0002-shared-ui-package.md new file mode 100644 index 000000000..3d1847c53 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0002-shared-ui-package.md @@ -0,0 +1,42 @@ +# ADR-0002: Use one shared React UI package + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +Tabularis already has a substantial React application. A separate browser frontend would duplicate components, state, translations, styles, accessibility work, tests, and business rules. The platform differences are primarily transport and host capabilities, not product design. + +## Decision + +Move the existing React application into one workspace package, `packages/web-ui`, after transport and platform boundaries are established. Tauri and browsers both build and run this package. + +Components consume a typed `TabularisClient` and semantic platform capabilities supplied by providers. Components must not select a transport or import native APIs directly. Tauri-specific and browser-specific behavior lives in transport and capability adapters. The root package remains an orchestrator for workspace and Tauri scripts. + +The move is mechanical: preserve source history, tests, translations, themes, public assets, and desktop behavior. It must not be used as an opportunity for a visual rewrite. + +## Consequences + +- Product fixes and features are implemented once. +- Platform behavior is visible at explicit adapter boundaries. +- Shared components must handle negotiated unsupported capabilities intentionally. +- Build and release tooling must resolve the workspace package for both targets. +- Direct native imports must be prevented outside the Tauri adapters. + +## Rejected alternatives + +### Create a second browser application + +Rejected because it would immediately create two implementations and make long-term parity dependent on duplicated work. + +### Share only a component library + +Rejected because separate application shells would still duplicate contexts, hooks, routing, state transitions, command use, translations, and tests. + +### Use micro-frontends per platform + +Rejected because deployment independence is not a goal and the added runtime and integration complexity would weaken the single-UI constraint. + +### Keep platform checks scattered through components + +Rejected because checks for Tauri globals or browser globals hide unsupported behavior, are difficult to test, and couple presentation code to hosts. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0003-http-and-websocket-transport.md b/web-ui-project/docs/architecture/decisions/ADR-0003-http-and-websocket-transport.md new file mode 100644 index 000000000..f8aa538e5 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0003-http-and-websocket-transport.md @@ -0,0 +1,43 @@ +# ADR-0003: Use HTTP for commands and WebSocket for events + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +Browser clients need request-response operations as well as asynchronous notifications, progress, cancellation coordination, prompts, and job state. Tauri currently provides invocation and event primitives, but browsers need standard network transports with equivalent observable behavior. + +## Decision + +Use authenticated HTTP for request-response operations and one authenticated WebSocket event channel per browser session for server-originated events. + +HTTP carries versioned RPC, session negotiation, health, upload, download, plugin asset, and static asset requests. The WebSocket carries typed event envelopes with event name, payload, request or correlation ID where applicable, and ordering information where a workflow requires it. + +The application publishes events through a runtime event abstraction. Tauri and WebSocket adapters consume that abstraction; application services do not depend on either host. Implement bounded per-session queues, disconnect handling, subscription cleanup, and an explicit overflow policy before event-heavy features migrate. + +The Rust HTTP framework is deliberately not selected by this ADR. It must support the security model, graceful shutdown, test servers, streaming, WebSockets, and shared runtime state without forcing business logic into handlers. + +## Consequences + +- Browsers use widely supported transports and ordinary JSON diagnostics. +- Commands and events remain independently testable through a shared typed contract. +- Reconnection, missed-event behavior, backpressure, and session ownership must be defined per workflow. +- Large result sets must use limits, pagination, or purpose-built streaming rather than unbounded event messages. + +## Rejected alternatives + +### HTTP polling for all events + +Rejected because polling adds latency and repeated load for progress, prompts, cancellation, and task updates. + +### WebSocket for both commands and events + +Rejected because request-response calls gain unnecessary correlation, retry, timeout, and reconnect complexity. HTTP already provides the required semantics. + +### Server-Sent Events + +Rejected as the sole event transport because workflows such as askpass and approvals require session-aware bidirectional coordination. SSE may be reconsidered only through a superseding decision. + +### Framework-specific application events + +Rejected because coupling services to Tauri or a web framework would prevent one headless runtime and one set of business rules. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0004-local-secure-default.md b/web-ui-project/docs/architecture/decisions/ADR-0004-local-secure-default.md new file mode 100644 index 000000000..1f8a1d192 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0004-local-secure-default.md @@ -0,0 +1,45 @@ +# ADR-0004: Make local authenticated access the secure default + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +Tabularis can administer databases, credentials, tunnels, plugins, files, AI providers, and local processes. Starting a web server therefore creates a security boundary even when the intended user is local. Binding broadly or relying only on network location could expose privileged operations unexpectedly. + +## Decision + +`tabularis web` binds to `127.0.0.1` by default and still requires an authenticated browser session. Startup generates high-entropy ephemeral credentials and opens a URL containing a single-use, short-lived bootstrap token. The server exchanges it for an `HttpOnly`, `SameSite=Strict` session cookie and removes the token from subsequent URLs. + +The local server rejects unexpected origins and hosts, redacts credentials and bootstrap URLs from logs, and exposes no sensitive data from its liveness endpoint. Session and request IDs may be logged, but secrets and full SQL result payloads may not. + +Non-loopback binding is a separate remote mode. It requires an explicit host option, configured authentication, explicit allowed origins, and TLS either directly or through a documented trusted reverse proxy. Authorization scopes, rate limiting, secure cookies, and auditing are required before remote mode is released. + +## Consequences + +- Local web mode is not an unauthenticated administration endpoint. +- Copying an ordinary post-bootstrap URL does not transfer the bootstrap secret. +- Session lifecycle, CSRF defenses, origin checks, token expiry, and log redaction require security tests. +- Remote mode is deferred until local parity and its additional controls are complete. + +## Rejected alternatives + +### Bind to all interfaces by default + +Rejected because it can expose database administration to the local network without informed consent. + +### Trust loopback without authentication + +Rejected because local malware, malicious pages, DNS rebinding, shared machines, and browser-origin attacks can still target local services. + +### Keep a bearer token in the URL + +Rejected because URLs leak through history, screenshots, referrers, logs, and copy-and-paste. Only a short-lived single-use bootstrap token may appear in the initial URL. + +### Store the session token in browser storage + +Rejected because JavaScript-readable storage increases the impact of script injection. An `HttpOnly` cookie is the default session credential. + +### Ship remote mode with local mode + +Rejected because remote exposure requires a broader authorization, TLS, deployment, and audit design that should not delay or weaken the local architecture proof. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0005-opaque-file-transfer-tokens.md b/web-ui-project/docs/architecture/decisions/ADR-0005-opaque-file-transfer-tokens.md new file mode 100644 index 000000000..56ec5d450 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0005-opaque-file-transfer-tokens.md @@ -0,0 +1,43 @@ +# ADR-0005: Transfer browser files through opaque tokens + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +Desktop dialogs return local paths that the native process can read or write. A browser path is not a trustworthy or meaningful server path, especially when the browser and Tabularis server are on different machines. Passing user-supplied paths to backend commands would permit path confusion and unauthorized filesystem access. + +## Decision + +Browser import workflows upload bytes to a server-managed temporary area and receive an opaque file token. Commands accept that token, not a browser-provided server path. Browser export workflows generate a server-side artifact and return an opaque download token consumed through an authenticated endpoint. + +Tokens are unguessable, bound to the authenticated session and intended operation, short-lived, and revocable. Upload limits, content validation, cleanup, and atomic file handling are mandatory. Download tokens are single-use where the workflow permits it. Token metadata may contain a display filename, media type, size, and expiry, but never grants arbitrary path selection. + +Desktop capability adapters may continue to use native file dialogs and paths. Both adapters call the same import, export, parsing, and job services after resolving their transport-specific file handle. + +Any future server-side path feature is a separate local-admin capability. It requires an explicit contract, canonicalization, allow-list or user-approved roots, and authorization checks. + +## Consequences + +- Browser clients cannot reinterpret a displayed filename as a backend path. +- Import and export business logic remains shared after file handles are resolved. +- Temporary storage quotas, expiry, interrupted transfer cleanup, and race conditions require tests. +- Large transfers need bounded or streaming I/O rather than buffering entire files in memory. + +## Rejected alternatives + +### Send browser path strings to commands + +Rejected because browser paths may be fake, partial, client-local, or malicious and must never select server files. + +### Expose a general server filesystem browser + +Rejected because broad filesystem access is not required for parity and substantially increases privilege and traversal risk. + +### Embed all files in RPC JSON + +Rejected because base64 increases memory and payload size, obscures upload limits, and is unsuitable for dumps, backups, blobs, and other large artifacts. + +### Duplicate import and export logic in web handlers + +Rejected because transport handlers should only resolve tokens and invoke the same application services used by desktop workflows. diff --git a/web-ui-project/docs/architecture/decisions/ADR-0006-browser-semantic-adaptations.md b/web-ui-project/docs/architecture/decisions/ADR-0006-browser-semantic-adaptations.md new file mode 100644 index 000000000..f1f6dd882 --- /dev/null +++ b/web-ui-project/docs/architecture/decisions/ADR-0006-browser-semantic-adaptations.md @@ -0,0 +1,49 @@ +# ADR-0006: Adapt desktop lifecycle semantics for browsers + +- **Status:** Accepted +- **Date:** 2026-08-21 + +## Context + +Some desktop capabilities have no identical browser primitive. Secondary native windows, window titles, attention requests, deep links, application restart, and the Tauri updater are host lifecycle concerns rather than database business logic. Pretending these APIs exist in a browser would produce brittle checks and incomplete workflows. + +## Decision + +Represent host operations as semantic platform capabilities and negotiate their availability at session startup. Shared components request outcomes such as opening a route, downloading a file, notifying the user, opening an external URL, requesting attention, or restarting the application. Platform adapters decide how to provide or reject each capability. + +Browser adaptations are: + +- secondary windows become routes or browser tabs keyed by a session or result identifier; +- native window title and chrome use browser title, routing, and browser-native controls; +- attention and notifications use permitted browser APIs with in-app fallback; +- deep links become browser URLs or an explicit installation route; +- restart means reconnecting or reloading only when the server reports that action as supported; +- desktop keeps the Tauri updater, while web reports server version and administrator upgrade guidance. + +Unsupported capabilities are explicit typed results and capability flags. Components must not infer the host from globals or fail because a native plugin is absent. Adapted workflows preserve the user outcome and shared business state, not native window mechanics. + +## Consequences + +- Desktop-only lifecycle behavior is documented rather than counted as missing parity. +- Shared components remain host-independent and testable with capability fakes. +- Browser permission denial and popup blocking need intentional fallbacks. +- Routes and event ownership must prevent stale secondary views from observing another session. +- Updating a web deployment remains an administrator operation, not a browser-side replacement for the desktop updater. + +## Rejected alternatives + +### Reproduce native windows exactly in the browser + +Rejected because browser tabs and routes have different ownership and security semantics; visual imitation does not provide native lifecycle control. + +### Remove desktop-only features from the shared UI + +Rejected because desktop behavior must remain compatible and capability adapters allow both hosts to share presentation code. + +### Scatter host detection through components + +Rejected because checks for Tauri or browser globals are untyped, difficult to test, and make unsupported states implicit. + +### Let the browser update server binaries + +Rejected because a browser session must not gain package-management authority. Web mode provides version information and deployment-specific guidance instead. diff --git a/web-ui-project/docs/web-ui-parity.json b/web-ui-project/docs/web-ui-parity.json new file mode 100644 index 000000000..d962a3170 --- /dev/null +++ b/web-ui-project/docs/web-ui-parity.json @@ -0,0 +1,565 @@ +{ + "schemaVersion": 1, + "generatedBy": "pnpm web:inventory:write", + "sources": { + "frontend": "packages/web-ui/src", + "tauriHandler": "src-tauri/src/transport/desktop/mod.rs" + }, + "classifications": { + "featureGroup": [ + "ai", + "application", + "backup", + "configuration", + "connections", + "data", + "database-objects", + "drivers", + "files", + "k8s", + "logs", + "metadata", + "notebooks", + "plugins", + "queries", + "saved-queries", + "ssh", + "tasks", + "themes", + "users", + "windows" + ], + "eventUse": [ + "none", + "emits", + "event-coordinated" + ], + "filesystemUse": [ + "none", + "read", + "write", + "read-write" + ], + "authorizationLevel": [ + "session", + "database", + "sensitive", + "local-admin" + ] + }, + "classificationNotes": { + "eventUse": "Whether command completion or progress participates in the frontend event bus.", + "filesystemUse": "User-visible host filesystem access only; internal application persistence is classified as none.", + "authorizationLevel": "Minimum intended web authorization scope; all levels still require an authenticated session." + }, + "summary": { + "literalCommandCount": 15, + "literalCallSiteCount": 16, + "dynamicCallSiteCount": 0, + "handlerRegistrationCount": 296, + "registeredCommandCount": 296, + "duplicateHandlerRegistrations": [], + "frontendCommandsMissingRegistration": [], + "registeredCommandsWithoutFrontendCall": 281 + }, + "commands": [ + { + "name": "check_for_updates", + "featureGroup": "application", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/contexts/UpdateProvider.tsx", + "line": 56 + } + ] + }, + { + "name": "consume_pending_deep_link_install", + "featureGroup": "application", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/hooks/useDeepLinkInstall.ts", + "line": 69 + } + ] + }, + { + "name": "download_and_install_update", + "featureGroup": "application", + "eventUse": "event-coordinated", + "filesystemUse": "write", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/contexts/UpdateProvider.tsx", + "line": 101 + } + ] + }, + { + "name": "fetch_blob", + "featureGroup": "data", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "database", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 420 + } + ] + }, + { + "name": "get_app_data_dir", + "featureGroup": "configuration", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 100 + } + ] + }, + { + "name": "get_linux_system_theme", + "featureGroup": "themes", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 116 + } + ] + }, + { + "name": "get_pending_explain_file", + "featureGroup": "files", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "sensitive", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/pages/VisualExplainPage.tsx", + "line": 93 + } + ] + }, + { + "name": "load_blob_from_file", + "featureGroup": "data", + "eventUse": "none", + "filesystemUse": "read", + "authorizationLevel": "sensitive", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 397 + } + ] + }, + { + "name": "load_explain_from_file", + "featureGroup": "files", + "eventUse": "none", + "filesystemUse": "read", + "authorizationLevel": "sensitive", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/pages/VisualExplainPage.tsx", + "line": 59 + } + ] + }, + { + "name": "open_connection_window", + "featureGroup": "windows", + "eventUse": "emits", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 277 + } + ] + }, + { + "name": "open_storage_location", + "featureGroup": "configuration", + "eventUse": "none", + "filesystemUse": "read", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 290 + } + ] + }, + { + "name": "read_file_as_data_url", + "featureGroup": "files", + "eventUse": "none", + "filesystemUse": "read", + "authorizationLevel": "sensitive", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 405 + } + ] + }, + { + "name": "relaunch_app", + "featureGroup": "application", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 289 + } + ] + }, + { + "name": "save_connection_icon", + "featureGroup": "connections", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "database", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/platform/tauriCapabilities.ts", + "line": 388 + } + ] + }, + { + "name": "set_window_title", + "featureGroup": "windows", + "eventUse": "none", + "filesystemUse": "none", + "authorizationLevel": "local-admin", + "registered": true, + "callSites": [ + { + "file": "packages/web-ui/src/contexts/DatabaseProvider.tsx", + "line": 196 + }, + { + "file": "packages/web-ui/src/pages/Editor.tsx", + "line": 726 + } + ] + } + ], + "dynamicInvocations": [], + "registeredCommandsWithoutFrontendCall": [ + "add_query_history_entry", + "alter_view", + "analyze_ai_explain_plan", + "apply_connection_import", + "apply_db_user_privileges", + "apply_prepared_tabularis_import", + "build_routine_call_sql", + "cancel_chatgpt_sign_in", + "cancel_database_backup", + "cancel_dump", + "cancel_export", + "cancel_import", + "cancel_plugin_install", + "cancel_query", + "cancel_theme_install", + "check_ai_key", + "check_ai_key_status", + "clear_ai_activity", + "clear_logs", + "clear_query_history", + "close_devtools", + "count_query", + "create_connection_group", + "create_connection_tag", + "create_db_user", + "create_group_path", + "create_notebook", + "create_personal_snapshot", + "create_personal_theme", + "create_saved_query_folder", + "create_sqlite_database", + "create_sqlite_file", + "create_trigger", + "create_view", + "decide_pending_approval", + "delete_ai_key", + "delete_connection", + "delete_connection_group", + "delete_connection_icon", + "delete_connection_tag", + "delete_custom_theme", + "delete_editor_preferences", + "delete_k8s_connection", + "delete_notebook", + "delete_proxy_password", + "delete_query_history_entry", + "delete_record", + "delete_saved_query", + "delete_saved_query_folder", + "delete_ssh_connection", + "delete_ui_state", + "detect_blob_mime", + "detect_mime_type", + "disable_plugin", + "disconnect_connection", + "drop_db_user", + "drop_foreign_key_action", + "drop_index_action", + "drop_routine", + "drop_trigger", + "drop_view", + "dump_database", + "duplicate_connection", + "duplicate_personal_theme", + "enable_plugin", + "execute_clipboard_import", + "execute_query", + "execute_query_batch", + "explain_ai_query", + "explain_query_plan", + "export_ai_activity_csv", + "export_ai_activity_json", + "export_ai_session_as_notebook", + "export_connections_file", + "export_logs", + "export_query_to_file", + "export_theme", + "fetch_blob_as_data_url", + "fetch_plugin_readme", + "fetch_plugin_registry", + "fetch_tabularium_plugin_preview", + "fetch_theme_package_detail", + "fetch_theme_registry", + "generate_ai_query", + "generate_cell_name", + "generate_tab_rename", + "get_active_connections", + "get_add_column_sql", + "get_ai_activity", + "get_ai_models", + "get_ai_schema_context", + "get_ai_session_events", + "get_ai_sessions", + "get_all_themes", + "get_alter_column_sql", + "get_available_databases", + "get_cellname_prompt", + "get_chatgpt_models", + "get_chatgpt_session", + "get_column_stats", + "get_columns", + "get_config", + "get_config_json", + "get_connection_by_id", + "get_connection_groups", + "get_connection_metadata", + "get_connections", + "get_connections_backup_status", + "get_connections_with_groups", + "get_create_foreign_key_sql", + "get_create_index_sql", + "get_create_table_sql", + "get_data_types", + "get_database_backup_status", + "get_db_privilege_catalog", + "get_db_user_grants", + "get_db_user_privileges", + "get_db_users", + "get_driver_manifest", + "get_drop_table_sql", + "get_explain_prompt", + "get_explainplan_prompt", + "get_file_stats", + "get_foreign_keys", + "get_indexes", + "get_installation_source", + "get_installed_plugins", + "get_k8s_connections", + "get_k8s_contexts_cmd", + "get_k8s_namespaces_cmd", + "get_k8s_resource_ports_cmd", + "get_k8s_resources_cmd", + "get_keybindings", + "get_last_active_connection", + "get_last_open_connections", + "get_log_settings", + "get_logs", + "get_materialized_view_columns", + "get_materialized_view_definition", + "get_materialized_views", + "get_mcp_status", + "get_plugin_dir", + "get_plugin_manifest", + "get_plugin_runtime_warnings", + "get_plugin_startup_errors", + "get_process_list", + "get_query_history", + "get_registered_drivers", + "get_routine_create_template", + "get_routine_definition", + "get_routine_edit_script", + "get_routine_parameters", + "get_routines", + "get_saved_queries", + "get_saved_query_folders", + "get_schema_preference", + "get_schema_snapshot", + "get_schemas", + "get_selected_schemas", + "get_server_now", + "get_ssh_connections", + "get_storage_location", + "get_system_prompt", + "get_system_stats", + "get_table_query_template", + "get_tables", + "get_tabrename_prompt", + "get_tabularis_children", + "get_theme_catalog", + "get_trigger_definition", + "get_triggers", + "get_ui_state", + "get_view_columns", + "get_view_definition", + "get_views", + "import_database", + "import_theme", + "insert_record", + "inspect_storage_location", + "install_local_theme_package", + "install_mcp_config", + "install_plugin", + "install_registry_theme", + "is_debug_mode", + "kill_plugin_process", + "list_connection_import_sources", + "list_connection_tags", + "list_databases", + "list_notebooks", + "list_pending_approvals", + "load_editor_preferences", + "load_notebook", + "log_frontend_event", + "map_inferred_column_types", + "move_connection_to_group", + "move_group_to_parent", + "move_saved_query", + "open_chatgpt_usage", + "open_devtools", + "open_er_diagram_window", + "open_plugins_dir", + "open_task_manager_window", + "preview_connection_import", + "preview_local_theme_package", + "preview_tabularis_import_file", + "preview_theme_document", + "proxy_password_is_set", + "read_plugin_file", + "read_sql_file", + "recover_theme_packages", + "refresh_materialized_view", + "register_active_connection", + "release_query_session", + "rename_notebook", + "rename_saved_query_folder", + "reorder_connections_in_group", + "reorder_groups", + "reset_cellname_prompt", + "reset_explain_prompt", + "reset_explainplan_prompt", + "reset_storage_location", + "reset_system_prompt", + "reset_tabrename_prompt", + "respond_ssh_askpass", + "restart_plugin_process", + "run_connections_backup", + "run_database_backup_now", + "save_cellname_prompt", + "save_config", + "save_config_json", + "save_connection", + "save_custom_theme", + "save_editor_preferences", + "save_explain_prompt", + "save_explainplan_prompt", + "save_k8s_connection", + "save_keybindings", + "save_notebook", + "save_query", + "save_ssh_connection", + "save_system_prompt", + "save_tabrename_prompt", + "select_chatgpt_profile", + "set_ai_key", + "set_connection_appearance", + "set_connection_tags", + "set_connections_backup_password", + "set_connections_backup_target_password", + "set_db_user_password", + "set_last_active_connection", + "set_last_open_connections", + "set_log_enabled", + "set_log_max_size", + "set_proxy_password", + "set_schema_preference", + "set_selected_databases", + "set_selected_schemas", + "set_storage_location", + "set_theme_package_enabled", + "set_ui_state", + "sign_in_chatgpt", + "sign_out_chatgpt", + "suggest_table_name", + "test_connection", + "test_k8s_connection_cmd", + "test_log", + "test_ssh_connection", + "test_ssm_connection_cmd", + "uninstall_plugin", + "uninstall_theme_package", + "update_connection", + "update_connection_group", + "update_connection_tag", + "update_k8s_connection", + "update_personal_snapshot", + "update_personal_theme", + "update_record", + "update_saved_query", + "update_ssh_connection", + "validate_k8s_path_cmd", + "write_sql_file" + ] +} diff --git a/web-ui-project/e2e/docker-compose.yml b/web-ui-project/e2e/docker-compose.yml new file mode 100644 index 000000000..4ed7146c5 --- /dev/null +++ b/web-ui-project/e2e/docker-compose.yml @@ -0,0 +1,29 @@ +name: tabularis-web-e2e + +services: + postgres: + image: postgres:16 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: tabularis-e2e + POSTGRES_DB: tabularis_e2e + ports: + - '45432:5432' + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U postgres -d tabularis_e2e'] + interval: 2s + timeout: 3s + retries: 30 + + mysql: + image: mysql:8.4 + environment: + MYSQL_ROOT_PASSWORD: tabularis-e2e + MYSQL_DATABASE: tabularis_e2e + ports: + - '43306:3306' + healthcheck: + test: ['CMD', 'mysqladmin', 'ping', '-h', '127.0.0.1', '-uroot', '-ptabularis-e2e'] + interval: 2s + timeout: 3s + retries: 45 diff --git a/web-ui-project/e2e/fixtures/plugins/e2e-driver/.tabularium b/web-ui-project/e2e/fixtures/plugins/e2e-driver/.tabularium new file mode 100644 index 000000000..49f7b7f1a --- /dev/null +++ b/web-ui-project/e2e/fixtures/plugins/e2e-driver/.tabularium @@ -0,0 +1,35 @@ +{ + "name": "e2e-driver", + "version": "1.0.0", + "description": "Deterministic external driver used by the browser E2E matrix.", + "default_port": null, + "executable": "driver.py", + "interpreter": "python3", + "default_username": "", + "color": "#7c3aed", + "icon": "database", + "capabilities": { + "schemas": false, + "views": false, + "routines": false, + "file_based": false, + "folder_based": false, + "connection_string": false, + "identifier_quote": "\"", + "sql_dialect": "generic", + "alter_primary_key": false, + "alter_column": false, + "create_foreign_keys": false, + "no_connection_required": true, + "manage_tables": false, + "readonly": true + }, + "data_types": [ + { + "name": "TEXT", + "category": "string", + "requires_length": false, + "requires_precision": false + } + ] +} diff --git a/web-ui-project/e2e/fixtures/plugins/e2e-driver/driver.py b/web-ui-project/e2e/fixtures/plugins/e2e-driver/driver.py new file mode 100755 index 000000000..106f9e2cd --- /dev/null +++ b/web-ui-project/e2e/fixtures/plugins/e2e-driver/driver.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Deterministic JSON-RPC fixture driver for Tabularis browser E2E tests.""" + +import json +import sys + + +def success(request_id: int, result: object) -> dict[str, object]: + return {"jsonrpc": "2.0", "result": result, "id": request_id} + + +def error(request_id: int, message: str) -> dict[str, object]: + return { + "jsonrpc": "2.0", + "error": {"code": -32601, "message": message}, + "id": request_id, + } + + +def dispatch(request: dict[str, object]) -> dict[str, object]: + request_id = request.get("id") + if not isinstance(request_id, int): + return error(0, "Invalid request id") + + method = request.get("method") + if method in {"initialize", "ping", "test_connection"}: + return success(request_id, None) + if method == "get_databases": + return success(request_id, ["fixture"]) + if method == "get_schemas": + return success(request_id, []) + if method == "get_tables": + return success(request_id, [{"name": "plugin_fixture"}]) + if method == "execute_query": + return success( + request_id, + { + "columns": ["fixture"], + "rows": [["driver-plugin-ok"]], + "affected_rows": 0, + "truncated": False, + "pagination": { + "page": 1, + "page_size": 100, + "total_rows": 1, + "has_more": False, + }, + }, + ) + return error(request_id, "Method not found") + + +for line in sys.stdin: + try: + message = dispatch(json.loads(line)) + except (TypeError, ValueError, json.JSONDecodeError) as exception: + message = error(0, f"Invalid request: {exception}") + print(json.dumps(message), flush=True) diff --git a/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/.tabularium b/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/.tabularium new file mode 100644 index 000000000..35988bf7c --- /dev/null +++ b/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/.tabularium @@ -0,0 +1,34 @@ +{ + "name": "e2e-ui-extension", + "version": "1.0.0", + "description": "Deterministic UI extension used by the browser E2E matrix.", + "default_port": null, + "default_username": "", + "color": "#0d9488", + "icon": "puzzle", + "capabilities": { + "schemas": false, + "views": false, + "routines": false, + "file_based": false, + "folder_based": false, + "connection_string": false, + "identifier_quote": "\"", + "sql_dialect": "generic", + "alter_primary_key": false, + "alter_column": false, + "create_foreign_keys": false, + "no_connection_required": true, + "manage_tables": false, + "readonly": true + }, + "data_types": [], + "ui_extensions": [ + { + "slot": "sidebar.footer.actions", + "module": "ui/e2e-extension.js", + "api_version": "0.1.1", + "order": 1 + } + ] +} diff --git a/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/ui/e2e-extension.js b/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/ui/e2e-extension.js new file mode 100644 index 000000000..f2841724d --- /dev/null +++ b/web-ui-project/e2e/fixtures/plugins/e2e-ui-extension/ui/e2e-extension.js @@ -0,0 +1,10 @@ +var __tabularis_plugin__ = function E2eUiExtension() { + return React.createElement( + 'span', + { + 'data-testid': 'e2e-ui-extension', + style: {fontSize: '10px', padding: '0 4px'}, + }, + 'E2E UI extension loaded', + ); +}; diff --git a/web-ui-project/e2e/global-setup.ts b/web-ui-project/e2e/global-setup.ts new file mode 100644 index 000000000..addff34b9 --- /dev/null +++ b/web-ui-project/e2e/global-setup.ts @@ -0,0 +1,75 @@ +import type {FullConfig} from '@playwright/test'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +const SESSION_COOKIE = 'tabularis_session'; + +async function waitForLaunchUrl(filePath: string): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + try { + const value = (await fs.readFile(filePath, 'utf8')).trim(); + if (value.length > 0) return value; + } catch { + // The fake browser opener creates the file after server bootstrap. + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(`Timed out waiting for the Web UI launch URL at ${filePath}`); +} + +function cookieValue(setCookie: string): string { + const firstPair = setCookie.split(';', 1)[0]; + const separator = firstPair.indexOf('='); + if (separator < 1 || firstPair.slice(0, separator) !== SESSION_COOKIE) { + throw new Error('The bootstrap response did not issue a Tabularis session cookie'); + } + return firstPair.slice(separator + 1); +} + +export default async function globalSetup(config: FullConfig): Promise { + const rootDir = path.resolve(import.meta.dirname, '../..'); + const runtimeDir = path.resolve( + process.env.TABULARIS_E2E_RUNTIME_DIR ?? path.join(rootDir, 'web-ui-project/.runtime/e2e'), + ); + const launchUrlFile = + process.env.TABULARIS_E2E_LAUNCH_URL_FILE ?? path.join(runtimeDir, 'launch-url'); + const launchUrl = await waitForLaunchUrl(launchUrlFile); + const response = await fetch(launchUrl, {redirect: 'manual'}); + if (response.status !== 303) { + throw new Error(`Web UI bootstrap failed with HTTP ${response.status}`); + } + const setCookie = response.headers.get('set-cookie'); + if (!setCookie) { + throw new Error('The bootstrap response omitted its session cookie'); + } + + const baseURL = config.projects[0]?.use.baseURL; + if (typeof baseURL !== 'string') { + throw new Error('The E2E project requires a base URL'); + } + const origin = new URL(baseURL); + await fs.mkdir(runtimeDir, {recursive: true}); + await fs.writeFile( + path.join(runtimeDir, 'storage-state.json'), + JSON.stringify( + { + cookies: [ + { + name: SESSION_COOKIE, + value: cookieValue(setCookie), + domain: origin.hostname, + path: '/', + expires: -1, + httpOnly: true, + secure: false, + sameSite: 'Strict', + }, + ], + origins: [], + }, + null, + 2, + ), + ); +} diff --git a/web-ui-project/e2e/playwright.config.ts b/web-ui-project/e2e/playwright.config.ts new file mode 100644 index 000000000..582dccd54 --- /dev/null +++ b/web-ui-project/e2e/playwright.config.ts @@ -0,0 +1,57 @@ +import {defineConfig, devices} from '@playwright/test'; +import path from 'node:path'; + +const rootDir = path.resolve(import.meta.dirname, '../..'); +const port = Number.parseInt(process.env.TABULARIS_E2E_PORT ?? '18080', 10); +const baseURL = `http://127.0.0.1:${port}`; +const runtimeDir = path.resolve( + process.env.TABULARIS_E2E_RUNTIME_DIR ?? path.join(rootDir, 'web-ui-project/.runtime/e2e'), +); +const chromiumExecutablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH; + +export default defineConfig({ + testDir: path.join(rootDir, 'web-ui-project/e2e/tests'), + outputDir: path.join(runtimeDir, 'test-results'), + globalSetup: path.join(rootDir, 'web-ui-project/e2e/global-setup.ts'), + fullyParallel: false, + workers: 1, + retries: process.env.CI ? 1 : 0, + reporter: process.env.CI + ? [['line'], ['html', {outputFolder: path.join(runtimeDir, 'report'), open: 'never'}]] + : 'list', + use: { + baseURL, + storageState: path.join(runtimeDir, 'storage-state.json'), + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + video: process.env.CI ? 'retain-on-failure' : 'off', + }, + webServer: { + command: 'bash web-ui-project/e2e/start-server.sh', + cwd: rootDir, + url: `${baseURL}/healthz`, + timeout: 120_000, + reuseExistingServer: false, + stdout: 'pipe', + stderr: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + launchOptions: chromiumExecutablePath + ? {executablePath: chromiumExecutablePath} + : undefined, + }, + }, + { + name: 'firefox', + use: {...devices['Desktop Firefox']}, + }, + { + name: 'webkit', + use: {...devices['Desktop Safari']}, + }, + ], +}); diff --git a/web-ui-project/e2e/run.sh b/web-ui-project/e2e/run.sh new file mode 100755 index 000000000..4154e0b0c --- /dev/null +++ b/web-ui-project/e2e/run.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +COMPOSE_FILE="$ROOT_DIR/web-ui-project/e2e/docker-compose.yml" +MANAGED_DATABASES="${TABULARIS_E2E_MANAGED_DATABASES:-0}" + +cd "$ROOT_DIR" + +cleanup() { + if [[ "$MANAGED_DATABASES" != "1" ]]; then + docker compose -f "$COMPOSE_FILE" down --volumes --remove-orphans + fi +} +trap cleanup EXIT + +if [[ "$MANAGED_DATABASES" != "1" ]]; then + docker compose -f "$COMPOSE_FILE" up --detach --wait +fi + +pnpm typecheck:web-e2e + +if [[ "${TABULARIS_E2E_SKIP_BUILD:-0}" != "1" ]]; then + pnpm --filter @tabularis/web-ui build + cargo build --manifest-path src-tauri/Cargo.toml +fi + +if [[ -z "${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-}" && -x /usr/bin/chromium ]]; then + export PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium +fi + +pnpm exec playwright test \ + --config web-ui-project/e2e/playwright.config.ts \ + "$@" diff --git a/web-ui-project/e2e/start-server.sh b/web-ui-project/e2e/start-server.sh new file mode 100755 index 000000000..37b0a4a84 --- /dev/null +++ b/web-ui-project/e2e/start-server.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +RUNTIME_DIR="${TABULARIS_E2E_RUNTIME_DIR:-$ROOT_DIR/web-ui-project/.runtime/e2e}" +RUNTIME_DIR="$(python3 -c 'import os, sys; print(os.path.abspath(sys.argv[1]))' "$RUNTIME_DIR")" +if [[ "$RUNTIME_DIR" == "/" || "$RUNTIME_DIR" == "$ROOT_DIR" || "$RUNTIME_DIR" == "$HOME" ]]; then + echo "Refusing to clear unsafe E2E runtime directory: $RUNTIME_DIR" >&2 + exit 1 +fi +PORT="${TABULARIS_E2E_PORT:-18080}" +CONFIG_HOME="$RUNTIME_DIR/config" +DATA_HOME="$RUNTIME_DIR/data" +APP_CONFIG_DIR="$CONFIG_HOME/tabularis" +APP_DATA_DIR="$DATA_HOME/tabularis" +LAUNCH_URL_FILE="${TABULARIS_E2E_LAUNCH_URL_FILE:-$RUNTIME_DIR/launch-url}" +SQLITE_PATH="${TABULARIS_E2E_SQLITE_PATH:-$RUNTIME_DIR/tabularis-e2e.sqlite}" +FIXTURE_PLUGINS="$ROOT_DIR/web-ui-project/e2e/fixtures/plugins" + +rm -rf "$RUNTIME_DIR" +mkdir -p "$APP_CONFIG_DIR" "$APP_DATA_DIR/plugins" "$RUNTIME_DIR/home" "$RUNTIME_DIR/bin" +cp -R "$FIXTURE_PLUGINS"/. "$APP_DATA_DIR/plugins/" + +cat >"$APP_CONFIG_DIR/config.json" <<'JSON' +{ + "activeExternalDrivers": ["e2e-driver", "e2e-ui-extension"], + "showWelcome": false, + "checkForUpdates": false, + "autoCheckUpdatesOnStartup": false, + "pingInterval": 0 +} +JSON + +python3 - "$SQLITE_PATH" <<'PY' +import sqlite3 +import sys + +connection = sqlite3.connect(sys.argv[1]) +connection.execute( + "CREATE TABLE IF NOT EXISTS tabularis_web_e2e " + "(id INTEGER PRIMARY KEY, value VARCHAR(64))" +) +connection.commit() +connection.close() +PY + +cat >"$RUNTIME_DIR/bin/xdg-open" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$1" >"$TABULARIS_E2E_LAUNCH_URL_FILE" +SH +chmod +x "$RUNTIME_DIR/bin/xdg-open" +rm -f "$LAUNCH_URL_FILE" + +export HOME="$RUNTIME_DIR/home" +export XDG_CONFIG_HOME="$CONFIG_HOME" +export XDG_DATA_HOME="$DATA_HOME" +export TABULARIS_E2E_LAUNCH_URL_FILE="$LAUNCH_URL_FILE" +export BROWSER="$RUNTIME_DIR/bin/xdg-open" +export PATH="$RUNTIME_DIR/bin:$PATH" + +exec "$ROOT_DIR/src-tauri/target/debug/tabularis" \ + web \ + --host 127.0.0.1 \ + --port "$PORT" \ + --web-root "$ROOT_DIR/packages/web-ui/dist" diff --git a/web-ui-project/e2e/tests/rpc.ts b/web-ui-project/e2e/tests/rpc.ts new file mode 100644 index 000000000..5fc38af7f --- /dev/null +++ b/web-ui-project/e2e/tests/rpc.ts @@ -0,0 +1,65 @@ +import type {Page} from '@playwright/test'; + +interface RpcError { + code: string; + message: string; + requestId: string; +} + +interface RpcSuccess { + ok: true; + data: unknown; +} + +interface RpcFailure { + ok: false; + error: RpcError; +} + +type RpcEnvelope = RpcSuccess | RpcFailure; + +function isRpcEnvelope(value: unknown): value is RpcEnvelope { + if (typeof value !== 'object' || value === null || !('ok' in value)) { + return false; + } + return (value as {ok: unknown}).ok === true || (value as {ok: unknown}).ok === false; +} + +export async function rpc(page: Page, command: string, payload: unknown = null): Promise { + const envelope = await page.evaluate( + async ({commandName, commandPayload}) => { + const sessionResponse = await fetch('/api/v1/session', { + credentials: 'same-origin', + cache: 'no-store', + }); + if (!sessionResponse.ok) { + throw new Error(`Session negotiation failed with HTTP ${sessionResponse.status}`); + } + const session = (await sessionResponse.json()) as {csrfToken?: unknown}; + if (typeof session.csrfToken !== 'string') { + throw new Error('Session negotiation omitted its CSRF token'); + } + const response = await fetch(`/api/v1/rpc/${encodeURIComponent(commandName)}`, { + method: 'POST', + credentials: 'same-origin', + cache: 'no-store', + headers: { + accept: 'application/json', + 'content-type': 'application/json', + 'x-tabularis-csrf': session.csrfToken, + }, + body: JSON.stringify(commandPayload), + }); + return response.json() as Promise; + }, + {commandName: command, commandPayload: payload}, + ); + + if (!isRpcEnvelope(envelope)) { + throw new Error(`RPC ${command} returned an invalid response envelope`); + } + if (!envelope.ok) { + throw new Error(`${envelope.error.code}: ${envelope.error.message}`); + } + return envelope.data as T; +} diff --git a/web-ui-project/e2e/tests/web-ui-matrix.spec.ts b/web-ui-project/e2e/tests/web-ui-matrix.spec.ts new file mode 100644 index 000000000..3ec7dcc09 --- /dev/null +++ b/web-ui-project/e2e/tests/web-ui-matrix.spec.ts @@ -0,0 +1,222 @@ +import {expect, test} from '@playwright/test'; +import path from 'node:path'; + +import {rpc} from './rpc'; + +interface ConnectionParameters { + driver: string; + database: string; + host?: string; + port?: number; + username?: string; + password?: string; + ssl_mode?: string; + save_in_keychain?: boolean; +} + +interface SavedConnection { + id: string; + name: string; + params: ConnectionParameters; +} + +interface QueryResult { + columns: string[]; + rows: unknown[][]; + affected_rows: number; + truncated: boolean; +} + +interface DriverManifest { + id: string; + name: string; + is_builtin: boolean; +} + +interface DatabaseFixture { + name: 'sqlite' | 'postgres' | 'mysql'; + params: ConnectionParameters; + identityQuery: string; + expectedIdentity: string; +} + +const rootDir = path.resolve(import.meta.dirname, '../../..'); +const runtimeDir = path.resolve( + process.env.TABULARIS_E2E_RUNTIME_DIR ?? path.join(rootDir, 'web-ui-project/.runtime/e2e'), +); +const databasePassword = process.env.TABULARIS_E2E_DATABASE_PASSWORD ?? 'tabularis-e2e'; + +const databaseFixtures: DatabaseFixture[] = [ + { + name: 'sqlite', + params: { + driver: 'sqlite', + database: + process.env.TABULARIS_E2E_SQLITE_PATH ?? + path.join(runtimeDir, 'tabularis-e2e.sqlite'), + save_in_keychain: false, + }, + identityQuery: 'SELECT sqlite_version()', + expectedIdentity: '.', + }, + { + name: 'postgres', + params: { + driver: 'postgres', + host: process.env.TABULARIS_E2E_POSTGRES_HOST ?? '127.0.0.1', + port: Number.parseInt(process.env.TABULARIS_E2E_POSTGRES_PORT ?? '45432', 10), + username: process.env.TABULARIS_E2E_POSTGRES_USER ?? 'postgres', + password: databasePassword, + database: process.env.TABULARIS_E2E_POSTGRES_DATABASE ?? 'tabularis_e2e', + ssl_mode: 'disable', + save_in_keychain: false, + }, + identityQuery: 'SELECT current_database()', + expectedIdentity: process.env.TABULARIS_E2E_POSTGRES_DATABASE ?? 'tabularis_e2e', + }, + { + name: 'mysql', + params: { + driver: 'mysql', + host: process.env.TABULARIS_E2E_MYSQL_HOST ?? '127.0.0.1', + port: Number.parseInt(process.env.TABULARIS_E2E_MYSQL_PORT ?? '43306', 10), + username: process.env.TABULARIS_E2E_MYSQL_USER ?? 'root', + password: databasePassword, + database: process.env.TABULARIS_E2E_MYSQL_DATABASE ?? 'tabularis_e2e', + save_in_keychain: false, + }, + identityQuery: 'SELECT DATABASE()', + expectedIdentity: process.env.TABULARIS_E2E_MYSQL_DATABASE ?? 'tabularis_e2e', + }, +]; + +async function saveConnection( + page: Parameters[0], + name: string, + params: ConnectionParameters, +): Promise { + return rpc(page, 'save_connection', { + name, + params, + environment: 'development', + }); +} + +async function execute( + page: Parameters[0], + connectionId: string, + query: string, +): Promise { + return rpc(page, 'execute_query', { + connectionId, + query, + limit: 100, + page: 1, + }); +} + +test.describe.configure({mode: 'serial'}); + +test.beforeEach(async ({page}) => { + await page.goto('/connections'); + await expect(page.locator('body')).toBeVisible(); +}); + +test('serves the shared UI and loads an authenticated UI extension', async ({page}) => { + await expect(page.locator('[data-testid="e2e-ui-extension"]')).toHaveText( + 'E2E UI extension loaded', + {timeout: 15_000}, + ); + + const drivers = await rpc(page, 'get_registered_drivers'); + expect(drivers).toEqual( + expect.arrayContaining([ + expect.objectContaining({id: 'e2e-driver', is_builtin: false}), + expect.objectContaining({id: 'e2e-ui-extension', is_builtin: false}), + ]), + ); +}); + +for (const fixture of databaseFixtures) { + test(`executes a real ${fixture.name} connection and query workflow`, async ({ + page, + browserName, + }) => { + const connection = await saveConnection( + page, + `E2E ${fixture.name} ${browserName}`, + fixture.params, + ); + + try { + await expect( + rpc(page, 'test_connection', { + request: {params: fixture.params, connection_id: connection.id}, + }), + ).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); + + await execute( + page, + connection.id, + 'CREATE TABLE IF NOT EXISTS tabularis_web_e2e (id INTEGER PRIMARY KEY, value VARCHAR(64))', + ); + await execute(page, connection.id, 'DELETE FROM tabularis_web_e2e'); + const marker = `${fixture.name}-${browserName}`; + await execute( + page, + connection.id, + `INSERT INTO tabularis_web_e2e (id, value) VALUES (1, '${marker}')`, + ); + const result = await execute( + page, + connection.id, + 'SELECT value FROM tabularis_web_e2e WHERE id = 1', + ); + expect(result.rows).toEqual([[marker]]); + expect(result.truncated).toBe(false); + } finally { + await rpc(page, 'disconnect_connection', {connectionId: connection.id}).catch( + () => undefined, + ); + // Headless Linux runners may not provide a Secret Service daemon; the + // isolated runtime is deleted after the suite, so cleanup is best-effort. + await rpc(page, 'delete_connection', {id: connection.id}).catch(() => undefined); + } + }); +} + +test('executes a query through an external JSON-RPC driver plugin', async ({page, browserName}) => { + const params: ConnectionParameters = { + driver: 'e2e-driver', + database: 'fixture', + save_in_keychain: false, + }; + const connection = await saveConnection(page, `E2E plugin ${browserName}`, params); + + try { + await expect( + rpc(page, 'test_connection', { + request: {params, connection_id: connection.id}, + }), + ).resolves.toContain('Connection successful'); + const result = await execute(page, connection.id, 'SELECT plugin_fixture'); + expect(result.columns).toEqual(['fixture']); + expect(result.rows).toEqual([['driver-plugin-ok']]); + } finally { + await rpc(page, 'disconnect_connection', {connectionId: connection.id}).catch( + () => undefined, + ); + await rpc(page, 'delete_connection', {id: connection.id}).catch(() => undefined); + } +}); diff --git a/web-ui-project/e2e/tsconfig.json b/web-ui-project/e2e/tsconfig.json new file mode 100644 index 000000000..ba15bd123 --- /dev/null +++ b/web-ui-project/e2e/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node", "@playwright/test"] + }, + "include": ["./**/*.ts"] +} diff --git a/web-ui-project/scripts/check-web-ui-documentation.test.mjs b/web-ui-project/scripts/check-web-ui-documentation.test.mjs new file mode 100644 index 000000000..07839bd22 --- /dev/null +++ b/web-ui-project/scripts/check-web-ui-documentation.test.mjs @@ -0,0 +1,88 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import {fileURLToPath} from 'node:url'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const guidePath = 'web-ui-project/docs/WEB_MODE_OPERATIONS.md'; +const read = (relativePath) => fs.readFileSync(path.join(root, relativePath), 'utf8'); + +test('the Web operator guide covers every Web CLI option', () => { + const guide = read(guidePath); + const cli = read('src-tauri/src/cli.rs'); + const webOptions = cli.slice(cli.indexOf('pub struct WebArgs')); + const optionOverrides = { + allowed_origins: 'allowed-origin', + trusted_proxies: 'trusted-proxy', + server_file_browser_roots: 'server-file-browser-root', + }; + const optionNames = [...webOptions.matchAll(/pub ([a-z_]+):/g)].map(([, name]) => { + const optionName = optionOverrides[name] ?? name.replaceAll('_', '-'); + return `--${optionName}`; + }); + + assert.deepEqual(optionNames, [ + '--host', + '--port', + '--no-open', + '--web-root', + '--auth', + '--public-url', + '--allowed-origin', + '--trusted-proxy', + '--allow-high-risk', + '--server-file-browser-root', + ]); + assert.ok(guide.includes('`web`'), 'web subcommand is undocumented'); + for (const option of optionNames) { + assert.ok(guide.includes(`\`${option}`), `${option} is undocumented`); + } +}); + +test('the Web operator guide covers the WEB-102 operations contract', () => { + const guide = read(guidePath); + const requiredSections = [ + 'CLI options', + 'Local security behavior', + 'Remote deployment and reverse proxy', + 'Data, configuration, and credential locations', + 'Browser limitations and adaptations', + 'Plugin compatibility', + 'Troubleshooting', + 'Upgrade and rollback', + ]; + + for (const section of requiredSections) { + assert.match(guide, new RegExp(`^## ${section}$`, 'm'), `${section} section is missing`); + } + + for (const expected of [ + 'TABULARIS_WEB_PASSWORD', + 'TABULARIS_WEB_PROXY_SECRET', + '~/.config/tabularis', + '~/.local/share/tabularis', + '%APPDATA%\\tabularis', + 'OS credential store', + '10,000 rows', + '@tabularis/plugin-api', + ]) { + assert.ok(guide.includes(expected), `${expected} guidance is missing`); + } +}); + +test('the Web documentation entry point and related guide links stay valid', () => { + const guide = read(guidePath); + const projectReadme = read('web-ui-project/README.md'); + + assert.match(projectReadme, /docs\/WEB_MODE_OPERATIONS\.md/); + + const links = [...guide.matchAll(/\[[^\]]+\]\(([^)]+\.md)\)/g)].map(([, link]) => link); + assert.ok(links.length >= 4, 'expected links to the specialized Web guides'); + for (const link of links) { + assert.ok( + fs.existsSync(path.resolve(path.dirname(path.join(root, guidePath)), link)), + `broken documentation link: ${link}`, + ); + } +}); diff --git a/web-ui-project/scripts/check-web-ui-frontend-boundaries.mjs b/web-ui-project/scripts/check-web-ui-frontend-boundaries.mjs new file mode 100644 index 000000000..99059aafe --- /dev/null +++ b/web-ui-project/scripts/check-web-ui-frontend-boundaries.mjs @@ -0,0 +1,228 @@ +#!/usr/bin/env node + +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; +import ts from 'typescript'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const FRONTEND_ROOT = 'packages/web-ui/src'; +const ALLOWLIST_PATH = 'web-ui-project/scripts/web-ui-tauri-boundary-allowlist.json'; + +function scriptKind(filePath) { + if (filePath.endsWith('.tsx')) return ts.ScriptKind.TSX; + if (filePath.endsWith('.jsx')) return ts.ScriptKind.JSX; + if (filePath.endsWith('.js')) return ts.ScriptKind.JS; + return ts.ScriptKind.TS; +} + +function addCount(counts, file) { + counts.set(file, (counts.get(file) ?? 0) + 1); +} + +function usageEntries(counts) { + return [...counts] + .sort(([left], [right]) => left.localeCompare(right)) + .map(([file, count]) => ({file, count})); +} + +export function collectBoundaryUsage(files) { + const tauriImports = new Map(); + const directInvokes = new Map(); + + for (const file of [...files].sort((left, right) => left.path.localeCompare(right.path))) { + const sourceFile = ts.createSourceFile( + file.path, + file.source, + ts.ScriptTarget.Latest, + true, + scriptKind(file.path), + ); + const namedInvokes = new Set(); + const coreNamespaces = new Set(); + + for (const statement of sourceFile.statements) { + if ( + !ts.isImportDeclaration(statement) || + !ts.isStringLiteral(statement.moduleSpecifier) + ) { + continue; + } + + const moduleName = statement.moduleSpecifier.text; + if (!moduleName.startsWith('@tauri-apps/')) continue; + addCount(tauriImports, file.path); + + if (moduleName !== '@tauri-apps/api/core' || !statement.importClause) { + continue; + } + const bindings = statement.importClause.namedBindings; + if (bindings && ts.isNamedImports(bindings)) { + for (const element of bindings.elements) { + if ((element.propertyName ?? element.name).text === 'invoke') { + namedInvokes.add(element.name.text); + } + } + } else if (bindings && ts.isNamespaceImport(bindings)) { + coreNamespaces.add(bindings.name.text); + } + } + + function visit(node) { + if ( + ts.isCallExpression(node) && + node.expression.kind === ts.SyntaxKind.ImportKeyword && + node.arguments.length === 1 && + ts.isStringLiteral(node.arguments[0]) && + node.arguments[0].text.startsWith('@tauri-apps/') + ) { + addCount(tauriImports, file.path); + } + + if (ts.isCallExpression(node)) { + const isNamedInvoke = + ts.isIdentifier(node.expression) && namedInvokes.has(node.expression.text); + const isNamespaceInvoke = + ts.isPropertyAccessExpression(node.expression) && + ts.isIdentifier(node.expression.expression) && + coreNamespaces.has(node.expression.expression.text) && + node.expression.name.text === 'invoke'; + if (isNamedInvoke || isNamespaceInvoke) addCount(directInvokes, file.path); + } + + ts.forEachChild(node, visit); + } + + visit(sourceFile); + } + + return { + tauriImports: usageEntries(tauriImports), + directInvokes: usageEntries(directInvokes), + }; +} + +function entryMap(entries, label, errors) { + const result = new Map(); + for (const [file, count] of Object.entries(entries)) { + if (!Number.isInteger(count) || count < 1) { + errors.push(`${file} has an invalid count in ${label}`); + } else { + result.set(file, count); + } + } + return result; +} + +function validateUsageGroup({actualEntries, allowedEntries, adapters, label, errors}) { + const actual = new Map(actualEntries.map(({file, count}) => [file, count])); + const allowed = entryMap(allowedEntries, `legacy ${label} allowlist`, errors); + const singular = label === 'Tauri imports' ? 'Tauri import' : 'direct invoke call'; + + for (const [file, count] of actual) { + if (adapters.has(file)) continue; + const allowance = allowed.get(file); + if (allowance === undefined) { + errors.push( + `${file} has ${count} ${count === 1 ? singular : label} and is not an adapter or temporary exception`, + ); + } else if (count !== allowance) { + errors.push( + `${file} has ${count} ${count === 1 ? singular : label} but its temporary allowance is ${allowance}`, + ); + } + } + + for (const file of allowed.keys()) { + if (adapters.has(file)) { + errors.push(`${file} is an adapter; remove its temporary ${label} exception`); + } else if (!actual.has(file)) { + errors.push(`${file} no longer has ${label}; remove its temporary exception`); + } + } +} + +export function validateBoundaryUsage(usage, allowlist) { + const errors = []; + if (allowlist.schemaVersion !== 1) { + errors.push( + `Unsupported boundary allowlist schema version: ${String(allowlist.schemaVersion)}`, + ); + } + + const adapters = new Set(); + for (const file of allowlist.adapterFiles) { + if (adapters.has(file)) errors.push(`${file} is duplicated in the adapter allowlist`); + adapters.add(file); + } + + validateUsageGroup({ + actualEntries: usage.tauriImports, + allowedEntries: allowlist.legacyTauriImports, + adapters, + label: 'Tauri imports', + errors, + }); + validateUsageGroup({ + actualEntries: usage.directInvokes, + allowedEntries: allowlist.legacyDirectInvokes, + adapters, + label: 'direct invoke calls', + errors, + }); + + return errors; +} + +function listFrontendFiles(directory) { + const files = []; + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { + const absolute = path.join(directory, entry.name); + if (entry.isDirectory()) { + files.push(...listFrontendFiles(absolute)); + } else if ( + /\.(?:[jt]sx?)$/.test(entry.name) && + !/\.(?:test|spec)\.[jt]sx?$/.test(entry.name) && + !entry.name.endsWith('.d.ts') + ) { + files.push({ + path: path.relative(ROOT, absolute).split(path.sep).join('/'), + source: fs.readFileSync(absolute, 'utf8'), + }); + } + } + return files; +} + +export function collectFrontendBoundaryUsage() { + return collectBoundaryUsage(listFrontendFiles(path.join(ROOT, FRONTEND_ROOT))); +} + +function run() { + if (process.argv.length > 2 && process.argv[2] !== '--check') { + console.error( + 'Usage: node web-ui-project/scripts/check-web-ui-frontend-boundaries.mjs [--check]', + ); + process.exitCode = 2; + return; + } + + const usage = collectFrontendBoundaryUsage(); + const allowlist = JSON.parse(fs.readFileSync(path.join(ROOT, ALLOWLIST_PATH), 'utf8')); + const errors = validateBoundaryUsage(usage, allowlist); + if (errors.length > 0) { + for (const error of errors) console.error(`- ${error}`); + process.exitCode = 1; + return; + } + + const importCount = usage.tauriImports.reduce((total, entry) => total + entry.count, 0); + const invokeCount = usage.directInvokes.reduce((total, entry) => total + entry.count, 0); + console.log( + `Frontend boundaries are current: ${importCount} Tauri imports and ${invokeCount} direct invoke calls are adapter-owned or temporarily allowlisted.`, + ); +} + +const isMain = + process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href; +if (isMain) run(); diff --git a/web-ui-project/scripts/check-web-ui-packaging.test.mjs b/web-ui-project/scripts/check-web-ui-packaging.test.mjs new file mode 100644 index 000000000..d2fceceb9 --- /dev/null +++ b/web-ui-project/scripts/check-web-ui-packaging.test.mjs @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import {fileURLToPath} from 'node:url'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const read = (relativePath) => fs.readFileSync(path.join(root, relativePath), 'utf8'); + +test('Tauri bundles the shared Web UI distribution as a resource', () => { + const config = JSON.parse(read('src-tauri/tauri.conf.json')); + + assert.equal(config.build.frontendDist, '../packages/web-ui/dist'); + assert.equal(config.bundle.resources['../packages/web-ui/dist/'], 'web-ui/'); +}); + +test('release builds verify packaged Web UI assets on every desktop platform', () => { + const workflow = read('.github/workflows/build.yml'); + + assert.match(workflow, /Verify packaged Web UI \(Linux\)/); + assert.match(workflow, /Verify packaged Web UI \(macOS\)/); + assert.match(workflow, /Verify packaged Web UI \(Windows\)/); + assert.match(workflow, /bundle\/appimage\/\*\.AppImage/); + assert.match(workflow, /Smoke-test headless Web mode \(Linux\)/); +}); + +test('Windows package extraction waits for MSI completion and checks its exit code', () => { + const workflow = read('.github/workflows/build.yml'); + + assert.match(workflow, /Start-Process msiexec\.exe/); + assert.match(workflow, /\$msiExtraction\.ExitCode/); +}); + +test('the Windows portable artifact carries its Web UI resources', () => { + const workflow = read('.github/workflows/build.yml'); + + assert.match(workflow, /x64-portable\.zip/); + assert.match(workflow, /Copy-Item packages\\web-ui\\dist/); + assert.doesNotMatch(workflow, /x64-portable\.exe/); +}); + +test('deployment examples follow the completed remote security model', () => { + const guide = read('web-ui-project/docs/WEB_REMOTE_SECURITY.md'); + + assert.match(guide, /## systemd example/); + assert.match(guide, /## Container example/); + assert.match(guide, /TABULARIS_WEB_PASSWORD/); + assert.match(guide, /--public-url https:\/\//); +}); diff --git a/web-ui-project/scripts/generate-web-ui-api-inventory.mjs b/web-ui-project/scripts/generate-web-ui-api-inventory.mjs new file mode 100644 index 000000000..dfaed3fa8 --- /dev/null +++ b/web-ui-project/scripts/generate-web-ui-api-inventory.mjs @@ -0,0 +1,524 @@ +#!/usr/bin/env node + +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; +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/transport/desktop/mod.rs'; +const INVENTORY_PATH = 'web-ui-project/docs/web-ui-parity.json'; + +const CLASSIFICATION_VALUES = { + featureGroup: [ + 'ai', + 'application', + 'backup', + 'configuration', + 'connections', + 'data', + 'database-objects', + 'drivers', + 'files', + 'k8s', + 'logs', + 'metadata', + 'notebooks', + 'plugins', + 'queries', + 'saved-queries', + 'ssh', + 'tasks', + 'themes', + 'users', + 'windows', + ], + eventUse: ['none', 'emits', 'event-coordinated'], + filesystemUse: ['none', 'read', 'write', 'read-write'], + authorizationLevel: ['session', 'database', 'sensitive', 'local-admin'], +}; + +function scriptKind(filePath) { + if (filePath.endsWith('.tsx')) return ts.ScriptKind.TSX; + if (filePath.endsWith('.jsx')) return ts.ScriptKind.JSX; + if (filePath.endsWith('.js')) return ts.ScriptKind.JS; + return ts.ScriptKind.TS; +} + +function invocationAliases(sourceFile) { + const named = new Set(); + const namespaces = new Set(); + + for (const statement of sourceFile.statements) { + if ( + !ts.isImportDeclaration(statement) || + !ts.isStringLiteral(statement.moduleSpecifier) || + statement.moduleSpecifier.text !== '@tauri-apps/api/core' || + !statement.importClause + ) { + continue; + } + + const bindings = statement.importClause.namedBindings; + if (bindings && ts.isNamedImports(bindings)) { + for (const element of bindings.elements) { + if ((element.propertyName ?? element.name).text === 'invoke') { + named.add(element.name.text); + } + } + } else if (bindings && ts.isNamespaceImport(bindings)) { + namespaces.add(bindings.name.text); + } + } + + return {named, namespaces}; +} + +function isInvokeCall(node, aliases) { + if (!ts.isCallExpression(node)) return false; + if (ts.isIdentifier(node.expression)) return aliases.named.has(node.expression.text); + return ( + ts.isPropertyAccessExpression(node.expression) && + ts.isIdentifier(node.expression.expression) && + aliases.namespaces.has(node.expression.expression.text) && + node.expression.name.text === 'invoke' + ); +} + +function literalCommand(argument) { + let current = argument; + while ( + ts.isParenthesizedExpression(current) || + ts.isAsExpression(current) || + ts.isTypeAssertionExpression(current) + ) { + current = current.expression; + } + if (ts.isStringLiteral(current) || ts.isNoSubstitutionTemplateLiteral(current)) { + return current.text; + } + return null; +} + +function enclosingFunctionName(node) { + let current = node.parent; + while (current) { + if ( + (ts.isFunctionDeclaration(current) || ts.isMethodDeclaration(current)) && + current.name + ) { + return current.name.getText(); + } + if ( + (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) && + current.parent && + ts.isVariableDeclaration(current.parent) && + ts.isIdentifier(current.parent.name) + ) { + return current.parent.name.text; + } + current = current.parent; + } + return null; +} + +function variableInitializers(sourceFile) { + const declarations = new Map(); + function visit(node) { + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) { + const entries = declarations.get(node.name.text) ?? []; + entries.push(node); + declarations.set(node.name.text, entries); + } + ts.forEachChild(node, visit); + } + visit(sourceFile); + return declarations; +} + +function expressionStringLiterals(node, declarations) { + const literals = new Set(); + const resolvedDeclarations = new Set(); + const anchor = node.getStart(); + + function visit(current) { + if (ts.isStringLiteral(current) || ts.isNoSubstitutionTemplateLiteral(current)) { + literals.add(current.text); + return; + } + if (ts.isIdentifier(current)) { + const declaration = (declarations.get(current.text) ?? []) + .filter((candidate) => candidate.getStart() < anchor) + .at(-1); + if (declaration && !resolvedDeclarations.has(declaration)) { + resolvedDeclarations.add(declaration); + visit(declaration.initializer); + } + return; + } + if (ts.isPropertyAssignment(current)) { + visit(current.initializer); + return; + } + ts.forEachChild(current, visit); + } + + visit(node); + return [...literals].sort(); +} + +export function extractFrontendInvocations(files) { + const literalInvocations = []; + const dynamicInvocations = []; + + for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { + const sourceFile = ts.createSourceFile( + file.path, + file.source, + ts.ScriptTarget.Latest, + true, + scriptKind(file.path), + ); + const aliases = invocationAliases(sourceFile); + const declarations = variableInitializers(sourceFile); + + function visit(node) { + if (isInvokeCall(node, aliases) && node.arguments.length > 0) { + const argument = node.arguments[0]; + const line = + sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1; + const command = literalCommand(argument); + if (command === null) { + dynamicInvocations.push({ + expression: argument.getText(sourceFile).replace(/\s+/g, ' '), + file: file.path, + line, + context: enclosingFunctionName(node), + possibleCommands: expressionStringLiterals(argument, declarations), + }); + } else { + literalInvocations.push({command, file: file.path, line}); + } + } + ts.forEachChild(node, visit); + } + + visit(sourceFile); + } + + return {literalInvocations, dynamicInvocations}; +} + +function findMacroBody(source) { + const marker = 'tauri::generate_handler!'; + const markerIndex = source.indexOf(marker); + if (markerIndex === -1) throw new Error('Tauri generate_handler! macro was not found'); + const openIndex = source.indexOf('[', markerIndex + marker.length); + if (openIndex === -1) throw new Error('Tauri generate_handler! macro has no body'); + + let depth = 0; + let quote = null; + let escaped = false; + let lineComment = false; + let blockComment = false; + + for (let index = openIndex; index < source.length; index += 1) { + const character = source[index]; + const next = source[index + 1]; + + if (lineComment) { + if (character === '\n') lineComment = false; + continue; + } + if (blockComment) { + if (character === '*' && next === '/') { + blockComment = false; + index += 1; + } + continue; + } + if (quote !== null) { + if (escaped) escaped = false; + else if (character === '\\') escaped = true; + else if (character === quote) quote = null; + continue; + } + if (character === '/' && next === '/') { + lineComment = true; + index += 1; + continue; + } + if (character === '/' && next === '*') { + blockComment = true; + index += 1; + continue; + } + if (character === '"' || character === "'") { + quote = character; + continue; + } + if (character === '[') depth += 1; + if (character === ']') { + depth -= 1; + if (depth === 0) return source.slice(openIndex + 1, index); + } + } + + throw new Error('Tauri generate_handler! macro body is not closed'); +} + +export function extractTauriHandlers(source) { + const body = findMacroBody(source) + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/.*$/gm, ''); + const handlers = body + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean) + .map((entry) => { + if (!/^(?:[A-Za-z_]\w*::)*[A-Za-z_]\w*$/.test(entry)) { + throw new Error(`Unsupported Tauri handler registration: ${entry}`); + } + return entry.split('::').at(-1); + }); + + return handlers; +} + +function classificationFor(command, previousCommands) { + const previous = previousCommands.get(command); + return { + featureGroup: previous?.featureGroup ?? null, + eventUse: previous?.eventUse ?? null, + filesystemUse: previous?.filesystemUse ?? null, + authorizationLevel: previous?.authorizationLevel ?? null, + }; +} + +function dynamicInvocationKey(invocation) { + return `${invocation.file}\0${invocation.context ?? ''}\0${invocation.expression}`; +} + +function dynamicClassificationFor(invocation, previousDynamic) { + const previous = previousDynamic.get(dynamicInvocationKey(invocation)); + return { + ...invocation, + possibleCommands: + invocation.possibleCommands.length > 0 + ? invocation.possibleCommands + : (previous?.possibleCommands ?? []), + featureGroup: previous?.featureGroup ?? null, + eventUse: previous?.eventUse ?? null, + filesystemUse: previous?.filesystemUse ?? null, + authorizationLevel: previous?.authorizationLevel ?? null, + }; +} + +export function buildInventory({frontend, handlers, previous = {}}) { + const previousCommands = new Map( + (previous.commands ?? []).map((command) => [command.name, command]), + ); + const previousDynamic = new Map( + (previous.dynamicInvocations ?? []).map((invocation) => [ + dynamicInvocationKey(invocation), + invocation, + ]), + ); + const handlerSet = new Set(handlers); + const duplicateHandlerRegistrations = [ + ...new Set(handlers.filter((handler, index) => handlers.indexOf(handler) !== index)), + ].sort(); + const callsByCommand = new Map(); + + for (const invocation of frontend.literalInvocations) { + const callSites = callsByCommand.get(invocation.command) ?? []; + callSites.push({file: invocation.file, line: invocation.line}); + callsByCommand.set(invocation.command, callSites); + } + + const commands = [...callsByCommand] + .sort(([left], [right]) => left.localeCompare(right)) + .map(([name, callSites]) => ({ + name, + ...classificationFor(name, previousCommands), + registered: handlerSet.has(name), + callSites, + })); + const frontendNames = new Set(commands.map((command) => command.name)); + const registeredCommandsWithoutFrontendCall = [...handlerSet] + .filter((handler) => !frontendNames.has(handler)) + .sort(); + const frontendCommandsMissingRegistration = commands + .filter((command) => !command.registered) + .map((command) => command.name); + const dynamicInvocations = frontend.dynamicInvocations.map((invocation) => { + const classified = dynamicClassificationFor(invocation, previousDynamic); + return { + ...classified, + unregisteredPossibleCommands: classified.possibleCommands.filter( + (command) => !handlerSet.has(command), + ), + }; + }); + + return { + schemaVersion: 1, + generatedBy: 'pnpm web:inventory:write', + sources: { + frontend: FRONTEND_ROOT, + tauriHandler: TAURI_HANDLER_PATH, + }, + classifications: CLASSIFICATION_VALUES, + classificationNotes: { + eventUse: + 'Whether command completion or progress participates in the frontend event bus.', + filesystemUse: + 'User-visible host filesystem access only; internal application persistence is classified as none.', + authorizationLevel: + 'Minimum intended web authorization scope; all levels still require an authenticated session.', + }, + summary: { + literalCommandCount: commands.length, + literalCallSiteCount: frontend.literalInvocations.length, + dynamicCallSiteCount: dynamicInvocations.length, + handlerRegistrationCount: handlers.length, + registeredCommandCount: handlerSet.size, + duplicateHandlerRegistrations, + frontendCommandsMissingRegistration, + registeredCommandsWithoutFrontendCall: registeredCommandsWithoutFrontendCall.length, + }, + commands, + dynamicInvocations, + registeredCommandsWithoutFrontendCall, + }; +} + +export function validateInventory(inventory) { + const errors = []; + const commands = inventory.commands ?? []; + const seen = new Set(); + + for (const command of commands) { + if (seen.has(command.name)) errors.push(`Command ${command.name} is duplicated`); + seen.add(command.name); + for (const field of Object.keys(CLASSIFICATION_VALUES)) { + if (command[field] === null || command[field] === undefined) { + errors.push(`Command ${command.name} is missing ${field} classification`); + } else if (!CLASSIFICATION_VALUES[field].includes(command[field])) { + errors.push( + `Command ${command.name} has invalid ${field} classification: ${command[field]}`, + ); + } + } + if (!command.registered) { + errors.push(`Frontend command ${command.name} is not registered by the Tauri handler`); + } + } + + for (const invocation of inventory.dynamicInvocations ?? []) { + const label = `${invocation.file}:${invocation.line} (${invocation.expression})`; + if ( + !Array.isArray(invocation.possibleCommands) || + invocation.possibleCommands.length === 0 + ) { + errors.push(`Dynamic invocation ${label} has no inventoried possible commands`); + } + for (const command of invocation.unregisteredPossibleCommands ?? []) { + errors.push(`Dynamic invocation ${label} may call unregistered command ${command}`); + } + for (const field of Object.keys(CLASSIFICATION_VALUES)) { + if (invocation[field] === null || invocation[field] === undefined) { + errors.push(`Dynamic invocation ${label} is missing ${field} classification`); + } else if (!CLASSIFICATION_VALUES[field].includes(invocation[field])) { + errors.push( + `Dynamic invocation ${label} has invalid ${field} classification: ${invocation[field]}`, + ); + } + } + } + + return errors; +} + +function listFrontendFiles(directory) { + const files = []; + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { + const absolute = path.join(directory, entry.name); + if (entry.isDirectory()) { + files.push(...listFrontendFiles(absolute)); + } else if ( + /\.(?:[jt]sx?)$/.test(entry.name) && + !/\.(?:test|spec)\.[jt]sx?$/.test(entry.name) && + !entry.name.endsWith('.d.ts') + ) { + files.push({ + path: path.relative(ROOT, absolute).split(path.sep).join('/'), + source: fs.readFileSync(absolute, 'utf8'), + }); + } + } + return files; +} + +function readPreviousInventory() { + const inventoryPath = path.join(ROOT, INVENTORY_PATH); + if (!fs.existsSync(inventoryPath)) return {}; + return JSON.parse(fs.readFileSync(inventoryPath, 'utf8')); +} + +function generateInventory() { + const frontend = extractFrontendInvocations(listFrontendFiles(path.join(ROOT, FRONTEND_ROOT))); + const handlers = extractTauriHandlers( + fs.readFileSync(path.join(ROOT, TAURI_HANDLER_PATH), 'utf8'), + ); + return buildInventory({frontend, handlers, previous: readPreviousInventory()}); +} + +function formatInventory(inventory) { + return `${JSON.stringify(inventory, null, 2)}\n`; +} + +function run() { + const mode = process.argv[2] ?? '--check'; + if (!['--check', '--write'].includes(mode)) { + console.error( + 'Usage: node web-ui-project/scripts/generate-web-ui-api-inventory.mjs [--check|--write]', + ); + process.exitCode = 2; + return; + } + + const inventory = generateInventory(); + const formatted = formatInventory(inventory); + const errors = validateInventory(inventory); + const inventoryPath = path.join(ROOT, INVENTORY_PATH); + + if (mode === '--write') { + fs.mkdirSync(path.dirname(inventoryPath), {recursive: true}); + fs.writeFileSync(inventoryPath, formatted); + } else { + const current = fs.existsSync(inventoryPath) ? fs.readFileSync(inventoryPath, 'utf8') : ''; + if (current !== formatted) { + errors.push( + `Inventory is stale; run pnpm web:inventory:write and classify new entries`, + ); + } + } + + if (errors.length > 0) { + for (const error of errors) console.error(`- ${error}`); + process.exitCode = 1; + return; + } + + console.log( + `Web UI API inventory is current: ${inventory.summary.literalCommandCount} commands, ` + + `${inventory.summary.literalCallSiteCount} call sites, ${inventory.summary.dynamicCallSiteCount} dynamic calls, ` + + `${inventory.summary.registeredCommandCount} registered handlers.`, + ); +} + +const isMain = + process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href; +if (isMain) run(); diff --git a/web-ui-project/scripts/run-web-ui-resilience-tests.sh b/web-ui-project/scripts/run-web-ui-resilience-tests.sh new file mode 100755 index 000000000..8f1a52b30 --- /dev/null +++ b/web-ui-project/scripts/run-web-ui-resilience-tests.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT_DIR" + +pnpm test --run packages/web-ui/tests/api/transports/httpTransport.test.ts + +cd src-tauri +cargo test transport::web::events_tests --lib +cargo test bounds_slow_rpc_work_per_session_and_across_the_server --lib +cargo test application::queries::tests --lib +cargo test session_cleanup --lib +cargo test runtime_api_clears_browser_preferences_when_a_session_ends --lib +cargo test browser_active_connections_are_isolated_by_session --lib +cargo test crashed_plugin_process_fails_pending_calls_without_hanging --lib +cargo test test_spawn_error_identifies_configured_program --lib +cargo test connection_test_failures_emit_correlated_progress --lib +cargo test runtime::tests --lib diff --git a/web-ui-project/scripts/run-web-ui-tasks.sh b/web-ui-project/scripts/run-web-ui-tasks.sh new file mode 100755 index 000000000..610b18f9b --- /dev/null +++ b/web-ui-project/scripts/run-web-ui-tasks.sh @@ -0,0 +1,451 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null || true)" +PROJECT_DIR="${ROOT_DIR}/web-ui-project" +PLAN_FILE="${PROJECT_DIR}/docs/WEB_UI_PLAN.md" +TASK_DIR="${PROJECT_DIR}/tasks" +PROGRESS_FILE="${TASK_DIR}/PROGRESS.md" +RUN_DIR="${PROJECT_DIR}/.runtime" +LOG_DIR="${RUN_DIR}/logs" +STATE_FILE="${RUN_DIR}/state.tsv" +LOCK_DIR="${RUN_DIR}/lock" +THINKING="${PI_WEB_UI_THINKING:-high}" +MODEL="${PI_WEB_UI_MODEL:-}" +CI_REPAIR_ATTEMPTS="${PI_WEB_UI_CI_REPAIR_ATTEMPTS:-3}" +CI_DISCOVERY_ATTEMPTS="${PI_WEB_UI_CI_DISCOVERY_ATTEMPTS:-30}" +TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN:-}" +TELEGRAM_CHAT_ID="${TELEGRAM_CHAT_ID:-}" +NOTIFY=1 +DRY_RUN=0 +FORCE=0 +TASKS=() + +usage() { + cat <<'EOF' +Usage: web-ui-project/scripts/run-web-ui-tasks.sh [options] [WEB-NNN ...] + +Runs one non-interactive Pi CLI session per task file, sequentially. With no +task IDs, processing resumes at the first PENDING task in +web-ui-project/tasks/PROGRESS.md. The runner stops at the first failed or +unvalidated task. Runtime logs and state are written under +web-ui-project/.runtime/ (ignored by Git). + +Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID to receive a Telegram message for +each task state change (started, skipped, finished, or failed). Both variables +must be set together. Dry runs do not send external notifications. + +Options: + --model MODEL Pi model pattern (default: Pi configuration) + --thinking LEVEL Thinking level (default: high) + --no-notify Disable desktop notifications + --dry-run Print the sessions that would run + --force Run tasks even when PROGRESS.md says COMPLETED + -h, --help Show this help + +Environment: + PI_WEB_UI_CI_REPAIR_ATTEMPTS Maximum CI repair sessions (default: 3) + PI_WEB_UI_CI_DISCOVERY_ATTEMPTS CI run lookup retries, two seconds each (default: 30) + +Examples: + pnpm web:tasks + pnpm web:tasks WEB-000 + pnpm web:tasks WEB-001 WEB-002 + PI_WEB_UI_MODEL=openai/gpt-5.6-sol pnpm web:tasks WEB-010 +EOF +} + +notify() { + local title="$1" + local message="$2" + printf '\a[%s] %s: %s\n' "$(date --iso-8601=seconds)" "$title" "$message" + + if (( NOTIFY )) && command -v notify-send >/dev/null 2>&1; then + notify-send "$title" "$message" >/dev/null 2>&1 || true + fi +} + +notify_telegram() { + local title="$1" + local message="$2" + + [[ -n "$TELEGRAM_BOT_TOKEN" ]] || return 0 + + if ! curl --silent --show-error --fail-with-body \ + --connect-timeout 5 --max-time 15 --retry 2 \ + --request POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + --data-urlencode "text=${title}: ${message}" \ + >/dev/null; then + echo "Warning: failed to send Telegram notification." >&2 + fi +} + +record_task_state() { + local task="$1" + local state="$2" + local reference="$3" + local title="$4" + local message="$5" + + printf '%s\t%s\t%s\t%s\n' \ + "$(date --iso-8601=seconds)" "$task" "$state" "$reference" >> "$STATE_FILE" + notify "$title" "$message" + notify_telegram "$title" "$message" +} + +completion_progress() { + awk -F '|' ' + function trim(value) { + gsub(/^[[:space:]]+|[[:space:]]+$/, "", value) + return value + } + { + task = trim($2) + status = trim($3) + if (task ~ /^WEB-[0-9][0-9][0-9]$/) { + total++ + if (status == "COMPLETED") completed++ + } + } + END { + percentage = total == 0 ? 0 : completed * 100 / total + printf "%.1f%% (%d/%d)", percentage, completed, total + } + ' "$PROGRESS_FILE" +} + +progress_field() { + local task="$1" + local column="$2" + + awk -F '|' -v task="$task" -v column="$column" ' + function trim(value) { + gsub(/^[[:space:]]+|[[:space:]]+$/, "", value) + return value + } + trim($2) == task { print trim($column) } + ' "$PROGRESS_FILE" +} + +find_ci_run() { + local head_sha="$1" + local attempt run_id + + for ((attempt = 1; attempt <= CI_DISCOVERY_ATTEMPTS; attempt++)); do + run_id="$(gh run list --workflow CI --commit "$head_sha" --limit 1 \ + --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null || true)" + if [[ -n "$run_id" ]]; then + printf '%s\n' "$run_id" + return 0 + fi + sleep 2 + done + return 1 +} + +watch_task_ci() { + local task="$1" + local log_file="$2" + local head_sha run_id watch_status + + head_sha="$(git rev-parse HEAD)" + if ! run_id="$(find_ci_run "$head_sha")"; then + echo "No CI run found for $task at $head_sha." | tee -a "$log_file" >&2 + FAILED_CI_REFERENCE="commit $head_sha with no CI run" + return 1 + fi + + FAILED_CI_REFERENCE="run $run_id for commit $head_sha" + echo "Watching CI run $run_id for $task at $head_sha." | tee -a "$log_file" + set +e + gh run watch "$run_id" --exit-status 2>&1 | tee -a "$log_file" + watch_status=${PIPESTATUS[0]} + set -e + if (( watch_status != 0 )); then + echo "CI run $run_id failed; collecting failed logs for repair." | tee -a "$log_file" >&2 + gh run view "$run_id" --log-failed 2>&1 | tee -a "$log_file" || true + fi + return "$watch_status" +} + +validate_progress_entry() { + local task="$1" + local row_count status summary verification updated + + row_count="$(awk -F '|' -v task="$task" ' + function trim(value) { + gsub(/^[[:space:]]+|[[:space:]]+$/, "", value) + return value + } + trim($2) == task { count++ } + END { print count + 0 } + ' "$PROGRESS_FILE")" + [[ "$row_count" == "1" ]] || { + echo "PROGRESS.md must contain exactly one row for $task." >&2 + return 1 + } + + status="$(progress_field "$task" 3)" + summary="$(progress_field "$task" 4)" + verification="$(progress_field "$task" 5)" + updated="$(progress_field "$task" 6)" + + [[ "$status" == "COMPLETED" ]] || { + echo "$task is not COMPLETED in PROGRESS.md (status: $status)." >&2 + return 1 + } + [[ -n "$summary" && "$summary" != "—" ]] || { + echo "$task has no completion summary in PROGRESS.md." >&2 + return 1 + } + [[ -n "$verification" && "$verification" != "—" ]] || { + echo "$task has no verification evidence in PROGRESS.md." >&2 + return 1 + } + [[ "$updated" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || { + echo "$task has no valid ISO completion date in PROGRESS.md." >&2 + return 1 + } + git ls-files --error-unmatch "$PROGRESS_FILE" >/dev/null 2>&1 || { + echo "PROGRESS.md must be committed before $task can be validated." >&2 + return 1 + } + if ! git diff --quiet -- "$PROGRESS_FILE" || \ + ! git diff --cached --quiet -- "$PROGRESS_FILE"; then + echo "PROGRESS.md has uncommitted changes; commit the $task record first." >&2 + return 1 + fi +} + +while (($#)); do + case "$1" in + --model) + [[ $# -ge 2 ]] || { echo "Missing value for --model" >&2; exit 2; } + MODEL="$2" + shift 2 + ;; + --thinking) + [[ $# -ge 2 ]] || { echo "Missing value for --thinking" >&2; exit 2; } + THINKING="$2" + shift 2 + ;; + --no-notify) + NOTIFY=0 + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + --force) + FORCE=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + WEB-[0-9][0-9][0-9]) + TASKS+=("$1") + shift + ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +[[ -n "$ROOT_DIR" ]] || { echo "Run this script inside the Tabularis repository." >&2; exit 1; } +mkdir -p "$PROJECT_DIR/docs" "$TASK_DIR" "$PROJECT_DIR/scripts" \ + "$PROJECT_DIR/tests" "$LOG_DIR" +[[ -f "$PLAN_FILE" ]] || { echo "Missing tracked plan: $PLAN_FILE" >&2; exit 1; } +[[ -f "$PROGRESS_FILE" ]] || { echo "Missing tracked progress ledger: $PROGRESS_FILE" >&2; exit 1; } +command -v pi >/dev/null 2>&1 || { echo "pi is not available in PATH." >&2; exit 1; } +command -v gh >/dev/null 2>&1 || { echo "gh is not available in PATH." >&2; exit 1; } +[[ "$CI_REPAIR_ATTEMPTS" =~ ^[0-9]+$ ]] || { + echo "PI_WEB_UI_CI_REPAIR_ATTEMPTS must be a non-negative integer." >&2 + exit 1 +} +[[ "$CI_DISCOVERY_ATTEMPTS" =~ ^[1-9][0-9]*$ ]] || { + echo "PI_WEB_UI_CI_DISCOVERY_ATTEMPTS must be a positive integer." >&2 + exit 1 +} +if [[ -n "$TELEGRAM_BOT_TOKEN" || -n "$TELEGRAM_CHAT_ID" ]]; then + [[ -n "$TELEGRAM_BOT_TOKEN" && -n "$TELEGRAM_CHAT_ID" ]] || { + echo "TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID must be set together." >&2 + exit 1 + } + command -v curl >/dev/null 2>&1 || { echo "curl is required for Telegram notifications." >&2; exit 1; } +fi + +if ((${#TASKS[@]} == 0)); then + resume_from_pending=0 + while IFS= read -r task_file; do + task="$(basename "$task_file" .md)" + task_status="$(progress_field "$task" 3)" + if (( ! resume_from_pending )) && [[ "$task_status" == "PENDING" ]]; then + resume_from_pending=1 + fi + if (( resume_from_pending )); then + TASKS+=("$task") + fi + done < <(find "$TASK_DIR" -maxdepth 1 -type f -name 'WEB-[0-9][0-9][0-9].md' | sort) +fi +if ((${#TASKS[@]} == 0)); then + echo "No PENDING Web UI tasks remain in $PROGRESS_FILE." + exit 0 +fi + +cd "$ROOT_DIR" + +if ! mkdir "$LOCK_DIR" 2>/dev/null; then + echo "Another Web UI task runner appears to be active: $LOCK_DIR" >&2 + exit 1 +fi +trap 'rm -rf "$LOCK_DIR"' EXIT + +for task in "${TASKS[@]}"; do + task_file="${TASK_DIR}/${task}.md" + [[ -f "$task_file" ]] || { echo "Task file not found: $task_file" >&2; exit 2; } + + row_count="$(progress_field "$task" 2 | wc -l)" + [[ "$row_count" == "1" ]] || { + echo "PROGRESS.md must contain exactly one row for $task." >&2 + exit 2 + } +done + +for task in "${TASKS[@]}"; do + task_file="${TASK_DIR}/${task}.md" + progress_status="$(progress_field "$task" 3)" + case "$progress_status" in + PENDING|IN_PROGRESS|BLOCKED|COMPLETED) ;; + *) echo "Invalid PROGRESS.md status for $task: $progress_status" >&2; exit 2 ;; + esac + + if [[ "$progress_status" == "COMPLETED" ]] && (( ! FORCE )); then + validate_progress_entry "$task" || exit 1 + record_task_state "$task" "SKIPPED(COMPLETED)" "$task_file" \ + "Web UI task skipped" "$task is already completed (progress: $(completion_progress))" + continue + fi + + timestamp="$(date -u +%Y%m%dT%H%M%SZ)" + log_file="${LOG_DIR}/${timestamp}-${task}.log" + prompt=$(cat <> "$STATE_FILE" + continue + fi + + record_task_state "$task" "STARTED" "$log_file" \ + "Web UI task started" "$task (progress: $(completion_progress); log: $log_file)" + + set +e + env -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_PROVIDER -u PI_MODEL \ + -u PI_REASONING_LEVEL "${cmd[@]}" 2>&1 | tee "$log_file" + status=${PIPESTATUS[0]} + set -e + + if validate_progress_entry "$task"; then + if (( status != 0 )); then + record_task_state "$task" "RECOVERING(PI-${status})" "$log_file" \ + "Web UI task CI recovery" \ + "$task returned status $status after committing completion; validating CI (progress: $(completion_progress))" + fi + + repair_attempt=0 + while ! watch_task_ci "$task" "$log_file"; do + if (( repair_attempt >= CI_REPAIR_ATTEMPTS )); then + record_task_state "$task" "FAILED(CI)" "$log_file" \ + "Web UI task CI failed" \ + "$task exhausted $CI_REPAIR_ATTEMPTS repair attempts after $FAILED_CI_REFERENCE (progress: $(completion_progress))" + exit 1 + fi + + repair_attempt=$((repair_attempt + 1)) + record_task_state "$task" "CI_REPAIR(${repair_attempt})" "$log_file" \ + "Web UI task CI repair" \ + "$task repair $repair_attempt/$CI_REPAIR_ATTEMPTS for $FAILED_CI_REFERENCE (progress: $(completion_progress))" + + repair_prompt=$(cat <&1 | tee -a "$log_file" + repair_status=${PIPESTATUS[0]} + set -e + + if (( repair_status != 0 )); then + record_task_state "$task" "FAILED(CI_REPAIR-${repair_status})" "$log_file" \ + "Web UI task CI repair failed" \ + "$task repair $repair_attempt exited with status $repair_status (progress: $(completion_progress))" + exit "$repair_status" + fi + if ! validate_progress_entry "$task"; then + record_task_state "$task" "FAILED(CI_REPAIR-PROGRESS)" "$log_file" \ + "Web UI task CI repair not validated" \ + "$task repair $repair_attempt left an invalid progress record (progress: $(completion_progress))" + exit 1 + fi + done + + record_task_state "$task" "FINISHED" "$log_file" \ + "Web UI task finished" "$task completed, validated, and CI is green (progress: $(completion_progress))" + elif (( status == 0 )); then + record_task_state "$task" "FAILED(PROGRESS)" "$log_file" \ + "Web UI task not validated" \ + "$task did not complete its PROGRESS.md record (progress: $(completion_progress))" + exit 1 + else + record_task_state "$task" "FAILED(${status})" "$log_file" \ + "Web UI task failed" "$task exited with status $status (progress: $(completion_progress))" + exit "$status" + fi +done diff --git a/web-ui-project/scripts/verify-linux-web-package.sh b/web-ui-project/scripts/verify-linux-web-package.sh new file mode 100755 index 000000000..f33338637 --- /dev/null +++ b/web-ui-project/scripts/verify-linux-web-package.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash + +set -euo pipefail + +usage() { + echo "Usage: $0 " >&2 + exit 2 +} + +mode=${1:-} +artifact=${2:-} +case "$mode" in + assets|headless|all) ;; + *) usage ;; +esac +[[ -f "$artifact" ]] || usage +artifact=$(realpath "$artifact") + +repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +source_web_root="$repo_root/packages/web-ui/dist" +extract_root=$(mktemp -d) +server_pid= + +cleanup() { + if [[ -n "$server_pid" ]]; then + kill "$server_pid" 2>/dev/null || true + wait "$server_pid" 2>/dev/null || true + fi + rm -rf "$extract_root" +} +trap cleanup EXIT + +case "$artifact" in + *.deb) + member=$(ar t "$artifact" | awk '/^data\.tar/{ print; exit }') + [[ -n "$member" ]] || { echo "The deb does not contain a data archive" >&2; exit 1; } + case "$member" in + *.gz) tar_args=(-xz) ;; + *.xz) tar_args=(-xJ) ;; + *.zst) tar_args=(--zstd -x) ;; + *) tar_args=(-x) ;; + esac + ar p "$artifact" "$member" | tar "${tar_args[@]}" -C "$extract_root" + package_root="$extract_root" + ;; + *.AppImage) + chmod +x "$artifact" + (cd "$extract_root" && "$artifact" --appimage-extract >/dev/null) + package_root="$extract_root/squashfs-root" + ;; + *) usage ;; +esac + +binary="$package_root/usr/bin/tabularis" +web_root="$package_root/usr/lib/tabularis/web-ui" + +verify_assets() { + [[ -x "$binary" ]] || { echo "Packaged Tabularis executable is missing" >&2; exit 1; } + [[ -f "$web_root/index.html" ]] || { echo "Packaged Web UI index is missing" >&2; exit 1; } + [[ -n "$(find "$web_root/assets" -type f -print -quit 2>/dev/null)" ]] || { + echo "Packaged Web UI assets are missing" >&2 + exit 1 + } + cmp "$source_web_root/index.html" "$web_root/index.html" +} + +smoke_headless() { + verify_assets + + local port log response + port=$(node -e 'const net=require("node:net");const server=net.createServer();server.listen(0,"127.0.0.1",()=>{console.log(server.address().port);server.close();});') + log="$extract_root/headless.log" + mkdir -p "$extract_root/home" "$extract_root/config" "$extract_root/data" + + ( + cd / + unset DISPLAY WAYLAND_DISPLAY XDG_SESSION_TYPE + HOME="$extract_root/home" \ + XDG_CONFIG_HOME="$extract_root/config" \ + XDG_DATA_HOME="$extract_root/data" \ + "$binary" web --no-open --port "$port" >"$log" 2>&1 + ) & + server_pid=$! + + response= + for _ in $(seq 1 120); do + response=$(curl -fsS "http://127.0.0.1:$port/healthz" 2>/dev/null || true) + [[ "$response" == "ok" ]] && break + if ! kill -0 "$server_pid" 2>/dev/null; then + cat "$log" >&2 + echo "Packaged Tabularis exited before becoming healthy" >&2 + exit 1 + fi + sleep 0.25 + done + [[ "$response" == "ok" ]] || { cat "$log" >&2; echo "Headless health check timed out" >&2; exit 1; } +} + +case "$mode" in + assets) verify_assets ;; + headless) smoke_headless ;; + all) verify_assets; smoke_headless ;; +esac diff --git a/web-ui-project/scripts/web-ui-tauri-boundary-allowlist.json b/web-ui-project/scripts/web-ui-tauri-boundary-allowlist.json new file mode 100644 index 000000000..c8d6182ec --- /dev/null +++ b/web-ui-project/scripts/web-ui-tauri-boundary-allowlist.json @@ -0,0 +1,23 @@ +{ + "schemaVersion": 1, + "adapterFiles": [ + "packages/web-ui/src/api/transports/tauriTransport.ts", + "packages/web-ui/src/platform/environment.ts", + "packages/web-ui/src/platform/tauriCapabilities.ts" + ], + "legacyTauriImports": { + "packages/web-ui/src/contexts/DatabaseProvider.tsx": 2, + "packages/web-ui/src/contexts/UpdateProvider.tsx": 2, + "packages/web-ui/src/hooks/useDeepLinkInstall.ts": 2, + "packages/web-ui/src/pages/Editor.tsx": 1, + "packages/web-ui/src/pages/VisualExplainPage.tsx": 1, + "packages/web-ui/src/utils/mcpApprovalAttention.ts": 1 + }, + "legacyDirectInvokes": { + "packages/web-ui/src/contexts/DatabaseProvider.tsx": 1, + "packages/web-ui/src/contexts/UpdateProvider.tsx": 2, + "packages/web-ui/src/hooks/useDeepLinkInstall.ts": 1, + "packages/web-ui/src/pages/Editor.tsx": 1, + "packages/web-ui/src/pages/VisualExplainPage.tsx": 2 + } +} diff --git a/web-ui-project/tasks/PROGRESS.md b/web-ui-project/tasks/PROGRESS.md new file mode 100644 index 000000000..39f9de0d2 --- /dev/null +++ b/web-ui-project/tasks/PROGRESS.md @@ -0,0 +1,57 @@ +# Web UI task progress + +This file is the authoritative completion ledger for `web-ui-project/scripts/run-web-ui-tasks.sh`. +Allowed statuses are `PENDING`, `IN_PROGRESS`, `BLOCKED`, and `COMPLETED`. +A completed row must include a concise summary, verification evidence, and an +ISO date. Do not use `|` inside table fields. + +| Task | Status | Summary | Verification | Updated | +|---|---|---|---|---| +| WEB-000 | COMPLETED | Created feat/web-ui from current main and enabled CI for feature-branch pushes and pull requests | pnpm typecheck; pnpm lint; pnpm test --run with 230 files and 3838 tests; pnpm test:rust with 1157 tests; pnpm build; CI trigger assertion | 2026-08-21 | +| WEB-001 | COMPLETED | Added a classified frontend IPC inventory with dynamic-call and Tauri registration drift checks in CI | pnpm typecheck; pnpm lint; pnpm web:inventory with 227 commands and 366 call sites; focused Vitest with 3 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-002 | COMPLETED | Added six accepted Web UI ADRs covering RPC, shared UI, transports, local security, file tokens, and browser adaptations | ADR structure and link checks; pnpm typecheck; pnpm lint; pnpm test --run with 232 files and 3845 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-010 | COMPLETED | Added typed startup connection metadata and query contracts with event envelopes shared errors request IDs authorization and a tracked escape hatch | compile-time contract assertions; pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm test --run with 232 files and 3845 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-011 | COMPLETED | Added one application-root typed client provider with a Tauri invoke listen and emit transport | pnpm typecheck; pnpm lint; pnpm web:inventory; focused Vitest with 3 files and 7 tests; full Vitest with 235 files and 3852 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-012 | COMPLETED | Added negotiated semantic platform capabilities with a root provider centralized runtime detection and a Tauri adapter | pnpm typecheck; pnpm lint; pnpm web:inventory with 227 commands and 367 call sites; focused Vitest with 4 files and 12 tests; full Vitest with 239 files and 3864 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-013 | COMPLETED | Migrated debug connections testing tables queries cancellation and progress events through TabularisClient with no direct Tauri calls for the slice | pnpm typecheck; pnpm lint; pnpm web:inventory with 221 commands and 334 call sites; focused Vitest with 8 files and 100 tests; full Vitest with 240 files and 3866 tests; pnpm test:rust with 1157 tests; pnpm build; GitNexus expected critical slice breadth; git diff --check | 2026-08-21 | +| WEB-014 | COMPLETED | Added ESLint Tauri import restrictions and an exact temporary import and direct invoke allowlist enforced in CI | pnpm typecheck; pnpm lint; pnpm web:inventory with 221 commands and 334 call sites; pnpm web:boundaries with 154 imports and 337 invokes; focused Vitest with 2 files and 6 tests; full Vitest with 241 files and 3869 tests; pnpm test:rust with 1157 tests; pnpm build; ESLint rejection assertion; GitNexus low risk; git diff --check | 2026-08-21 | +| WEB-020 | COMPLETED | Scaffolded @tabularis/web-ui with relocated frontend configuration package scripts and root compatibility delegators | dev server smoke; pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm web:boundaries; focused Vitest with 2 tests; full Vitest with 242 files and 3871 tests; package and root builds; pnpm test:rust with 1157 tests; GitNexus staged low risk; git diff --check | 2026-08-21 | +| WEB-021 | COMPLETED | Moved the single frontend source asset and test trees into packages/web-ui and wired desktop tooling to the package | dev server smoke; pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm web:boundaries; focused Vitest with 3 files and 10 tests; full Vitest with 242 files and 3873 tests; package and root builds; Tauri debug build; pnpm test:rust with 1157 tests; plugin API sync; GitNexus staged low risk; git diff --check | 2026-08-21 | +| WEB-022 | COMPLETED | Centralized root-based browser routes and enabled explicit Vite SPA fallback with direct-navigation coverage | pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm web:boundaries; focused Vitest with 12 tests; full Vitest with 243 files and 3885 tests; package and root builds; production preview fallback for 10 routes; pnpm test:rust with 1157 tests; Tauri debug build; GitNexus task low risk; git diff --check | 2026-08-21 | +| WEB-030 | COMPLETED | Added typed web CLI options with loopback defaults mode conflicts scoped web arguments and platform launch fallback | focused Cargo tests with 8 tests; CLI help and conflict smoke; pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm web:boundaries; package and root builds; pnpm test:rust with 1165 tests; GitNexus medium task scope and expected critical branch scope; rustfmt check; git diff --check | 2026-08-21 | +| WEB-031 | COMPLETED | Extracted shared headless bootstrap with runtime path event secret state lifecycle driver and plugin boundaries | focused Cargo with 29 tests; pnpm typecheck; pnpm lint; pnpm web:inventory; pnpm web:boundaries; full Vitest with 243 files and 3885 tests; pnpm test:rust with 1168 tests; package root and Tauri debug builds; headless web smoke; GitNexus medium task scope and expected critical branch scope; git diff --check | 2026-08-21 | +| WEB-032 | COMPLETED | Added an Axum headless server with health and session endpoints packaged SPA assets browser launch and graceful runtime cleanup | Focused Cargo with 15 tests; full Vitest with 243 files and 3885 tests; pnpm test:rust with 1172 tests; typecheck; lint; inventory; boundaries; package root Tauri debug and deb builds; extracted deb health SPA and SIGTERM smoke | 2026-08-21 | +| WEB-033 | COMPLETED | Added one-time bootstrap exchange with expiring HttpOnly sessions strict origin and host checks CSRF logout body limits request IDs and redacted startup | Focused Cargo with 5 tests; full Vitest with 243 files and 3885 tests; pnpm test:rust with 1174 passed and 4 ignored; typecheck; lint; inventory; boundaries; package and root builds; Tauri debug build; headless auth and redaction smoke; GitNexus task low risk; git diff --check | 2026-08-21 | +| WEB-040 | COMPLETED | Added authenticated v1 RPC dispatch for debug connection listing and query cancellation with shared services typed payloads stable errors deadlines cancellation IDs and authorization metadata | Focused Cargo with 10 web and 3 cancellation tests; real authenticated HTTP parity fixture; pnpm typecheck; pnpm lint; full Vitest with 243 files and 3885 tests; pnpm test:rust with 1179 passed and 4 ignored; inventory; boundaries; package and root builds; Cargo debug build; GitNexus medium task scope; git diff --check | 2026-08-21 | +| WEB-041 | COMPLETED | Added authenticated session-scoped WebSocket events with authorization policies bounded queues and histories heartbeat cleanup and sequence replay | Focused web Cargo with 17 tests including real authenticated WebSocket; full Rust with 1186 passed and 4 ignored; full Vitest with 243 files and 3885 tests; typecheck; lint; inventory; boundaries; package and root builds; Cargo build; rustfmt; GitNexus medium branch scope; git diff --check | 2026-08-21 | +| WEB-042 | COMPLETED | Added authenticated browser session bootstrap typed HTTP RPC normalized transport errors WebSocket subscriptions with replay reconnection and one-time runtime selection | Focused Vitest with 4 files and 13 tests; full Vitest with 245 files and 3893 tests; pnpm test:rust with 1186 passed and 4 ignored; typecheck; lint; inventory; boundaries; package root and Cargo builds; real Chromium session UI and typed RPC smoke; GitNexus staged low risk; git diff --check | 2026-08-21 | +| WEB-043 | COMPLETED | Added reusable RPC behavior suites for a Tauri mock and live loopback web server with shared complex serialization fixtures and an explicit CI gate | pnpm test:web-contract with 6 frontend and 1 Rust test; typecheck; lint; inventory; boundaries; full Vitest with 246 files and 3899 tests; pnpm test:rust with 1187 passed and 4 ignored; package and root builds; Cargo build; focused Rust web with 18 tests; GitNexus task low risk; git diff --check | 2026-08-21 | +| WEB-050 | COMPLETED | Added typed web parity for connection CRUD groups tags drivers active state progress and session-bound icon uploads with write-only secrets | pnpm typecheck; pnpm lint; inventory with 194 commands and 302 call sites; boundaries; focused Vitest with 92 tests; full Vitest with 246 files and 3902 tests; web contract with 8 frontend tests and Rust fixture; pnpm test:rust with 1191 passed and 4 ignored; package and root builds; Cargo build; authenticated HTTP CRUD and icon test; headless smoke; rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-21 | +| WEB-051 | COMPLETED | Added shared SSH and K8s profile tunnel validation progress and session-scoped askpass parity with write-only secrets and local-admin authorization | pnpm typecheck; pnpm lint; inventory with 178 commands and 285 call sites; boundaries; focused Vitest with 140 tests; full Vitest with 246 files and 3903 tests; web contract with 8 frontend tests and Rust fixture; pnpm test:rust with 1197 passed and 4 ignored; package root and Cargo builds; authenticated HTTP profile CRUD test; headless health and auth smoke; targeted rustfmt; GitNexus critical expected tunnel flow scope; git diff --check | 2026-08-21 | +| WEB-052 | COMPLETED | Added shared metadata services and database-authorized RPC parity for explorer discovery snapshots and selected-schema preferences across desktop and web | pnpm typecheck; pnpm lint; inventory with 163 commands and 231 call sites; boundaries; focused Vitest with 114 tests; full Vitest with 246 files and 3905 tests; web contract with 10 frontend tests and Rust fixture; pnpm test:rust with 1200 passed and 4 ignored; package and root builds; Cargo build; authenticated SQLite HTTP metadata and preference test; targeted rustfmt; GitNexus expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-053 | COMPLETED | Added shared query execution batch count explain server-time cancellation and session-isolated active-connection parity with bounded web responses | pnpm typecheck; pnpm lint; inventory with 159 commands and 226 call sites; boundaries; focused Vitest with 55 tests; full Vitest with 246 files and 3907 tests; web contract with 12 frontend tests and Rust fixture; pnpm test:rust with 1207 passed and 4 ignored; package root and Cargo builds; authenticated SQLite HTTP query batch count explain server-time and request cancellation test; targeted rustfmt; GitNexus critical expected query-flow scope; git diff --check | 2026-08-22 | +| WEB-054 | COMPLETED | Added shared record services and typed insert update delete and BLOB parity with session-scoped bounded uploads previews and single-use downloads | pnpm typecheck; pnpm lint; inventory with 155 commands and 218 call sites; boundaries with 133 imports and 220 invokes; focused Vitest; full Vitest with 248 files and 3921 tests; web contract with 14 frontend and 1 Rust test; pnpm test:rust with 1215 passed and 4 ignored; package root and Cargo builds; authenticated SQLite HTTP CRUD upload preview single-use download and payload-limit test; targeted rustfmt; GitNexus critical expected data-grid and RPC scope; git diff --check | 2026-08-22 | +| WEB-055 | COMPLETED | Added shared typed web parity for views materialized views routines triggers DDL generation and sensitive user privilege administration | pnpm typecheck; pnpm lint; inventory with 126 commands and 173 call sites; boundaries with 123 imports and 175 invokes; focused Vitest task suites; full Vitest with 248 files and 3923 tests; web contract with 16 frontend and 1 Rust test; pnpm test:rust with 1216 passed and 4 ignored; package root and Cargo builds; authenticated SQLite HTTP object lifecycle and DDL test; MySQL user and MySQL PostgreSQL routine unit suites; targeted rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-060 | COMPLETED | Added shared typed settings keybindings themes prompts editor preferences and session-isolated connection restore state with locked config writes | pnpm typecheck; pnpm lint; inventory with 105 commands and 138 call sites; boundaries with 120 imports and 138 invokes; focused Vitest with 231 tests; full Vitest with 249 files and 3926 tests; web contract with 18 frontend and 1 Rust test; pnpm test:rust with 1225 passed and 4 ignored; package root and Cargo builds; authenticated HTTP preference test; targeted rustfmt; GitNexus high expected scope; git diff --check | 2026-08-22 | +| WEB-061 | COMPLETED | Added shared typed saved query and query history CRUD with strict connection scoping atomic locked persistence and concurrent session safety | pnpm typecheck; pnpm lint; inventory with 97 commands and 130 call sites; boundaries with 118 imports and 130 invokes; focused frontend and Rust suites; full Vitest with 250 files and 3930 tests; web contract with 20 frontend and 1 Rust test; pnpm test:rust with 1231 passed and 4 ignored; package root and Cargo builds; authenticated HTTP CRUD and cross-connection rejection test; GitNexus critical expected branch scope; git diff --check | 2026-08-22 | +| WEB-062 | COMPLETED | Added shared typed notebook CRUD and execution parity with opaque browser imports and browser-safe downloads while preserving notebook formats charts outline and history | pnpm typecheck; pnpm lint; inventory with 91 commands and 123 call sites; boundaries with 113 imports and 123 invokes; focused Vitest with 175 tests; full Vitest with 251 files and 3936 tests; web contract with 22 frontend and 1 Rust test; pnpm test:rust with 1234 passed and 4 ignored; package root and Cargo builds; authenticated HTTP notebook CRUD and cross-connection test; targeted rustfmt; GitNexus critical expected notebook flow scope; git diff --check | 2026-08-22 | +| WEB-063 | COMPLETED | Added opaque shared route sessions and platform adapters for results JSON schema visual explain task manager and connection tabs while retaining native desktop windows | pnpm typecheck; pnpm lint; focused Vitest with 10 files and 71 tests; full Vitest with 254 files and 3947 tests; pnpm test:rust with 1235 passed and 4 ignored; package root and Cargo builds; inventory with 84 commands and 110 call sites; boundaries with 104 imports and 110 invokes; headless health and auth smoke; targeted rustfmt; GitNexus expected critical shared route scope; git diff --check | 2026-08-22 | +| WEB-070 | COMPLETED | Added authenticated streaming file transfers with opaque purpose-bound session tokens safe metadata limits expiry atomic cleanup and single-use downloads | pnpm typecheck; pnpm lint; inventory with 84 commands and 110 call sites; boundaries with 104 imports and 110 invokes; focused frontend and Rust transfer suites; full Vitest with 254 files and 3948 tests; web contract with 22 frontend and 1 Rust test; pnpm test:rust with 1239 passed and 4 ignored; package root and Cargo builds; authenticated HTTP upload and BLOB compatibility tests; targeted rustfmt; GitNexus medium task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-071 | COMPLETED | Added shared typed encrypted connection export uploaded import and backup parity with session-scoped tokens write-only secrets server targets and browser downloads | pnpm typecheck; pnpm lint; inventory with 72 commands and 98 call sites; boundaries with 96 imports and 98 invokes; focused Vitest with 31 tests; full Vitest with 256 files and 3954 tests; web contract with 24 frontend and 1 Rust test; pnpm test:rust with 1248 passed and 4 ignored; package root and Cargo builds; authenticated HTTP export upload preview and apply test; headless health and token-redaction smoke; targeted rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-072 | COMPLETED | Added shared typed database dump and import jobs with session-scoped cancellation progress streamed uploads and downloads plus disconnect cleanup | pnpm typecheck; pnpm lint; inventory with 68 commands and 94 call sites; boundaries with 92 imports and 94 invokes; focused frontend and Rust suites; full Vitest with 257 files and 3962 tests; web contract with 26 frontend and 1 Rust test; pnpm test:rust with 1254 passed and 4 ignored; package root and Cargo builds; authenticated SQLite HTTP dump download and uploaded import round trip; headless health and token-redaction smoke; targeted rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-073 | COMPLETED | Added shared query AI activity log theme and diagram exports with streamed browser downloads session cleanup and validated BLOB file parity | pnpm typecheck; pnpm lint; inventory with 62 commands and 88 call sites; boundaries with 82 imports and 88 invokes; focused Vitest with 127 tests; full Vitest with 258 files and 3966 tests; web contract with 28 frontend and 1 Rust test; pnpm test:rust with 1260 passed and 4 ignored; generic and transfer cleanup Rust suites; package root and Cargo builds; authenticated SQLite HTTP query export; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-080 | COMPLETED | Added shared typed AI parity for write-only provider keys models generation explanations naming activity sessions exports and session-owned approvals | pnpm typecheck; pnpm lint; inventory with 44 commands and 61 call sites; boundaries with 72 imports and 61 invokes; focused Vitest with 104 tests; full Vitest with 259 files and 3971 tests; web contract with 30 frontend tests and Rust fixture; pnpm test:rust with 1264 passed and 4 ignored; package root and Cargo builds; authenticated HTTP AI activity session and approval test; headless health and token-redaction smoke; targeted rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-081 | COMPLETED | Added shared local-admin plugin registry lifecycle startup-error and task-action parity over typed desktop and web transports with runtime-scoped paths | pnpm typecheck; pnpm lint; inventory with 32 commands and 40 call sites; boundaries with 66 imports and 40 invokes; focused frontend with 132 tests; full Vitest with 259 files and 3973 tests; web contract with 32 frontend tests and Rust fixture; pnpm test:rust with 1269 passed and 4 ignored; package root and Cargo builds; authenticated HTTP registry installed-list startup-error and invalid-path smoke; targeted rustfmt; GitNexus expected critical scope; git diff --check | 2026-08-22 | +| WEB-082 | COMPLETED | Added authenticated allowlisted plugin UI assets with shared desktop and web loading automatic API compatibility strict CSP documented trust and all-slot parity coverage | pnpm typecheck; pnpm lint; focused Vitest with 32 tests; full Vitest with 261 files and 3983 tests; web contract with 32 frontend and 1 Rust test; pnpm test:rust with 1272 passed and 4 ignored; package root Cargo plugin API and create-plugin builds; create-plugin smoke; authenticated HTTP CSP test; inventory; boundaries; targeted rustfmt; GitNexus staged low risk; git diff --check | 2026-08-22 | +| WEB-083 | COMPLETED | Added shared typed log viewing controls process monitoring and browser-safe task actions with local-admin destructive-operation guards | pnpm typecheck; pnpm lint; focused Vitest with 4 files and 70 tests; full Vitest with 263 files and 3988 tests; web contract with 34 frontend tests and Rust fixture; pnpm test:rust with 1278 passed and 4 ignored; authenticated HTTP operational RPC test; inventory with 23 commands and 30 call sites; boundaries with 61 imports and 30 invokes; package root and Cargo builds; targeted rustfmt; GitNexus critical expected shared-client scope; git diff --check | 2026-08-22 | +| WEB-084 | COMPLETED | Added shared typed MCP host status and installation parity with loopback-only local-admin Web access explicit capability negotiation and unambiguous process modes | pnpm typecheck; pnpm lint; focused Vitest with 50 tests; full Vitest with 264 files and 3991 tests; web contract with 36 frontend tests and Rust fixture; pnpm test:rust with 1284 passed and 4 ignored; package root and Cargo builds; authenticated local and remote HTTP policy smoke; CLI mode conflict smoke; inventory; boundaries; targeted rustfmt; GitNexus high shared contract scope; git diff --check | 2026-08-22 | +| WEB-090 | COMPLETED | Added typed browser clipboard and dialog handling with denied-notification and blocked-link fallbacks while preserving native desktop adapters | pnpm typecheck; pnpm lint; focused Vitest with 94 tests; full Vitest with 266 files and 4000 tests; pnpm test:web-contract with 36 frontend and 1 Rust test; pnpm test:rust with 1284 passed and 4 ignored; package and root builds; inventory; boundaries with 31 imports and 26 invokes; GitNexus medium task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-091 | COMPLETED | Added validated browser plugin install routes with explicit confirmation and selected-registry forwarding while preserving native deep-link handling | pnpm typecheck; pnpm lint; focused Vitest with 29 tests; full Vitest with 269 files and 4016 tests; web contract with 36 frontend and 1 Rust test; pnpm test:rust with 1286 passed and 4 ignored; package and root builds; inventory; boundaries; authenticated headless route smoke; targeted rustfmt; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-092 | COMPLETED | Added explicit browser updater disablement with negotiated server version and build metadata localized administrator guidance and preserved native desktop updates | pnpm typecheck; pnpm lint; focused Vitest with 35 tests; full Vitest with 269 files and 4020 tests; web contract with 36 frontend and 1 Rust test; pnpm test:rust with 1286 passed and 4 ignored; package and root builds; Cargo build; authenticated headless session build smoke; inventory; boundaries; targeted rustfmt; GitNexus task low risk and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-093 | COMPLETED | Added password and trusted-proxy remote authentication with HTTPS origins rate limits secure sessions audit logging and a restricted-by-default high-risk policy | pnpm typecheck; pnpm lint; focused Vitest with 30 tests; full Vitest with 269 files and 4021 tests; web contract with 36 frontend tests and Rust fixture; pnpm test:rust with 1289 passed and 4 ignored; focused Web Rust with 48 tests; package root and Cargo builds; inventory; boundaries; authenticated remote password HTTP smoke; GitNexus high task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-094 | COMPLETED | Added cross-platform packaged Web UI checks a resource-complete Windows portable zip headless Linux smoke coverage and secure service deployment examples | pnpm web:packaging with 4 tests; pnpm typecheck; pnpm lint; inventory; boundaries; full Vitest with 269 files and 4021 tests; web contract with 36 frontend tests and Rust fixture; pnpm test:rust with 1289 passed and 4 ignored; package and root builds; signed debug deb build; extracted deb asset and display-free headless smoke from outside the repository; workflow YAML and targeted rustfmt checks; GitNexus low task scope and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-095 | COMPLETED | Added bounded global and per-session Web RPC admission session query cleanup crash and refresh coverage plus a focused resilience CI gate | pnpm test:web-resilience; pnpm typecheck; pnpm lint; inventory; boundaries; packaging with 4 tests; full Vitest with 269 files and 4022 tests; web contract with 36 frontend tests and Rust fixture; pnpm test:rust with 1292 passed and 4 ignored; package root and Cargo builds; targeted rustfmt; GitNexus task low risk and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-100 | COMPLETED | Added an authenticated Playwright E2E gate for real SQLite PostgreSQL MySQL driver-plugin and UI-extension workflows across Chromium Firefox and WebKit projects | Chromium E2E with 5 tests; Firefox E2E with 5 tests; CI three-browser gate; pnpm typecheck; pnpm lint; focused Vitest with 38 tests; full Vitest with 269 files and 4022 tests; pnpm test:web-contract; pnpm test:web-resilience; pnpm test:rust with 1292 passed and 4 ignored; package and root builds; inventory; boundaries; packaging; GitNexus task low risk and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-101 | COMPLETED | Added a signed 29-row desktop and Web parity audit with an evidence and matrix-drift CI check | pnpm web:manual-parity; typecheck; lint; inventory with 21 commands and 26 call sites; boundaries with 30 imports and 26 invokes; focused capabilities with 38 tests; full Vitest with 270 files and 4023 tests; web contract with 36 frontend tests and Rust fixture; web resilience; pnpm test:rust with 1292 library tests passed and 4 ignored; package and root builds; Chromium E2E with 5 tests; desktop and authenticated Web launch smokes; packaging with 4 tests; GitNexus low task risk; git diff --check | 2026-08-22 | +| WEB-102 | COMPLETED | Added a tested Web operator guide covering CLI security deployment storage browser plugins troubleshooting upgrades and rollback | pnpm web:docs with 3 tests; CLI Cargo with 8 tests; pnpm typecheck; pnpm lint; inventory with 21 commands and 26 call sites; boundaries with 30 imports and 26 invokes; full Vitest with 270 files and 4023 tests; pnpm test:rust with 1292 passed and 4 ignored; packaging with 4 tests; manual parity; package and root builds; GitNexus task low risk and expected critical branch scope; git diff --check | 2026-08-22 | +| WEB-103 | COMPLETED | Closed final merge-readiness gates and made Windows release artifact extraction reliably wait for MSI completion | pnpm lint; pnpm typecheck; pnpm test:coverage with 270 files and 4023 tests; pnpm build; pnpm test:rust with 1292 passed and 4 ignored; package build; three-browser E2E CI; boundaries with 30 imports and 26 invokes; security and shared-service review; packaging with 5 tests; cross-platform release matrix; GitNexus expected critical branch scope; git diff --check | 2026-08-22 | diff --git a/web-ui-project/tasks/WEB-000.md b/web-ui-project/tasks/WEB-000.md new file mode 100644 index 000000000..535facaca --- /dev/null +++ b/web-ui-project/tasks/WEB-000.md @@ -0,0 +1,16 @@ +# WEB-000 — Create `feat/web-ui` + +**Phase:** Phase 0 — Governance and measurable baseline (3–5 days) + +- Start from clean, updated `main`. +- Preserve unrelated local changes outside the branch. +- Push branch and configure CI to run on it. + +Acceptance: + +- Branch exists locally and remotely. +- Baseline desktop build and tests are recorded. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-001.md b/web-ui-project/tasks/WEB-001.md new file mode 100644 index 000000000..800ef6bb5 --- /dev/null +++ b/web-ui-project/tasks/WEB-001.md @@ -0,0 +1,18 @@ +# WEB-001 — Generate the API inventory + +**Phase:** Phase 0 — Governance and measurable baseline (3–5 days) + +- Add a script that extracts literal frontend command names. +- Compare them with Tauri handler registration. +- Inventory dynamic command names separately. +- Classify commands by feature group, event use, filesystem use, and authorization level. +- Produce a machine-readable parity file, for example `web-ui-project/docs/web-ui-parity.json`. + +Acceptance: + +- All 224 currently referenced command names are classified. +- CI fails if an unclassified direct invocation is introduced. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-002.md b/web-ui-project/tasks/WEB-002.md new file mode 100644 index 000000000..c2ad2e780 --- /dev/null +++ b/web-ui-project/tasks/WEB-002.md @@ -0,0 +1,20 @@ +# WEB-002 — Add architecture decision records + +**Phase:** Phase 0 — Governance and measurable baseline (3–5 days) + +Document: + +- command RPC rather than duplicated REST APIs; +- shared UI package rather than a second UI; +- HTTP + WebSocket transport; +- local-only secure default; +- upload/download tokens instead of browser-controlled server paths; +- updater and desktop-window semantic adaptations. + +Acceptance: + +- Decisions and rejected alternatives are reviewable before implementation. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-010.md b/web-ui-project/tasks/WEB-010.md new file mode 100644 index 000000000..ce118419e --- /dev/null +++ b/web-ui-project/tasks/WEB-010.md @@ -0,0 +1,17 @@ +# WEB-010 — Define typed command and event contracts + +**Phase:** Phase 1 — Frontend transport seam (8–12 days) + +- Add `CommandMap`, `EventMap`, shared error shape, and request IDs. +- Begin with startup, connections, metadata, and query commands. +- Add compile-time contract tests. +- Define a controlled escape hatch for commands not migrated yet; track every use. + +Acceptance: + +- A typed call catches invalid payloads and return assumptions at compile time. +- No `any` is introduced. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-011.md b/web-ui-project/tasks/WEB-011.md new file mode 100644 index 000000000..5559e1acc --- /dev/null +++ b/web-ui-project/tasks/WEB-011.md @@ -0,0 +1,17 @@ +# WEB-011 — Add `TabularisClientProvider` + +**Phase:** Phase 1 — Frontend transport seam (8–12 days) + +- Create one client instance at the application root. +- Expose hooks that do not know the selected transport. +- Add Tauri transport using current `invoke`, `listen`, and `emit` APIs. +- Preserve current behavior. + +Acceptance: + +- Initial migrated callers pass existing tests. +- Components do not import transport implementations. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-012.md b/web-ui-project/tasks/WEB-012.md new file mode 100644 index 000000000..78a57ec77 --- /dev/null +++ b/web-ui-project/tasks/WEB-012.md @@ -0,0 +1,16 @@ +# WEB-012 — Define platform capabilities + +**Phase:** Phase 1 — Frontend transport seam (8–12 days) + +- Add the semantic capability interface. +- Implement the Tauri adapter first. +- Add capability negotiation and unsupported-capability errors. +- Centralize environment detection. + +Acceptance: + +- No migrated component imports dialog, filesystem, opener, clipboard, event, or window APIs directly. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-013.md b/web-ui-project/tasks/WEB-013.md new file mode 100644 index 000000000..c41d4f9dd --- /dev/null +++ b/web-ui-project/tasks/WEB-013.md @@ -0,0 +1,21 @@ +# WEB-013 — Migrate a representative vertical slice + +**Phase:** Phase 1 — Frontend transport seam (8–12 days) + +Migrate: + +- `is_debug_mode`; +- `get_connections`; +- `test_connection`; +- `get_tables`; +- `execute_query`; +- `cancel_query` and query events. + +Acceptance: + +- Desktop functionality is unchanged. +- The slice proves request, response, errors, cancellation, and events. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-014.md b/web-ui-project/tasks/WEB-014.md new file mode 100644 index 000000000..f6b35d670 --- /dev/null +++ b/web-ui-project/tasks/WEB-014.md @@ -0,0 +1,15 @@ +# WEB-014 — Enforce frontend boundaries + +**Phase:** Phase 1 — Frontend transport seam (8–12 days) + +- Add ESLint restrictions preventing Tauri imports outside adapter files. +- Add a CI check for direct `invoke()` use. +- Maintain an explicit temporary allowlist and drive it to zero. + +Acceptance: + +- New direct Tauri coupling fails CI. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-020.md b/web-ui-project/tasks/WEB-020.md new file mode 100644 index 000000000..c84114b0a --- /dev/null +++ b/web-ui-project/tasks/WEB-020.md @@ -0,0 +1,22 @@ +# WEB-020 — Scaffold workspace package + +**Phase:** Phase 2 — Create `packages/web-ui` without duplication (5–8 days) + +- Add `packages/web-ui/package.json` with name `@tabularis/web-ui`. +- Move Vite, TypeScript, Vitest, PostCSS, and frontend-specific configuration. +- Add package scripts for dev, build, typecheck, lint, and test. +- Keep root scripts as compatibility delegators. + +Acceptance: + +```bash +pnpm --filter @tabularis/web-ui dev +pnpm --filter @tabularis/web-ui build +pnpm --filter @tabularis/web-ui test --run +``` + +all work. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-021.md b/web-ui-project/tasks/WEB-021.md new file mode 100644 index 000000000..3e38ce62b --- /dev/null +++ b/web-ui-project/tasks/WEB-021.md @@ -0,0 +1,18 @@ +# WEB-021 — Move frontend source and assets + +**Phase:** Phase 2 — Create `packages/web-ui` without duplication (5–8 days) + +- Move, do not copy, root `src/`, relevant `public/`, and `index.html`. +- Update aliases, test setup, coverage paths, scripts, and imports. +- Update Tauri `frontendDist` and development URL integration. +- Preserve root output compatibility only if release tooling requires it. + +Acceptance: + +- Exactly one implementation of every component exists. +- Desktop development and release builds use `packages/web-ui`. +- Frontend test count does not decrease unexpectedly. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-022.md b/web-ui-project/tasks/WEB-022.md new file mode 100644 index 000000000..5daccff9a --- /dev/null +++ b/web-ui-project/tasks/WEB-022.md @@ -0,0 +1,15 @@ +# WEB-022 — Make routing server-safe + +**Phase:** Phase 2 — Create `packages/web-ui` without duplication (5–8 days) + +- Ensure direct navigation to every route receives SPA fallback. +- Verify `/connections`, `/editor`, `/settings`, schema diagrams, visual explain, JSON viewer, task manager, and result sessions. +- Decide BrowserRouter base-path behavior. + +Acceptance: + +- Refreshing every supported browser route succeeds. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-030.md b/web-ui-project/tasks/WEB-030.md new file mode 100644 index 000000000..5b2d7c9fb --- /dev/null +++ b/web-ui-project/tasks/WEB-030.md @@ -0,0 +1,24 @@ +# WEB-030 — Extend CLI + +**Phase:** Phase 3 — Headless backend bootstrap (8–12 days) + +Add the Web subcommand and its options: + +```text +web +--host default 127.0.0.1 +--port default 8080 +--no-open +--web-root development/testing override +--auth later remote mode +``` + +Define conflicts with `--mcp` and `--explain`. + +Acceptance: + +- CLI tests cover defaults, conflicts, help, and platform fallback behavior. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-031.md b/web-ui-project/tasks/WEB-031.md new file mode 100644 index 000000000..8acfbf657 --- /dev/null +++ b/web-ui-project/tasks/WEB-031.md @@ -0,0 +1,26 @@ +# WEB-031 — Extract shared bootstrap + +**Phase:** Phase 3 — Headless backend bootstrap (8–12 days) + +Extract initialization shared by desktop, MCP where appropriate, and web: + +- rustls provider; +- logging; +- sqlx drivers; +- application paths; +- caches and cancellation state; +- built-in driver registration; +- external driver plugin loading; +- schedulers and shutdown hooks. + +Do not require a `tauri::AppHandle` for platform-neutral initialization. Introduce focused runtime interfaces for paths, events, and secrets. + +Acceptance: + +- Desktop startup remains unchanged externally. +- Unit tests can bootstrap application services without a WebView. +- `web` does not require creating a Tauri window. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-032.md b/web-ui-project/tasks/WEB-032.md new file mode 100644 index 000000000..b66fb9571 --- /dev/null +++ b/web-ui-project/tasks/WEB-032.md @@ -0,0 +1,19 @@ +# WEB-032 — Add HTTP server skeleton + +**Phase:** Phase 3 — Headless backend bootstrap (8–12 days) + +- Add Axum or the selected Rust web framework. +- Serve health, session negotiation, static assets, and SPA fallback. +- Embed release assets or resolve them relative to the installation reliably. +- Implement graceful shutdown and cleanup of tunnels/plugins/jobs. +- Print the final URL and optionally open the browser. + +Acceptance: + +- Packaged `tabularis web --no-open` starts without a graphical session. +- `curl /healthz` succeeds. +- Browser loads the shared UI. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-033.md b/web-ui-project/tasks/WEB-033.md new file mode 100644 index 000000000..4057fafb8 --- /dev/null +++ b/web-ui-project/tasks/WEB-033.md @@ -0,0 +1,17 @@ +# WEB-033 — Local session security + +**Phase:** Phase 3 — Headless backend bootstrap (8–12 days) + +- Add one-time bootstrap tokens, secure session cookies, origin checking, CSRF protection, body limits, request IDs, and redaction. +- Add expiration and logout. +- Ensure static assets do not require leaking bearer tokens in URLs. + +Acceptance: + +- Requests without a valid session fail. +- Cross-origin and replay tests fail safely. +- Tokens do not appear in standard logs. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-040.md b/web-ui-project/tasks/WEB-040.md new file mode 100644 index 000000000..299673af5 --- /dev/null +++ b/web-ui-project/tasks/WEB-040.md @@ -0,0 +1,18 @@ +# WEB-040 — Implement versioned RPC dispatcher + +**Phase:** Phase 4 — RPC and event infrastructure (8–12 days) + +- Decode command name and typed payload. +- Map application errors into stable error codes. +- Add request deadlines and cancellation identifiers. +- Add authorization metadata per command group. +- Avoid a second copy of business logic or validation. + +Acceptance: + +- Representative Phase 1 commands execute over real HTTP. +- Tauri and HTTP contract fixtures produce equivalent results. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-041.md b/web-ui-project/tasks/WEB-041.md new file mode 100644 index 000000000..367edb642 --- /dev/null +++ b/web-ui-project/tasks/WEB-041.md @@ -0,0 +1,24 @@ +# WEB-041 — Implement WebSocket event bus + +**Phase:** Phase 4 — RPC and event infrastructure (8–12 days) + +Support: + +- connection health; +- query cancellation/status; +- dump/import/export progress; +- plugin installation progress; +- AI approvals/activity; +- SSH askpass; +- update/server lifecycle notifications where applicable. + +Add reconnection, heartbeat, subscription cleanup, session scoping, and bounded queues. + +Acceptance: + +- Slow/disconnected clients cannot grow memory without bounds. +- Events are delivered only to authorized sessions. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-042.md b/web-ui-project/tasks/WEB-042.md new file mode 100644 index 000000000..0e5af148d --- /dev/null +++ b/web-ui-project/tasks/WEB-042.md @@ -0,0 +1,17 @@ +# WEB-042 — Implement browser HTTP transport + +**Phase:** Phase 4 — RPC and event infrastructure (8–12 days) + +- Add session bootstrap. +- Add typed RPC calls. +- Add WebSocket subscriptions and reconnection. +- Normalize errors to the same frontend error model as Tauri. +- Select transport once during application bootstrap. + +Acceptance: + +- The Phase 1 vertical slice works in a real browser. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-043.md b/web-ui-project/tasks/WEB-043.md new file mode 100644 index 000000000..7ddde7a45 --- /dev/null +++ b/web-ui-project/tasks/WEB-043.md @@ -0,0 +1,15 @@ +# WEB-043 — Add dual-transport contract harness + +**Phase:** Phase 4 — RPC and event infrastructure (8–12 days) + +- Define reusable behavior suites. +- Run suites against the Tauri adapter mock and live web test server. +- Add serialization fixtures for complex results, blobs, decimals, dates, and nullable values. + +Acceptance: + +- Contract drift fails CI. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-050.md b/web-ui-project/tasks/WEB-050.md new file mode 100644 index 000000000..bd64e7df2 --- /dev/null +++ b/web-ui-project/tasks/WEB-050.md @@ -0,0 +1,15 @@ +# WEB-050 — Connections, groups, tags, and appearance + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate connection CRUD, duplication, active connections, groups, ordering, tags, driver manifests, connection icons, and connection test progress. + +Special handling: + +- icon selection uses upload tokens; +- secret values are write-only from the browser; +- responses never echo stored credentials. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-051.md b/web-ui-project/tasks/WEB-051.md new file mode 100644 index 000000000..c16134d25 --- /dev/null +++ b/web-ui-project/tasks/WEB-051.md @@ -0,0 +1,15 @@ +# WEB-051 — SSH and K8s connections + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate SSH profiles, K8s profiles, validation, tunnel lifecycle, progress events, and askpass. + +Special handling: + +- askpass prompts are bound to the initiating session; +- unattended prompts time out and cancel safely; +- remote mode requires stronger authorization. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-052.md b/web-ui-project/tasks/WEB-052.md new file mode 100644 index 000000000..71353150f --- /dev/null +++ b/web-ui-project/tasks/WEB-052.md @@ -0,0 +1,9 @@ +# WEB-052 — Metadata explorer + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate databases, schemas, tables, columns, keys, indexes, materialized views, routines, triggers, snapshots, and selected-schema preferences. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-053.md b/web-ui-project/tasks/WEB-053.md new file mode 100644 index 000000000..84c47ca51 --- /dev/null +++ b/web-ui-project/tasks/WEB-053.md @@ -0,0 +1,15 @@ +# WEB-053 — Query execution + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate single and batch execution, count, server time, explain plan, cancellation, active connection registration, and disconnect. + +Special handling: + +- define response-size policy and optional pagination/streaming; +- cancellation survives WebSocket reconnect through request IDs; +- concurrent browser sessions are isolated. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-054.md b/web-ui-project/tasks/WEB-054.md new file mode 100644 index 000000000..31d8af1c6 --- /dev/null +++ b/web-ui-project/tasks/WEB-054.md @@ -0,0 +1,14 @@ +# WEB-054 — Data editing and blobs + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate insert, update, delete, referenced records, MIME detection, blob upload, preview, and download. + +Special handling: + +- replace server file paths with upload/download tokens; +- enforce payload limits and temporary-file cleanup. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-055.md b/web-ui-project/tasks/WEB-055.md new file mode 100644 index 000000000..b5fe83e34 --- /dev/null +++ b/web-ui-project/tasks/WEB-055.md @@ -0,0 +1,13 @@ +# WEB-055 — Database objects and user management + +**Phase:** Phase 5 — Core database parity (15–22 days) + +Migrate views, materialized views, routines, triggers, DDL generation, users, grants, passwords, and privilege application. + +Acceptance for Phase 5: + +- Connections, editor, schema explorer, result grid, object editors, and user management pass browser E2E tests against MySQL, PostgreSQL, and SQLite. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-060.md b/web-ui-project/tasks/WEB-060.md new file mode 100644 index 000000000..e68cbced3 --- /dev/null +++ b/web-ui-project/tasks/WEB-060.md @@ -0,0 +1,10 @@ +# WEB-060 — Settings, keybindings, and themes + +**Phase:** Phase 6 — Persistence and productivity parity (10–15 days) + +- Migrate config, prompts, editor preferences, keybindings, custom themes, and connection selection state. +- Separate user/session preferences from server-global settings where concurrent sessions could conflict. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-061.md b/web-ui-project/tasks/WEB-061.md new file mode 100644 index 000000000..b2942b266 --- /dev/null +++ b/web-ui-project/tasks/WEB-061.md @@ -0,0 +1,10 @@ +# WEB-061 — Saved queries and query history + +**Phase:** Phase 6 — Persistence and productivity parity (10–15 days) + +- Migrate full CRUD and connection scoping. +- Verify multiple sessions do not corrupt shared state. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-062.md b/web-ui-project/tasks/WEB-062.md new file mode 100644 index 000000000..19a0e01d1 --- /dev/null +++ b/web-ui-project/tasks/WEB-062.md @@ -0,0 +1,11 @@ +# WEB-062 — Notebooks + +**Phase:** Phase 6 — Persistence and productivity parity (10–15 days) + +- Migrate notebook CRUD and execution. +- Adapt import/export to browser upload/download. +- Preserve charts, outline, history, HTML export, and file format compatibility. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-063.md b/web-ui-project/tasks/WEB-063.md new file mode 100644 index 000000000..dfcc3cf9b --- /dev/null +++ b/web-ui-project/tasks/WEB-063.md @@ -0,0 +1,21 @@ +# WEB-063 — Secondary windows + +**Phase:** Phase 6 — Persistence and productivity parity (10–15 days) + +Replace Tauri window operations with shared session models and routes: + +- results window -> `/results-window?session=...`; +- JSON viewer -> `/json-viewer?session=...`; +- schema diagram -> `/schema-diagram?...`; +- visual explain -> `/visual-explain?...`; +- task manager -> `/task-manager`; +- connection window -> route/new browser tab. + +Acceptance: + +- Browser refresh and new-tab flows preserve or clearly expire session state. +- Desktop continues to use native windows through its capability adapter. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-070.md b/web-ui-project/tasks/WEB-070.md new file mode 100644 index 000000000..d64a14e03 --- /dev/null +++ b/web-ui-project/tasks/WEB-070.md @@ -0,0 +1,12 @@ +# WEB-070 — Upload/download token service + +**Phase:** Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) + +- Stream files rather than buffering whole files in memory. +- Use opaque tokens, size limits, expiration, ownership, and cleanup. +- Add safe filenames and content types. +- Add tests for traversal, token guessing, reuse, and interrupted transfers. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-071.md b/web-ui-project/tasks/WEB-071.md new file mode 100644 index 000000000..2425487bb --- /dev/null +++ b/web-ui-project/tasks/WEB-071.md @@ -0,0 +1,12 @@ +# WEB-071 — Connection import/export and backup + +**Phase:** Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) + +- Migrate encrypted connection export/import. +- Migrate foreign-application import using uploaded files. +- Migrate backup status, password setup, manual runs, and generated downloads. +- Clearly distinguish server-host backup targets from browser downloads. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-072.md b/web-ui-project/tasks/WEB-072.md new file mode 100644 index 000000000..938046081 --- /dev/null +++ b/web-ui-project/tasks/WEB-072.md @@ -0,0 +1,11 @@ +# WEB-072 — Database dump/import + +**Phase:** Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) + +- Migrate long-running jobs and cancellation. +- Upload imports and stream dump downloads. +- Preserve progress reporting and cleanup on disconnect. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-073.md b/web-ui-project/tasks/WEB-073.md new file mode 100644 index 000000000..6a92f43ac --- /dev/null +++ b/web-ui-project/tasks/WEB-073.md @@ -0,0 +1,15 @@ +# WEB-073 — Generic exports and logs + +**Phase:** Phase 7 — Files, jobs, backup, and import/export parity (12–18 days) + +- Migrate query export, AI activity export, logs export, blob files, theme import/export, and diagram export. +- Browser downloads replace native save dialogs. + +Acceptance: + +- Large-file tests demonstrate bounded memory use. +- Interrupted jobs and expired tokens clean resources. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-080.md b/web-ui-project/tasks/WEB-080.md new file mode 100644 index 000000000..a4cb43898 --- /dev/null +++ b/web-ui-project/tasks/WEB-080.md @@ -0,0 +1,11 @@ +# WEB-080 — AI and approval flows + +**Phase:** Phase 8 — AI, plugins, and operational parity (15–22 days) + +- Migrate key status/write/delete, model discovery, generation, explanation, plan analysis, naming, activity, sessions, exports, and approvals. +- Never send provider keys back to the browser. +- Scope pending approval prompts to authorized sessions. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-081.md b/web-ui-project/tasks/WEB-081.md new file mode 100644 index 000000000..fa41d2792 --- /dev/null +++ b/web-ui-project/tasks/WEB-081.md @@ -0,0 +1,11 @@ +# WEB-081 — Plugin driver lifecycle + +**Phase:** Phase 8 — AI, plugins, and operational parity (15–22 days) + +- Reuse the existing plugin manager and JSON-RPC subprocess lifecycle. +- Migrate registry, preview, readme, install, cancel, uninstall, enable, disable, startup errors, and task actions. +- Define which filesystem/plugin-directory commands are local-admin only. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-082.md b/web-ui-project/tasks/WEB-082.md new file mode 100644 index 000000000..57bcba8df --- /dev/null +++ b/web-ui-project/tasks/WEB-082.md @@ -0,0 +1,13 @@ +# WEB-082 — Plugin UI extensions + +**Phase:** Phase 8 — AI, plugins, and operational parity (15–22 days) + +- Serve installed UI bundles through authenticated endpoints. +- Reuse the existing `@tabularis/plugin-api` host contract. +- Add API-version compatibility checks. +- Apply a strict CSP and document the trust model for third-party JavaScript. +- Verify every existing slot in desktop and web. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-083.md b/web-ui-project/tasks/WEB-083.md new file mode 100644 index 000000000..c9625a2a8 --- /dev/null +++ b/web-ui-project/tasks/WEB-083.md @@ -0,0 +1,11 @@ +# WEB-083 — Logs and task manager + +**Phase:** Phase 8 — AI, plugins, and operational parity (15–22 days) + +- Migrate log viewing/settings/clear/export. +- Migrate system stats, child processes, plugin process kill/restart. +- Restrict destructive operations in remote mode. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-084.md b/web-ui-project/tasks/WEB-084.md new file mode 100644 index 000000000..b21bc7691 --- /dev/null +++ b/web-ui-project/tasks/WEB-084.md @@ -0,0 +1,12 @@ +# WEB-084 — MCP behavior + +**Phase:** Phase 8 — AI, plugins, and operational parity (15–22 days) + +- Show MCP status in local web mode. +- Permit host configuration only in local/admin sessions. +- Disable or require explicit enablement in remote mode. +- Ensure `--mcp` and `web` process modes remain unambiguous. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-090.md b/web-ui-project/tasks/WEB-090.md new file mode 100644 index 000000000..555d82c39 --- /dev/null +++ b/web-ui-project/tasks/WEB-090.md @@ -0,0 +1,11 @@ +# WEB-090 — Clipboard, dialogs, notifications, and external URLs + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +- Complete browser capability implementations. +- Handle permission denial predictably. +- Provide accessible fallback UI. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-091.md b/web-ui-project/tasks/WEB-091.md new file mode 100644 index 000000000..8ce569e09 --- /dev/null +++ b/web-ui-project/tasks/WEB-091.md @@ -0,0 +1,20 @@ +# WEB-091 — Deep links and install links + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +- Define browser install route semantics. +- Preserve plugin confirmation and registry selection. +- Keep desktop deep-link handling unchanged. + +## Browser install route contract + +- The canonical route is `/install/:slug?version=®istry=`. +- `slug` is required and uses the registry plugin ID format: lowercase ASCII letters, digits, and hyphens with a maximum length of 64. +- `version` and `registry` are optional. A selected registry must be an HTTP or HTTPS base URL without credentials, query parameters, or fragments. +- A valid route always opens the existing plugin confirmation modal. Installation starts only after an explicit confirmation and uses the selected registry without changing the configured default registry. +- Cancelled or invalid routes return to `/connections` without installing. Successful installs also replace the route with `/connections` so refreshing cannot repeat the request. +- Native `tabularis://install` parsing, event delivery, cold-start replay, and confirmation remain unchanged. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-092.md b/web-ui-project/tasks/WEB-092.md new file mode 100644 index 000000000..6d25b5abb --- /dev/null +++ b/web-ui-project/tasks/WEB-092.md @@ -0,0 +1,11 @@ +# WEB-092 — Updater adaptation + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +- Desktop keeps the native updater. +- Web mode exposes server version/build information. +- UI shows documented server-upgrade guidance instead of attempting browser-side binary replacement. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-093.md b/web-ui-project/tasks/WEB-093.md new file mode 100644 index 000000000..907ca108d --- /dev/null +++ b/web-ui-project/tasks/WEB-093.md @@ -0,0 +1,11 @@ +# WEB-093 — Remote authenticated mode + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +- Add password/auth proxy mode, TLS/reverse-proxy documentation, rate limiting, audit events, secure cookies, and origin allowlist. +- Add explicit high-risk capability policy. +- Perform threat modeling before enabling non-loopback bind. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-094.md b/web-ui-project/tasks/WEB-094.md new file mode 100644 index 000000000..715b8ac50 --- /dev/null +++ b/web-ui-project/tasks/WEB-094.md @@ -0,0 +1,12 @@ +# WEB-094 — Packaging + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +- Include `packages/web-ui/dist` in Linux, macOS, and Windows artifacts. +- Verify path resolution when launched outside the repository. +- Verify `tabularis web` on headless Linux without WebKit/display initialization. +- Add container/systemd examples only after the security model is complete. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-095.md b/web-ui-project/tasks/WEB-095.md new file mode 100644 index 000000000..b248605a6 --- /dev/null +++ b/web-ui-project/tasks/WEB-095.md @@ -0,0 +1,20 @@ +# WEB-095 — Performance and resilience + +**Phase:** Phase 9 — Browser adaptations and release hardening (12–18 days) + +Test: + +- large query results; +- slow clients; +- multiple sessions; +- reconnects; +- abandoned jobs; +- plugin crashes; +- tunnel failures; +- graceful shutdown; +- memory/CPU bounds; +- browser refresh during active operations. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-100.md b/web-ui-project/tasks/WEB-100.md new file mode 100644 index 000000000..971edcbc0 --- /dev/null +++ b/web-ui-project/tasks/WEB-100.md @@ -0,0 +1,18 @@ +# WEB-100 — Automated E2E matrix + +**Phase:** Phase 10 — Final parity gate (8–12 days) + +Run browser E2E tests against real: + +- SQLite; +- PostgreSQL; +- MySQL; +- optional SSH and K8s fixtures; +- one driver plugin; +- one UI extension plugin. + +Cover Chromium first; add Firefox and WebKit where browser APIs allow equivalent behavior. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-101.md b/web-ui-project/tasks/WEB-101.md new file mode 100644 index 000000000..7ff0d21f9 --- /dev/null +++ b/web-ui-project/tasks/WEB-101.md @@ -0,0 +1,18 @@ +# WEB-101 — Manual parity audit + +**Phase:** Phase 10 — Final parity gate (8–12 days) + +For every feature-matrix row: + +- desktop evidence; +- web evidence; +- adaptation rationale; +- known limitation; +- test reference; +- reviewer sign-off. + +No row may remain `unknown`. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-102.md b/web-ui-project/tasks/WEB-102.md new file mode 100644 index 000000000..3a6955a3d --- /dev/null +++ b/web-ui-project/tasks/WEB-102.md @@ -0,0 +1,18 @@ +# WEB-102 — Documentation + +**Phase:** Phase 10 — Final parity gate (8–12 days) + +Document: + +- CLI options; +- local security behavior; +- remote deployment and reverse proxy; +- data/config/credential locations; +- browser limitations; +- plugin compatibility; +- troubleshooting; +- upgrade and rollback. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tasks/WEB-103.md b/web-ui-project/tasks/WEB-103.md new file mode 100644 index 000000000..e44bbfc95 --- /dev/null +++ b/web-ui-project/tasks/WEB-103.md @@ -0,0 +1,27 @@ +# WEB-103 — Merge readiness + +**Phase:** Phase 10 — Final parity gate (8–12 days) + +Required gates: + +```bash +pnpm lint +pnpm typecheck +pnpm test:coverage +pnpm build +pnpm test:rust +pnpm --filter @tabularis/web-ui build +``` + +Also require: + +- E2E matrix green; +- security review complete; +- GitNexus change detection reviewed against `main`; +- no unapproved direct Tauri imports in shared UI; +- no duplicate business logic in web handlers; +- release artifacts manually smoke-tested on all supported operating systems. + +## Completion record + +Before finishing, update the matching row in `web-ui-project/tasks/PROGRESS.md` with `COMPLETED` or `BLOCKED`, a concise summary, verification evidence, and the date. Do not use `|` inside progress fields. diff --git a/web-ui-project/tests/runWebUiTasks.test.mjs b/web-ui-project/tests/runWebUiTasks.test.mjs new file mode 100644 index 000000000..5bc26a2a7 --- /dev/null +++ b/web-ui-project/tests/runWebUiTasks.test.mjs @@ -0,0 +1,291 @@ +import {execFileSync, spawnSync} from 'node:child_process'; +import { + chmodSync, + cpSync, + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; + +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +const runnerSource = join(process.cwd(), 'web-ui-project/scripts/run-web-ui-tasks.sh'); + +function writeExecutable(path, contents) { + writeFileSync(path, contents); + chmodSync(path, 0o755); +} + +function git(cwd, ...args) { + return execFileSync('git', args, {cwd, encoding: 'utf8'}); +} + +describe('run-web-ui-tasks', () => { + let root; + let binDir; + let piArgsFile; + let curlArgsFile; + let ghArgsFile; + let ghWatchCountFile; + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'tabularis-web-ui-runner-')); + binDir = join(root, 'bin'); + piArgsFile = join(root, 'pi-args.txt'); + curlArgsFile = join(root, 'curl-args.txt'); + ghArgsFile = join(root, 'gh-args.txt'); + ghWatchCountFile = join(root, 'gh-watch-count.txt'); + + mkdirSync(join(root, 'web-ui-project/scripts'), {recursive: true}); + mkdirSync(join(root, 'web-ui-project/tasks'), {recursive: true}); + mkdirSync(join(root, 'web-ui-project/docs'), {recursive: true}); + mkdirSync(binDir); + cpSync(runnerSource, join(root, 'web-ui-project/scripts/run-web-ui-tasks.sh')); + chmodSync(join(root, 'web-ui-project/scripts/run-web-ui-tasks.sh'), 0o755); + + writeFileSync(join(root, 'web-ui-project/docs/WEB_UI_PLAN.md'), '# Test plan\n'); + writeFileSync(join(root, 'web-ui-project/tasks/WEB-999.md'), '# Test task\n'); + writeFileSync( + join(root, 'web-ui-project/tasks/PROGRESS.md'), + '| Task | Status | Summary | Verification | Updated |\n' + + '| --- | --- | --- | --- | --- |\n' + + '| WEB-998 | PENDING | — | — | — |\n' + + '| WEB-999 | PENDING | — | — | — |\n', + ); + + git(root, 'init', '--quiet'); + git(root, 'config', 'user.name', 'Runner Test'); + git(root, 'config', 'user.email', 'runner@example.test'); + git(root, 'add', '.'); + git(root, 'commit', '--quiet', '-m', 'test fixture'); + + writeExecutable( + join(binDir, 'pi'), + `#!/usr/bin/env bash +printf '%s\\n' '--- invocation ---' "$@" >> "$MOCK_PI_ARGS_FILE" +if [[ " $* " != *" --print "* ]]; then + sleep 30 + exit 99 +fi +if [[ "\${PI_MOCK_RESULT:-success}" == "failure" ]]; then + echo "mock Pi failure" + exit 7 +fi +cat > web-ui-project/tasks/PROGRESS.md <<'EOF' +| Task | Status | Summary | Verification | Updated | +| --- | --- | --- | --- | --- | +| WEB-998 | PENDING | — | — | — | +| WEB-999 | COMPLETED | Mock implementation | Mock verification | 2026-08-21 | +EOF +git add web-ui-project/tasks/PROGRESS.md +if [[ " $* " == *"ci-repair"* ]]; then + echo "repaired" > ci-repair.txt + git add ci-repair.txt + git commit --quiet --amend --no-edit + echo "mock Pi repaired CI" +else + git commit --quiet -m "test: complete task" + echo "mock Pi completed" +fi +`, + ); + + writeExecutable( + join(binDir, 'gh'), + `#!/usr/bin/env bash +printf '%s\\n' "$*" >> "$MOCK_GH_ARGS_FILE" +if [[ "$1 $2" == "run list" ]]; then + echo "4242" + exit 0 +fi +if [[ "$1 $2" == "run watch" ]]; then + count=0 + [[ ! -f "$MOCK_GH_WATCH_COUNT_FILE" ]] || count="$(cat "$MOCK_GH_WATCH_COUNT_FILE")" + count=$((count + 1)) + printf '%s\\n' "$count" > "$MOCK_GH_WATCH_COUNT_FILE" + if [[ "\${GH_MOCK_FAIL_ONCE:-}" == "1" && "$count" == "1" ]]; then + echo "mock CI failure" + exit 1 + fi + echo "mock CI success" + exit 0 +fi +if [[ "$1 $2" == "run view" ]]; then + echo "mock failed logs" + exit 0 +fi +exit 2 +`, + ); + + writeExecutable( + join(binDir, 'curl'), + `#!/usr/bin/env bash +printf '%s\\n' "$@" >> "$MOCK_CURL_ARGS_FILE" +printf '{"ok":true}\\n' +`, + ); + writeExecutable(join(binDir, 'notify-send'), '#!/usr/bin/env bash\nexit 0\n'); + }); + + afterEach(() => { + rmSync(root, {recursive: true, force: true}); + }); + + function run(extraEnv = {}) { + return spawnSync('bash', ['web-ui-project/scripts/run-web-ui-tasks.sh', 'WEB-999'], { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + env: { + ...process.env, + PATH: `${binDir}:/usr/bin:/bin`, + MOCK_PI_ARGS_FILE: piArgsFile, + MOCK_CURL_ARGS_FILE: curlArgsFile, + MOCK_GH_ARGS_FILE: ghArgsFile, + MOCK_GH_WATCH_COUNT_FILE: ghWatchCountFile, + TELEGRAM_BOT_TOKEN: 'test-token', + TELEGRAM_CHAT_ID: '-100123456', + ...extraEnv, + }, + }); + } + + it('creates runtime folders and resumes from the first pending task', () => { + writeFileSync(join(root, 'web-ui-project/tasks/WEB-997.md'), '# Completed task\n'); + writeFileSync(join(root, 'web-ui-project/tasks/WEB-998.md'), '# First pending task\n'); + writeFileSync( + join(root, 'web-ui-project/tasks/PROGRESS.md'), + '| Task | Status | Summary | Verification | Updated |\n' + + '| --- | --- | --- | --- | --- |\n' + + '| WEB-997 | COMPLETED | Existing | Verified | 2026-08-21 |\n' + + '| WEB-998 | PENDING | — | — | — |\n' + + '| WEB-999 | PENDING | — | — | — |\n', + ); + + const result = spawnSync( + 'bash', + ['web-ui-project/scripts/run-web-ui-tasks.sh', '--dry-run'], + { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + env: { + ...process.env, + PATH: `${binDir}:/usr/bin:/bin`, + MOCK_PI_ARGS_FILE: piArgsFile, + MOCK_CURL_ARGS_FILE: curlArgsFile, + MOCK_GH_ARGS_FILE: ghArgsFile, + MOCK_GH_WATCH_COUNT_FILE: ghWatchCountFile, + TELEGRAM_BOT_TOKEN: 'test-token', + TELEGRAM_CHAT_ID: '-100123456', + }, + }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).not.toContain('web-ui-WEB-997'); + expect(result.stdout.indexOf('web-ui-WEB-998')).toBeLessThan( + result.stdout.indexOf('web-ui-WEB-999'), + ); + expect(existsSync(join(root, 'web-ui-project/.runtime/logs'))).toBe(true); + }); + + it('notifies Telegram when a task starts and when it finishes', () => { + const result = run(); + + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + expect(readFileSync(piArgsFile, 'utf8').split('\n')).toContain('--print'); + expect(readFileSync(join(root, 'web-ui-project/.runtime/state.tsv'), 'utf8')).toContain( + '\tWEB-999\tFINISHED\t', + ); + + const curlArgs = readFileSync(curlArgsFile, 'utf8'); + expect(curlArgs.match(/sendMessage/g)).toHaveLength(2); + expect(curlArgs).toContain('https://api.telegram.org/bottest-token/sendMessage'); + expect(curlArgs).toContain('chat_id=-100123456'); + expect(curlArgs).toContain('text=Web UI task started: WEB-999 (progress: 0.0% (0/2); log:'); + expect(curlArgs).toContain( + 'text=Web UI task finished: WEB-999 completed, validated, and CI is green (progress: 50.0% (1/2))', + ); + }); + + it('starts a Pi repair session after failed CI and watches the amended result', () => { + const result = run({GH_MOCK_FAIL_ONCE: '1'}); + + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + const piArgs = readFileSync(piArgsFile, 'utf8'); + expect(piArgs.match(/--- invocation ---/g)).toHaveLength(2); + expect(piArgs).toContain('web-ui-WEB-999-ci-repair-1'); + expect(piArgs).toContain('Repair the failed CI for exactly task WEB-999'); + + const state = readFileSync(join(root, 'web-ui-project/.runtime/state.tsv'), 'utf8'); + expect(state).toContain('\tWEB-999\tCI_REPAIR(1)\t'); + expect(state).toContain('\tWEB-999\tFINISHED\t'); + + const ghArgs = readFileSync(ghArgsFile, 'utf8'); + expect(ghArgs.match(/run watch 4242 --exit-status/g)).toHaveLength(2); + expect(ghArgs).toContain('run view 4242 --log-failed'); + expect(readFileSync(ghWatchCountFile, 'utf8').trim()).toBe('2'); + + const curlArgs = readFileSync(curlArgsFile, 'utf8'); + expect(curlArgs.match(/sendMessage/g)).toHaveLength(3); + expect(curlArgs).toContain('text=Web UI task CI repair: WEB-999 repair 1/3'); + expect(curlArgs).toContain('progress: 50.0% (1/2)'); + }); + + it("returns Pi's failure status and sends a terminal failure notification", () => { + const result = run({PI_MOCK_RESULT: 'failure'}); + + expect(result.error).toBeUndefined(); + expect(result.status).toBe(7); + expect(readFileSync(join(root, 'web-ui-project/.runtime/state.tsv'), 'utf8')).toContain( + '\tWEB-999\tFAILED(7)\t', + ); + const curlArgs = readFileSync(curlArgsFile, 'utf8'); + expect(curlArgs.match(/sendMessage/g)).toHaveLength(2); + expect(curlArgs).toContain('text=Web UI task started: WEB-999 (progress: 0.0% (0/2); log:'); + expect(curlArgs).toContain( + 'text=Web UI task failed: WEB-999 exited with status 7 (progress: 0.0% (0/2))', + ); + }); + + it('notifies Telegram when a completed task is skipped', () => { + writeFileSync( + join(root, 'web-ui-project/tasks/PROGRESS.md'), + '| Task | Status | Summary | Verification | Updated |\n' + + '| --- | --- | --- | --- | --- |\n' + + '| WEB-999 | COMPLETED | Existing implementation | Existing verification | 2026-08-21 |\n', + ); + git(root, 'add', 'web-ui-project/tasks/PROGRESS.md'); + git(root, 'commit', '--quiet', '-m', 'test: mark task completed'); + + const result = run(); + + expect(result.status).toBe(0); + expect(readFileSync(join(root, 'web-ui-project/.runtime/state.tsv'), 'utf8')).toContain( + '\tWEB-999\tSKIPPED(COMPLETED)\t', + ); + expect(readFileSync(curlArgsFile, 'utf8')).toContain( + 'text=Web UI task skipped: WEB-999 is already completed', + ); + expect(() => readFileSync(piArgsFile, 'utf8')).toThrow(); + }); + + it('rejects incomplete Telegram configuration before starting Pi', () => { + const result = run({TELEGRAM_CHAT_ID: ''}); + + expect(result.status).toBe(1); + expect(result.stderr).toContain( + 'TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID must be set together.', + ); + expect(() => readFileSync(piArgsFile, 'utf8')).toThrow(); + }); +}); diff --git a/web-ui-project/tests/webManualParityAudit.test.mjs b/web-ui-project/tests/webManualParityAudit.test.mjs new file mode 100644 index 000000000..3874b3830 --- /dev/null +++ b/web-ui-project/tests/webManualParityAudit.test.mjs @@ -0,0 +1,63 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + +import {expect, test} from 'vitest'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const read = (relativePath) => fs.readFileSync(path.join(root, relativePath), 'utf8'); + +function tableRows(document, header) { + const lines = document.split('\n'); + const headerIndex = lines.indexOf(header); + expect(headerIndex, `Missing table header: ${header}`).not.toBe(-1); + + const rows = []; + for (const line of lines.slice(headerIndex + 2)) { + if (!line.startsWith('|')) break; + rows.push( + line + .slice(1, -1) + .split('|') + .map((cell) => cell.trim()), + ); + } + return rows; +} + +test('the signed manual audit covers every planned parity area', () => { + const planRows = tableRows( + read('web-ui-project/docs/WEB_UI_PLAN.md'), + '| Area | Web behavior | Parity type | Primary transport needs |', + ); + const auditRows = tableRows( + read('web-ui-project/docs/WEB_MANUAL_PARITY_AUDIT.md'), + '| Area | Desktop evidence | Web evidence | Adaptation rationale | Known limitation | Test reference | Reviewer sign-off |', + ); + + const plannedAreas = planRows.map(([area]) => area); + const auditedAreas = auditRows.map(([area]) => area); + expect(auditedAreas).toEqual(plannedAreas); + + for (const row of auditRows) { + expect(row, `Unexpected audit column count for ${row[0]}`).toHaveLength(7); + for (const cell of row) { + expect(cell, `Empty audit evidence for ${row[0]}`).not.toHaveLength(0); + expect(cell, `Unresolved audit value for ${row[0]}`).not.toMatch( + /\b(?:unknown|tbd|todo)\b/i, + ); + expect(cell, `Missing audit value for ${row[0]}`).not.toBe('—'); + } + const references = [...row[5].matchAll(/`([^`]+)`/g)].map((match) => match[1]); + expect(references, `Missing test reference for ${row[0]}`).not.toHaveLength(0); + for (const reference of references) { + expect( + fs.existsSync(path.join(root, reference)), + `Missing referenced evidence ${reference} for ${row[0]}`, + ).toBe(true); + } + expect(row[6], `Missing reviewer approval for ${row[0]}`).toMatch( + /^Approved by Web UI parity reviewer on \d{4}-\d{2}-\d{2}$/, + ); + } +}); diff --git a/web-ui-project/tests/webUiApiInventory.test.mjs b/web-ui-project/tests/webUiApiInventory.test.mjs new file mode 100644 index 000000000..466639649 --- /dev/null +++ b/web-ui-project/tests/webUiApiInventory.test.mjs @@ -0,0 +1,83 @@ +import {describe, expect, it} from 'vitest'; + +import { + buildInventory, + extractFrontendInvocations, + extractTauriHandlers, + validateInventory, +} from '../scripts/generate-web-ui-api-inventory.mjs'; + +describe('web UI API inventory', () => { + it('extracts literal and dynamic calls through imported invoke aliases', () => { + const result = extractFrontendInvocations([ + { + path: 'src/example.ts', + source: ` + import { invoke as callTauri } from "@tauri-apps/api/core"; + const commandName = shouldSave ? "save_prompt" : "reset_prompt"; + callTauri("get_tables", { connectionId }); + callTauri(commandName, payload); + `, + }, + ]); + + expect(result.literalInvocations).toEqual([ + {command: 'get_tables', file: 'src/example.ts', line: 4}, + ]); + expect(result.dynamicInvocations).toEqual([ + { + expression: 'commandName', + file: 'src/example.ts', + line: 5, + context: null, + possibleCommands: ['reset_prompt', 'save_prompt'], + }, + ]); + }); + + it('extracts registered command names from the Tauri handler macro', () => { + const handlers = extractTauriHandlers(` + .invoke_handler(tauri::generate_handler![ + commands::get_tables, + // Keep module-qualified registrations readable. + plugins::commands::install_plugin, + is_debug_mode, + ]) + `); + + expect(handlers).toEqual(['get_tables', 'install_plugin', 'is_debug_mode']); + }); + + it('rejects new, unclassified, and unregistered direct invocations', () => { + const inventory = buildInventory({ + frontend: { + literalInvocations: [ + {command: 'get_tables', file: 'src/example.ts', line: 2}, + {command: 'new_command', file: 'src/example.ts', line: 3}, + ], + dynamicInvocations: [], + }, + handlers: ['get_tables'], + previous: { + commands: [ + { + name: 'get_tables', + featureGroup: 'metadata', + eventUse: 'none', + filesystemUse: 'none', + authorizationLevel: 'database', + }, + ], + }, + }); + const errors = validateInventory(inventory); + + expect(errors).toEqual([ + 'Command new_command is missing featureGroup classification', + 'Command new_command is missing eventUse classification', + 'Command new_command is missing filesystemUse classification', + 'Command new_command is missing authorizationLevel classification', + 'Frontend command new_command is not registered by the Tauri handler', + ]); + }); +}); diff --git a/web-ui-project/tests/webUiFrontendBoundaries.test.mjs b/web-ui-project/tests/webUiFrontendBoundaries.test.mjs new file mode 100644 index 000000000..68341b69e --- /dev/null +++ b/web-ui-project/tests/webUiFrontendBoundaries.test.mjs @@ -0,0 +1,85 @@ +import {describe, expect, it} from 'vitest'; + +import { + collectBoundaryUsage, + validateBoundaryUsage, +} from '../scripts/check-web-ui-frontend-boundaries.mjs'; + +const emptyAllowlist = { + schemaVersion: 1, + adapterFiles: [], + legacyTauriImports: {}, + legacyDirectInvokes: {}, +}; + +describe('web UI frontend boundaries', () => { + it('finds Tauri imports and direct invoke calls through aliases', () => { + const usage = collectBoundaryUsage([ + { + path: 'src/example.ts', + source: ` + import { invoke as callTauri } from "@tauri-apps/api/core"; + import * as tauriCore from "@tauri-apps/api/core"; + import { open } from "@tauri-apps/plugin-dialog"; + callTauri("first_command"); + tauriCore.invoke("second_command"); + `, + }, + ]); + + expect(usage).toEqual({ + tauriImports: [{file: 'src/example.ts', count: 3}], + directInvokes: [{file: 'src/example.ts', count: 2}], + }); + }); + + it('allows adapters and exact temporary legacy entries', () => { + const errors = validateBoundaryUsage( + { + tauriImports: [ + {file: 'src/api/transports/tauriTransport.ts', count: 2}, + {file: 'src/legacy.tsx', count: 1}, + ], + directInvokes: [ + {file: 'src/api/transports/tauriTransport.ts', count: 2}, + {file: 'src/legacy.tsx', count: 3}, + ], + }, + { + ...emptyAllowlist, + adapterFiles: ['src/api/transports/tauriTransport.ts'], + legacyTauriImports: {'src/legacy.tsx': 1}, + legacyDirectInvokes: {'src/legacy.tsx': 3}, + }, + ); + + expect(errors).toEqual([]); + }); + + it('rejects new coupling and stale temporary entries', () => { + const errors = validateBoundaryUsage( + { + tauriImports: [ + {file: 'src/legacy.tsx', count: 2}, + {file: 'src/new-component.tsx', count: 1}, + ], + directInvokes: [{file: 'src/legacy.tsx', count: 2}], + }, + { + ...emptyAllowlist, + legacyTauriImports: { + 'src/legacy.tsx': 1, + 'src/removed.tsx': 1, + }, + legacyDirectInvokes: {'src/legacy.tsx': 1}, + }, + ); + + expect(errors).toEqual([ + 'src/legacy.tsx has 2 Tauri imports but its temporary allowance is 1', + 'src/new-component.tsx has 1 Tauri import and is not an adapter or temporary exception', + 'src/removed.tsx no longer has Tauri imports; remove its temporary exception', + 'src/legacy.tsx has 2 direct invoke calls but its temporary allowance is 1', + ]); + }); +}); diff --git a/web-ui-project/tests/webUiWorkspace.test.mjs b/web-ui-project/tests/webUiWorkspace.test.mjs new file mode 100644 index 000000000..ddecf7f46 --- /dev/null +++ b/web-ui-project/tests/webUiWorkspace.test.mjs @@ -0,0 +1,64 @@ +import {existsSync, readFileSync} from 'node:fs'; +import {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +import {describe, expect, it} from 'vitest'; + +const repositoryRoot = join(dirname(fileURLToPath(import.meta.url)), '../..'); +const webUiRoot = join(repositoryRoot, 'packages/web-ui'); +const frontendConfigFiles = [ + 'postcss.config.js', + 'tsconfig.app.json', + 'tsconfig.json', + 'tsconfig.node.json', + 'vite.config.ts', + 'vitest.config.ts', +]; +const delegatedScripts = ['build', 'dev', 'lint', 'preview', 'test', 'test:coverage', 'typecheck']; +const frontendOwnedPaths = ['index.html', 'public', 'src', 'tests/setup.ts']; + +function readPackageJson(path) { + return JSON.parse(readFileSync(path, 'utf8')); +} + +describe('web UI workspace', () => { + it('owns the frontend package scripts and configuration', () => { + const webUiPackage = readPackageJson(join(webUiRoot, 'package.json')); + + expect(webUiPackage.name).toBe('@tabularis/web-ui'); + expect(webUiPackage.private).toBe(true); + for (const script of delegatedScripts) { + expect(webUiPackage.scripts[script]).toEqual(expect.any(String)); + } + for (const configFile of frontendConfigFiles) { + expect(existsSync(join(webUiRoot, configFile)), configFile).toBe(true); + expect(existsSync(join(repositoryRoot, configFile)), configFile).toBe(false); + } + }); + + it('owns the frontend source, assets, and tests', () => { + for (const ownedPath of frontendOwnedPaths) { + expect(existsSync(join(webUiRoot, ownedPath)), ownedPath).toBe(true); + } + for (const movedPath of ['index.html', 'public', 'src']) { + expect(existsSync(join(repositoryRoot, movedPath)), movedPath).toBe(false); + } + }); + + it('keeps root frontend scripts as compatibility delegators', () => { + const rootPackage = readPackageJson(join(repositoryRoot, 'package.json')); + + for (const script of delegatedScripts) { + expect(rootPackage.scripts[script]).toBe(`pnpm --filter @tabularis/web-ui ${script}`); + } + }); + + it('configures desktop development and builds to use the web UI package', () => { + const tauriConfig = readPackageJson(join(repositoryRoot, 'src-tauri/tauri.conf.json')); + + expect(tauriConfig.build.frontendDist).toBe('../packages/web-ui/dist'); + expect(tauriConfig.build.devUrl).toBe('http://localhost:5173'); + expect(tauriConfig.build.beforeDevCommand).toBe('pnpm dev'); + expect(tauriConfig.build.beforeBuildCommand).toBe('pnpm build'); + }); +});