diff --git a/.config/nextest.toml b/.config/nextest.toml index f0caa8061d..798f8f0b55 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -16,5 +16,5 @@ test-group = "windows-clipboard" # that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own # timeout. [[profile.default.overrides]] -filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))' +filter = 'package(=ide-svn) | (package(=ide-host) & binary(=integration) & (test(/^svn::/) | test(/^ij_svn_roots::/)))' slow-timeout = { period = "60s", terminate-after = 5 } diff --git a/.github/workflows/cancel-on-close.yml b/.github/workflows/cancel-on-close.yml index e09b259705..7d29809139 100644 --- a/.github/workflows/cancel-on-close.yml +++ b/.github/workflows/cancel-on-close.yml @@ -12,7 +12,7 @@ jobs: cancel: runs-on: ubuntu-latest steps: - - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | // A merged or closed PR's remaining CI only holds runners other PRs wait for. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 24f34f76dd..519f2ee064 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -117,14 +117,7 @@ jobs: # SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online. runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 - with: - node-version: 22 - cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} - package-manager-cache: ${{ runner.environment != 'self-hosted' }} + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { components: "clippy, rustfmt" } # Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache @@ -146,11 +139,11 @@ jobs: echo "$CARGO_TARGET_DIR is ${size} MB; clearing it" rm -rf "$CARGO_TARGET_DIR" fi - - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 + - uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12 with: { tool: nextest } # ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet` # CLI; with CI set they fail, not skip, when it is missing. - - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: dotnet-version: 10.0.x - name: Linux deps @@ -169,17 +162,20 @@ jobs: shell: bash run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version # tauri-build checks that frontendDist exists. - - run: pnpm install --frozen-lockfile && mkdir -p dist + - run: mkdir -p dist shell: bash - if: runner.os == 'Linux' run: cargo fmt --all --check - - run: cargo clippy --workspace --all-targets -- -D warnings + # On PRs, run clippy on Linux only; macOS/Windows still compile and test all targets + # via nextest, and run clippy on main/merge_group so platform-only lints are still caught. + - if: runner.os == 'Linux' || github.event_name != 'pull_request' + run: cargo clippy --workspace --all-targets -- -D warnings # Test fixtures write LF files; keep Git from converting them on checkout. - run: git config --global core.autocrlf false - name: Restore Maven artifacts for Java build tests id: jbuild-maven-cache if: runner.environment == 'github-hosted' - uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/jbuild-maven-repository key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }} @@ -213,13 +209,13 @@ jobs: exit 1 - name: Save Maven artifacts for Java build tests if: steps.jbuild-maven.outputs.prepared == 'true' - uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/jbuild-maven-repository key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }} # python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without # YAPPI_PYTHON those tests return early. - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 if: runner.environment == 'github-hosted' id: yappi-python with: { python-version: "3.12", update-environment: false } @@ -235,7 +231,7 @@ jobs: "$venv_py" -m pip install yappi==1.7.6 echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV" # python_memray.rs profiles real runs. memray has no Windows build. - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 if: runner.os != 'Windows' && runner.environment == 'github-hosted' id: memray-python with: { python-version: "3.12", update-environment: false } @@ -257,7 +253,7 @@ jobs: docker pull busybox:latest # --workspace, not -p ide-host: -p would rebuild instead of reusing the test build above. cargo nextest run --workspace --run-ignored only \ - -E 'package(=ide-host) & binary(=remote_daemon) & test(=compose_service_survives_disconnect_and_is_removed_on_stop)' + -E 'package(=ide-host) & binary(=integration) & test(=remote_daemon::compose_service_survives_disconnect_and_is_removed_on_stop)' # nextest skips doctests; ide-command's are its compile-fail tests. - if: runner.os == 'Linux' run: cargo test --doc -p ide-command @@ -291,12 +287,14 @@ jobs: timeout-minutes: 40 runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { targets: x86_64-unknown-linux-musl } - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: runner.environment != 'self-hosted' - with: { key: server-musl } + with: + key: server-musl + save-if: ${{ github.ref == 'refs/heads/main' }} - name: Persistent Cargo target dir if: runner.environment == 'self-hosted' shell: bash @@ -320,7 +318,7 @@ jobs: timeout-minutes: 30 runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { targets: wasm32-wasip2, components: "clippy, rustfmt" } - if: runner.environment != 'self-hosted' @@ -356,9 +354,9 @@ jobs: cargo test --locked --manifest-path "$dir/Cargo.toml" echo "::endgroup::" done - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: { node-version: 22, package-manager-cache: false } # Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test. - name: Web pages typecheck and test @@ -385,9 +383,9 @@ jobs: timeout-minutes: 15 runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable - - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 + - uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12 with: { tool: cargo-deny } - run: cargo deny check @@ -398,19 +396,19 @@ jobs: timeout-minutes: 30 runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container. - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable if: runner.environment == 'self-hosted' - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} package-manager-cache: ${{ runner.environment != 'self-hosted' }} # src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing. - - uses: actions/setup-dotnet@v5 + - uses: actions/setup-dotnet@v6 with: dotnet-version: | 10.0.x @@ -431,10 +429,10 @@ jobs: timeout-minutes: 15 runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} @@ -453,10 +451,10 @@ jobs: matrix: shard: [1, 2, 3, 4] steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} @@ -464,7 +462,7 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm exec playwright install --with-deps chromium - run: pnpm e2e --shard=${{ matrix.shard }}/4 - - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: failure() with: name: playwright-report-${{ matrix.shard }} diff --git a/.github/workflows/cnb-mirror.yml b/.github/workflows/cnb-mirror.yml index 77501bb2fc..754f26b8eb 100644 --- a/.github/workflows/cnb-mirror.yml +++ b/.github/workflows/cnb-mirror.yml @@ -36,10 +36,10 @@ jobs: echo "::notice::CNB_TOKEN unset: not mirroring $TAG" echo "skip=true" >> "$GITHUB_OUTPUT" fi - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: steps.token.outputs.skip != 'true' with: { sparse-checkout: scripts } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 if: steps.token.outputs.skip != 'true' with: { node-version: 22 } - name: Download release diff --git a/.github/workflows/homebrew.yml b/.github/workflows/homebrew.yml index 660ac2bfc9..c2b1c4969e 100644 --- a/.github/workflows/homebrew.yml +++ b/.github/workflows/homebrew.yml @@ -42,16 +42,16 @@ jobs: echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG" echo "skip=true" >> "$GITHUB_OUTPUT" fi - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: steps.check.outputs.skip != 'true' with: { sparse-checkout: scripts } - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: steps.check.outputs.skip != 'true' with: repository: ${{ env.TAP }} ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }} path: tap - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 if: steps.check.outputs.skip != 'true' with: { node-version: 22 } - name: Download DMGs diff --git a/.github/workflows/language-smoke.yml b/.github/workflows/language-smoke.yml index 9e3312d97c..1a3b3966ab 100644 --- a/.github/workflows/language-smoke.yml +++ b/.github/workflows/language-smoke.yml @@ -26,6 +26,9 @@ on: - "src/features/build/**" - "src/features/build-tools/**" - "src/platform/**" + - "!src/platform/locales/text/**" + - "!src/platform/locales/*.json" + - "src/platform/locales/en.json" - "src/workbench/**" - "src/ui/**" - "src/editor/api.ts" @@ -89,6 +92,7 @@ jobs: pull-requests: read outputs: languages: ${{ steps.classify.outputs.languages }} + groups: ${{ steps.classify.outputs.groups }} steps: - id: classify env: @@ -98,8 +102,18 @@ jobs: set -euo pipefail all="typescript python rust go java kotlin php c cpp" emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; } + emit_groups() { + jq -nc --argjson langs "$1" ' + [ + { name: "jvm", languages: ($langs | map(select(. == "java" or . == "kotlin"))) }, + { name: "systems", languages: ($langs | map(select(. == "rust" or . == "go" or . == "c" or . == "cpp"))) }, + { name: "scripting", languages: ($langs | map(select(. == "typescript" or . == "python" or . == "php"))) } + ] | map(select(.languages | length > 0))' + } if [ "$GITHUB_EVENT_NAME" != pull_request ]; then - echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT" + langs_json=$(emit "$all") + echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT" + echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT" exit 0 fi gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \ @@ -108,8 +122,9 @@ jobs: # Crates outside what the smoke runs (language servers, debuggers, run configurations, # SDKs, build tools, the project model, Find Usages candidates, debug stream traces): # cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of - # ide-lsp/dap/run/sdk/tools. - unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/' + # ide-lsp/dap/run/sdk/tools. Also skip non-English lazy locale catalogs (smoke always + # runs in the default English locale). + unused='^(crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/|src/platform/locales/text/)' # The workflow's paths, less those handled per language below. smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)' langs="" @@ -117,6 +132,8 @@ jobs: case "$f" in crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;; crates/*/tests/* | crates/*/benches/*) ;; + src/platform/locales/en.json) langs="$all"; break ;; + src/platform/locales/*.json) ;; fixtures/ts-app/*) langs+=" typescript" ;; fixtures/python-app/*) langs+=" python" ;; fixtures/rust-app/*) langs+=" rust" ;; @@ -141,7 +158,9 @@ jobs: *) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;; esac done < files.txt - echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT" + langs_json=$(emit "$langs") + echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT" + echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT" # Builds the smoke test binaries and openidea-server once for every language below. build: @@ -157,7 +176,7 @@ jobs: # stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB). CARGO_PROFILE_DEV_DEBUG: line-tables-only steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: runner.environment != 'self-hosted' @@ -186,16 +205,16 @@ jobs: test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke # A tar keeps the executable bits, which artifacts drop. tar -cf smoke-bin.tar smoke-bin - - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 } smoke: - name: Language smoke (${{ matrix.language }}) + name: Language smoke (${{ matrix.group.name }}) needs: [changes, build] strategy: fail-fast: false matrix: - language: ${{ fromJSON(needs.changes.outputs.languages) }} + group: ${{ fromJSON(needs.changes.outputs.groups) }} # Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the # SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online. runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }} @@ -205,29 +224,30 @@ jobs: env: CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # Tool versions, shared with the evals (pnpm eval). - run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV" - - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable + - if: contains(matrix.group.languages, 'rust') + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { components: "rust-analyzer, rustfmt" } - - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: { name: smoke-bin } - run: | tar -xf smoke-bin.tar && rm smoke-bin.tar mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/ - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} package-manager-cache: ${{ runner.environment != 'self-hosted' }} - - if: matrix.language == 'typescript' + - if: contains(matrix.group.languages, 'typescript') run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT" # The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+). - - if: matrix.language == 'c' || matrix.language == 'cpp' + - if: contains(matrix.group.languages, 'c') || contains(matrix.group.languages, 'cpp') shell: bash run: | pkgs=() @@ -243,22 +263,22 @@ jobs: exit 1 fi - - if: matrix.language == 'python' - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - if: contains(matrix.group.languages, 'python') + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: { python-version: "3.12" } - - if: matrix.language == 'python' + - if: contains(matrix.group.languages, 'python') run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF" - - if: matrix.language == 'go' - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + - if: contains(matrix.group.languages, 'go') + uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: { go-version: "1.27", cache: false } - - if: matrix.language == 'go' + - if: contains(matrix.group.languages, 'go') run: go install "golang.org/x/tools/gopls@$GOPLS" - - if: matrix.language == 'java' || matrix.language == 'kotlin' - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1 + - if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin') + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: { distribution: temurin, java-version: "${{ env.JAVA }}" } - - if: matrix.language == 'java' + - if: contains(matrix.group.languages, 'java') run: | command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; } mkdir -p "$RUNNER_TEMP/jdtls" @@ -267,10 +287,12 @@ jobs: echo "$RUNNER_TEMP/jdtls/bin" >> "$GITHUB_PATH" # The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH. - - if: matrix.language == 'kotlin' - uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3 - with: { gradle-version: "${{ env.GRADLE }}" } - - if: matrix.language == 'kotlin' + - if: contains(matrix.group.languages, 'kotlin') + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + gradle-version: "${{ env.GRADLE }}" + cache-read-only: ${{ github.ref != 'refs/heads/main' }} + - if: contains(matrix.group.languages, 'kotlin') run: | mkdir -p "$RUNNER_TEMP/kotlin-lsp" "$RUNNER_TEMP/bin" curl -fsSL "https://download.jetbrains.com/language-server/kotlin-server/$KOTLIN_LSP/kotlin-server-$KOTLIN_LSP.tar.gz" \ @@ -279,31 +301,48 @@ jobs: echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" # Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke. - - if: matrix.language == 'php' + - if: contains(matrix.group.languages, 'php') uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 with: { php-version: "8.5", coverage: xdebug, tools: composer } - - if: matrix.language == 'php' + - if: contains(matrix.group.languages, 'php') run: npm install --global "intelephense@$INTELEPHENSE" # The binaries from the build job, run from the crate directory as `cargo test` does. - - working-directory: crates/ide-host - run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }} - # Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in. - - if: matrix.language == 'typescript' + - name: Code intelligence and project smoke working-directory: crates/ide-host - run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style - - if: matrix.language == 'java' - working-directory: crates/ide-host - run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier - - if: matrix.language == 'kotlin' - working-directory: crates/ide-host - run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync - - if: matrix.language == 'python' - working-directory: crates/ide-host - run: ../../smoke-bin/project_smoke --ignored --exact python_venv + shell: bash + run: | + set -euo pipefail + status=0 + for lang in ${{ join(matrix.group.languages, ' ') }}; do + echo "::group::language_smoke ($lang)" + ../../smoke-bin/language_smoke --ignored --exact "$lang" || status=1 + # Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in. + if [ "$lang" = typescript ]; then + ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style || status=1 + fi + if [ "$lang" = java ]; then + ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier || status=1 + fi + if [ "$lang" = kotlin ]; then + ../../smoke-bin/project_smoke --ignored --exact gradle_sync || status=1 + fi + if [ "$lang" = python ]; then + ../../smoke-bin/project_smoke --ignored --exact python_venv || status=1 + fi + echo "::endgroup::" + done + exit "$status" - run: pnpm install --frozen-lockfile - - run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$" - - run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$" + - name: Run and debug smoke + shell: bash # The IDE installs the debugger from GitHub releases: authenticated, against rate limits. env: { GITHUB_TOKEN: "${{ github.token }}" } + run: | + set -euo pipefail + pattern="^($(echo "${{ join(matrix.group.languages, '|') }}"))$" + status=0 + pnpm smoke smoke/run.test.ts -t "$pattern" || status=1 + pnpm smoke smoke/debug.test.ts -t "$pattern" || status=1 + exit "$status" diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 704a3559e4..7b8c244947 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -30,7 +30,7 @@ jobs: outputs: tag: ${{ steps.tag.outputs.tag }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: { ref: main, fetch-depth: 0 } - id: changed env: @@ -41,7 +41,7 @@ jobs: echo "::notice::main has not changed since $last" echo "skip=true" >> "$GITHUB_OUTPUT" fi - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 if: steps.changed.outputs.skip != 'true' with: { node-version: 22 } - name: Version commit and tag diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index e210c90363..ae039fe093 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -18,7 +18,7 @@ jobs: if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft runs-on: ubuntu-latest steps: - - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const pr = context.payload.pull_request; diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 9f2140ec4d..e07d71755e 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -72,11 +72,11 @@ jobs: target: x86_64-pc-windows-msvc runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: { ref: "${{ env.TAG }}" } - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: { node-version: 22, cache: pnpm } - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { targets: "${{ matrix.target }}" } @@ -198,7 +198,7 @@ jobs: - { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 } runs-on: ${{ matrix.runner }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: { ref: "${{ env.TAG }}" } - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: { targets: "${{ matrix.target }}" } @@ -238,13 +238,13 @@ jobs: env: UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: steps.signing.outputs.updater == 'true' with: { ref: "${{ env.TAG }}" } - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 if: steps.signing.outputs.updater == 'true' with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 if: steps.signing.outputs.updater == 'true' with: { node-version: 22, cache: pnpm } - if: steps.signing.outputs.updater == 'true' @@ -270,7 +270,7 @@ jobs: needs: build runs-on: ubuntu-latest steps: - - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: RELEASE_ID: ${{ inputs.release_id }} with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c7ace04171..cbda49c0c0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,7 +37,7 @@ jobs: outputs: release_id: ${{ steps.release.outputs.id }} steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: { ref: "${{ env.TAG }}" } - name: Tag matches app version run: | @@ -57,7 +57,7 @@ jobs: exit 1 fi - id: release - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: NIGHTLY: ${{ inputs.nightly == true }} with: @@ -126,7 +126,7 @@ jobs: echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published" echo "skip=true" >> "$GITHUB_OUTPUT" fi - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: steps.key.outputs.skip != 'true' with: { ref: "${{ env.TAG }}" } - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable @@ -135,10 +135,10 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: steps.key.outputs.skip != 'true' with: { key: release-plugins } - - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 if: steps.key.outputs.skip != 'true' with: { version: 11 } - - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 if: steps.key.outputs.skip != 'true' with: { node-version: 22 } # Builds the web pages; fails when a checked-in component isn't built from these sources. @@ -183,7 +183,7 @@ jobs: needs: [create-release, binaries, plugins] runs-on: ubuntu-latest steps: - - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: RELEASE_ID: ${{ needs.create-release.outputs.release_id }} with: diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index bc9e5b3d5e..9528bcb0f2 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -4,7 +4,7 @@ `src/ui/brands/*.svg` use the unmodified logo paths from [Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through -Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md). +Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos; `dotnet_dark.svg` lightens .NET's purple for dark themes). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md). ## DuckDB symbol @@ -75,6 +75,11 @@ The read/write usage filter assets (`actions/showReadAccess{,_dark}.svg` and [`e992ff4750b4c36afe2caadfa8b191a8f36fb7a2`](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2/platform/icons/src/expui/actions). Their original copyright headers and Apache-2.0 licensing are retained. +The `actions/showImportStatements{,_dark}.svg` asset is copied unmodified from +`platform/icons/src/expui/actions/` at intellij-community commit +[`71290c3174`](https://github.com/JetBrains/intellij-community/tree/71290c3174/platform/icons/src). +Its original copyright headers and Apache-2.0 licensing are retained. + - [intellij-rust](https://github.com/intellij-rust/intellij-rust) (MIT): `src/main/resources/icons/expui/rustFile{,_dark}.svg` → `src/ui/expui/fileTypes/rust{,_dark}.svg`; diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index b49517ffe7..afba6f84b4 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String); #[derive(Default)] pub struct AgentCatalogs { state: Mutex, + /// Orders model requests by when they were made, not when they reach `state`. + tickets: std::sync::atomic::AtomicU64, #[cfg(test)] clock_ms: std::sync::atomic::AtomicU64, } @@ -49,6 +51,8 @@ struct Entry { abort: Option, flight_model: Option, requested_model: Option, + /// Ticket of the newest model request applied: an older one arriving late can't supersede it. + model_ticket: u64, model_failures: HashMap, catalog: Option, } @@ -254,11 +258,13 @@ impl AgentCatalogs { } let unavailable = || "The agent did not report settings for the selected model".to_owned(); let spec = shared.spec(provider).ok_or_else(unavailable)?; + // Taken now: the blocking task may run after a newer selection's request. + let ticket = self.ticket(); let flight = { let catalogs = self.clone(); let shared = shared.clone(); let model = model.to_owned(); - tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1) + tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1) .await .map_err(|e| e.to_string())? }; @@ -331,12 +337,49 @@ impl AgentCatalogs { } /// Start or join a lookup. No queued refresh can outlive the request that asked for it. + /// The model the running discovery of `provider` looks up, if one is running. + #[cfg(test)] + pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option> { + let state = self.state.lock(); + let entry = state.entries.get(&Self::key(shared, provider))?; + entry.flight.as_ref().map(|_| entry.flight_model.clone()) + } + + #[cfg(test)] + pub(crate) fn request_as_of( + self: &Arc, + shared: &Arc, + spec: provider::ProviderSpec, + model: &str, + ticket: u64, + ) -> Option> { + self.request_with(shared, spec, false, Some(model), ticket).1 + } + + pub(crate) fn ticket(&self) -> u64 { + self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 + } + pub(crate) fn request( self: &Arc, shared: &Arc, spec: provider::ProviderSpec, force: bool, model: Option<&str>, + ) -> (AgentModelCatalog, Option>) { + let ticket = self.ticket(); + self.request_with(shared, spec, force, model, ticket) + } + + /// [`Self::request`] for a request made when `ticket` was taken. A model request older than + /// the newest one applied neither changes the requested model nor supersedes its flight. + fn request_with( + self: &Arc, + shared: &Arc, + spec: provider::ProviderSpec, + force: bool, + model: Option<&str>, + ticket: u64, ) -> (AgentModelCatalog, Option>) { let key = Self::key(shared, &spec.id); let context = LaunchContext::new(spec.clone(), &shared.paths.project_root); @@ -388,6 +431,7 @@ impl AgentCatalogs { abort: None, flight_model: None, requested_model: None, + model_ticket: 0, model_failures: HashMap::new(), }, ); @@ -404,10 +448,15 @@ impl AgentCatalogs { || (!fresh && catalog.model_option().is_none()) }) .map(str::to_owned); - if model.is_some() && entry.requested_model.as_deref() != model { - entry.requested_model = model.map(str::to_owned); + let stale = model.is_some() && ticket < entry.model_ticket; + if model.is_some() && !stale { + entry.model_ticket = ticket; + if entry.requested_model.as_deref() != model { + entry.requested_model = model.map(str::to_owned); + } } - let superseded = model.is_some() + let superseded = !stale + && model.is_some() && entry.flight.is_some() && (entry.flight_model.is_some() || target.is_some()) && entry.flight_model.as_deref() != target.as_deref(); diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 0ab468af62..69b6e995e0 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -1574,6 +1574,9 @@ pub struct AgentPluginCapabilities { pub hook_files: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub stdio_commands: Vec, + /// Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub lsp_commands: Vec, #[serde(default)] pub has_lsp: bool, #[serde(default)] @@ -1581,7 +1584,7 @@ pub struct AgentPluginCapabilities { /// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub native_harnesses: Vec, - /// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents). + /// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents). #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub capability_hash: Option, diff --git a/crates/ide-agent/src/native/claude/cli.rs b/crates/ide-agent/src/native/claude/cli.rs index 3f501b6e8c..99affc5c97 100644 --- a/crates/ide-agent/src/native/claude/cli.rs +++ b/crates/ide-agent/src/native/claude/cli.rs @@ -134,13 +134,14 @@ impl Cli for Process { } } -/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`). +/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`); an empty value counts as +/// unset, and a leading `~` is the user's home. pub(crate) fn config_dir(env: &[(String, String)]) -> Option { let set = env .iter() - .find(|(k, _)| k == "CLAUDE_CONFIG_DIR") - .map(|(_, v)| PathBuf::from(v)) - .or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from)); + .find(|(k, v)| k == "CLAUDE_CONFIG_DIR" && !v.is_empty()) + .map(|(_, v)| PathBuf::from(crate::provider::expand_home(v))) + .or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)); set.or_else(|| { std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| Path::new(&h).join(".claude")) }) @@ -160,4 +161,19 @@ mod tests { "--resume a --fork-session --session-id b" ); } + + #[test] + fn an_empty_config_dir_is_unset() { + let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), String::new())]); + assert!(dir.is_some_and(|d| d.is_absolute())); + let set = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "/home/me/.claude-work".into())]); + assert_eq!(set, Some(PathBuf::from("/home/me/.claude-work"))); + } + + #[test] + fn a_config_dir_under_the_home_folder_can_start_with_a_tilde() { + let home = crate::home_dir().unwrap(); + let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "~/.claude-work".into())]); + assert_eq!(dir, Some(home.join(".claude-work"))); + } } diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index ecca42a17b..25432b5e09 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -37,12 +37,13 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else const EARLY_CANCEL: Duration = Duration::from_secs(2); const EXIT_GRACE: Duration = Duration::from_millis(100); -/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `/.copilot`). +/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `/.copilot`); an empty value counts as +/// unset, and a leading `~` is the user's home. pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option { env.iter() - .find(|(key, _)| key == "COPILOT_HOME") - .map(|(_, value)| PathBuf::from(value)) - .or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from)) + .find(|(key, value)| key == "COPILOT_HOME" && !value.is_empty()) + .map(|(_, value)| PathBuf::from(crate::provider::expand_home(value))) + .or_else(|| std::env::var_os("COPILOT_HOME").filter(|v| !v.is_empty()).map(PathBuf::from)) .or_else(|| home.map(|home| home.join(".copilot"))) } diff --git a/crates/ide-agent/src/native/copilot/tests.rs b/crates/ide-agent/src/native/copilot/tests.rs index f84258a049..1ddd1fd70c 100644 --- a/crates/ide-agent/src/native/copilot/tests.rs +++ b/crates/ide-agent/src/native/copilot/tests.rs @@ -124,7 +124,17 @@ fn resolves_copilot_home_from_agent_env_or_user_home() { ); if std::env::var_os("COPILOT_HOME").is_none() { assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot"))); + assert_eq!( + super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)), + Some(home.join(".copilot")) + ); } + assert!(super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)).is_some_and(|d| d.is_absolute())); + let user_home = crate::home_dir().unwrap(); + assert_eq!( + super::config_dir(&[("COPILOT_HOME".into(), "~/.copilot-work".into())], Some(home)), + Some(user_home.join(".copilot-work")) + ); } #[test] diff --git a/crates/ide-agent/src/plugins.rs b/crates/ide-agent/src/plugins.rs index 9eda0acae4..4689f282c5 100644 --- a/crates/ide-agent/src/plugins.rs +++ b/crates/ide-agent/src/plugins.rs @@ -2203,13 +2203,15 @@ fn inspect_fetched_subtree( } skill_names.sort(); skill_names.dedup(); - let ExecutableCapabilities { mcp_names, stdio_commands, hook_files, capability_hash, .. } = executable; + let ExecutableCapabilities { mcp_names, stdio_commands, lsp_commands, hook_files, capability_hash, .. } = + executable; if formats.is_empty() && skill_names.is_empty() && mcp_names.is_empty() && rule_count == 0 && hook_files.is_empty() + && lsp_commands.is_empty() && subagent_count == 0 && command_count == 0 { @@ -2241,6 +2243,7 @@ fn inspect_fetched_subtree( command_count, hook_files, stdio_commands, + lsp_commands, has_lsp, has_canvas_or_app, native_harnesses: native_harnesses.into_iter().collect(), @@ -2337,6 +2340,7 @@ impl PluginFiles for DiskPluginFiles<'_> { struct ExecutableCapabilities { mcp_names: BTreeSet, stdio_commands: Vec, + lsp_commands: Vec, hook_files: Vec, hook_harnesses: BTreeSet, capability_hash: Option, @@ -2345,6 +2349,7 @@ struct ExecutableCapabilities { fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabilities { let mut mcp_names = BTreeSet::new(); let mut stdio_commands = BTreeSet::new(); + let mut lsp_commands = BTreeSet::new(); let mut hook_files = BTreeSet::new(); let mut hook_harnesses = BTreeSet::new(); let mut hook_contents: BTreeMap> = BTreeMap::new(); @@ -2369,6 +2374,9 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil if let Some(mcp) = manifest.get("mcpServers") { collect_in_memory_mcp_summary(mcp, files, &mut mcp_names, &mut stdio_commands); } + if let Some(lsp) = manifest.get("lspServers") { + collect_lsp_commands(lsp, files, &mut lsp_commands, &mut HashSet::new()); + } let (paths, objects) = manifest_hook_declarations(rel, &manifest); for path in paths { add_hook_file(path, &mut hook_contents); @@ -2382,6 +2390,13 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil collect_in_memory_mcp_summary(&value, files, &mut mcp_names, &mut stdio_commands); } } + for rel in [".lsp.json", "lsp.json"] { + if let Some(bytes) = files.read(rel) + && let Ok(value) = parse_jsonc(&String::from_utf8_lossy(&bytes)) + { + collect_lsp_commands(&value, files, &mut lsp_commands, &mut HashSet::new()); + } + } for (label, bytes) in inline_hooks { hook_files.insert(label.clone()); hook_contents.insert(label, bytes); @@ -2400,12 +2415,14 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil } } let stdio_commands: Vec = stdio_commands.into_iter().collect(); + let lsp_commands: Vec = lsp_commands.into_iter().collect(); let digests: Vec<(&str, &[u8])> = hook_contents.iter().map(|(rel, bytes)| (rel.as_str(), bytes.as_slice())).collect(); - let capability_hash = compute_capability_hash(&stdio_commands, &digests); + let capability_hash = compute_capability_hash(&stdio_commands, &lsp_commands, &digests); ExecutableCapabilities { mcp_names, stdio_commands, + lsp_commands, hook_files: hook_files.into_iter().collect(), hook_harnesses, capability_hash, @@ -2478,6 +2495,59 @@ fn collect_in_memory_mcp_summary_inner( } } +/// `name: command args env:K=V` for each language server a `.lsp.json` file, a manifest's +/// `lspServers` value (an object, a path to such a file, or a list of either) declares. +fn collect_lsp_commands( + val: &Value, + files: &dyn PluginFiles, + out: &mut BTreeSet, + visited_files: &mut HashSet, +) { + match val { + Value::String(rel) => { + let clean = rel.trim().trim_start_matches("./").trim_start_matches('/'); + if visited_files.insert(clean.to_owned()) + && let Some(bytes) = files.read(clean) + && let Ok(parsed) = parse_jsonc(&String::from_utf8_lossy(&bytes)) + { + collect_lsp_commands(&parsed, files, out, visited_files); + } + } + Value::Array(items) => { + for item in items { + collect_lsp_commands(item, files, out, visited_files); + } + } + Value::Object(obj) => { + if let Some(nested) = obj.get("lspServers") { + collect_lsp_commands(nested, files, out, visited_files); + return; + } + for (name, entry) in obj { + let Some(cmd) = entry.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) + else { + continue; + }; + let mut parts = vec![cmd.to_owned()]; + parts.extend(extract_string_array(entry.get("args"))); + let env = entry + .get("env") + .and_then(Value::as_object) + .into_iter() + .flatten() + .map(|(key, value)| format!("{}={}", key, scalar_capability_value(value))) + .collect::>() + .join(" "); + if !env.is_empty() { + parts.push(format!("env:{env}")); + } + out.insert(format!("{name}: {}", parts.join(" "))); + } + } + _ => {} + } +} + fn scalar_capability_value(value: &Value) -> String { match value { Value::String(value) => value.clone(), @@ -2746,6 +2816,7 @@ pub fn inspect_plugin_dir( && mcp_names.is_empty() && rule_files.is_empty() && hook_rel_names.is_empty() + && executable.lsp_commands.is_empty() && subagent_count == 0 && command_count == 0) { @@ -2803,6 +2874,7 @@ pub fn inspect_plugin_dir( command_count, hook_files: hook_rel_names, stdio_commands: executable.stdio_commands, + lsp_commands: executable.lsp_commands, has_lsp, has_canvas_or_app, native_harnesses: native_harnesses.into_iter().collect(), @@ -2815,8 +2887,12 @@ pub fn inspect_plugin_dir( }) } -fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -> Option { - if stdio_commands.is_empty() && hooks.is_empty() { +fn compute_capability_hash( + stdio_commands: &[String], + lsp_commands: &[String], + hooks: &[(&str, &[u8])], +) -> Option { + if stdio_commands.is_empty() && lsp_commands.is_empty() && hooks.is_empty() { return None; } let mut hasher = blake3::Hasher::new(); @@ -2828,6 +2904,14 @@ fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) - hasher.update(cmd.as_bytes()); hasher.update(b"\0"); } + // Only added when present, so the hash of a plugin without language servers stays as approved before. + let mut sorted_lsp = lsp_commands.to_vec(); + sorted_lsp.sort(); + for cmd in sorted_lsp { + hasher.update(b"lsp:"); + hasher.update(cmd.as_bytes()); + hasher.update(b"\0"); + } for (rel, bytes) in hooks { hasher.update(b"hook:"); hasher.update(rel.as_bytes()); @@ -5682,6 +5766,63 @@ mod tests { assert!(codex_text.contains("https://github.com/acme/plugins.git")); } + #[test] + fn language_servers_a_plugin_ships_need_execution_consent() { + let tmp = tempfile::tempdir().unwrap(); + // A `.lsp.json` file, an inline `lspServers` object and a path to one in the manifest. + let file = tmp.path().join("lsp-file"); + write(&file.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-file","version":"1.0.0"}"#); + write(&file.join(".lsp.json"), r#"{"go":{"command":"/bin/sh","args":["-c","touch /tmp/x"]}}"#); + let inline = tmp.path().join("lsp-inline"); + write( + &inline.join(".claude-plugin/plugin.json"), + r#"{"name":"lsp-inline","lspServers":{"py":{"command":"pyright-langserver","args":["--stdio"],"env":{"A":"1"}}}}"#, + ); + let linked = tmp.path().join("lsp-linked"); + write(&linked.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-linked","lspServers":"./servers.json"}"#); + write(&linked.join("servers.json"), r#"{"rs":{"command":"rust-analyzer"}}"#); + let cases = [ + (&file, "go: /bin/sh -c touch /tmp/x"), + (&inline, "py: pyright-langserver --stdio env:A=1"), + (&linked, "rs: rust-analyzer"), + ]; + for (dir, command) in cases { + let installed = inspect_plugin_dir(dir, AgentPluginSource::ClaudeUser, McpScope::User, None, true) + .unwrap() + .capabilities; + let scanned = scan_local_subtree(dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap(); + let preview = inspect_fetched_subtree(&scanned, "plugin", None).unwrap().capabilities; + for caps in [&installed, &preview] { + assert_eq!(caps.lsp_commands, vec![command.to_owned()], "{}", dir.display()); + assert!(caps.requires_consent, "{}", dir.display()); + assert!(caps.capability_hash.is_some()); + } + // The install dialog's approval matches the hash of the installed folder. + assert_eq!(installed.capability_hash, preview.capability_hash); + } + + // Changing the server command invalidates an earlier approval. + let before = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap(); + write(&file.join(".lsp.json"), r#"{"go":{"command":"gopls"}}"#); + let after = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap(); + assert_ne!(before.capabilities.capability_hash, after.capabilities.capability_hash); + + // A plugin without language servers keeps its hash: approvals given before stay valid. + let mut v1 = blake3::Hasher::new(); + v1.update(b"openidea-agent-plugin-caps-v1\0mcp:k8s: npx -y k8s-mcp\0"); + assert_eq!( + compute_capability_hash(&["k8s: npx -y k8s-mcp".to_owned()], &[], &[]), + Some(v1.finalize().to_hex().to_string()) + ); + let skills_only = tmp.path().join("skills-only"); + write(&skills_only.join(".claude-plugin/plugin.json"), r#"{"name":"skills-only"}"#); + write(&skills_only.join("skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\n"); + let caps = inspect_plugin_dir(&skills_only, AgentPluginSource::ClaudeUser, McpScope::User, None, true) + .unwrap() + .capabilities; + assert!(caps.lsp_commands.is_empty() && !caps.requires_consent && caps.capability_hash.is_none()); + } + #[test] fn marketplace_browse_preview_and_pinned_native_install_roundtrip() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 58a531fe9b..f749613333 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -194,6 +194,9 @@ impl ProviderSpec { } fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self { + for (_, value) in &mut self.env { + *value = expand_home(value); + } if let Some(program) = self.managed_cli.take() { self.command = program; } else if self.driver != Driver::Acp { @@ -235,7 +238,7 @@ impl ProviderSpec { return Some(LoginLaunch { program, args: separate_args.iter().map(|s| (*s).to_owned()).collect(), - env: self.env.iter().cloned().collect(), + env: self.env.iter().map(|(name, value)| (name.clone(), expand_home(value))).collect(), }); } @@ -1201,6 +1204,21 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) specs } +/// `value` with a leading `~` (alone or before a path separator) replaced by the user's home, +/// as a shell does for `NAME=~/path`. +pub(crate) fn expand_home(value: &str) -> String { + let rest = match value.strip_prefix('~') { + Some("") => "", + Some(rest) if rest.starts_with('/') || rest.starts_with('\\') => &rest[1..], + _ => return value.to_owned(), + }; + match crate::home_dir() { + Some(home) if rest.is_empty() => home.to_string_lossy().into_owned(), + Some(home) => home.join(rest).to_string_lossy().into_owned(), + None => value.to_owned(), + } +} + /// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]). #[cfg(test)] pub(crate) fn installed(command: &str) -> bool { @@ -1647,6 +1665,20 @@ mod tests { assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV)); } + #[test] + fn a_leading_tilde_in_the_environment_is_the_home_folder() { + let home = crate::home_dir().unwrap(); + let mut spec = builtin_spec("claude").unwrap(); + for (name, value) in [("A", "~/.claude-work"), ("B", "~"), ("C", "a~/b"), ("D", "~user/x"), ("E", "/abs")] { + spec.env.push((name.into(), value.into())); + } + let resolved = spec.resolve_for_launch(Path::new(".")); + let value = |name: &str| resolved.env.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone()).unwrap(); + assert_eq!(value("A"), home.join(".claude-work").to_string_lossy()); + assert_eq!(value("B"), home.to_string_lossy()); + assert_eq!((value("C"), value("D"), value("E")), ("a~/b".into(), "~user/x".into(), "/abs".into())); + } + #[test] fn acp_adapters_of_native_agents_are_unlisted_until_customized() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 15f887b53a..75da86cc4b 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -4455,6 +4455,56 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl restored.shutdown(); } +/// A model request reaches the catalogs from a blocking task, so it may arrive after a newer +/// selection's; arriving late, it must not supersede (and abort) the newer discovery. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_model_request_never_supersedes_a_newer_discovery() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + *agent.model_options.lock() = HashMap::from([ + ("big".into(), effort_options(&["low", "high"], "high")), + ("small".into(), effort_options(&["minimal", "medium"], "minimal")), + ("plain".into(), vec![]), + ]); + let mgr = manager(tmp.path(), agent.clone()); + let task = mgr + .create(NewAgentTask { + prompt: text("again"), + provider: "claude-acp".into(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + mgr.shutdown(); + let restored = Arc::new(manager(tmp.path(), agent.clone())); + let (catalogs, shared) = (restored.shared.paths.catalogs.clone(), restored.shared.clone()); + let spec = || shared.spec("claude-acp").unwrap(); + + let late = catalogs.ticket(); + let (release, gate) = std::sync::mpsc::channel(); + *agent.model_config_gate.lock() = Some(gate); + let newer = { + let (catalogs, shared) = (catalogs.clone(), shared.clone()); + tokio::spawn(async move { catalogs.load_levels(&shared, "claude-acp", "plain").await }) + }; + tokio::time::timeout(Duration::from_secs(5), async { + while agent.model_config_gate.lock().is_some() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into()))); + + catalogs.request_as_of(&shared, spec(), "small", late); + assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())), "not superseded"); + release.send(()).unwrap(); + assert_eq!(newer.await.unwrap().unwrap(), Vec::::new()); + restored.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() { for value in [None, Some("false"), Some("true")] { diff --git a/crates/ide-build/src/application_update.rs b/crates/ide-build/src/application_update.rs index 26df54ad71..6cd718a8df 100644 --- a/crates/ide-build/src/application_update.rs +++ b/crates/ide-build/src/application_update.rs @@ -49,9 +49,8 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide &script, format!( r#"import org.gradle.util.GradleVersion - -gradle.projectsEvaluated {{ - def p = gradle.rootProject.project({}) +{} +def register = {{ p -> def update = {{ t -> t.dependsOn 'processResources' // Resolved here so the action holds no task or project (configuration cache). @@ -63,9 +62,14 @@ gradle.projectsEvaluated {{ if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update) else p.tasks.create('openideaUpdateResources', update) }} +// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also +// run in included builds, which may have a project at the same path. +if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }} +else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }} "#, - literal(&p.path), - literal(&manifest.to_string_lossy()) + crate::gradle::ISOLATED_PROJECTS_SCRIPT, + literal(&manifest.to_string_lossy()), + path = literal(&p.path), ), )?; return Ok(ResourceBuild { @@ -204,6 +208,42 @@ mod tests { assert!(!script.contains("build/resources/main")); // The task owns custom output locations. } + /// The resource-update task's init script on a real Gradle, with and without Isolated Projects (#8261). + #[test] + fn gradle_resources_update_with_and_without_isolated_projects() { + let Some((gradle, version)) = crate::gradle::test_gradle() else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let builds = crate::gradle::write_test_builds( + &base, + // The build realizes tasks early and moves the resources in `afterEvaluate`. + "plugins { id 'java' }\ntasks.all {}\nafterEvaluate { sourceSets.main.output.resourcesDir = file('build/custom') }\n", + "plugins { java }\ntasks.all {}\nafterEvaluate { sourceSets[\"main\"].output.setResourcesDir(file(\"build/custom\")) }\n", + &[("src/main/resources/static/index.html", "after")], + ); + for (root, isolated) in builds { + // Before Gradle 8.8 the script keeps reading the project from the root, as before. + if isolated && version < (8, 8) { + continue; + } + let cache = root.join("cache"); + let mut model = crate::load(&root, &cache, None); + model.gradle[0].command = gradle.to_string_lossy().into_owned(); + for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } { + let plan = plan(&root, &model, Path::new("app"), &cache).unwrap(); + let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args) + .unwrap_or_else(|e| panic!("{pass}:\n{e}")); + assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}"); + let dir = fs::read_to_string(cache.join("resource-output.txt")).unwrap(); + assert_eq!(Path::new(&dir), root.join("app/build/custom")); + assert_eq!(fs::read_to_string(Path::new(&dir).join("static/index.html")).unwrap(), "after"); + } + } + } + #[test] fn publishes_maven_and_gradle_resource_outputs_to_the_runtime_classpath() { for layout in ["target/classes", "build/resources/main", "custom resource output"] { diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 4c541900d3..e4416ec7a0 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -294,7 +294,7 @@ pub fn plan( } BuildSystem::TypeScript => ts_steps(&dir, kind), BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)), - BuildSystem::Dotnet => dotnet_steps(&dir, kind)?, + BuildSystem::Dotnet => dotnet_steps(&dir, kind, file)?, // Never detected from a folder: it comes from the Project Structure (`structure_plan`). BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")), } @@ -553,10 +553,24 @@ fn dotnet_target(dir: &Path) -> Option { solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned() } -/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds, +/// `dotnet build` of `file` when it is a solution or project in `dir` (a run configuration's +/// project), else of the directory's solution or project; Rebuild skips incremental builds, /// Build Artifacts publishes. The summary that repeats every message is left out. -fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult> { - let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?; +fn dotnet_steps(dir: &Path, kind: BuildKind, file: Option<&Path>) -> IdeResult> { + let given = file.filter(|f| { + f.parent() == Some(dir) + && f.is_file() + && f.extension().is_some_and(|e| { + matches!( + e.to_string_lossy().to_ascii_lowercase().as_str(), + "sln" | "slnx" | "csproj" | "fsproj" | "vbproj" + ) + }) + }); + let target = given + .map(Path::to_path_buf) + .or_else(|| dotnet_target(dir)) + .ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?; let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" }; let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild); @@ -1734,6 +1748,36 @@ mod tests { let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new()) .unwrap(); assert_eq!(p.steps[0].args[0], "publish"); + // A run configuration's project is built even when its folder holds other projects or a + // solution that sort first (#8179). + write(&net, "src/Host/Legacy.csproj", ""); + write(&net, "src/Host/Main.csproj", ""); + write(&net, "src/Host/All.sln", ""); + for name in ["Main.csproj", "All.sln", "Legacy.csproj"] { + let file = net.join("src/Host").join(name); + let p = plan( + &net, + &BuildModel::default(), + BuildKind::Build, + Some(&file), + None, + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(p.steps[0].args[1], name); + } + let p = plan( + &net, + &BuildModel::default(), + BuildKind::Build, + Some(&net.join("src/Host/Program.cs")), + None, + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(p.steps[0].args[1], "All.sln"); let cm = tmp.path().join("cm"); write(&cm, "CMakeLists.txt", "project(app)"); diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs index db0aeb9002..c4623b757f 100644 --- a/crates/ide-build/src/compile/single.rs +++ b/crates/ide-build/src/compile/single.rs @@ -603,17 +603,16 @@ pub fn gradle_compile_file_plan( fs::create_dir_all(cache)?; let init_script = cache.join("gradle-compile-cp.init.gradle"); fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?; - let args = vec![ - "--console=plain".into(), - "-q".into(), - "-Dorg.gradle.configuration-cache=false".into(), + let gradle_dir = subdir(root, &gradle.dir); + let mut args = vec!["--console=plain".into(), "-q".into(), "-Dorg.gradle.configuration-cache=false".into()]; + args.extend(crate::gradle::no_isolated_projects(&gradle_dir, &gradle.env)); + args.extend([ "--init-script".into(), init_script.to_string_lossy().into_owned(), format!("-Popenidea.target={}", project.path), format!("-Popenidea.scope={scope}"), "help".into(), - ]; - let gradle_dir = subdir(root, &gradle.dir); + ]); let mut reported: Option = None; let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| { if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") { diff --git a/crates/ide-build/src/gradle.rs b/crates/ide-build/src/gradle.rs index 5eb1753785..fcdfa4fcc0 100644 --- a/crates/ide-build/src/gradle.rs +++ b/crates/ide-build/src/gradle.rs @@ -12,6 +12,65 @@ use std::time::{Duration, Instant}; pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"]; pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"]; +const ISOLATED_PROJECTS: [&str; 2] = ["org.gradle.isolated-projects", "org.gradle.unsafe.isolated-projects"]; + +/// Arguments turning Isolated Projects off for the IDE's own model reads of the build at `dir`, when +/// the build enables it: Gradle refuses them without the configuration cache, and their init scripts +/// read projects across the build. Other builds keep their command line. Gradle 9 still reads the +/// Gradle 8 name. +pub(crate) fn no_isolated_projects(dir: &Path, env: &BTreeMap) -> Vec { + // The variable as the Gradle process gets it: the project's and the login shell's environment too. + let inherited = ide_core::process::host_vars_in(dir) + .chain(ide_core::process::shell_env_in(dir)) + .find(|(key, _)| key == "GRADLE_USER_HOME") + .map(|(_, value)| value); + let home = user_home(dir, env, inherited, dirs::home_dir()); + if !isolated_projects(dir, home.as_deref()) { + return Vec::new(); + } + ISOLATED_PROJECTS.iter().map(|key| format!("-D{key}=false")).collect() +} + +fn user_home( + dir: &Path, + env: &BTreeMap, + inherited: Option, + home: Option, +) -> Option { + let set = env.get("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| inherited.map(PathBuf::from)); + set.map(|path| dir.join(path)).or_else(|| Some(home?.join(".gradle"))) +} + +/// The user home's `gradle.properties` overrides the build's; when the two names disagree, Gradle +/// keeps Isolated Projects off. +fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool { + let user = user_home.map(file_properties).unwrap_or_default(); + let build = file_properties(dir); + let values: Vec = ISOLATED_PROJECTS + .iter() + .filter_map(|key| user.get(*key).or_else(|| build.get(*key))) + .map(|value| value.eq_ignore_ascii_case("true")) + .collect(); + values.contains(&true) && !values.contains(&false) +} + +/// Groovy for init scripts that add a task to one project (needs `GradleVersion` imported): `isolated` +/// is whether the build enables Isolated Projects on Gradle 8.8+, where such a script must register +/// it from `gradle.lifecycle` instead of reading the project from the root. `BuildFeatures` (8.5+) is +/// only injected, so a class compiled at run time reads it. +pub(crate) const ISOLATED_PROJECTS_SCRIPT: &str = r#"def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +"#; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -1125,6 +1184,70 @@ pub(crate) fn has_war_plugin(script: &str) -> bool { script.split(|c: char| !c.is_alphanumeric() && c != '_').any(|word| word == "war") } +/// A real Gradle for tests (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path) and its +/// version as (major, minor); `None` without it or without `JAVA_HOME`. +#[cfg(test)] +pub(crate) fn test_gradle() -> Option<(PathBuf, (u32, u32))> { + std::env::var_os("JAVA_HOME")?; + let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))?; + let out = std::process::Command::new(&gradle).arg("--version").output().ok()?; + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let version = text.lines().find_map(|l| l.strip_prefix("Gradle "))?.trim().to_owned(); + let mut parts = version.split('.').map(|p| p.parse::().unwrap_or(0)); + Some((gradle.clone(), (parts.next()?, parts.next().unwrap_or(0)))) +} + +/// Runs a planned Gradle command in `root`; its output, or the failure with it. +#[cfg(test)] +pub(crate) fn run_test_gradle(root: &Path, cwd: &str, command: &str, args: &[String]) -> Result { + let out = std::process::Command::new(command).args(args).current_dir(root.join(cwd)).output().unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + if out.status.success() { Ok(text) } else { Err(text) } +} + +/// Two builds for init-script tests, each with `files` under `app`: one in the Groovy DSL without +/// Isolated Projects, one in the Kotlin DSL with it (and so the configuration cache). +#[cfg(test)] +pub(crate) fn write_test_builds( + base: &Path, + groovy: &str, + kotlin: &str, + files: &[(&str, &str)], +) -> [(PathBuf, bool); 2] { + let plain = base.join("plain"); + let isolated = base.join("isolated"); + let mut all = vec![ + (plain.join("gradle.properties"), "org.gradle.daemon=false\n".to_owned()), + (plain.join("settings.gradle"), "rootProject.name = 'plain'\ninclude 'app'\n".to_owned()), + (plain.join("app/build.gradle"), groovy.to_owned()), + ( + isolated.join("gradle.properties"), + "org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\ + org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n" + .to_owned(), + ), + ( + isolated.join("settings.gradle.kts"), + "rootProject.name = \"isolated\"\ninclude(\"app\")\nincludeBuild(\"inc\")\n".to_owned(), + ), + // An included build with a project at the same path, whose tasks are realized early. + (isolated.join("inc/settings.gradle.kts"), "rootProject.name = \"inc\"\ninclude(\"app\")\n".to_owned()), + (isolated.join("inc/app/build.gradle.kts"), "plugins { java }\ntasks.all {}\n".to_owned()), + (isolated.join("app/build.gradle.kts"), kotlin.to_owned()), + ]; + for (rel, text) in files { + all.push((plain.join("app").join(rel), text.to_string())); + all.push((isolated.join("app").join(rel), text.to_string())); + } + for (path, text) in all { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + [(plain, false), (isolated, true)] +} + #[cfg(test)] mod tests { #[test] @@ -1578,6 +1701,53 @@ dependencies { use super::*; + #[test] + fn isolated_projects_are_read_from_the_build_and_the_user_home() { + let temp = tempfile::tempdir().unwrap(); + let (build, home) = (temp.path().join("build"), temp.path().join("home")); + std::fs::create_dir_all(&build).unwrap(); + std::fs::create_dir_all(&home).unwrap(); + let enabled = |user_home: Option<&Path>| isolated_projects(&build, user_home); + assert!(!enabled(Some(&home)), "no gradle.properties"); + std::fs::write(build.join("gradle.properties"), "org.gradle.jvmargs=-Xmx2g\n").unwrap(); + assert!(!enabled(Some(&home)), "not enabled"); + std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap(); + assert!(enabled(Some(&home)), "the build's gradle.properties"); + assert!(enabled(None)); + std::fs::write(home.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap(); + assert!(!enabled(Some(&home)), "the user home overrides the build"); + std::fs::write(build.join("gradle.properties"), "").unwrap(); + std::fs::write(home.join("gradle.properties"), "org.gradle.unsafe.isolated-projects = true\n").unwrap(); + assert!(enabled(Some(&home)), "the user home's gradle.properties, Gradle 8 name"); + std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap(); + assert!(!enabled(Some(&home)), "disabled under either name wins"); + } + + #[test] + fn the_gradle_user_home_is_the_builds_setting_then_the_environment_then_dot_gradle() { + let dir = Path::new("/build"); + let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), "/setting".to_owned())]); + let inherited = || Some(std::ffi::OsString::from("/inherited")); + let home = || Some(PathBuf::from("/home/u")); + assert_eq!(user_home(dir, &env, inherited(), home()), Some(PathBuf::from("/setting"))); + assert_eq!(user_home(dir, &BTreeMap::new(), inherited(), home()), Some(PathBuf::from("/inherited"))); + assert_eq!(user_home(dir, &BTreeMap::new(), None, home()), Some(PathBuf::from("/home/u/.gradle"))); + let relative = Some(std::ffi::OsString::from("gradle-home")); + assert_eq!(user_home(dir, &BTreeMap::new(), relative, home()), Some(PathBuf::from("/build/gradle-home"))); + } + + #[test] + fn builds_without_isolated_projects_keep_their_command_line() { + let temp = tempfile::tempdir().unwrap(); + let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), temp.path().join("home").display().to_string())]); + assert!(no_isolated_projects(temp.path(), &env).is_empty()); + std::fs::write(temp.path().join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap(); + assert_eq!( + no_isolated_projects(temp.path(), &env), + ["-Dorg.gradle.isolated-projects=false", "-Dorg.gradle.unsafe.isolated-projects=false"] + ); + } + #[test] fn settings_scripts() { let kts = r#" diff --git a/crates/ide-build/src/jbuild/model.rs b/crates/ide-build/src/jbuild/model.rs index 3a8d904d1e..008fb2d3ec 100644 --- a/crates/ide-build/src/jbuild/model.rs +++ b/crates/ide-build/src/jbuild/model.rs @@ -300,6 +300,7 @@ pub(super) fn gradle_step( &["--console=plain", "--no-configuration-cache"], &subdir(root, &g.dir), ); + step.args.extend(crate::gradle::no_isolated_projects(&step.cwd, &g.env)); step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]); step.args.push(format!("-Popenidea.build.output={}", output_root.display())); if let Some(file) = model_file { diff --git a/crates/ide-build/src/jbuild/tests.rs b/crates/ide-build/src/jbuild/tests.rs index e04013fdef..080c6124e0 100644 --- a/crates/ide-build/src/jbuild/tests.rs +++ b/crates/ide-build/src/jbuild/tests.rs @@ -792,6 +792,22 @@ fn builds_gradle_projects_with_javac_and_only_what_changed() { assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path())); } +#[test] +fn builds_gradle_projects_that_enable_isolated_projects() { + let Some(f) = Fixture::gradle(&[ + ( + "gradle.properties", + "org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), + ]) else { + return; + }; + let built = f.launch(false); + assert_eq!(built.failure, None, "{:?}\n{}", built.messages, build_output_tail(&f.events.lock().unwrap())); + assert!(f.out("t.app/classes/a/A.class").is_file()); +} + #[test] fn leaves_gradle_projects_with_other_compilers_to_gradle() { let Some(f) = Fixture::gradle(&[ diff --git a/crates/ide-build/src/sync.rs b/crates/ide-build/src/sync.rs index f450a96f72..9a2aef9cc4 100644 --- a/crates/ide-build/src/sync.rs +++ b/crates/ide-build/src/sync.rs @@ -499,11 +499,9 @@ pub fn sync_gradle_model( "-q".into(), // The init script reports the evaluated projects, even when a build enables the configuration cache. "-Dorg.gradle.configuration-cache=false".into(), - "--init-script".into(), - init_script.to_string_lossy().into_owned(), - "tasks".into(), - "--all".into(), ]; + args.extend(gradle::no_isolated_projects(&root.join(&model.dir), &options.env)); + args.extend(["--init-script".into(), init_script.to_string_lossy().into_owned(), "tasks".into(), "--all".into()]); if options.offline { args.push("--offline".into()); } @@ -1208,4 +1206,42 @@ mod tests { assert!(args.contains("-T1"), "args: {args}"); assert!(args.contains("maven-help-plugin:"), "args: {args}"); } + + /// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path). + #[test] + fn gradle_sync_lists_tasks_of_builds_that_enable_isolated_projects() { + let has_jdk = std::env::var_os("JAVA_HOME").is_some(); + let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(std::path::PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())); + let Some(gradle) = gradle.filter(|_| has_jdk) else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let files = [ + ( + "gradle.properties", + "org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ("settings.gradle", "rootProject.name = 'root'\ninclude 'lib'\n"), + ("build.gradle", ""), + ("lib/build.gradle", "plugins { id 'java' }\n"), + ]; + for (rel, text) in files { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let mut model = gradle::load(&root).unwrap(); + model.command = gradle.to_string_lossy().into_owned(); + let cache = root.join(".cache"); + sync_gradle_model(&root, &cache, &model, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap(); + let loaded = crate::load(&root, &cache, None); + let build = &loaded.gradle[0]; + assert_eq!(build.sync_error, None); + let lib = build.projects.iter().find(|p| p.path == ":lib").expect("the reported :lib project"); + assert!(lib.tasks.iter().any(|t| t.name == "compileJava"), "{:?}", lib.tasks); + } } diff --git a/crates/ide-build/src/web.rs b/crates/ide-build/src/web.rs index 43d46913a2..4c363f9283 100644 --- a/crates/ide-build/src/web.rs +++ b/crates/ide-build/src/web.rs @@ -161,9 +161,8 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu &script, format!( r#"import org.gradle.util.GradleVersion - -gradle.projectsEvaluated {{ - def p = gradle.rootProject.project({}) +{} +def register = {{ p -> def artifact = {{ t -> t.dependsOn 'war' // Resolved here so the action holds no task or project (configuration cache). @@ -180,9 +179,14 @@ gradle.projectsEvaluated {{ if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact) else p.tasks.create('openideaTomcatArtifact', artifact) }} +// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also +// run in included builds, which may have a project at the same path. +if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }} +else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }} "#, - groovy_literal(path), - groovy_literal(&manifest.to_string_lossy()) + crate::gradle::ISOLATED_PROJECTS_SCRIPT, + groovy_literal(&manifest.to_string_lossy()), + path = groovy_literal(path), ), )?; let task = format!("{}:openideaTomcatArtifact", path.trim_end_matches(':')); @@ -274,6 +278,42 @@ mod tests { assert!(!crate::gradle::has_war_plugin("// plugins { war }")); } + /// The WAR task's init script on a real Gradle, with and without Isolated Projects (#8261). + #[test] + fn gradle_war_artifact_builds_with_and_without_isolated_projects() { + let Some((gradle, version)) = crate::gradle::test_gradle() else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let builds = crate::gradle::write_test_builds( + &base, + // The build realizes tasks early and applies the WAR plugin in `afterEvaluate`. + "plugins { id 'java' }\ntasks.all {}\nafterEvaluate { apply plugin: 'war' }\n", + "plugins { java }\ntasks.all {}\nafterEvaluate { apply(plugin = \"war\") }\n", + &[("src/main/webapp/index.html", "war")], + ); + for (root, isolated) in builds { + // Before Gradle 8.8 the script keeps reading the project from the root, as before. + if isolated && version < (8, 8) { + continue; + } + let cache = root.join("cache"); + let mut model = crate::load(&root, &cache, None); + model.gradle[0].command = gradle.to_string_lossy().into_owned(); + let id = artifacts(&root, &model).into_iter().find(|a| a.id.contains(":app")).expect("the app WAR").id; + for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } { + let plan = build(&root, &model, &id, &cache).unwrap(); + let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args) + .unwrap_or_else(|e| panic!("{pass}:\n{e}")); + assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}"); + let war = fs::read_to_string(cache.join("artifact-path.txt")).unwrap(); + assert!(Path::new(&war).is_file() && war.ends_with(".war"), "{war}"); + } + } + } + #[test] fn gradle_manifest_paths_preserve_windows_characters() { for path in [r"C:\工作 区\Tomcat's cache\artifact-path.txt", r"\\server\share\artifact-path.txt"] { diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index f803904d69..1210434a0f 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -467,6 +467,8 @@ pub enum LspRefreshKind { FlutterOutline, /// Spring bean markers of open documents may have changed. SpringBeanMarkers, + /// Spring AOP markers of open documents may have changed. + SpringAopMarkers, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] diff --git a/crates/ide-core/src/output_encoding.rs b/crates/ide-core/src/output_encoding.rs index 94c30e91fb..006cee7d17 100644 --- a/crates/ide-core/src/output_encoding.rs +++ b/crates/ide-core/src/output_encoding.rs @@ -170,8 +170,24 @@ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\ import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } -allprojects { - each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +eachProject { p -> + each(p.tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' } } "; @@ -622,7 +638,7 @@ mod tests { #[test] fn gradle_script_respects_the_builds_own_file_encoding() { let s = GRADLE_FILE_ENCODING_SCRIPT; - assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}"); + assert!(s.contains("each(p.tasks.withType(JavaExec))"), "{s}"); assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}"); assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}"); assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}"); diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs index ddb2dc5912..c2ea891f8c 100644 --- a/crates/ide-core/src/process.rs +++ b/crates/ide-core/src/process.rs @@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command { cmd } +/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`, +/// `.bat`) always run through it. +#[cfg_attr(not(windows), allow(dead_code))] +const CMD_ENV_LIMIT: usize = 8191; + #[cfg(windows)] fn compact_batch_path(cmd: &mut Command) { - use std::os::windows::ffi::OsStrExt; use std::path::{Component, Prefix}; - // Rust runs these files through cmd.exe, which drops inherited variables over this limit. - const CMD_ENV_LIMIT: usize = 8191; + // Rust runs these files through cmd.exe. let extension = Path::new(cmd.get_program()).extension(); if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) { return; @@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) { Some((_, path)) => path.map(OsStr::to_owned), None => std::env::var_os("PATH"), }; - let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return }; - - // The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are - // missing now, keeping search precedence and leaving UNC and relative paths alone. - let dirs = std::env::split_paths(&path).filter(|dir| { + let Some(path) = path else { return }; + // The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing + // now, leaving UNC and relative paths alone. + let present = |dir: &Path| { let local = dir.is_absolute() && matches!(dir.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_))); !local || !std::fs::symlink_metadata(dir) .is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory)) - }); - if let Ok(compact) = std::env::join_paths(dirs) - && compact.encode_wide().count() <= CMD_ENV_LIMIT - { + }; + if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) { cmd.env("PATH", compact); } } +/// The 8.3 form of `dir`, when the volume has one. +#[cfg(windows)] +fn short_path(dir: &Path) -> Option { + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW; + + let wide: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); + let mut buf = vec![0u16; wide.len()]; + let len = u32::try_from(buf.len()).ok()?; + // SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated. + let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize; + // 0 is an error; a value of at least the buffer's length is the size a longer form needs. + if written == 0 || written >= buf.len() { + return None; + } + buf.truncate(written); + Some(OsString::from_wide(&buf).into()) +} + +/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later +/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping +/// the search order; when that is still too long, directories take `shorten`'s form, longest +/// first, until it fits. `None` when `path` fits already or nothing got shorter. +#[cfg_attr(not(windows), allow(dead_code))] +fn compact_path_list( + path: &OsStr, + limit: usize, + present: impl Fn(&Path) -> bool, + shorten: impl Fn(&Path) -> Option, +) -> Option { + let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count(); + let original = width(path); + if original <= limit { + return None; + } + let mut seen = std::collections::HashSet::new(); + let mut dirs: Vec = std::env::split_paths(path) + .filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d)) + .collect(); + let mut joined = std::env::join_paths(&dirs).ok()?; + if width(&joined) > limit { + let mut longest: Vec = (0..dirs.len()).collect(); + longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str()))); + let mut total = width(&joined); + for i in longest { + if total <= limit { + break; + } + if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) { + total -= width(dirs[i].as_os_str()) - width(short.as_os_str()); + dirs[i] = short; + } + } + joined = std::env::join_paths(&dirs).ok()?; + } + (width(&joined) < original).then_some(joined) +} + /// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and /// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` → /// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id. @@ -1295,6 +1353,26 @@ mod tests { assert_eq!(session, pid, "the child leads its own session"); } + #[test] + fn compacts_a_path_too_long_for_cmd() { + let sep = if cfg!(windows) { ";" } else { ":" }; + let join = |dirs: &[&str]| OsString::from(dirs.join(sep)); + let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40)); + let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone")); + let present = |d: &Path| !d.ends_with("gone"); + let never = |_: &Path| None; + // Fits already: left alone. + assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None); + // Later duplicates and missing directories go, the order stays. + let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]); + assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c]))); + // Still too long: the longest directories take their short form until it fits. + let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy()))); + let path = join(&[&a, &format!("{b}-longer"), &c]); + assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c]))); + assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"]))); + } + #[test] fn process_alive_tells_live_from_dead_pids() { assert!(process_alive(std::process::id())); diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs index 336d4c1616..a0f07c4935 100644 --- a/crates/ide-coverage/src/plan.rs +++ b/crates/ide-coverage/src/plan.rs @@ -9,7 +9,23 @@ const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage. import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } -allprojects { p -> +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +eachProject { p -> p.plugins.withId('java') { p.apply plugin: 'jacoco' each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') } @@ -582,4 +598,97 @@ mod tests { CoveragePrepared::Unsupported { .. } )); } + + /// The coverage init script on a real Gradle, with and without Isolated Projects (#8261). + /// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path). + #[test] + fn gradle_init_script_configures_each_project() { + let gradle = std::env::var_os("JAVA_HOME").and_then(|_| { + std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(std::path::PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())) + }); + let Some(gradle) = gradle else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let version = std::process::Command::new(&gradle).arg("--version").output().unwrap(); + let version = + String::from_utf8_lossy(&version.stdout).lines().find_map(|l| l.strip_prefix("Gradle ").map(str::to_owned)); + let mut parts = version + .expect("a `Gradle x.y` line") + .trim() + .split('.') + .map(|p| p.parse::().unwrap_or(0)) + .collect::>(); + parts.resize(2, 0); + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let script = base.join("coverage.init.gradle"); + std::fs::write(&script, GRADLE_INIT).unwrap(); + for (name, props) in [ + ("plain", ""), + ( + "isolated", + "org.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ] { + if name == "isolated" && (parts[0], parts[1]) < (8, 8) { + // Before Gradle 8.8 the script keeps reading every project, as the plain build checked. + continue; + } + let root = base.join(name); + for (rel, text) in [ + ("gradle.properties", format!("org.gradle.daemon=false\n{props}")), + ("settings.gradle", "include 'lib'\n".to_owned()), + ("build.gradle", String::new()), + ( + "lib/build.gradle", + "plugins { id 'java' }\nrepositories { mavenCentral() }\n\ + dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'; \ + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\n\ + test { useJUnitPlatform() }\n" + .to_owned(), + ), + ( + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static int one() { return 1; } }\n".to_owned(), + ), + ( + "lib/src/test/java/l/LTest.java", + "package l;\nclass LTest { @org.junit.jupiter.api.Test void one() { L.one(); } }\n".to_owned(), + ), + ] { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let report = root.join("lib/build/reports/jacoco/test/jacocoTestReport.xml"); + // With Isolated Projects the configuration cache is on: a miss, then a hit. + for pass in if name == "isolated" { &["miss", "hit"][..] } else { &["run"][..] } { + // Fresh test results and execution data, so each pass runs the tests under the agent. + for dir in ["lib/build/jacoco", "lib/build/test-results", "lib/build/reports"] { + let _ = std::fs::remove_dir_all(root.join(dir)); + } + let out = std::process::Command::new(&gradle) + .args(["--console=plain", "--init-script"]) + .arg(&script) + .arg(":lib:test") + .current_dir(&root) + .output() + .unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "{name} {pass}:\n{text}"); + let xml = + std::fs::read_to_string(&report).unwrap_or_else(|_| panic!("{name} {pass}: no report\n{text}")); + assert_eq!(text.contains("Reusing configuration cache."), *pass == "hit", "{name} {pass}:\n{text}"); + let method = + xml.split(r#"").next()); + assert!( + method.is_some_and(|m| m.contains(r#""#)), + "{name} {pass}: {xml}" + ); + } + } + } } diff --git a/crates/ide-dap/tests/debugpy.rs b/crates/ide-dap/tests/integration/debugpy.rs similarity index 100% rename from crates/ide-dap/tests/debugpy.rs rename to crates/ide-dap/tests/integration/debugpy.rs diff --git a/crates/ide-dap/tests/godot.rs b/crates/ide-dap/tests/integration/godot.rs similarity index 100% rename from crates/ide-dap/tests/godot.rs rename to crates/ide-dap/tests/integration/godot.rs diff --git a/crates/ide-dap/tests/integration/main.rs b/crates/ide-dap/tests/integration/main.rs new file mode 100644 index 0000000000..55b5a8b98a --- /dev/null +++ b/crates/ide-dap/tests/integration/main.rs @@ -0,0 +1,6 @@ +mod debugpy; +mod godot; +mod php_debug; +mod real_adapters; +mod script_debuggers; +mod unity; diff --git a/crates/ide-dap/tests/php_debug.rs b/crates/ide-dap/tests/integration/php_debug.rs similarity index 100% rename from crates/ide-dap/tests/php_debug.rs rename to crates/ide-dap/tests/integration/php_debug.rs diff --git a/crates/ide-dap/tests/real_adapters.rs b/crates/ide-dap/tests/integration/real_adapters.rs similarity index 100% rename from crates/ide-dap/tests/real_adapters.rs rename to crates/ide-dap/tests/integration/real_adapters.rs diff --git a/crates/ide-dap/tests/script_debuggers.rs b/crates/ide-dap/tests/integration/script_debuggers.rs similarity index 100% rename from crates/ide-dap/tests/script_debuggers.rs rename to crates/ide-dap/tests/integration/script_debuggers.rs diff --git a/crates/ide-dap/tests/unity.rs b/crates/ide-dap/tests/integration/unity.rs similarity index 100% rename from crates/ide-dap/tests/unity.rs rename to crates/ide-dap/tests/integration/unity.rs diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs index f67027f803..25f5e53d98 100644 --- a/crates/ide-db/src/conn.rs +++ b/crates/ide-db/src/conn.rs @@ -1433,6 +1433,83 @@ impl Pool { r } + /// Runs exactly one statement in a driver-enforced read-only session: a write (including one + /// in a `WITH` clause) fails in the database, whatever the statement text looks like. Drivers + /// without such a session are refused rather than guarded by a keyword check. SQL that + /// [`split`](crate::split::split) reads as more than one statement is refused here as well, so + /// a direct caller cannot hand a MySQL/PostgreSQL multi-statement batch to the session. + pub async fn execute_read_only( + &self, + sql: &str, + max_rows: usize, + cancel: &CancellationToken, + ) -> IdeResult { + let driver = self.driver(); + let statements = crate::split::split(sql, driver); + if statements.len() != 1 { + return Err(IdeError::invalid(format!( + "read-only execution runs exactly one statement, but this SQL has {}", + statements.len() + ))); + } + if self.transaction_read_only() { + // The pool runs every statement in a verified `BEGIN READ ONLY` transaction. + return self.execute_from(sql, 0, max_rows, cancel).await; + } + if !matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_) | Pool::Oracle(_)) { + return Err(read_only_unsupported(driver)); + } + if driver == DbDriver::Mysql { + // The server runs executable comments and further statements that `split` reads as + // comments; the client cannot turn its multi-statement handling off. + crate::split::mysql_guard(sql)?; + } + if let Pool::Oracle(_) = self { + // Oracle commits a statement through `Held::command`, which would end the read-only + // transaction before the user's statement runs. It has its own non-committing path. + let started = Instant::now(); + let mut conn = Held::acquire_own(self).await?; + let result = match &mut conn { + Held::Oracle(c) => crate::oracle::execute_read_only(c, sql, max_rows, cancel).await, + _ => unreachable!("acquired an Oracle connection"), + }; + conn.discard().await; + return result.map(|fetched| query_result(sql, fetched, started)); + } + // A dedicated connection keeps the transaction or PRAGMA off every pooled connection. + let mut conn = Held::acquire_own(self).await?; + if let Held::Sqlite(c) = &mut conn { + // A future dropped mid-session (a timeout, a shutdown) must close this connection + // instead of returning one with `PRAGMA query_only` still on to the pool. + c.close_on_drop(); + } + if let Err(e) = open_read_only_session(&mut conn, driver, sql).await { + conn.discard().await; + return Err(e); + } + let result = match conn.execute_from(self, sql, 0, max_rows, cancel).await { + Ok(result) => result, + Err(e) => { + // A failed or cancelled statement must not return an open transaction or query_only. + conn.discard().await; + return Err(e); + } + }; + match close_read_only_session(&mut conn, driver).await { + Ok(()) => { + if let Held::Sqlite(c) = &mut conn { + // The PRAGMA is off again: this connection may go back to the pool. + c.return_to_pool().await; + } + Ok(result) + } + Err(e) => { + conn.discard().await; + Err(e) + } + } + } + /// Runs `statements` in one transaction; each must change `expect_one` /// row when flagged (table editor submits). pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult { @@ -1530,6 +1607,161 @@ impl Pool { } } +fn driver_name(driver: DbDriver) -> &'static str { + driver.display_name() +} + +pub(crate) fn read_only_unsupported(driver: DbDriver) -> IdeError { + IdeError::invalid(format!( + "{} has no read-only session: OpenIDEA refuses to run statements on it without one", + driver_name(driver) + )) +} + +/// Opens the driver's read-only session, then checks that the server took it. +async fn open_read_only_session(conn: &mut Held, driver: DbDriver, sql: &str) -> IdeResult<()> { + match driver { + DbDriver::Sqlite => { + conn.command("PRAGMA query_only = ON").await?; + if read_only_setting(conn, "PRAGMA query_only").await?.as_deref() != Some("1") { + return Err(IdeError::invalid("SQLite did not enter a read-only session: PRAGMA query_only is not 1")); + } + } + DbDriver::Postgres => { + conn.command("BEGIN READ ONLY").await?; + if read_only_setting(conn, "SHOW transaction_read_only").await?.as_deref() != Some("on") { + return Err(IdeError::invalid( + "PostgreSQL did not enter a read-only transaction: transaction_read_only is not on", + )); + } + if let Held::Postgres(c) = conn { + // sqlx sends the statement as the UTF-8 bytes of the Rust string and decodes text + // results as UTF-8, but the server converts those bytes from `client_encoding` + // before parsing them, and the source's startup script can change that (and + // `standard_conforming_strings`) on every connection. Pin and verify both, as the + // MySQL path pins utf8mb4. + pg_read_only::pin_encoding(c).await.map_err(db_err)?; + // No transaction guard checks this dedicated session's statement, so let the + // server parse it as one command before the simple query protocol runs it. + pg_read_only::check_single_always(c, sql).await.map_err(db_err)?; + } + } + DbDriver::Mysql => { + // sqlx sends a statement as the UTF-8 bytes of the Rust string and decodes text + // results as UTF-8, but the server's parser reads those bytes as + // `character_set_client`. Pin that connection to utf8mb4 (over the source's + // `charset` and any startup script) and verify it: in an East-Asian multibyte + // charset an ASCII backslash or quote can be swallowed as the second byte of a + // character, so the server would split a statement differently than `split` does. + conn.command("SET NAMES utf8mb4").await?; + let (client, connection) = mysql_connection_charsets(conn).await?; + for (name, value) in + [("character_set_client", client.as_str()), ("character_set_connection", connection.as_str())] + { + if !mysql_charset_is_safe(value) { + return Err(IdeError::invalid(format!( + "this MySQL/MariaDB connection reads SQL as {value} ({name}): the server could read \ + the statement's quotes or backslashes differently than the statement splitter, so \ + a hidden second statement could run" + ))); + } + } + // MySQL has no per-transaction flag to read back (`transaction_read_only` is the + // session default, which `START TRANSACTION READ ONLY` does not change). Set and + // verify the session default first, so a vendor that ignores the clause is refused; + // the statement boundary above is what keeps a second, overriding transaction out. + conn.command("SET SESSION TRANSACTION READ ONLY").await?; + if !mysql_session_read_only(conn).await? { + return Err(IdeError::invalid( + "MySQL/MariaDB did not take the read-only session: its transaction_read_only setting is off", + )); + } + let mode = read_only_setting(conn, "SELECT @@SESSION.sql_mode").await?.unwrap_or_default(); + if let Some(flag) = mysql_quote_mode_unsupported(&mode) { + return Err(IdeError::invalid(format!( + "this MySQL/MariaDB session sets {flag}: its quotes no longer read like the statement splitter's, \ + so a hidden second statement could run" + ))); + } + conn.command("START TRANSACTION READ ONLY").await?; + if !mysql_session_read_only(conn).await? { + return Err(IdeError::invalid( + "MySQL/MariaDB did not keep the read-only session: its transaction_read_only setting is off", + )); + } + } + DbDriver::Oracle => unreachable!("Oracle read-only sessions run in oracle::execute_read_only"), + _ => return Err(read_only_unsupported(driver)), + } + Ok(()) +} + +/// The session's read-only default: `transaction_read_only` (MySQL 5.7+, MariaDB 11+), then +/// MariaDB's older `tx_read_only`. A server with neither has no read-only session to verify. +async fn mysql_session_read_only(conn: &mut Held) -> IdeResult { + for name in ["transaction_read_only", "tx_read_only"] { + let sql = format!("SELECT @@SESSION.{name}"); + match read_only_setting(conn, &sql).await { + Ok(Some(value)) => { + return match value.trim().to_ascii_lowercase().as_str() { + "1" | "on" => Ok(true), + "0" | "off" => Ok(false), + other => Err(IdeError::invalid(format!("MySQL/MariaDB reported {name} as {other}"))), + }; + } + Ok(None) => {} + Err(error) if error.message.contains("Unknown system variable") => {} + Err(error) => return Err(error), + } + } + Err(IdeError::invalid( + "this MySQL-compatible server has no transaction_read_only (or tx_read_only) setting, \ + so its read-only session cannot be verified", + )) +} + +/// Whether a MySQL connection charset decodes every ASCII byte as itself, so the server reads a +/// statement the way [`split`](crate::split::split) and `mysql_guard` do. UTF-8 charsets, ASCII, +/// latin1 and binary qualify; East-Asian multibyte charsets (GBK, Big5, SJIS, CP932, GB18030, +/// EUC-KR…) can consume an ASCII byte as part of a multibyte character. +fn mysql_charset_is_safe(name: &str) -> bool { + matches!(name.trim().to_ascii_lowercase().as_str(), "utf8mb4" | "utf8mb3" | "utf8" | "ascii" | "latin1" | "binary") +} + +/// The session's `character_set_client` and `character_set_connection`; `SET NAMES` sets both. +async fn mysql_connection_charsets(conn: &mut Held) -> IdeResult<(String, String)> { + let (_, rows, _, _, _) = + conn.fetch_rows("SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection", 1).await?; + let row = rows + .into_iter() + .next() + .ok_or_else(|| IdeError::invalid("MySQL/MariaDB did not report its connection character set"))?; + let mut columns = row.into_iter(); + Ok((columns.next().flatten().unwrap_or_default(), columns.next().flatten().unwrap_or_default())) +} + +/// The sql_mode values that change how the server reads quotes; the statement splitter assumes +/// MySQL's defaults, so a session with either could split differently than the server parses. +fn mysql_quote_mode_unsupported(mode: &str) -> Option<&'static str> { + ["NO_BACKSLASH_ESCAPES", "ANSI_QUOTES"] + .into_iter() + .find(|flag| mode.split(',').any(|value| value.trim().eq_ignore_ascii_case(flag))) +} + +async fn read_only_setting(conn: &mut Held, sql: &str) -> IdeResult> { + let (_, rows, _, _, _) = conn.fetch_rows(sql, 1).await?; + Ok(rows.into_iter().next().and_then(|row| row.into_iter().next().flatten())) +} + +/// Ends the read-only session a successful statement ran in. +async fn close_read_only_session(conn: &mut Held, driver: DbDriver) -> IdeResult<()> { + match driver { + DbDriver::Sqlite => conn.command("PRAGMA query_only = OFF").await, + DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle => conn.command("ROLLBACK").await, + _ => Ok(()), + } +} + /// A connection of a pool, or one opened beside it that closes when dropped. pub enum Lease { Pooled(bb8::PooledConnection<'static, M>), @@ -1654,7 +1886,7 @@ impl Held { fn before_statement(&mut self, sql: &str) { let control = sql.trim().trim_end_matches(';').trim().to_ascii_uppercase(); if let Held::Mysql(c) = self { - if matches!(control.as_str(), "BEGIN" | "START TRANSACTION") { + if control == "BEGIN" || control == "START TRANSACTION" || control.starts_with("START TRANSACTION ") { c.in_transaction = true; return; } @@ -2284,4 +2516,75 @@ mod tests { assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE"); assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}"); } + + #[tokio::test] + async fn read_only_execution_refuses_writes_and_leaves_the_pool_usable() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("read-only.db"); + std::fs::File::create(&file).unwrap(); + let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() }; + let pool = Pool::connect(&source, None, None).await.unwrap(); + let cancel = CancellationToken::new(); + pool.execute("CREATE TABLE t (x INTEGER)", 1, &cancel).await.unwrap(); + + let result = pool.execute_read_only("SELECT 1", 1, &cancel).await.unwrap(); + assert_eq!(result.rows, vec![vec![Some("1".into())]]); + + let refused = pool.execute_read_only("INSERT INTO t VALUES (1)", 10, &cancel).await.unwrap_err(); + assert_eq!(refused.kind, ErrorKind::InvalidInput); + assert!(refused.message.to_lowercase().contains("readonly"), "{}", refused.message); + + // The guarded statement changed nothing, and the PRAGMA did not stay on the pool. + pool.execute("INSERT INTO t VALUES (2)", 1, &cancel).await.unwrap(); + let rows = pool.execute("SELECT x FROM t", 10, &cancel).await.unwrap().rows; + assert_eq!(rows, vec![vec![Some("2".into())]]); + } + + #[test] + fn mysql_quote_modes_that_change_lexing_are_named() { + assert_eq!(mysql_quote_mode_unsupported("ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES"), None); + assert_eq!(mysql_quote_mode_unsupported("ANSI_QUOTES,STRICT_TRANS_TABLES"), Some("ANSI_QUOTES")); + assert_eq!(mysql_quote_mode_unsupported("no_backslash_escapes"), Some("NO_BACKSLASH_ESCAPES")); + assert_eq!(mysql_quote_mode_unsupported(""), None); + } + + #[test] + fn mysql_connection_charsets_that_can_swallow_ascii_are_refused() { + for safe in ["utf8mb4", "utf8mb3", "utf8", "ascii", "latin1", "binary", "UTF8MB4", " utf8mb4 "] { + assert!(mysql_charset_is_safe(safe), "{safe}"); + } + for unsafe_charset in ["gbk", "big5", "sjis", "cp932", "gb18030", "euckr", "ujis", ""] { + assert!(!mysql_charset_is_safe(unsafe_charset), "{unsafe_charset}"); + } + } + + #[tokio::test] + async fn read_only_execution_refuses_a_second_statement() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("read-only-statements.db"); + std::fs::File::create(&file).unwrap(); + let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() }; + let pool = Pool::connect(&source, None, None).await.unwrap(); + let cancel = CancellationToken::new(); + for sql in + ["SELECT 1; SELECT 2", "SELECT 1; START TRANSACTION READ WRITE; DELETE FROM t", "SELECT 1; DELETE FROM t"] + { + let refused = pool.execute_read_only(sql, 1, &cancel).await.unwrap_err(); + assert_eq!(refused.kind, ErrorKind::InvalidInput, "{sql}"); + assert!(refused.message.contains("exactly one statement"), "{sql}: {}", refused.message); + } + // One statement with a trailing `;` (and comments) is still one statement. + let result = pool.execute_read_only("SELECT 1; -- done", 1, &cancel).await.unwrap(); + assert_eq!(result.rows, vec![vec![Some("1".into())]]); + } + + #[test] + fn drivers_without_a_read_only_session_are_refused() { + for driver in [DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Snowflake, DbDriver::Jdbc] { + let error = read_only_unsupported(driver); + assert_eq!(error.kind, ErrorKind::InvalidInput); + assert!(error.message.contains(driver_name(driver)), "{}", error.message); + assert!(error.message.contains("no read-only session"), "{}", error.message); + } + } } diff --git a/crates/ide-db/src/conn/pg_read_only.rs b/crates/ide-db/src/conn/pg_read_only.rs index 53dbd3ca5b..dcfa6e7eb5 100644 --- a/crates/ide-db/src/conn/pg_read_only.rs +++ b/crates/ide-db/src/conn/pg_read_only.rs @@ -2,7 +2,7 @@ use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err}; use ide_core::{IdeError, IdeResult}; -use sqlx::{Executor, SqlSafeStr}; +use sqlx::{Executor, Row, SqlSafeStr}; // Take the first snapshot before user SQL, fixing the transaction characteristics on this backend. pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1"; @@ -110,11 +110,64 @@ pub(super) fn startup(statements: &[String]) -> Result<(Vec, Vec // validates that the text denotes a single command, including under the server's quoting rules. pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> { if sql.contains(';') { - conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?; + check_single_always(conn, sql).await?; } Ok(()) } +/// Prepares `sql` whatever it contains, so the server parses it as one command with its own +/// lexer before the simple query protocol runs it. The dedicated read-only connection has no +/// transaction guard; a difference between the splitter's lexing and the server's (an encoding, +/// a newline or an escape rule) then becomes a parse error instead of a hidden second statement. +pub(super) async fn check_single_always(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> { + conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?; + Ok(()) +} + +/// Whether the server reports a client encoding that reads the statement's UTF-8 bytes as UTF-8 +/// (it spells UTF-8 `UTF8`, and some servers `UNICODE`). +pub(super) fn utf8_client_encoding(name: &str) -> bool { + matches!(name.trim().to_ascii_uppercase().as_str(), "UTF8" | "UNICODE") +} + +/// Pins the settings the statement splitter assumes and verifies the server took them. A +/// PostgreSQL server converts the statement text from `client_encoding` before parsing it, so a +/// multibyte client encoding could end a string at a different quote than `split` did; with +/// `standard_conforming_strings` off, a plain `'…'` literal takes backslash escapes `split` does +/// not read. A startup script can set either on every connection, so both are pinned per session. +pub(super) async fn pin_encoding(conn: &mut PgConnection) -> Result<(), sqlx::Error> { + // `SET LOCAL`: both callers are inside the read-only transaction, so the source's own + // session settings come back when it ends. + sqlx::raw_sql("SET LOCAL client_encoding TO 'UTF8'").execute(&mut *conn).await?; + let encoding = pg_show(conn, "SHOW client_encoding").await?; + if !utf8_client_encoding(&encoding) { + return Err(sqlx::Error::Configuration( + format!( + "PostgreSQL reports client_encoding {encoding}, not UTF8: the server could read the statement's \ + quotes or escapes differently than the statement splitter, so a hidden second statement could run" + ) + .into(), + )); + } + sqlx::raw_sql("SET LOCAL standard_conforming_strings TO on").execute(&mut *conn).await?; + let conforming = pg_show(conn, "SHOW standard_conforming_strings").await?; + if !conforming.trim().eq_ignore_ascii_case("on") { + return Err(sqlx::Error::Configuration( + format!( + "PostgreSQL reports standard_conforming_strings {conforming}, not on: the server could read a \ + string's backslash differently than the statement splitter, so a hidden second statement could run" + ) + .into(), + )); + } + Ok(()) +} + +async fn pg_show(conn: &mut PgConnection, sql: &'static str) -> Result { + let row = sqlx::raw_sql(sql).fetch_one(conn).await?; + row.try_get(0) +} + impl PgHandle { pub(super) async fn start_read_only(&mut self) -> IdeResult<()> { self.in_transaction = true; @@ -125,6 +178,8 @@ impl PgHandle { check_single(self, sql).await.map_err(db_err)?; sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?; } + // After the startup settings: one of them may have changed either setting. + pin_encoding(self).await.map_err(db_err)?; self.apply_local_path().await } .await; @@ -220,7 +275,17 @@ impl Held { #[cfg(test)] mod tests { - use super::validate; + use super::{utf8_client_encoding, validate}; + + #[test] + fn only_utf8_spellings_pass_the_client_encoding_check() { + for name in ["UTF8", "utf8", "Unicode", " UNICODE "] { + assert!(utf8_client_encoding(name), "{name}"); + } + for name in ["GBK", "SJIS", "BIG5", "LATIN1", "SQL_ASCII", ""] { + assert!(!utf8_client_encoding(name), "{name}"); + } + } #[test] fn names_transaction_control_and_accepts_quoted_text() { diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 6c173dc0f7..264cdc6e1a 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -1992,6 +1992,27 @@ impl DbManager { self.execute_from(id, statement, 0, max_rows, cancel, None).await } + /// Runs `statement` in a driver-enforced read-only session (see [`Pool::execute_read_only`]). + /// Exactly one statement is required: SQL that splits into several is refused at the + /// connection layer, so a direct caller cannot smuggle in a second one. Not recorded in the + /// query history: it runs outside the console, only after the caller confirmed the exact + /// statement. `id` is one data source id; callers that expose this to agents must also require + /// one unqualified id and a source that is not plugin-owned. + pub async fn execute_read_only_query( + &self, + id: &str, + statement: &str, + max_rows: usize, + cancel: &CancellationToken, + ) -> IdeResult { + // Refuse a driver without a read-only session before opening (and connecting) its pool. + let source = self.source(id)?; + if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) { + return Err(conn::read_only_unsupported(source.driver)); + } + self.pool(id).await?.execute_read_only(statement, max_rows, cancel).await + } + /// Refuses transaction control anywhere in a guarded console script before running its first statement. pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> { self.validate_console_script(id, statements, None).await diff --git a/crates/ide-db/src/oracle.rs b/crates/ide-db/src/oracle.rs index 3a53b1c208..243ba1be59 100644 --- a/crates/ide-db/src/oracle.rs +++ b/crates/ide-db/src/oracle.rs @@ -315,8 +315,10 @@ fn open(state: &State) -> Result { Ok(OracleHandle { conn: Some(conn), context }) } -/// Runs `f` with the connection on the blocking pool. Cancelling drops the -/// connection instead of returning it (its statement keeps running server-side). +/// Runs `f` with the connection on the blocking pool. Cancelling stops the wait and drops the +/// connection instead of returning it, but only when the blocking call ends: the driver has no +/// break API, so the statement keeps running server-side until it finishes, and closing the +/// connection then rolls its transaction back. async fn with_conn( c: &mut OracleConnection, cancel: &CancellationToken, @@ -367,6 +369,53 @@ pub(crate) async fn run( with_conn(c, cancel, move |conn| statements(conn, &state, &sql, skip, max, mode)).await } +/// Runs one statement in a verified read-only transaction on its own connection. Auto-commit is +/// off whatever the source's mode: [`statement`] must not commit the transaction away, and the +/// transaction is always rolled back (a dropped connection rolls it back server-side too). +pub(crate) async fn execute_read_only( + c: &mut OracleConnection, + sql: &str, + max: usize, + cancel: &CancellationToken, +) -> IdeResult { + let sql = sql.to_owned(); + with_conn(c, cancel, move |conn| { + // `SET TRANSACTION READ ONLY` must be the first statement of its transaction; a startup + // script may have left one open. + conn.rollback().map_err(|e| oracle_err(&e))?; + statement(conn, "SET TRANSACTION READ ONLY", 0, 0, Cells::Text, false)?; + verify_read_only(conn)?; + // The user's statement is the only other statement in the transaction; `split` is not + // used here, so a `;` cannot smuggle in a second one. + let result = statement(conn, &sql, 0, max, Cells::Display, false); + let rollback = conn.rollback().map_err(|e| oracle_err(&e)); + match (result, rollback) { + (Ok(fetched), Ok(())) => Ok(fetched), + (Err(error), _) => Err(error), + (Ok(_), Err(error)) => Err(error), + } + }) + .await +} + +/// Proves the server took `SET TRANSACTION READ ONLY`: a locking read is refused in a read-only +/// transaction (`ORA-01456`). `NOWAIT` keeps the probe from waiting on another session's DUAL +/// lock if the transaction did not take; no row is locked when it did. +fn verify_read_only(conn: &mut oracledb::Connection) -> IdeResult<()> { + match conn.query_row("SELECT 1 FROM DUAL FOR UPDATE NOWAIT", &[]) { + Ok(_) => Err(IdeError::invalid("Oracle did not enter a read-only transaction: a locking read succeeded")), + Err(e) if read_only_violation(&e) => Ok(()), + Err(e) => Err(IdeError::new( + ErrorKind::PermissionDenied, + format!("Oracle did not confirm the read-only transaction: {}", oracle_err(&e).message), + )), + } +} + +fn read_only_violation(e: &oracledb::Error) -> bool { + matches!(e.kind(), oracledb::ErrorKind::DbError(db) if db.code() as u32 == 1456) +} + /// The table editor's edits in one transaction. pub(crate) async fn transaction(c: &mut OracleConnection, statements: &[(String, bool)]) -> IdeResult { if c.state.read_only { @@ -1028,6 +1077,50 @@ mod tests { drop(raw); } + /// The read-only session `execute_read_only` opens: a write and `EXPLAIN PLAN` (which writes + /// `PLAN_TABLE`) are refused by the database, and no change is left behind. Skipped unless + /// `OPENIDEA_ORACLE_TEST` names a live server. + #[tokio::test] + async fn a_read_only_session_refuses_writes_and_leaves_no_change() { + let Some(spec) = std::env::var("OPENIDEA_ORACLE_TEST").ok().filter(|s| !s.is_empty()) else { return }; + let (source, password) = live_source(&spec); + let secrets = vec![source.user.clone(), source.host.clone(), source.database.clone()]; + let pool = crate::conn::Pool::connect(&source, Some(&password), None).await.expect("connect"); + let c = CancellationToken::new(); + let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple()); + let _ = drop_if_present(&pool, &format!("table {table}")).await; + pool.rows(&format!("create table {table} (id number)"), 0).await.expect("create table"); + pool.rows(&format!("insert into {table} values (1)"), 0).await.expect("insert a row"); + + let selected = + pool.execute_read_only(&format!("select count(*) from {table}"), 1, &c).await.expect("a query runs"); + assert_eq!(selected.rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1")); + + let write = pool + .execute_read_only(&format!("insert into {table} values (2)"), 1, &c) + .await + .expect_err("a write is refused in the read-only transaction"); + assert!( + write.message.contains("1456") || write.message.to_ascii_lowercase().contains("read only"), + "{}", + write.message + ); + let explain = pool + .execute_read_only("explain plan for select 1 from dual", 1, &c) + .await + .expect_err("EXPLAIN PLAN writes PLAN_TABLE, so the read-only transaction refuses it"); + assert!( + explain.message.contains("1456") || explain.message.to_ascii_lowercase().contains("read only"), + "{}", + explain.message + ); + + let rows = pool.rows(&format!("select count(*) from {table}"), 1).await.expect("count after the refusals"); + assert_eq!(rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1")); + let _ = drop_if_present(&pool, &format!("table {table}")).await; + pass("read-only", "a write and EXPLAIN PLAN were refused; the table kept its one row", &secrets); + } + /// An account whose only verifier is `10G` (see `DBA_USERS.PASSWORD_VERSIONS`): /// the thin driver speaks 11G and later verifiers, so the server rejects even /// the correct password with ORA-01017 until the account is reset diff --git a/crates/ide-db/src/source.rs b/crates/ide-db/src/source.rs index 570872e195..8ec0054879 100644 --- a/crates/ide-db/src/source.rs +++ b/crates/ide-db/src/source.rs @@ -31,6 +31,20 @@ pub enum DbDriver { } impl DbDriver { + /// The driver's name in messages and tool output. + pub fn display_name(self) -> &'static str { + match self { + DbDriver::Sqlite => "SQLite", + DbDriver::Postgres => "PostgreSQL", + DbDriver::Mysql => "MySQL", + DbDriver::SqlServer => "SQL Server", + DbDriver::Clickhouse => "ClickHouse", + DbDriver::Oracle => "Oracle", + DbDriver::Snowflake => "Snowflake", + DbDriver::Jdbc => "JDBC", + } + } + pub fn default_port(self) -> Option { match self { DbDriver::Sqlite | DbDriver::Jdbc => None, @@ -766,10 +780,16 @@ fn read(path: &Path) -> IdeResult> { } fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> { + let mut ids = HashSet::new(); for s in sources { if s.id.is_empty() || s.name.trim().is_empty() { return Err(IdeError::invalid("every data source needs an id and a name")); } + // A connection target resolves an id to the first source with it; duplicates make that + // ambiguous (and a crafted file must not redirect a console or a tool to another entry). + if !ids.insert(s.id.as_str()) { + return Err(IdeError::invalid(format!("duplicate data source id '{}'", s.id))); + } } if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; @@ -983,6 +1003,15 @@ mod tests { assert_eq!(load(tmp.path()).unwrap(), vec![s]); } + #[test] + fn saving_refuses_duplicate_ids() { + let tmp = tempfile::tempdir().unwrap(); + let source = DataSource { id: "a".into(), name: "one".into(), ..Default::default() }; + let duplicate = vec![source.clone(), DataSource { name: "two".into(), ..source }]; + let error = save(tmp.path(), &duplicate).unwrap_err(); + assert!(error.message.contains("duplicate data source id 'a'"), "{}", error.message); + } + #[test] fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() { let mut introspection = DbIntrospection { diff --git a/crates/ide-db/src/split.rs b/crates/ide-db/src/split.rs index 2058f77717..3d17ed4aca 100644 --- a/crates/ide-db/src/split.rs +++ b/crates/ide-db/src/split.rs @@ -7,6 +7,7 @@ //! Offsets are UTF-16 code units, like everything on the IPC boundary. use crate::DbDriver; +use ide_core::{IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; @@ -316,9 +317,7 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec - { + '-' if next == Some('-') && (!mysql || mysql_dash_comment(chars.get(i + 2).map(|c| c.1))) => { state = State::LineComment; i += 1; } @@ -452,7 +451,9 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec { - if c == '\n' { + // PostgreSQL ends a `--` comment at `\r` as well as `\n` (`scan.l`: + // `non_newline [^\n\r]`); MySQL and SQLite read a bare `\r` as comment text. + if c == '\n' || (postgres && c == '\r') { state = State::Code; } } @@ -469,6 +470,128 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec) -> bool { + next.is_none_or(|c| c == ' ' || c.is_ascii_control()) +} + +/// Whether `/*!` or `/*M!`, whose contents a MySQL/MariaDB server runs as SQL, starts at `i`. +fn executable_comment_start(chars: &[char], i: usize) -> bool { + chars.get(i) == Some(&'/') + && chars.get(i + 1) == Some(&'*') + && (chars.get(i + 2) == Some(&'!') + || (matches!(chars.get(i + 2), Some('M' | 'm')) && chars.get(i + 3) == Some(&'!'))) +} + +/// Refuses what a MySQL/MariaDB server runs but [`split`] reads as a comment or a literal: +/// executable comments (`/*! … */`, `/*M! … */`), whose contents the server tokenizes as SQL, +/// and `INTO OUTFILE` / `INTO DUMPFILE`, which write a file on the server. The client cannot +/// switch the server's multi-statement handling off, so a statement handed to a MySQL/MariaDB +/// read-only session must pass this first (with the default quote modes, see +/// `mysql_quote_mode_unsupported` in `conn`). +/// +/// Executable comments are refused wherever they appear outside a string or a quoted identifier, +/// even inside a genuine comment: the conservative refusal cannot be bypassed if the comment +/// rules of this guard and the server ever diverge. +pub fn mysql_guard(sql: &str) -> IdeResult<()> { + let chars: Vec = sql.chars().collect(); + let mut state = State::Code; + // The last word outside quotes and comments, so `INTO /* … */ OUTFILE` is one clause. + let mut last = String::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + if !matches!(state, State::Single | State::Double | State::Backtick) && executable_comment_start(&chars, i) { + return Err(IdeError::invalid( + "MySQL executable comments (/*! … */ and /*M! … */) are not allowed here: \ + the server runs their contents as SQL", + )); + } + match state { + State::Code => match c { + '\'' => state = State::Single, + '"' => state = State::Double, + '`' => state = State::Backtick, + '#' => state = State::LineComment, + '-' if next == Some('-') && mysql_dash_comment(chars.get(i + 2).copied()) => { + state = State::LineComment; + i += 1; + } + '/' if next == Some('*') => { + state = State::BlockComment; + i += 1; + } + c if c.is_alphanumeric() || c == '_' || c == '$' => { + let start = i; + while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_' || *c == '$') { + i += 1; + } + let word: String = chars[start..i].iter().collect::().to_ascii_uppercase(); + if matches!(word.as_str(), "OUTFILE" | "DUMPFILE") && last == "INTO" { + return Err(IdeError::invalid( + "MySQL INTO OUTFILE / INTO DUMPFILE is not allowed here: it writes a file on the server", + )); + } + last = word; + continue; + } + c if c.is_whitespace() => {} + _ => last.clear(), + }, + State::Single => { + if c == '\\' { + i += 1; + } else if c == '\'' { + if next == Some('\'') { + i += 1; + } else { + state = State::Code; + } + } + } + State::Double => { + if c == '\\' { + i += 1; + } else if c == '"' { + if next == Some('"') { + i += 1; + } else { + state = State::Code; + } + } + } + State::Backtick => { + if c == '`' { + if next == Some('`') { + i += 1; + } else { + state = State::Code; + } + } + } + State::LineComment => { + if c == '\n' { + state = State::Code; + } + } + State::BlockComment => { + if c == '*' && next == Some('/') { + state = State::Code; + i += 1; + } + } + // MySQL quotes identifiers only with backticks. + State::Bracket => unreachable!("MySQL has no bracketed identifiers"), + } + i += 1; + } + Ok(()) +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Unit { Sql, @@ -777,6 +900,82 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str { mod tests { use super::*; + #[test] + fn mysql_executable_comments_are_refused_outside_literals() { + for sql in [ + "SELECT 1 /*!50000 , 2 */", + "/*! START TRANSACTION READ WRITE; DELETE FROM t; */ SELECT 1", + "SELECT 1 /*M!100000 , 2 */", + "select 1 /*m! , 2 */", + // Also inside a genuine comment: the conservative refusal cannot be bypassed by a + // future difference between the guard's comment rules and the server's. + "SELECT 1 -- /*! hidden in a comment */", + "SELECT 1 # /*! hidden in a comment */", + "SELECT 1 /* /*! inside a block comment */", + ] { + let error = mysql_guard(sql).unwrap_err(); + assert!(error.message.contains("executable comments"), "{sql}: {}", error.message); + } + // The same text inside a literal or a quoted identifier is data, not code. + for sql in [ + "SELECT '/*! DELETE FROM t */'", + "SELECT \"/*M! x */\", `/*! y */` FROM t", + "SELECT 'it''s /*! fine */'", + "SELECT 'a\\' /*! still text */'", + ] { + mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message)); + } + } + + #[test] + fn mysql_dash_comment_uses_mysqls_ascii_rule_like_the_splitter() { + // U+00A0 (NO-BREAK SPACE) and other Unicode spaces do not start a `--` comment on the + // server: `--` is two minus signs and the executable comment that follows is code. + for sql in [ + "SELECT 1 --\u{00a0}/*! x */", + "SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; DELETE FROM users; */", + "SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/x' */", + "SELECT 1 --\u{2003}/*M! DELETE FROM users */", + ] { + let error = mysql_guard(sql).unwrap_err(); + assert!(error.message.contains("executable comments"), "{sql}: {}", error.message); + } + // An ASCII space, tab or control character after `--` is a comment, as before. + for sql in ["SELECT 1 -- ordinary comment\n+ 1", "SELECT 1 --\tcomment\n+ 1", "SELECT 1 --\n+ 1"] { + mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message)); + } + // `split` applies the same rule: the text after `--` is code (and the `;` there splits), + // so the guard is the layer that refuses the executable comment. + assert_eq!( + texts("SELECT 5 --\u{00a0} 1; SELECT 2", DbDriver::Mysql), + vec!["SELECT 5 --\u{00a0} 1", "SELECT 2"] + ); + assert_eq!(texts("SELECT 5 -- 1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5 -- 1; SELECT 2"]); + } + + #[test] + fn mysql_into_outfile_is_refused_outside_literals_and_comments() { + for sql in [ + "SELECT * FROM t INTO OUTFILE '/tmp/x'", + "SELECT * FROM t INTO DUMPFILE '/tmp/x'", + "SELECT * FROM t INTO/**/OUTFILE '/tmp/x'", + "SELECT * FROM t INTO /* c */\n OUTFILE '/tmp/x'", + "select * from t into outfile '/tmp/x'", + ] { + let error = mysql_guard(sql).unwrap_err(); + assert!(error.message.contains("INTO OUTFILE"), "{sql}: {}", error.message); + } + for sql in [ + "SELECT 'INTO OUTFILE /tmp/x'", + "SELECT 1 AS outfile, 2 AS dumpfile FROM t", + "SELECT 1 /* INTO OUTFILE '/tmp/x' */", + "SELECT 1 -- INTO OUTFILE '/tmp/x'", + "SELECT @outfile FROM t", + ] { + mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message)); + } + } + #[test] fn clickhouse_session_settings_split_after_comments_and_quoted_values() { let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1"; @@ -852,6 +1051,17 @@ mod tests { ); } + #[test] + fn postgres_line_comments_end_at_a_carriage_return_like_the_server() { + // `scan.l` reads `\r` as a newline, so the `;` after it ends the statement; MySQL and + // SQLite keep a bare `\r` inside the comment. + let sql = "SELECT 1 --\r; SELECT 2"; + assert_eq!(texts(sql, DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]); + assert_eq!(texts(sql, DbDriver::Mysql), vec![sql]); + assert_eq!(texts(sql, DbDriver::Sqlite), vec![sql]); + assert_eq!(texts("SELECT 1 --\r\n; SELECT 2", DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]); + } + #[test] fn mysql_double_quoted_strings_and_dashes() { let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#; diff --git a/crates/ide-db/tests/clickhouse.rs b/crates/ide-db/tests/integration/clickhouse.rs similarity index 100% rename from crates/ide-db/tests/clickhouse.rs rename to crates/ide-db/tests/integration/clickhouse.rs diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/integration/jdbc.rs similarity index 100% rename from crates/ide-db/tests/jdbc.rs rename to crates/ide-db/tests/integration/jdbc.rs diff --git a/crates/ide-db/tests/integration/main.rs b/crates/ide-db/tests/integration/main.rs new file mode 100644 index 0000000000..9ad25080c6 --- /dev/null +++ b/crates/ide-db/tests/integration/main.rs @@ -0,0 +1,11 @@ +mod clickhouse; +mod jdbc; +mod mysql; +mod pg_console_sessions; +mod pg_console_transactions; +mod postgres; +mod snowflake; +mod sqlite; +mod sqlite_console_sessions; +mod sqlserver; +mod ssh_tunnel; diff --git a/crates/ide-db/tests/mysql.rs b/crates/ide-db/tests/integration/mysql.rs similarity index 81% rename from crates/ide-db/tests/mysql.rs rename to crates/ide-db/tests/integration/mysql.rs index 802030bce8..0b6d7b3cba 100644 --- a/crates/ide-db/tests/mysql.rs +++ b/crates/ide-db/tests/integration/mysql.rs @@ -2,7 +2,7 @@ //! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server. use ide_core::{CancellationToken, IdeResult}; -use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbRowEdit}; +use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit}; const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"]; @@ -13,6 +13,14 @@ fn server() -> Option<(String, u16, String, String)> { } async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option { + manager_with_properties(tmp, startup_script, Vec::new()).await +} + +async fn manager_with_properties( + tmp: &tempfile::TempDir, + startup_script: &str, + properties: Vec, +) -> Option { let (host, port, user, password) = server()?; let root = tmp.path().to_path_buf(); let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json"))); @@ -24,6 +32,7 @@ async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option IdeResult<()> { } Ok(()) } + +/// The MySQL/MariaDB read-only session: a query runs; writes, executable comments and +/// `INTO OUTFILE` are refused. Skipped without `OPENIDEA_TEST_MYSQL`. +#[tokio::test] +async fn the_read_only_session_refuses_writes_and_server_side_escapes() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp, "").await else { return Ok(()) }; + let c = CancellationToken::new(); + let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple()); + for stmt in [ + format!("DROP TABLE IF EXISTS {table}"), + format!("CREATE TABLE {table} (id INT PRIMARY KEY)"), + format!("INSERT INTO {table} VALUES (1)"), + ] { + db.execute("m", &stmt, 1, &c).await?; + } + + let rows = db.execute_read_only_query("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into())]]); + + let write = db + .execute_read_only_query("m", &format!("INSERT INTO {table} VALUES (2)"), 1, &c) + .await + .expect_err("the read-only transaction refuses a write"); + assert!( + write.message.to_ascii_lowercase().contains("read only") || write.message.contains("1792"), + "{}", + write.message + ); + let comment = db + .execute_read_only_query("m", "SELECT 1 /*! , 2 */", 1, &c) + .await + .expect_err("an executable comment is refused before the server runs it"); + assert!(comment.message.contains("executable comment"), "{}", comment.message); + let outfile = db + .execute_read_only_query("m", &format!("SELECT * FROM {table} INTO OUTFILE '/tmp/openidea-ro'"), 1, &c) + .await + .expect_err("INTO OUTFILE is refused"); + assert!(outfile.message.contains("INTO OUTFILE"), "{}", outfile.message); + // `--` followed by a non-ASCII space is two minus signs to the server, not a comment; the + // guard must read it the same way instead of hiding the executable comment behind it. + for payload in [ + "SELECT 1 --\u{00a0}/*! x */".to_owned(), + format!( + "SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; \ + DELETE FROM {table}; */" + ), + "SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/openidea-ro' */".to_owned(), + ] { + let error = db + .execute_read_only_query("m", &payload, 1, &c) + .await + .expect_err("the executable comment is refused before the server runs it"); + assert!(error.message.contains("executable comment"), "{payload}: {}", error.message); + } + + let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into())]], "nothing else was written"); + db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?; + Ok(()) +} + +/// A source configured with an unsafe connection charset (`charset=gbk`) cannot make the server +/// read a statement differently than the client: the read-only connection is pinned to utf8mb4, +/// so an ASCII backslash is never swallowed as the second byte of a GBK character. Skipped +/// without `OPENIDEA_TEST_MYSQL`. +#[tokio::test] +async fn the_read_only_connection_is_pinned_to_utf8mb4_whatever_the_source_charset() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = + manager_with_properties(&tmp, "", vec![DbProperty { name: "charset".into(), value: "gbk".into() }]).await + else { + return Ok(()); + }; + let c = CancellationToken::new(); + let charsets = db + .execute_read_only_query( + "m", + "SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection", + 1, + &c, + ) + .await?; + assert_eq!(charsets.rows, vec![vec![Some("utf8mb4".into()), Some("utf8mb4".into())]]); + + let table = format!("openidea_charset_{}", uuid::Uuid::new_v4().simple()); + for stmt in [ + format!("DROP TABLE IF EXISTS {table}"), + format!("CREATE TABLE {table} (id INT)"), + format!("INSERT INTO {table} VALUES (1)"), + ] { + db.execute("m", &stmt, 1, &c).await?; + } + // Read as GBK, the `\` would be consumed as the second byte of a character, the string would + // end early and the tail would run as two more statements. + let payload = format!("SELECT '中\\' ; START TRANSACTION READ WRITE; DELETE FROM {table}; -- '"); + db.execute_read_only_query("m", &payload, 1, &c).await?; + let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into())]], "no hidden statement ran"); + db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?; + Ok(()) +} diff --git a/crates/ide-db/tests/pg_console_sessions.rs b/crates/ide-db/tests/integration/pg_console_sessions.rs similarity index 100% rename from crates/ide-db/tests/pg_console_sessions.rs rename to crates/ide-db/tests/integration/pg_console_sessions.rs diff --git a/crates/ide-db/tests/pg_console_transactions.rs b/crates/ide-db/tests/integration/pg_console_transactions.rs similarity index 100% rename from crates/ide-db/tests/pg_console_transactions.rs rename to crates/ide-db/tests/integration/pg_console_transactions.rs diff --git a/crates/ide-db/tests/postgres.rs b/crates/ide-db/tests/integration/postgres.rs similarity index 90% rename from crates/ide-db/tests/postgres.rs rename to crates/ide-db/tests/integration/postgres.rs index bb8e049246..8273bad71f 100644 --- a/crates/ide-db/tests/postgres.rs +++ b/crates/ide-db/tests/integration/postgres.rs @@ -234,6 +234,90 @@ async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResu Ok(()) } +/// A data-changing statement hidden in a CTE is not a query: the read-only session refuses it +/// in the database, whatever the statement text looks like, and the table keeps its rows. +#[tokio::test] +async fn a_write_hidden_in_a_cte_is_refused_by_the_read_only_session() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let c = CancellationToken::new(); + let table = format!("public.oi_cte_{}", uuid::Uuid::new_v4().simple()); + for stmt in [ + format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"), + format!("INSERT INTO {table} VALUES (1, 'kept')"), + ] { + db.execute("p", &stmt, 10, &c).await?; + } + let statement = format!("WITH d AS (DELETE FROM {table} RETURNING *) SELECT * FROM d"); + let error = db + .execute_read_only_query("p", &statement, 10, &c) + .await + .expect_err("the read-only transaction must refuse a DELETE in a CTE"); + assert!(error.message.contains("25006"), "{}", error.message); + let rows = db.execute("p", &format!("SELECT id, name FROM {table} ORDER BY id"), 10, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]); + db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?; + Ok(()) +} + +/// PostgreSQL's scanner ends a `--` comment at `\r` as well as `\n`; the splitter must agree, so +/// a bare CR cannot hide `COMMIT; DELETE …` from the one-statement check. The hidden statements +/// would otherwise run on the dedicated `BEGIN READ ONLY` connection. +#[tokio::test] +async fn a_carriage_return_cannot_hide_a_second_statement() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let c = CancellationToken::new(); + let table = format!("public.oi_cr_{}", uuid::Uuid::new_v4().simple()); + for stmt in [format!("CREATE TABLE {table} (id INT PRIMARY KEY)"), format!("INSERT INTO {table} VALUES (1)")] { + db.execute("p", &stmt, 10, &c).await?; + } + let payload = format!("SELECT 1 --\r; COMMIT; DELETE FROM {table}; --"); + let error = db.execute_read_only_query("p", &payload, 10, &c).await.expect_err("the hidden DELETE must not run"); + assert!(error.message.contains("exactly one statement"), "{}", error.message); + let rows = db.execute("p", &format!("SELECT count(*) FROM {table}"), 10, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into())]]); + db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?; + Ok(()) +} + +/// A startup script can change the connection's `client_encoding`; the read-only session pins it +/// to UTF-8 anyway, so the server reads the statement's bytes exactly as the splitter did. +#[tokio::test] +async fn a_startup_script_cannot_change_the_read_only_sessions_encoding() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let c = CancellationToken::new(); + let table = format!("public.oi_gbk_{}", uuid::Uuid::new_v4().simple()); + for stmt in [ + format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"), + format!("INSERT INTO {table} VALUES (1, 'kept')"), + ] { + db.execute("p", &stmt, 10, &c).await?; + } + let mut sources = db.sources()?; + let mut source = sources[0].clone(); + source.id = "gbk".into(); + source.name = "GBK startup".into(); + source.read_only = true; + source.options.startup_script = "SET client_encoding TO 'GBK'".into(); + sources.push(source); + db.save_sources(sources).await?; + db.set_password("gbk", server().map(|(.., password)| password), false).await?; + + let encoding = db.execute_read_only_query("gbk", "SELECT current_setting('client_encoding')", 1, &c).await?; + assert_eq!(encoding.rows, vec![vec![Some("UTF8".into())]]); + // In GBK the backslash before the quote is a trail byte of the preceding character, so the + // server would end the E-string early and run the hidden `COMMIT; DELETE …`. + let payload = format!("SELECT E'中\\' ; COMMIT; DELETE FROM {table}; -- '"); + let result = db.execute_read_only_query("gbk", &payload, 1, &c).await?; + assert_eq!(result.rows.len(), 1, "{:?}", result.rows); + let rows = db.execute("p", &format!("SELECT id, name FROM {table}"), 10, &c).await?; + assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]); + db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?; + Ok(()) +} + #[tokio::test] async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> { let tmp = tempfile::tempdir().unwrap(); @@ -701,7 +785,7 @@ async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target executable: std::env::current_exe()?.to_string_lossy().into_owned(), arguments: vec![ "--exact".into(), - "postgres_tunnel_fixture".into(), + "postgres::postgres_tunnel_fixture".into(), "--skip".into(), "listen={localPort}".into(), "--skip".into(), @@ -758,7 +842,7 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i executable: std::env::current_exe()?.to_string_lossy().into_owned(), arguments: vec![ "--exact".into(), - "postgres_tunnel_fixture".into(), + "postgres::postgres_tunnel_fixture".into(), "--skip".into(), "listen={localPort}".into(), "--skip".into(), diff --git a/crates/ide-db/tests/snowflake.rs b/crates/ide-db/tests/integration/snowflake.rs similarity index 99% rename from crates/ide-db/tests/snowflake.rs rename to crates/ide-db/tests/integration/snowflake.rs index c5bf12463a..3161cb82f5 100644 --- a/crates/ide-db/tests/snowflake.rs +++ b/crates/ide-db/tests/integration/snowflake.rs @@ -320,7 +320,7 @@ async fn explorer_metadata_against_a_real_account() { // each is either answered or refused by Snowflake (an edition or privilege it needs), never // misread by the client. `USE` goes to what the session already has. let fixture: serde_json::Value = - serde_json::from_str(include_str!("fixtures/snowflake/commands.json")).expect("the fixture parses"); + serde_json::from_str(include_str!("../fixtures/snowflake/commands.json")).expect("the fixture parses"); let mut statements: Vec<(String, String)> = fixture["commands"] .as_array() .expect("commands") diff --git a/crates/ide-db/tests/sqlite.rs b/crates/ide-db/tests/integration/sqlite.rs similarity index 90% rename from crates/ide-db/tests/sqlite.rs rename to crates/ide-db/tests/integration/sqlite.rs index 56be982464..0a7fb35cf4 100644 --- a/crates/ide-db/tests/sqlite.rs +++ b/crates/ide-db/tests/integration/sqlite.rs @@ -1,10 +1,11 @@ //! Introspection, queries and table edits against a real SQLite file. -use ide_core::{CancellationToken, IdeResult}; +use ide_core::{CancellationToken, IdeResult, error::ErrorKind}; use ide_db::{ CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind, DbVisibilityChange, QueryResult, SortKey, }; +use std::time::Duration; async fn setup() -> (tempfile::TempDir, DbManager) { let tmp = tempfile::tempdir().unwrap(); @@ -527,3 +528,56 @@ async fn data_sources_edited_on_disk_close_their_connections() -> IdeResult<()> assert!(!db.reconcile_sources().await); Ok(()) } + +/// A read-only query whose future is dropped or cancelled mid-flight must not leave +/// `PRAGMA query_only` on a pooled connection: a later write through the pool still works. +#[tokio::test] +async fn a_dropped_or_cancelled_read_only_query_leaves_the_pool_writable() -> IdeResult<()> { + let (_tmp, db) = setup().await; + let pool = db.pool("s1").await?; + // CPU-bound and touches no table, so it holds no file lock while it runs. Large enough that + // it cannot finish within the 50 ms before the abort, even on a fast machine. + let slow = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000000) \ + SELECT count(*) FROM c"; + let spawn = |cancel: CancellationToken| { + let pool = pool.clone(); + tokio::spawn(async move { pool.execute_read_only(slow, 1, &cancel).await }) + }; + + // Dropped mid-query, as a timeout used to drop it. + let handle = spawn(CancellationToken::new()); + tokio::time::sleep(Duration::from_millis(50)).await; + handle.abort(); + let _ = handle.await; + + // Cancelled mid-query, as a cancelled MCP request does. + let cancel = CancellationToken::new(); + let handle = spawn(cancel.clone()); + tokio::time::sleep(Duration::from_millis(50)).await; + cancel.cancel(); + let error = handle.await.unwrap().expect_err("the cancelled query returns an error"); + assert_eq!(error.kind, ErrorKind::Cancelled); + + // Let either worker finish: a dropped session's connection must close, not return with + // query_only still on. Take every connection the pool has (4 pool + 4 console sessions) and + // read the PRAGMA, so a poisoned slot cannot hide in the unchecked rest. + tokio::time::sleep(Duration::from_millis(1500)).await; + let c = CancellationToken::new(); + let mut held = Vec::new(); + for _ in 0..8 { + let mut conn = ide_db::Held::acquire(&pool).await?; + let rows = conn.execute(&pool, "PRAGMA query_only", 1, &c).await?.rows; + assert_eq!(rows, vec![vec![Some("0".into())]], "a pooled connection kept query_only"); + held.push(conn); + } + drop(held); + + // A pool slot that kept query_only would answer SQLITE_READONLY, intermittently. + for n in 0..20 { + let sql = format!("INSERT INTO users (name) VALUES ('after{n}')"); + pool.execute(&sql, 1, &c).await?; + } + let rows = pool.execute("SELECT count(*) FROM users WHERE name LIKE 'after%'", 1, &c).await?.rows; + assert_eq!(rows, vec![vec![Some("20".into())]]); + Ok(()) +} diff --git a/crates/ide-db/tests/sqlite_console_sessions.rs b/crates/ide-db/tests/integration/sqlite_console_sessions.rs similarity index 100% rename from crates/ide-db/tests/sqlite_console_sessions.rs rename to crates/ide-db/tests/integration/sqlite_console_sessions.rs diff --git a/crates/ide-db/tests/sqlserver.rs b/crates/ide-db/tests/integration/sqlserver.rs similarity index 100% rename from crates/ide-db/tests/sqlserver.rs rename to crates/ide-db/tests/integration/sqlserver.rs diff --git a/crates/ide-db/tests/ssh_tunnel.rs b/crates/ide-db/tests/integration/ssh_tunnel.rs similarity index 100% rename from crates/ide-db/tests/ssh_tunnel.rs rename to crates/ide-db/tests/integration/ssh_tunnel.rs diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index 8b6881afab..be23e42335 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -187,6 +187,7 @@ pub const EVENT_KINDS: &[&str] = &[ "problems-changed", "project-closed", "watched-files-changed", + "project-tree-expanded", ]; impl std::fmt::Display for ActivationEvent { @@ -483,7 +484,8 @@ impl Manifest { { self.needs_api(&format!("`{event}`"), 18)?; } - if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output")) { + if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output" | "project-tree-expanded")) + { self.needs_api(&format!("`{event}`"), 21)?; } if !seen.insert(event) { @@ -705,6 +707,10 @@ mod tests { ); assert!(ActivationEvent::parse("on-event:document-changed").is_ok()); assert!(ActivationEvent::parse("on-event:websocket-ready").is_ok()); + assert_eq!( + ActivationEvent::parse("on-event:project-tree-expanded"), + Ok(ActivationEvent::Event("project-tree-expanded".into())) + ); let err = ActivationEvent::parse("on-event:keystroke").unwrap_err(); assert!(err.contains("unknown event kind") && err.contains("action-performed"), "{err}"); assert!(ActivationEvent::parse("on-event:scheduled").is_err(), "declared with on-schedule"); @@ -1126,6 +1132,21 @@ mod net_ask_api_tests { } } + #[test] + fn project_tree_expanded_requires_api_1_21() { + for engine in ["^1.20", "^1.21"] { + let manifest = format!( + "id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:project-tree-expanded\"]\n" + ); + let parsed = Manifest::parse(&manifest); + if engine == "^1.21" { + parsed.unwrap(); + } else { + assert!(parsed.unwrap_err().contains("new in plugin API 1.21"), "{engine}"); + } + } + } + #[test] fn doc_files_require_api_1_18_and_relative_paths() { for field in ["description-file", "change-notes-file"] { diff --git a/crates/ide-host/src/mcp/database.rs b/crates/ide-host/src/mcp/database.rs new file mode 100644 index 0000000000..9a3f566a67 --- /dev/null +++ b/crates/ide-host/src/mcp/database.rs @@ -0,0 +1,728 @@ +//! Database tools: the project's data sources, their schemas and objects, and read-only SQL. + +use crate::mcp::tool::{Call, Output, Param, ParamType, Tool}; +use ide_core::error::ErrorKind; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use ide_db::{DataSource, DbDriver, DbObjectKind, DbTableKind, SchemaObjects, split}; +use serde::Serialize; +use serde_json::{Value, json}; +use std::future::Future; +use std::time::Duration; + +const DEFAULT_MAX_ROWS: usize = 100; +const MAX_ROWS: usize = 1000; +/// UTF-16 units a cell keeps; the rest is reported in `truncated`. +const MAX_CELL_UNITS: usize = 4096; +const QUERY_TIMEOUT: Duration = Duration::from_secs(30); +/// Catalog reads can be slower than a query on a big schema; they do not run the user's SQL. +const METADATA_TIMEOUT: Duration = Duration::from_secs(60); +/// How long a cancelled or timed-out task gets to run its rollback / reset before the tool returns. +const STOP_GRACE: Duration = Duration::from_secs(5); + +pub fn tools() -> Vec { + vec![ + list_database_connections(), + list_database_schemas(), + list_schema_objects(), + get_database_object_description(), + execute_sql_query(), + ] +} + +/// The connection a tool may use. The id must be exactly one data source's id: `DbManager` +/// resolves `:` by prefix and takes the first matching entry, so a colon or a +/// duplicate id could reach an entry other than the one checked here (a plugin-owned source and +/// its credentials, for example). Plugin-owned sources stay out of these tools entirely. +fn connection(call: &Call, id: &str) -> IdeResult { + if id.contains(':') { + return Err(IdeError::invalid( + "connectionId must be one id from list_database_connections, without a `:database` part", + )); + } + let mut matches = call.project().db.sources()?.into_iter().filter(|source| source.id == id); + let Some(source) = matches.next() else { + return Err(IdeError::not_found(format!("no data source {id}"))); + }; + if matches.next().is_some() { + return Err(IdeError::invalid(format!( + "more than one data source has the id {id}; rename or remove one in the Database tool window" + ))); + } + if source.plugin_owner.is_some() { + return Err(IdeError::not_found(format!("no data source {id}"))); + } + source.resolved() +} + +/// The `database` value a tool may show: an Oracle Database field can hold a TNS descriptor, +/// which embeds the host and port. +fn database_field(source: &DataSource) -> String { + let database = source.database.trim(); + if source.driver == DbDriver::Oracle && (database.starts_with('(') || database.contains('=')) { + return String::new(); + } + source.database.clone() +} + +/// Replaces every ASCII-case-insensitive occurrence of `needle` in `haystack`. ASCII case folding +/// keeps byte lengths, so an offset found in the lowered copy is a valid boundary of the original. +fn replace_ascii_case_insensitive(haystack: &mut String, needle: &str, replacement: &str) { + let lowered = needle.to_ascii_lowercase(); + let mut from = 0; + loop { + let Some(at) = haystack[from..].to_ascii_lowercase().find(&lowered) else { return }; + let start = from + at; + haystack.replace_range(start..start + needle.len(), replacement); + from = start + replacement.len(); + } +} + +/// Replaces the data source's URL, host and user in an error before it reaches the agent: driver +/// and tunnel errors quote them (auth failures name the user, tunnel failures the host), in +/// whatever case the server reports (Oracle upper-cases user names). Percent-encoded forms are +/// redacted too, and the plain forms are matched case-insensitively. +fn redact_error(mut error: IdeError, source: &DataSource) -> IdeError { + let mut secrets = vec![source.url.trim().to_owned(), source.host.trim().to_owned(), source.user.trim().to_owned()]; + for value in [source.host.trim(), source.user.trim()] { + if !value.is_empty() { + secrets.push(percent_encode(value)); + } + } + for secret in secrets { + // Every configured value, however short: the tool text promises the user and host never + // appear, and a one- or two-character name is still a name. + if !secret.is_empty() { + replace_ascii_case_insensitive(&mut error.message, &secret, ""); + } + } + error +} + +fn percent_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(byte as char); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +/// Runs a catalog read with the request's cancellation and a time limit. The `DbManager` +/// metadata methods take no token; dropping their future closes the connection they were using. +async fn bounded(call: &Call, deadline: Duration, task: impl Future>) -> IdeResult { + tokio::select! { + biased; + () = call.cancel.cancelled() => Err(IdeError::cancelled()), + result = tokio::time::timeout(deadline, task) => match result { + Ok(result) => result, + Err(_) => Err(IdeError::new( + ErrorKind::TimedOut, + format!("the database did not answer within {} seconds", deadline.as_secs()), + )), + }, + } +} + +/// Runs a read-only query until it finishes, the request is cancelled, or `deadline` passes. On +/// either stop the driver's token is cancelled and its cleanup (rollback, reset, close) is +/// awaited, instead of dropping the future and leaving a driver's work running. +async fn until_stopped( + deadline: Duration, + cancel: &CancellationToken, + token: &CancellationToken, + task: impl Future>, +) -> IdeResult { + tokio::pin!(task); + tokio::select! { + biased; + result = &mut task => result, + () = cancel.cancelled() => { + token.cancel(); + let _ = tokio::time::timeout(STOP_GRACE, &mut task).await; + Err(IdeError::cancelled()) + } + () = tokio::time::sleep(deadline) => { + token.cancel(); + let _ = tokio::time::timeout(STOP_GRACE, &mut task).await; + Err(IdeError::new( + ErrorKind::TimedOut, + format!("the statement did not finish within {} seconds", deadline.as_secs()), + )) + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ConnectionInfo { + id: String, + name: String, + driver: DbDriver, + database: String, + read_only: bool, + global: bool, +} + +fn list_database_connections() -> Tool { + Tool::new( + "list_database_connections", + "Lists the project's database connections (data sources): `id`, `name`, `driver`, `database`, +`readOnly` and `global`. Needs a trusted project; in Restricted Mode the call is refused. +Use a connection's `id` as `connectionId` in the other database tools. +`database` is the source's configured database; it is empty when none is configured, and a source +configured only by a URL is not read here, so its URL does not appear. Global data sources are +stored app-wide, are listed in every project and carry `\"global\": true`. +Never returns passwords, secrets, URLs, hosts or user names.", + |call| async move { + call.project.require_trust()?; + let connections: Vec<_> = call + .project() + .db + .sources()? + .into_iter() + .filter(|source| source.plugin_owner.is_none()) + .map(|source| { + let database = database_field(&source); + ConnectionInfo { + id: source.id, + name: source.name, + driver: source.driver, + database, + read_only: source.read_only, + global: source.global, + } + }) + .collect(); + Output::json(json!({ "connections": connections })) + }, + ) +} + +fn list_database_schemas() -> Tool { + Tool::new( + "list_database_schemas", + "Lists the schemas a database connection exposes (its databases on MySQL and Oracle). +Returns `connectionId`, the configured `database`, and `schemas`. Needs a trusted project; in +Restricted Mode the call is refused.", + |call| async move { + call.project.require_trust()?; + let connection_id = call.str("connectionId")?; + let source = connection(&call, &connection_id)?; + let schemas = bounded(&call, METADATA_TIMEOUT, call.project().db.schemas(&connection_id)) + .await + .map_err(|e| redact_error(e, &source))?; + Output::json(json!({ + "connectionId": connection_id, + "database": database_field(&source), + "schemas": schemas, + })) + }, + ) + .param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`")) +} + +fn list_schema_objects() -> Tool { + Tool::new( + "list_schema_objects", + "Lists a schema's tables, views, materialized views, routines (functions and procedures), packages, sequences +and other objects, as `{ kind, name }`; table-like objects and routines also carry `comment`, `arguments` and +`returns` when the database has them. +Pass `kind` to filter (case-insensitive): `table`, `view`, `materializedView`, `function`, `procedure`, `package`, +`sequence`, `routine` (functions and procedures), or another object kind the database reports. An unknown kind +returns an empty list. Needs a trusted project; in Restricted Mode the call is refused.", + |call| async move { + call.project.require_trust()?; + let connection_id = call.str("connectionId")?; + let schema = call.str("schema")?; + let kind = call.opt_str("kind")?; + let source = connection(&call, &connection_id)?; + let db = &call.project().db; + let tables = bounded(&call, METADATA_TIMEOUT, db.tables(&connection_id, &schema)) + .await + .map_err(|e| redact_error(e, &source))?; + let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema)) + .await + .map_err(|e| redact_error(e, &source))?; + let objects = schema_objects(tables, objects, kind.as_deref()); + Output::json(json!({ + "connectionId": connection_id, + "schema": schema, + "objects": objects, + })) + }, + ) + .param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`")) + .param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`")) + .param(Param::optional( + "kind", + ParamType::String, + "Only objects of this kind: table, view, materializedView, function, procedure, package, sequence, routine", + )) +} + +fn schema_objects(tables: Vec, objects: SchemaObjects, wanted: Option<&str>) -> Vec { + let mut out = Vec::new(); + for table in tables { + let kind = match table.kind { + DbTableKind::Table => "table", + DbTableKind::View => "view", + DbTableKind::MaterializedView => "materializedView", + }; + if !kind_matches(wanted, kind) { + continue; + } + let mut object = json!({ "kind": kind, "name": table.name }); + if let Some(comment) = table.comment { + object["comment"] = json!(comment); + } + out.push(object); + } + for routine in objects.routines { + let kind = if routine.kind == DbObjectKind::Procedure { "procedure" } else { "function" }; + if !kind_matches(wanted, kind) { + continue; + } + let mut object = json!({ "kind": kind, "name": routine.name }); + if !routine.arguments.is_empty() { + object["arguments"] = json!(routine.arguments); + } + if let Some(returns) = routine.returns { + object["returns"] = json!(returns); + } + out.push(object); + } + for package in objects.packages { + if kind_matches(wanted, "package") { + out.push(json!({ "kind": "package", "name": package.name })); + } + } + for sequence in objects.sequences { + if kind_matches(wanted, "sequence") { + out.push(json!({ "kind": "sequence", "name": sequence.name })); + } + } + for object in objects.others { + if kind_matches(wanted, &object.kind) { + out.push(json!({ "kind": object.kind, "name": object.name })); + } + } + out +} + +fn kind_matches(wanted: Option<&str>, kind: &str) -> bool { + wanted.is_none_or(|wanted| { + wanted.eq_ignore_ascii_case(kind) + || (wanted.eq_ignore_ascii_case("routine") && matches!(kind, "function" | "procedure")) + }) +} + +fn get_database_object_description() -> Tool { + Tool::new( + "get_database_object_description", + "Describes a table, view or materialized view: columns (type, nullability, default, primary key and comment), +indexes, foreign keys, triggers and the object's comment, plus the owner, tablespace, access method, +storage options and partitioning when the database reports them. +Describing routines, packages and sequences is not supported yet. Needs a trusted project; in +Restricted Mode the call is refused.", + |call| async move { + call.project.require_trust()?; + let connection_id = call.str("connectionId")?; + let schema = call.str("schema")?; + let object_name = call.str("objectName")?; + if let Some(kind) = call.opt_str("kind")? + && !is_table_like_kind(&kind) + { + return Err(description_unsupported(&kind)); + } + let source = connection(&call, &connection_id)?; + let db = &call.project().db; + let details = bounded(&call, METADATA_TIMEOUT, db.table_details(&connection_id, &schema, &object_name)) + .await + .map_err(|e| redact_error(e, &source))?; + if details.columns.is_empty() { + let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema)) + .await + .map_err(|e| redact_error(e, &source))?; + if let Some(kind) = schema_object_kind(&objects, &object_name) { + return Err(description_unsupported(kind)); + } + return Err(IdeError::not_found(format!("{schema}.{object_name}"))); + } + Output::json(json!({ + "connectionId": connection_id, + "schema": schema, + "objectName": object_name, + "details": details, + })) + }, + ) + .param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`")) + .param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`")) + .param(Param::required("objectName", ParamType::String, "Table, view or materialized view name")) + .param(Param::optional( + "kind", + ParamType::String, + "Object kind from `list_schema_objects`; only table, view and materializedView are described", + )) +} + +fn is_table_like_kind(kind: &str) -> bool { + ["table", "view", "materializedView"].iter().any(|known| kind.eq_ignore_ascii_case(known)) +} + +fn schema_object_kind<'a>(objects: &'a SchemaObjects, name: &str) -> Option<&'a str> { + if objects.routines.iter().any(|routine| routine.name == name) { + return Some("routine"); + } + if objects.packages.iter().any(|package| package.name == name) { + return Some("package"); + } + if objects.sequences.iter().any(|sequence| sequence.name == name) { + return Some("sequence"); + } + objects.others.iter().find(|object| object.name == name).map(|object| object.kind.as_str()) +} + +fn description_unsupported(kind: &str) -> IdeError { + IdeError::invalid(format!( + "describing a {kind} is not supported yet; this tool describes tables, views and materialized views only" + )) +} + +fn execute_sql_query() -> Tool { + Tool::new( + "execute_sql_query", + "Runs one read-only SQL statement (SELECT, WITH or EXPLAIN) against a data source after the user confirms +the exact statement. It runs in a driver-enforced read-only session on SQLite, PostgreSQL, MySQL/MariaDB and +Oracle; other drivers are refused. Multiple statements, writes and DDL are refused. On Oracle, EXPLAIN is +refused (EXPLAIN PLAN writes PLAN_TABLE). On MySQL/MariaDB, executable comments (`/*! … */`, `/*M! … */`) and +INTO OUTFILE/INTO DUMPFILE are refused, and the connection is pinned to utf8mb4 so the server reads the +statement exactly as the splitter did. MySQL/MariaDB and MySQL-compatible servers are supported only when +they accept `SET NAMES utf8mb4` and report a read-only transaction (`transaction_read_only` or +`tx_read_only`); otherwise this tool refuses. On PostgreSQL, the connection is pinned to `client_encoding` +UTF8 with `standard_conforming_strings = on`, and the server parses the statement as one command before it +runs, so a difference from the splitter's lexing is refused rather than executed. The metadata tools are +unaffected. \"Read-only\" means no +changes to tables, views and schema through the statement; functions with server-side side effects (for +example PostgreSQL lo_export, Oracle UTL_FILE, MySQL LOAD_FILE) are outside that guarantee. Use a database +account with read-only privileges for agent access: the IDE's read-only session is defense in depth, not a +full sandbox. +Returns at most `maxRows` rows (default 100, clamped to 1000), each cell cut to 4096 UTF-16 units. The query +is cancelled after 30 seconds, with up to 5 seconds more to roll back and close. The result and errors never +include the data source URL, host or user.", + execute_query, + ) + .write() + .param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`")) + .param(Param::required( + "sql", + ParamType::String, + "One read-only statement: SELECT, WITH or EXPLAIN; leading SQL comments are allowed", + )) + .param(Param::optional( + "maxRows", + ParamType::Integer, + "Rows to return at most (default 100, clamped to 1..=1000)", + )) +} + +async fn execute_query(call: Call) -> IdeResult { + let connection_id = call.str("connectionId")?; + let sql = call.str("sql")?; + let max_rows = match call.opt_i64("maxRows")? { + Some(rows) => rows.clamp(1, MAX_ROWS as i64) as usize, + None => DEFAULT_MAX_ROWS, + }; + let source = connection(&call, &connection_id)?; + if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) { + return Err(IdeError::invalid(format!( + "{} has no read-only session; execute_sql_query runs on SQLite, PostgreSQL, MySQL/MariaDB and Oracle only", + source.driver.display_name() + ))); + } + if source.driver == DbDriver::Mysql { + // The server executes these even though `split` reads them as comments or literals. + split::mysql_guard(&sql)?; + } + let statements = split::split(&sql, source.driver); + let statement = match statements.as_slice() { + [] => return Err(IdeError::invalid("the SQL is empty")), + [statement] => statement, + _ => { + return Err(IdeError::invalid(format!( + "exactly one statement is allowed, but the SQL has {}", + statements.len() + ))); + } + }; + match leading_keyword(&statement.text, source.driver) { + Some(keyword) if matches!(keyword.as_str(), "SELECT" | "WITH" | "EXPLAIN") => { + if source.driver == DbDriver::Oracle && keyword == "EXPLAIN" { + return Err(IdeError::invalid("EXPLAIN is not allowed on Oracle: EXPLAIN PLAN writes PLAN_TABLE")); + } + } + Some(keyword) => { + return Err(IdeError::invalid(format!( + "{keyword} is not allowed: execute_sql_query runs SELECT, WITH and EXPLAIN statements only" + ))); + } + None => { + return Err(IdeError::invalid("execute_sql_query runs SELECT, WITH and EXPLAIN statements only")); + } + } + let database = database_field(&source); + let database = if database.is_empty() { "(default)" } else { database.as_str() }; + let detail = format!("Driver: {}\nDatabase: {database}\nSQL:\n{}", source.driver.display_name(), statement.text); + call.confirm(&format!("SQL on {}", source.name), Some(detail)).await?; + + let token = call.cancel.child_token(); + let work = call.project().db.execute_read_only_query(&connection_id, &statement.text, max_rows, &token); + let mut result = + until_stopped(QUERY_TIMEOUT, &call.cancel, &token, work).await.map_err(|e| redact_error(e, &source))?; + result.cap_cells(MAX_CELL_UNITS); + let row_count = result.rows.len(); + Output::json(json!({ + "connectionId": connection_id, + "statement": result.statement, + "columns": result.columns, + "rows": result.rows, + "rowCount": row_count, + "hasMore": result.has_more, + "truncated": result.truncated, + "elapsedMs": result.elapsed_ms, + "affected": result.affected, + })) +} + +/// The first keyword of `sql`, past leading whitespace and SQL comments, uppercased. +fn leading_keyword(sql: &str, driver: DbDriver) -> Option { + let mut text = sql; + loop { + text = text.trim_start(); + if let Some(comment) = text.strip_prefix("--") { + // PostgreSQL ends a line comment at `\r` as well as `\n` (`scan.l`), as `split` does; + // the other drivers keep a bare `\r` in the comment. + let end = comment + .char_indices() + .find(|&(_, c)| c == '\n' || (driver == DbDriver::Postgres && c == '\r')) + .map_or(comment.len(), |(at, _)| at); + text = &comment[end..]; + } else if let Some(comment) = text.strip_prefix('#') { + text = comment.split_once('\n').map_or("", |(_, rest)| rest); + } else if let Some(comment) = text.strip_prefix("/*") { + text = after_block_comment(comment); + } else { + let end = text.find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '$'))).unwrap_or(text.len()); + return (end > 0).then(|| text[..end].to_ascii_uppercase()); + } + } +} + +/// The text after a `/*` comment, past nested block comments (`/* /* */ */`). +fn after_block_comment(mut text: &str) -> &str { + let mut depth = 1usize; + while let Some(at) = text.find(['/', '*']) { + text = &text[at..]; + if let Some(rest) = text.strip_prefix("/*") { + depth += 1; + text = rest; + } else if let Some(rest) = text.strip_prefix("*/") { + depth -= 1; + text = rest; + if depth == 0 { + return text; + } + } else { + text = &text[1..]; + } + } + "" +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exposes_exactly_the_five_database_tools() { + let names: Vec<_> = tools().into_iter().map(|tool| tool.metadata.name).collect(); + assert_eq!( + names, + [ + "list_database_connections", + "list_database_schemas", + "list_schema_objects", + "get_database_object_description", + "execute_sql_query", + ] + ); + } + + #[test] + fn only_execute_sql_query_is_not_read_only() { + for tool in tools() { + assert_eq!(tool.metadata.read_only, tool.metadata.name != "execute_sql_query", "{}", tool.metadata.name); + } + } + + #[test] + fn execute_sql_query_requires_a_connection_and_a_statement() { + let tool = tools().into_iter().find(|tool| tool.metadata.name == "execute_sql_query").unwrap(); + let required = tool.metadata.input_schema["required"].as_array().unwrap(); + for name in ["connectionId", "sql"] { + assert!(required.iter().any(|value| value == name), "{name}"); + assert_eq!(tool.metadata.input_schema["properties"][name]["type"], "string", "{name}"); + } + } + + #[test] + fn accepts_select_with_and_explain_past_comments() { + for sql in [ + "SELECT 1", + "-- note\nSELECT 1", + "/* outer /* nested */ comment */ WITH x AS (SELECT 1) SELECT * FROM x", + " \n\t EXPLAIN SELECT 1", + ] { + assert!( + matches!(leading_keyword(sql, DbDriver::Postgres).as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")), + "{sql}" + ); + } + } + + /// PostgreSQL ends a leading `--` comment at `\r` too, like the fixed splitter. + #[test] + fn a_carriage_return_ends_a_postgres_leading_comment() { + assert_eq!(leading_keyword("-- note\rSELECT 1", DbDriver::Postgres).as_deref(), Some("SELECT")); + for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::SqlServer] { + assert_eq!(leading_keyword("-- note\rSELECT 1", driver), None, "{driver:?}"); + } + } + + #[test] + fn refuses_other_leading_keywords() { + for sql in [ + "INSERT INTO t VALUES (1)", + "UPDATE t SET x = 1", + "DELETE FROM t", + "CREATE TABLE t (x INT)", + "CALL p()", + "COPY t FROM stdin", + "PRAGMA query_only = ON", + "# comment\nUPDATE t SET x = 1", + ] { + let keyword = leading_keyword(sql, DbDriver::Postgres); + assert!(!matches!(keyword.as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")), "{sql}: {keyword:?}"); + } + } + + #[test] + fn errors_hide_the_url_host_and_user() { + let source = DataSource { + driver: DbDriver::Postgres, + host: "db.example.invalid".into(), + user: "alice@example.com".into(), + url_only: true, + url: "postgres://alice%40example.com:pw@db.example.invalid:5432/app".into(), + ..Default::default() + }; + for message in [ + "[28P01] password authentication failed for user \"alice@example.com\"".to_owned(), + "connection to server at db.example.invalid (10.0.0.5), port 5432 failed".to_owned(), + "user alice%40example.com cannot log in".to_owned(), + "ALICE%40EXAMPLE.COM cannot log in".to_owned(), + "Alice%40Example.com cannot log in".to_owned(), + "DB.EXAMPLE.INVALID refused the connection".to_owned(), + "could not open postgres://alice%40example.com:pw@db.example.invalid:5432/app".to_owned(), + ] { + let error = redact_error(IdeError::invalid(message.clone()), &source); + let lower = error.message.to_ascii_lowercase(); + for secret in ["alice", "db.example.invalid", "pw@db"] { + assert!(!lower.contains(secret), "{message} -> {}", error.message); + } + } + // However short: a one- or two-character name is still a configured name. + let short = DataSource { host: "q".into(), user: "ab".into(), ..Default::default() }; + let error = + redact_error(IdeError::invalid("password authentication failed for user \"ab\" at q".to_owned()), &short); + assert!(!error.message.to_ascii_lowercase().contains("ab"), "{}", error.message); + assert!(!error.message.contains('q'), "{}", error.message); + assert!(error.message.contains(""), "{}", error.message); + } + + #[test] + fn an_oracle_tns_descriptor_is_not_shown_as_the_database() { + let mut source = DataSource { + driver: DbDriver::Oracle, + database: "(DESCRIPTION=(HOST=db.local))".into(), + ..Default::default() + }; + assert_eq!(database_field(&source), ""); + source.database = "PROD=(DESCRIPTION=(HOST=db.local))".into(); + assert_eq!(database_field(&source), ""); + source.database = "ORCLPDB1".into(); + assert_eq!(database_field(&source), "ORCLPDB1"); + } + + #[tokio::test] + async fn a_deadline_cancels_the_task_and_awaits_its_cleanup() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let cancel = CancellationToken::new(); + let token = cancel.child_token(); + let cleaned = Arc::new(AtomicBool::new(false)); + let task = { + let (token, cleaned) = (token.clone(), cleaned.clone()); + async move { + token.cancelled().await; + cleaned.store(true, Ordering::SeqCst); + Err::<(), _>(IdeError::cancelled()) + } + }; + let error = until_stopped(Duration::from_millis(20), &cancel, &token, task).await.unwrap_err(); + assert_eq!(error.kind, ErrorKind::TimedOut); + assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the timeout returned"); + } + + #[tokio::test] + async fn cancelling_the_request_cancels_the_task() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let cancel = CancellationToken::new(); + let token = cancel.child_token(); + let cleaned = Arc::new(AtomicBool::new(false)); + let task = { + let (token, cleaned) = (token.clone(), cleaned.clone()); + async move { + token.cancelled().await; + cleaned.store(true, Ordering::SeqCst); + Err::<(), _>(IdeError::cancelled()) + } + }; + let canceller = cancel.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(20)).await; + canceller.cancel(); + }); + let error = until_stopped(Duration::from_secs(30), &cancel, &token, task).await.unwrap_err(); + assert_eq!(error.kind, ErrorKind::Cancelled); + assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the call returned"); + } + + #[test] + fn kind_filter_is_case_insensitive_and_routine_covers_functions_and_procedures() { + assert!(kind_matches(None, "table")); + assert!(kind_matches(Some("materializedview"), "materializedView")); + assert!(kind_matches(Some("ROUTINE"), "function")); + assert!(kind_matches(Some("routine"), "procedure")); + assert!(!kind_matches(Some("routine"), "table")); + assert!(!kind_matches(Some("stage"), "table")); + } +} diff --git a/crates/ide-host/src/mcp/mod.rs b/crates/ide-host/src/mcp/mod.rs index 5d92615ec4..888ae662c7 100644 --- a/crates/ide-host/src/mcp/mod.rs +++ b/crates/ide-host/src/mcp/mod.rs @@ -2,6 +2,7 @@ mod automations; mod background; mod check; +mod database; mod debug; mod devcontainer; mod edit; @@ -55,6 +56,7 @@ fn tools(local_desktop: bool) -> Vec { tools.extend(run::tools()); tools.extend(vcs::tools()); tools.extend(http::tools()); + tools.extend(database::tools()); if local_desktop { tools.extend(devcontainer::tools()); } diff --git a/crates/ide-host/src/ops/doc/commands.rs b/crates/ide-host/src/ops/doc/commands.rs index fbbf81fc8b..75c5e26661 100644 --- a/crates/ide-host/src/ops/doc/commands.rs +++ b/crates/ide-host/src/ops/doc/commands.rs @@ -8,6 +8,7 @@ use ide_text::LineEnding; use ide_workspace::settings::SettingsScope; use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry}; use std::path::{Path, PathBuf}; +use std::sync::Arc; /// Opens a read-only virtual document (see `lsp_virtual_document`) as an /// editor buffer, so syntax features and language-server requests work in it. @@ -165,7 +166,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult Vec::new(), - None => syntax(), + None => Arc::unwrap_or_clone(syntax()), }) }) .await @@ -186,7 +187,7 @@ pub async fn doc_folding(host: &Host, window: &str, doc: DocId) -> IdeResult) -> Vec { /// Gutter markers of plugin `line-markers` providers for an open document. #[command(trust = trusted)] -pub async fn plugin_line_markers( - host: &Host, - window: &str, - doc: DocId, -) -> IdeResult> { +pub async fn plugin_line_markers(host: &Host, window: &str, doc: DocId) -> IdeResult { let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::LineMarkers) else { - return Ok(Vec::new()); + return Ok(Default::default()); }; - let markers = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default(); - Ok(markers + let (markers, late) = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default(); + let markers = markers .into_iter() .map(|(plugin_id, m)| crate::plugins::LineMarkerInfo { plugin_id, @@ -715,7 +711,25 @@ pub async fn plugin_line_markers( tooltip: m.tooltip, target: m.target.map(|l| Location { path: l.path.into(), range: l.range, uri: None }), }) - .collect()) + .collect(); + Ok(crate::plugins::LineMarkers { markers, late }) +} + +/// The languages whose plugin line markers a save of `path` can change: those a plugin declares for +/// `line-markers` along with the file's language (`"*"` for every language). Does not load plugin +/// code. By path, not document: closing a tab saves it and then closes its document. +#[command(trust = trusted)] +pub async fn plugin_line_marker_languages( + host: &Host, + window: &str, + path: std::path::PathBuf, +) -> IdeResult> { + let Some(plugins) = editor_providers(ProviderKind::LineMarkers) else { + return Ok(Vec::new()); + }; + let project = host.project(window)?; + let language = blocking(move || Ok(project.documents.language_of(&path, None).language.0)).await?; + Ok(plugins.line_marker_languages_with(&language)) } /// Where other files import the document's file (Find Usages on a file, a Vue component's @@ -776,6 +790,26 @@ pub async fn lsp_spring_bean_markers( result } +/// The document's Spring AOP markers (advised methods with their advices, advice methods with +/// the methods they advise); `None` when no server attached to it provides them. Cancel with +/// `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn lsp_spring_aop_markers( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, +) -> IdeResult>> { + let lsp = host.project(window)?.lsp.clone(); + let cancel = host.begin_request(request); + let result = tokio::select! { + result = lsp.spring_aop_markers(doc, cancel.clone()) => result, + _ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()), + }; + host.end_request(request); + result +} + /// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos` /// instead of its `.d.ts`. Cancel with `cancel_request(request)`. #[command(trust = trusted)] @@ -1780,6 +1814,48 @@ pub async fn lsp_hierarchy_refactor( .await } +/// What can move at `pos` and where it can go (java-analyzer's `moveInfo`). +#[command(trust = trusted)] +pub async fn lsp_move_info(host: &Host, window: &str, request: RequestId, doc: DocId, pos: Pos) -> IdeResult { + let project = host.project(window)?; + let cancel = host.begin_request(request); + let result = project.lsp.java_move_info(doc, pos, cancel).await; + host.end_request(request); + result +} + +/// Checks the chosen move and computes its edit (java-analyzer's `move`). +#[command(trust = trusted)] +pub async fn lsp_move_edit( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, + pos: Pos, + destination: MoveChoice, +) -> IdeResult { + let project = host.project(window)?; + let documents = project.documents.clone(); + let version = blocking(move || documents.version(doc)).await?; + let cancel = host.begin_request(request); + let result = project.lsp.java_move_refactor(doc, pos, destination, cancel).await; + host.end_request(request); + let mut refactored = result?; + blocking(move || { + if project.documents.version(doc)? != version { + return Err(ide_core::IdeError::new( + ide_core::error::ErrorKind::OutOfSync, + "document changed while computing the refactoring; request it again", + )); + } + if let Some(edit) = &mut refactored.edit { + project.documents.prepare_workspace_edit(edit)?; + } + Ok(refactored) + }) + .await +} + #[command(trust = trusted)] pub async fn lsp_signature_info( host: &Host, @@ -3752,10 +3828,13 @@ ide_command::domain!( lsp_gotos, lsp_hierarchy_members, lsp_hierarchy_refactor, + lsp_move_info, + lsp_move_edit, lsp_hover, lsp_implementation_locations, lsp_file_references, lsp_spring_bean_markers, + lsp_spring_aop_markers, lsp_switch_source_header, lsp_source_definition, lsp_open_typescript_file, @@ -3791,6 +3870,7 @@ ide_command::domain!( plugin_color_presentations, plugin_formatters, plugin_language_visuals, + plugin_line_marker_languages, plugin_line_markers, prepare_workspace_edit, redo_workspace_edit, diff --git a/crates/ide-host/src/ops/scaffold.rs b/crates/ide-host/src/ops/scaffold.rs index 72546bf1bc..e903bfada2 100644 --- a/crates/ide-host/src/ops/scaffold.rs +++ b/crates/ide-host/src/ops/scaffold.rs @@ -33,8 +33,35 @@ pub async fn scaffold_options( /// The programs a generator needs for `values`, and whether they are installed. #[command(trust = always)] -pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult> { - blocking(move || ide_scaffold::requirements(&generator, &values)).await +pub async fn scaffold_requirements(host: &Host, generator: String, values: Values) -> IdeResult> { + let configured = configured_goroot(host); + blocking(move || { + let goroot = goroot(configured, &generator, &values); + ide_scaffold::requirements(&generator, &values, goroot.as_deref()) + }) + .await +} + +/// The GOROOT chosen in the global settings (those of new projects). +fn configured_goroot(host: &Host) -> Option { + host.global_settings.read_effective(|s| ide_sdk::apply::absolute_setting_path(&s.languages.go.goroot)) +} + +/// The Go a generator that needs `go` runs: the GOROOT chosen in Settings; else `go` from `PATH`, +/// where a version manager picks it for the target folder; else, with no `go` on `PATH` (an app +/// started from the Dock or Finder), the first Go install found on this machine, as listed in +/// Settings › Languages › Go. Blocking: detection runs `go version`. +fn goroot(configured: Option, generator: &str, values: &Values) -> Option { + configured.or_else(|| { + if !ide_scaffold::needs_program(generator, values, "go") { + return None; + } + let path = ide_core::process::host_var_os("PATH").unwrap_or_default(); + if ide_core::process::find_executable("go", &path).is_some() { + return None; + } + ide_sdk::detect(ide_sdk::SdkKind::Go, None).into_iter().find_map(|sdk| sdk.home.map(IpcPath::into_path_buf)) + }) } /// Whether a project named `name` cannot be created in `location`: something other than an @@ -61,8 +88,10 @@ pub async fn scaffold_create( ) -> IdeResult { // Trusted because the user just created it; a failed or cancelled run leaves no files behind. let cancel = host.begin_request(request); + let configured = configured_goroot(host); let result = blocking(move || { - ide_scaffold::create(&req, &cancel, &|e| { + let goroot = goroot(configured, &req.generator, &req.values); + ide_scaffold::create(&req, goroot.as_deref(), &cancel, &|e| { let _ = on_event.send(e); }) }) diff --git a/crates/ide-host/src/ops/svn.rs b/crates/ide-host/src/ops/svn.rs index c70a3b47a3..f243b1fb10 100644 --- a/crates/ide-host/src/ops/svn.rs +++ b/crates/ide-host/src/ops/svn.rs @@ -148,9 +148,10 @@ pub async fn svn_upgrade( version: String, ) -> IdeResult<()> { let project = host.project(window)?; - let cancel = host.begin_request(request); + project.require_trust()?; + let cancel = host.begin_project_request(window, request); let result = blocking(move || { - with_working_copy(&project, Some(&repo), |wc| wc.upgrade(&version, &cancel))?; + with_working_copy(&project, Some(&repo), |wc| wc.upgrade(&repo, &version, &cancel))?; project.vcs_changed(); Ok(()) }) @@ -844,6 +845,11 @@ pub struct SvnIncomingPath { /// The file in the working copy, for a path under the working copy's URL. pub local: Option, pub kind: String, + /// The repository path it was copied from (`svn copy`, or the new half of a move). + #[serde(default)] + pub copy_from: Option, + #[serde(default)] + pub copy_from_revision: Option, } /// The Incoming tab's revisions of every Subversion working copy, and the working copies that @@ -877,6 +883,8 @@ fn incoming_revision(root: &str, r: ide_svn::IncomingRevision) -> SvnIncomingRev path: p.path, local: p.local.map(|l| l.display().to_string()), kind: p.kind, + copy_from_revision: p.copy_from.as_ref().map(|(_, r)| u32::try_from(*r).unwrap_or(u32::MAX)), + copy_from: p.copy_from.map(|(path, _)| path), }) .collect(), } @@ -895,7 +903,7 @@ pub async fn svn_revisions_between( ) -> IdeResult> { let project = host.project(window)?; project.require_trust()?; - let cancel = host.begin_request(request); + let cancel = host.begin_project_request(window, request); let result = blocking(move || { with_working_copy(&project, Some(&repo), |wc| { let root = wc.root().display().to_string(); @@ -908,23 +916,42 @@ pub async fn svn_revisions_between( result } -/// Incoming: for each Subversion working copy, the revisions committed to its URL after its -/// BASE revision, from BASE+1 to HEAD, as IntelliJ's Incoming tab lists them. +/// Incoming: for each Subversion working copy, the revisions the server has that it does not, as +/// IntelliJ's Incoming tab lists them. The working copies are read side by side, so one whose +/// server does not answer does not hold up the others. `quiet` (the tab reading by itself, not a +/// Refresh) asks for no login: a working copy that needs one shows the error instead. #[command(trust = trusted)] pub async fn svn_incoming_revisions( host: &Host, window: &str, request: ide_core::RequestId, + quiet: bool, ) -> IdeResult { let project = host.project(window)?; project.require_trust()?; - let cancel = host.begin_request(request); + let cancel = host.begin_project_request(window, request); let result = blocking(move || { + let backends = project.backends(); + let read = |wc: &WorkingCopy| { + if quiet { ide_svn::quietly(|| wc.incoming_revisions(&cancel)) } else { wc.incoming_revisions(&cancel) } + }; + let results: Vec<(String, IdeResult>)> = std::thread::scope(|scope| { + let running: Vec<_> = backends + .iter() + .filter_map(|backend| as_svn(backend.as_ref())) + .map(|wc| (wc.root().display().to_string(), scope.spawn(|| read(wc)))) + .collect(); + running + .into_iter() + .map(|(root, handle)| { + let result = handle.join().unwrap_or_else(|_| Err(ide_core::IdeError::internal("svn read failed"))); + (root, result) + }) + .collect() + }); let mut out = SvnIncomingRevisions::default(); - for backend in project.backends() { - let Some(wc) = as_svn(backend.as_ref()) else { continue }; - let root = wc.root().display().to_string(); - match wc.incoming_revisions(&cancel) { + for (root, result) in results { + match result { Ok(found) => out.revisions.extend(found.into_iter().map(|r| incoming_revision(&root, r))), Err(e) if cancel.is_cancelled() => return Err(e), Err(e) => out.errors.push(SvnWorkingCopyError { root, message: e.message }), @@ -938,24 +965,33 @@ pub async fn svn_incoming_revisions( result } -/// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project. +/// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project, +/// with their switched folders; `request` stops the scan for those. #[command(trust = trusted)] pub async fn svn_working_copy_info( host: &Host, window: &str, + request: ide_core::RequestId, repo: Option, ) -> IdeResult> { let project = host.project(window)?; project.require_trust()?; - blocking(move || { + let cancel = host.begin_project_request(window, request); + let result = blocking(move || { if let Some(path) = repo.as_deref() { - return with_working_copy(&project, Some(path), |wc| Ok(vec![wc.working_copy_info_for(path)?.into()])); + return with_working_copy(&project, Some(path), |wc| { + Ok(vec![SvnWorkingCopyInfo { + formats: wc.supported_formats(), + ..wc.working_copy_info_for(path)?.into() + }]) + }); } let mut infos: Vec = Vec::new(); for backend in project.backends() { if let Some(wc) = as_svn(backend.as_ref()) { // One working copy that cannot be read shows its error; the others still show. - match wc.working_copy_infos() { + match wc.working_copy_infos(&cancel) { + Err(e) if cancel.is_cancelled() => return Err(e), Ok(found) => { let formats = wc.supported_formats(); infos.extend( @@ -975,7 +1011,9 @@ pub async fn svn_working_copy_info( mark_externals(&mut infos); Ok(infos) }) - .await + .await; + host.end_request(request); + result } /// A working copy root inside another listed working copy is an external of it: svn checks @@ -1245,7 +1283,7 @@ pub async fn svn_update_options( on_output: crate::ops::Channel, ) -> IdeResult { let project = host.project(window)?; - let cancel = host.begin_request(request); + let cancel = host.begin_project_request(window, request); let result = blocking(move || { let report = |line: String| { let _ = on_output.send(line); diff --git a/crates/ide-host/src/ops/term.rs b/crates/ide-host/src/ops/term.rs index 69b6353f1b..319d8e3198 100644 --- a/crates/ide-host/src/ops/term.rs +++ b/crates/ide-host/src/ops/term.rs @@ -74,11 +74,13 @@ pub(crate) fn apply_output_rate(host: &Host, window: &str) { } /// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the -/// built-in client with the configuration's saved password, key or agent. +/// built-in client with the configuration's saved password, key or agent. With `cwd` (Remote +/// Host › Start SSH Session in Directory) the shell starts in that remote folder. pub async fn spawn_ssh( host: &Host, window: &str, id: &str, + cwd: Option<&str>, cols: u16, rows: u16, on_output: Emit, @@ -93,7 +95,7 @@ pub async fn spawn_ssh( let out = feed.clone(); let process = session .spawn( - "", + &ssh_shell_command(cwd), Some(size), Box::new(move |chunk| match chunk { ide_ssh::Output::Stdout(data) | ide_ssh::Output::Stderr(data) => out.output(data), @@ -134,6 +136,16 @@ pub async fn spawn_ssh( ) } +/// The exec command of an SSH terminal: empty for the account's shell, or a `cd` into `cwd` that +/// then replaces itself with the login shell. A `cd` that fails prints its error and leaves the +/// shell in the home folder. +fn ssh_shell_command(cwd: Option<&str>) -> String { + match cwd.map(str::trim).filter(|d| !d.is_empty()) { + None => String::new(), + Some(dir) => format!("cd -- {}; exec \"${{SHELL:-/bin/sh}}\" -l", ide_ssh::shell::tilde_quote(dir)), + } +} + enum SshInput { Data(Vec), Resize(u16, u16), diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index be576b57e4..9e85996371 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -367,6 +367,18 @@ pub struct UpdateReport { pub from_revision: Option, #[serde(default)] pub to_revision: Option, + /// Externals the update fetched, each with its own revision. + #[serde(default)] + pub externals: Vec, +} + +/// The files of an external an update fetched: another repository, at its own revision. +#[derive(Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ExternalUpdateReport { + pub root: PathBuf, + pub items: Vec, + pub to_revision: Option, } /// One file or folder of an [`UpdateReport`]: `action` is svn's four status columns as it @@ -376,6 +388,18 @@ pub struct UpdateReport { pub struct UpdatedItemReport { pub path: PathBuf, pub action: String, + /// Its path in the repository (`/trunk/src/a.txt`), when known. + #[serde(default)] + pub repo_path: Option, + /// Its own revision before the update, when not the working copy's (`from_revision`). + #[serde(default)] + pub from_revision: Option, +} + +impl From for UpdatedItemReport { + fn from(i: ide_vcs::UpdatedItem) -> Self { + Self { path: i.path, action: i.action, repo_path: i.repo_path, from_revision: i.from_revision } + } } #[derive(Serialize, Deserialize, Type)] @@ -2040,13 +2064,18 @@ pub async fn vcs_remote( b.update(paths, &cancel, &out).map(|summary| { Some(RemoteOpReport::Update(UpdateReport { updated_files: u32::try_from(summary.changed).unwrap_or(u32::MAX), - items: summary - .items - .into_iter() - .map(|i| UpdatedItemReport { path: i.path, action: i.action }) - .collect(), + items: summary.items.into_iter().map(Into::into).collect(), from_revision: summary.from_revision, to_revision: summary.to_revision, + externals: summary + .externals + .into_iter() + .map(|e| ExternalUpdateReport { + root: e.root, + items: e.items.into_iter().map(Into::into).collect(), + to_revision: e.to_revision, + }) + .collect(), })) }) }) diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index f9fd2368ca..9919a406af 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -80,6 +80,17 @@ pub trait PluginWorkspace: Send + Sync { ) -> Result { Err(HostError::Failed("agent fork unavailable".into())) } + /// Start a new agent task in the invoking window's project, unsent, and open it in + /// the Agents window for the user to review and send (API 1.21). + fn start_agent_task( + &self, + _client: &str, + _provider: &str, + _prompt: &str, + _fork: Option<(&str, &Path)>, + ) -> Result { + Err(HostError::Failed("agent task unavailable".into())) + } /// Roots of the open projects. fn projects(&self) -> Vec; @@ -303,6 +314,16 @@ const DEFAULT_STREAM_BUFFER: usize = 256 << 10; const DEFAULT_STREAM_MAX_TOTAL: usize = 32 << 20; /// Most processes one plugin keeps running at once. const MAX_PROCESSES: usize = 8; +/// Pending `events.schedule` timers per plugin. +const MAX_TIMERS: usize = 16; + +/// A pending `events.schedule` timer: fires `id` in window `client` at `due`. +#[derive(Clone, Debug)] +pub(super) struct Timer { + pub id: String, + pub due: Instant, + pub client: Option, +} /// Most output one stream of a handle holds until the plugin reads it. const MAX_PENDING: usize = 1 << 20; /// Most files `find-files` walks before giving up. @@ -799,6 +820,8 @@ pub(super) struct Shared { pub subscriptions: Mutex, /// Paths outside their project that plugins watch (kept across idle reclaim). pub(super) external_watches: super::external_watch::ExternalWatches, + /// plugin → its pending `events.schedule` timers (kept across idle reclaim). + pub(super) timers: Mutex>>, /// plugin → files it shows problems for, withdrawn when it stops. diagnostics: Mutex>>, project_generations: Mutex>, @@ -907,6 +930,7 @@ impl Shared { closed_clients: Mutex::default(), subscriptions: Mutex::default(), external_watches: Default::default(), + timers: Mutex::default(), diagnostics: Mutex::default(), project_generations: Mutex::default(), log_tabs: Mutex::default(), @@ -1053,6 +1077,9 @@ impl Shared { self.prompts.lock().retain(|_, entry| entry.client != client); drop(closed); self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client)); + for timers in self.timers.lock().values_mut() { + timers.retain(|t| t.client.as_deref() != Some(client)); + } self.loopbacks.read().forget_window(client); self.window_status.lock().retain(|(window, ..), _| window != client); self.view_badges.lock().retain(|(window, ..), _| window != client); @@ -1109,6 +1136,24 @@ impl Shared { .retain(|(p, w), _| plugin.is_some_and(|plugin| plugin != p) || window.is_some_and(|window| window != w)); } + /// Removes the timers due at `now`: (plugin, window, id), earliest first. + pub(super) fn take_due_timers(&self, now: Instant) -> Vec<(String, Option, String)> { + let mut due = Vec::new(); + let mut all = self.timers.lock(); + for (plugin, timers) in all.iter_mut() { + timers.retain(|t| { + if t.due > now { + return true; + } + due.push((t.due, plugin.clone(), t.client.clone(), t.id.clone())); + false + }); + } + all.retain(|_, timers| !timers.is_empty()); + due.sort_by_key(|(at, ..)| *at); + due.into_iter().map(|(_, plugin, client, id)| (plugin, client, id)).collect() + } + pub fn client_closed(&self, client: &str) -> bool { self.closed_clients.lock().contains(client) } @@ -1213,6 +1258,7 @@ impl Shared { } if subscriptions { self.external_watches.remove_plugin(plugin); + self.timers.lock().remove(plugin); } if subscriptions && self.subscriptions.lock().remove(plugin) { self.sink.emit(None, PluginEvent::SubscriptionsChanged); @@ -2441,6 +2487,23 @@ impl HostApi for PluginApi { .ok_or_else(|| HostError::NotFound("window project".into()))? .fork_agent_session(client, agent, session_id, cwd) } + fn start_agent_task( + &self, + client: &str, + provider: &str, + prompt: &str, + fork: Option<(&str, &Path)>, + ) -> Result { + let task_id = self + .shared + .workspace() + .ok_or_else(|| HostError::NotFound("window project".into()))? + .start_agent_task(client, provider, prompt, fork)?; + self.shared + .sink + .emit(Some(client), PluginEvent::OpenAgentTask { task_id: task_id.clone(), prompt: prompt.to_owned() }); + Ok(task_id) + } fn console_rules(&self, rules: Vec) -> Result<(), HostError> { let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?; let mut all = self.shared.console_rules.lock(); @@ -3797,6 +3860,27 @@ impl HostApi for PluginApi { self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged); } } + + fn schedule(&self, client: Option<&str>, id: &str, after: Duration) -> Result<(), HostError> { + if client.is_some_and(|c| self.shared.client_closed(c)) { + return Err(HostError::Cancelled); + } + let mut timers = self.shared.timers.lock(); + let mine = timers.entry(self.id().to_owned()).or_default(); + mine.retain(|t| t.id != id); + if mine.len() >= MAX_TIMERS { + return Err(HostError::Invalid(format!("at most {MAX_TIMERS} timers may be pending: cancel one first"))); + } + mine.push(Timer { id: id.to_owned(), due: Instant::now() + after, client: client.map(str::to_owned) }); + Ok(()) + } + + fn cancel_schedule(&self, id: &str) { + let mut timers = self.shared.timers.lock(); + if let Some(mine) = timers.get_mut(self.id()) { + mine.retain(|t| t.id != id); + } + } fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result { self.start_process_stream(cmd, cwd, client, None) } @@ -4393,6 +4477,31 @@ impl PluginWorkspace for HostWorkspace { Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id) } + fn start_agent_task( + &self, + client: &str, + provider: &str, + prompt: &str, + fork: Option<(&str, &Path)>, + ) -> Result { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let project = host.project(client).map_err(failed)?; + project.require_trust().map_err(failed)?; + if let Some((session_id, cwd)) = fork { + // The fork path validates the recording and builds the invocation itself. + return Ok(project.agents.fork_session(provider, session_id, cwd).map_err(failed)?.id); + } + let request = ide_agent::NewAgentTask { + prompt: ide_agent::AgentPrompt { text: prompt.to_owned(), ..Default::default() }, + provider: provider.to_owned(), + isolation: ide_agent::Isolation::Local, + // Unsent: the prompt only names the task; the user reviews it in the Agents window and sends. + idle: true, + ..Default::default() + }; + Ok(host.runtime.block_on(project.agents.create(request)).map_err(failed)?.id) + } + fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option { client .and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path)) @@ -5865,6 +5974,33 @@ impl PluginApi { items .iter_mut() .for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some())); + // Hover-card actions (API 1.21): bounded, and each command must be one the plugin declares. + for item in &items { + if item.actions.len() > 4 { + return Err(HostError::Invalid("at most 4 actions per decoration".into())); + } + for a in &item.actions { + if a.label.is_empty() || a.label.len() > 64 || a.label.chars().any(char::is_control) { + return Err(HostError::Invalid( + "action label must be 1-64 bytes without control characters".into(), + )); + } + if a.tooltip.as_ref().is_some_and(|t| t.len() > 256) { + return Err(HostError::Invalid("action tooltip is at most 256 bytes".into())); + } + if a.argument.as_ref().is_some_and(|s| s.len() > 4096) { + return Err(HostError::Invalid("action argument is at most 4 KiB".into())); + } + } + } + if items.iter().any(|d| !d.actions.is_empty()) { + let commands = self.shared.ui.items("commands", Some(self.id())); + for a in items.iter().flat_map(|d| &d.actions) { + if !commands.iter().any(|c| c.key == a.command) { + return Err(HostError::NotFound(format!("the plugin declares no command {:?}", a.command))); + } + } + } // An item with its own colors (API 1.17) may leave the style empty. items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some())); if items.iter().any(|d| d.range.start > d.range.end) { @@ -6217,6 +6353,7 @@ mod workbench_tests { after: Some("after".into()), markdown_hover: None, colors: None, + actions: vec![], }; api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap(); assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1); diff --git a/crates/ide-host/src/plugins/files_changed.rs b/crates/ide-host/src/plugins/files_changed.rs index 93a595dc4f..d1d970048f 100644 --- a/crates/ide-host/src/plugins/files_changed.rs +++ b/crates/ide-host/src/plugins/files_changed.rs @@ -480,7 +480,8 @@ mod tests { #[test] fn every_runtime_event_has_a_matching_manifest_activation() { for kind in ide_plugin::EventKind::ALL { - if kind != ide_plugin::EventKind::Scheduled { + // `on-schedule` and `events.schedule` timers activate the plugin themselves. + if !matches!(kind, ide_plugin::EventKind::Scheduled | ide_plugin::EventKind::Timer) { assert!(ide_extension::EVENT_KINDS.contains(&kind.name())); } } diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 5e61ea9fee..5ba9d66fc0 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -2144,6 +2144,10 @@ impl PluginHost { pub fn project_closed(&self, root: &Path, window: &str) { self.shared.close_project_generation(root); self.shared.external_watches.remove_project(root); + // Timers set for the window's project don't outlive it. + for timers in self.shared.timers.lock().values_mut() { + timers.retain(|t| t.client.as_deref() != Some(window)); + } self.withdraw_project_run_targets(root); self.shared.run_configurations.write().retain(|(_, r), _| r != root); @@ -2359,6 +2363,28 @@ impl PluginHost { } } + /// Queues the `events.schedule` timers due at `now` for their plugin and window. + fn queue_due_timers(&self, now: Instant) { + let due = self.shared.take_due_timers(now); + if due.is_empty() { + return; + } + let mut queues = self.queues.lock(); + for (plugin, client, id) in due { + if client.as_deref().is_some_and(|c| self.shared.client_closed(c)) { + continue; + } + let queue = queues.entry((plugin, client)).or_insert_with(|| EventQueue { + since: now, + last_event: now, + events: Vec::new(), + files_source: None, + }); + queue.last_event = now; + queue.events.push(WorkbenchEvent::Timer(id)); + } + } + pub fn post_events(&self, client: Option<&str>, events: Vec) { self.post_events_from(client, events, None); } @@ -2446,6 +2472,7 @@ impl PluginHost { | WorkbenchEvent::RunExited(_) | WorkbenchEvent::TerminalExited(_) | WorkbenchEvent::ContentTabAction(_) + | WorkbenchEvent::Timer(_) ) { remaining -= 1; @@ -2470,6 +2497,7 @@ impl PluginHost { pub fn flush_events_at(&self, now: Instant) { self.reload_changed_links(); self.queue_watched_changes(now); + self.queue_due_timers(now); let running: BTreeSet = self .plugins .read() @@ -2494,7 +2522,9 @@ impl PluginHost { let (id, _client) = key; let running = running.contains(id); let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_))); - let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled)); + // Due now: a timer was set for this moment, an `on-schedule` period elapsed. + let has_scheduled = + q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled | WorkbenchEvent::Timer(_))); // Already debounced by the watcher, like project file changes. let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_))); let debounce = debounces.get(id).copied(); @@ -2680,6 +2710,7 @@ impl PluginHost { | EventKind::RunExited | EventKind::TerminalExited | EventKind::ContentTabAction + | EventKind::Timer ) }) { diff --git a/crates/ide-host/src/plugins/providers.rs b/crates/ide-host/src/plugins/providers.rs index ac86243977..c6357926c4 100644 --- a/crates/ide-host/src/plugins/providers.rs +++ b/crates/ide-host/src/plugins/providers.rs @@ -128,6 +128,29 @@ impl Providers { out } + /// Each plugin's languages declared for `kind`, in declaration order. + fn languages_by_plugin(&self, kind: ProviderKind) -> Vec<(String, Vec)> { + let mut out: Vec<(String, Vec)> = Vec::new(); + for (_, plugin, kinds, languages) in self.items.read().iter() { + if !kinds.contains(&kind) { + continue; + } + let at = match out.iter().position(|(id, _)| id == plugin) { + Some(at) => at, + None => { + out.push((plugin.clone(), Vec::new())); + out.len() - 1 + } + }; + for language in languages { + if !out[at].1.contains(language) { + out[at].1.push(language.clone()); + } + } + } + out + } + /// One coherent declaration snapshot, preserving the first match per plugin. fn matching>(&self, kind: ProviderKind, language: &str) -> T { let items = self.items.read(); @@ -301,6 +324,11 @@ use std::collections::BTreeSet; use std::sync::Weak; use std::time::{Duration, Instant}; +fn usable_provider(p: &LoadedPlugin) -> bool { + let m = p.meta.lock(); + matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty() +} + /// What the plugins answered for completion in the editor. #[derive(Debug, Default)] pub(crate) struct EditorCompletion { @@ -342,13 +370,29 @@ impl PluginHost { .plugins_for(kind, language) .into_iter() .filter_map(|id| self.get(&id).ok()) - .filter(|p| { - let m = p.meta.lock(); - matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty() - }) + .filter(|p| usable_provider(p)) .collect() } + /// The languages a usable plugin declares for `line-markers` along with `language` (`"*"` for + /// every language), without loading any plugin: a saved file of `language` can change the + /// markers of the files of these languages. + pub fn line_marker_languages_with(&self, language: &str) -> Vec { + let mut out: Vec = Vec::new(); + for (id, languages) in self.providers.languages_by_plugin(ProviderKind::LineMarkers) { + let covers = languages.iter().any(|l| l == "*" || l == language); + if !covers || !self.get(&id).is_ok_and(|p| usable_provider(&p)) { + continue; + } + for l in languages { + if !out.contains(&l) { + out.push(l); + } + } + } + out + } + /// Edit-path calls (soft / hard deadline) to every usable plugin that /// declares `kind` for `language`, in plugin order, leaving out those that /// failed or were late. Each plugin runs on its own thread, so the calls @@ -399,6 +443,14 @@ impl PluginHost { plugins: Vec>, f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, ) -> Vec<(Arc, R)> { + self.edit_calls_plugins_late(plugins, f).0 + } + /// [`Self::edit_calls_plugins`], plus the ids of the plugins whose call was dropped as late. + fn edit_calls_plugins_late( + &self, + plugins: Vec>, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> (Vec<(Arc, R)>, Vec) { let (soft, hard) = (self.limits.edit_soft, self.limits.edit_hard); let queued: Vec<_> = plugins .into_iter() @@ -413,13 +465,18 @@ impl PluginHost { Some((plugin, actor, started, call)) }) .collect(); - queued + let mut late = Vec::new(); + let answers = queued .into_iter() .filter_map(|(plugin, actor, started, call)| { let result = call.and_then(Pending::wait); + if matches!(result, Err(ActorError::SoftTimeout)) { + late.push(plugin.id().to_owned()); + } self.finish_provider_call(&plugin, &actor, started, result).map(|r| (plugin, r)) }) - .collect() + .collect(); + (answers, late) } fn edit_calls_cancellable( @@ -663,14 +720,18 @@ impl PluginHost { }) } - pub fn provide_line_markers(&self, doc: &ProviderDocument) -> Vec<(String, LineMarker)> { + /// The markers by plugin id, and the ids of the plugins too late to answer: they gave no + /// answer, not "no markers". + pub fn provide_line_markers(&self, doc: &ProviderDocument) -> (Vec<(String, LineMarker)>, Vec) { let d = Arc::new(doc.clone()); - self.edit_calls(ProviderKind::LineMarkers, &doc.language, move |rt, timeout| { - rt.provide_line_markers(&d, timeout) - }) - .into_iter() - .flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m))) - .collect() + let plugins = self.provider_plugins(ProviderKind::LineMarkers, &doc.language); + let (answers, late) = + self.edit_calls_plugins_late(plugins, move |rt, timeout| rt.provide_line_markers(&d, timeout)); + let markers = answers + .into_iter() + .flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m))) + .collect(); + (markers, late) } pub fn provide_semantic_tokens(&self, doc: &ProviderDocument) -> Vec { diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index 076d0e2d9b..1978a578bf 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -283,6 +283,10 @@ pub enum PluginEvent { /// Open the IDE's native table data grid in the invoking window (API 1.21). #[serde(rename_all = "camelCase")] OpenDatabaseTable { plugin_id: String, source_id: String, catalog: Option, schema: String, table: String }, + /// Open a plugin-started task in the invoking window's Agents window (API 1.21): + /// created unsent, with `prompt` in its message field for the user to review and send. + #[serde(rename_all = "camelCase")] + OpenAgentTask { task_id: String, prompt: String }, /// Complete replacement of one plugin's clickable console link rules (API 1.21). #[serde(rename_all = "camelCase")] ConsoleLinksChanged { plugin_id: String, rules: Vec }, @@ -546,6 +550,16 @@ pub struct LineMarkerInfo { pub target: Option, } +/// The answer of the `line-markers` providers for a document. +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct LineMarkers { + pub markers: Vec, + /// Plugins whose call ran past the edit-path budget and was dropped: they gave no answer, + /// so the editor keeps the markers it shows from them. + pub late: Vec, +} + /// A plugin's before-commit check to run (`[[contributes.commitChecks]]`). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] diff --git a/crates/ide-host/src/python_move.rs b/crates/ide-host/src/python_move.rs index 800ccb02b6..e3d7027621 100644 --- a/crates/ide-host/src/python_move.rs +++ b/crates/ide-host/src/python_move.rs @@ -202,7 +202,7 @@ pub async fn move_symbols( let problems: Vec = moved .warnings .into_iter() - .map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message }) + .map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message, location: None }) .collect(); // The token names the warnings shown: others that appear meanwhile are asked about again. let mut hasher = std::hash::DefaultHasher::new(); diff --git a/crates/ide-host/src/python_signature.rs b/crates/ide-host/src/python_signature.rs index e815223d3b..470bc1d1c0 100644 --- a/crates/ide-host/src/python_signature.rs +++ b/crates/ide-host/src/python_signature.rs @@ -225,7 +225,11 @@ pub async fn change_signature( let problems: Vec = changed .warnings .iter() - .map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message: message.clone() }) + .map(|message| RefactoringProblem { + severity: ProblemSeverity::Warning, + message: message.clone(), + location: None, + }) .collect(); if !problems.is_empty() && confirmation.as_deref() != Some(CONFIRMATION) { return Ok(ServerRefactored { problems, edit: None, confirmation: Some(CONFIRMATION.into()) }); diff --git a/crates/ide-host/tests/agent_approvals.rs b/crates/ide-host/tests/integration/agent_approvals.rs similarity index 99% rename from crates/ide-host/tests/agent_approvals.rs rename to crates/ide-host/tests/integration/agent_approvals.rs index 7ad2bf329b..2dfceb40c8 100644 --- a/crates/ide-host/tests/agent_approvals.rs +++ b/crates/ide-host/tests/integration/agent_approvals.rs @@ -1,6 +1,6 @@ //! The mode new agent tasks start in. -mod common; +use crate::common; use ide_host::{Host, HostConfig}; use serde_json::json; diff --git a/crates/ide-host/tests/agent_automations.rs b/crates/ide-host/tests/integration/agent_automations.rs similarity index 99% rename from crates/ide-host/tests/agent_automations.rs rename to crates/ide-host/tests/integration/agent_automations.rs index 8a207cc6bc..6449e79284 100644 --- a/crates/ide-host/tests/agent_automations.rs +++ b/crates/ide-host/tests/integration/agent_automations.rs @@ -4,7 +4,7 @@ //! worktree auto-GC + retention cap, `NeedsInput` approval, in-session `Send Later` / `/loop`, //! and persistent `openidea-server --daemon` keep-alive across disconnects. -mod common; +use crate::common; use ide_agent::{ AgentPrompt, AutomationContinuity, AutomationPermissionMode, AutomationRunOrigin, AutomationRunStatus, diff --git a/crates/ide-host/tests/agent_env_secrets.rs b/crates/ide-host/tests/integration/agent_env_secrets.rs similarity index 99% rename from crates/ide-host/tests/agent_env_secrets.rs rename to crates/ide-host/tests/integration/agent_env_secrets.rs index 684f9b785e..a1c98c69bb 100644 --- a/crates/ide-host/tests/agent_env_secrets.rs +++ b/crates/ide-host/tests/integration/agent_env_secrets.rs @@ -1,6 +1,6 @@ //! Values of agents' environment variables live in the credential store; agent files keep only their names. -mod common; +use crate::common; use ide_host::Host; use ide_ssh::secrets::testing::{files_containing, use_memory_store}; diff --git a/crates/ide-host/tests/agent_mcp.rs b/crates/ide-host/tests/integration/agent_mcp.rs similarity index 99% rename from crates/ide-host/tests/agent_mcp.rs rename to crates/ide-host/tests/integration/agent_mcp.rs index 766e3c6e77..6ecdb63ad9 100644 --- a/crates/ide-host/tests/agent_mcp.rs +++ b/crates/ide-host/tests/integration/agent_mcp.rs @@ -1,6 +1,6 @@ //! External MCP servers in Settings › Agents, as the host stores and lists them. -mod common; +use crate::common; use ide_agent::{McpScope, McpServer, McpServerInput}; use ide_core::settings::McpTransport; diff --git a/crates/ide-host/tests/agent_model_refresh.rs b/crates/ide-host/tests/integration/agent_model_refresh.rs similarity index 99% rename from crates/ide-host/tests/agent_model_refresh.rs rename to crates/ide-host/tests/integration/agent_model_refresh.rs index a16cf58f46..b59d3cfda3 100644 --- a/crates/ide-host/tests/agent_model_refresh.rs +++ b/crates/ide-host/tests/integration/agent_model_refresh.rs @@ -1,7 +1,6 @@ //! Separate project windows share discovery and its backend-enforced cooldown. -#![cfg(unix)] -mod common; +use crate::common; use ide_agent::AgentEvent; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/attached_excludes.rs b/crates/ide-host/tests/integration/attached_excludes.rs similarity index 99% rename from crates/ide-host/tests/attached_excludes.rs rename to crates/ide-host/tests/integration/attached_excludes.rs index 51d4a63d95..55883ffd4a 100644 --- a/crates/ide-host/tests/attached_excludes.rs +++ b/crates/ide-host/tests/integration/attached_excludes.rs @@ -1,5 +1,5 @@ //! Each project of a workspace keeps its own excluded folders: they apply below that project only. -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/binary_args.rs b/crates/ide-host/tests/integration/binary_args.rs similarity index 99% rename from crates/ide-host/tests/binary_args.rs rename to crates/ide-host/tests/integration/binary_args.rs index 79b3443945..5355cc1dcc 100644 --- a/crates/ide-host/tests/binary_args.rs +++ b/crates/ide-host/tests/integration/binary_args.rs @@ -1,6 +1,6 @@ //! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers. -mod common; +use crate::common; use ide_core::IpcBytes; use ide_host::Host; diff --git a/crates/ide-host/tests/close_project.rs b/crates/ide-host/tests/integration/close_project.rs similarity index 99% rename from crates/ide-host/tests/close_project.rs rename to crates/ide-host/tests/integration/close_project.rs index 59db0fbef6..da70372f9f 100644 --- a/crates/ide-host/tests/close_project.rs +++ b/crates/ide-host/tests/integration/close_project.rs @@ -1,8 +1,7 @@ //! Closing a project takes the background processes of its window with it, as IDEA does, //! and leaves the other windows' processes alone. -#![cfg(unix)] -mod common; +use crate::common; use ide_host::{Host, ops}; use std::sync::Arc; diff --git a/crates/ide-host/tests/container_php_real.rs b/crates/ide-host/tests/integration/container_php_real.rs similarity index 99% rename from crates/ide-host/tests/container_php_real.rs rename to crates/ide-host/tests/integration/container_php_real.rs index 7c54432b41..a9114579f3 100644 --- a/crates/ide-host/tests/container_php_real.rs +++ b/crates/ide-host/tests/integration/container_php_real.rs @@ -1,7 +1,7 @@ //! The PHP of a Docker and of a Compose run target, against a real daemon. Ignored by default: //! `docker` with the Compose plugin must be on `PATH` and able to pull `php:8.3-cli`. -mod common; +use crate::common; use ide_host::{Host, ops}; use std::sync::Arc; diff --git a/crates/ide-host/tests/container_python_real.rs b/crates/ide-host/tests/integration/container_python_real.rs similarity index 99% rename from crates/ide-host/tests/container_python_real.rs rename to crates/ide-host/tests/integration/container_python_real.rs index 7da78f8e12..fd6312efe3 100644 --- a/crates/ide-host/tests/container_python_real.rs +++ b/crates/ide-host/tests/integration/container_python_real.rs @@ -3,9 +3,8 @@ //! daemon can bind-mount (on this machine, or at the same path in a VM such as OrbStack's), //! `docker` with the Compose plugin and `basedpyright-langserver` must be on `PATH`, and //! this machine's Python must not have Django installed. -#![cfg(unix)] -mod common; +use crate::common; use ide_core::IdeEvent; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/csharpier.rs b/crates/ide-host/tests/integration/csharpier.rs similarity index 99% rename from crates/ide-host/tests/csharpier.rs rename to crates/ide-host/tests/integration/csharpier.rs index 0abdf9e558..275a767e96 100644 --- a/crates/ide-host/tests/csharpier.rs +++ b/crates/ide-host/tests/integration/csharpier.rs @@ -2,7 +2,7 @@ //! It downloads CSharpier, so it runs only on request: //! `cargo test -p ide-host --test csharpier -- --ignored`; skipped without a .NET SDK. -mod common; +use crate::common; use ide_core::error::ErrorKind; use ide_core::{IdeEvent, IdeResult, Pos, Range, TextEdit}; diff --git a/crates/ide-host/tests/data_dirs.rs b/crates/ide-host/tests/integration/data_dirs.rs similarity index 99% rename from crates/ide-host/tests/data_dirs.rs rename to crates/ide-host/tests/integration/data_dirs.rs index efb437ddfa..c2f4bb7fcc 100644 --- a/crates/ide-host/tests/data_dirs.rs +++ b/crates/ide-host/tests/integration/data_dirs.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/db_consoles.rs b/crates/ide-host/tests/integration/db_consoles.rs similarity index 99% rename from crates/ide-host/tests/db_consoles.rs rename to crates/ide-host/tests/integration/db_consoles.rs index 6243d700a0..7be5899657 100644 --- a/crates/ide-host/tests/db_consoles.rs +++ b/crates/ide-host/tests/integration/db_consoles.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_host::Host; use ide_host::ops::db; diff --git a/crates/ide-host/tests/debug_jvm_memory_ipc.rs b/crates/ide-host/tests/integration/debug_jvm_memory_ipc.rs similarity index 99% rename from crates/ide-host/tests/debug_jvm_memory_ipc.rs rename to crates/ide-host/tests/integration/debug_jvm_memory_ipc.rs index b137e96b85..6acee4cc3f 100644 --- a/crates/ide-host/tests/debug_jvm_memory_ipc.rs +++ b/crates/ide-host/tests/integration/debug_jvm_memory_ipc.rs @@ -2,7 +2,7 @@ //! that sends no real window (the desktop shell once passed `""`) never reaches the debugger, //! and a project in Restricted Mode never reads the debuggee's memory. -mod common; +use crate::common; use ide_core::IdeError; use ide_host::Host; diff --git a/crates/ide-host/tests/directory_sync.rs b/crates/ide-host/tests/integration/directory_sync.rs similarity index 99% rename from crates/ide-host/tests/directory_sync.rs rename to crates/ide-host/tests/integration/directory_sync.rs index 32478757a5..c1316a793e 100644 --- a/crates/ide-host/tests/directory_sync.rs +++ b/crates/ide-host/tests/integration/directory_sync.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{ diff --git a/crates/ide-host/tests/distribution.rs b/crates/ide-host/tests/integration/distribution.rs similarity index 100% rename from crates/ide-host/tests/distribution.rs rename to crates/ide-host/tests/integration/distribution.rs diff --git a/crates/ide-host/tests/docker_run_targets_real.rs b/crates/ide-host/tests/integration/docker_run_targets_real.rs similarity index 99% rename from crates/ide-host/tests/docker_run_targets_real.rs rename to crates/ide-host/tests/integration/docker_run_targets_real.rs index 81c12b3a58..e942bf7bd6 100644 --- a/crates/ide-host/tests/docker_run_targets_real.rs +++ b/crates/ide-host/tests/integration/docker_run_targets_real.rs @@ -2,9 +2,8 @@ //! `OPENIDEA_DOCKER_TEST_DIR` names an empty folder the daemon can bind-mount //! (on this machine, or at the same path in a VM such as OrbStack's), and //! `docker` with the Compose plugin must be on `PATH`. -#![cfg(unix)] -mod common; +use crate::common; use ide_host::{Host, ops}; use ide_run::{OutputChunk, RunConfig}; diff --git a/crates/ide-host/tests/external_log.rs b/crates/ide-host/tests/integration/external_log.rs similarity index 99% rename from crates/ide-host/tests/external_log.rs rename to crates/ide-host/tests/integration/external_log.rs index 9c9786ac20..d8ba02bd68 100644 --- a/crates/ide-host/tests/external_log.rs +++ b/crates/ide-host/tests/integration/external_log.rs @@ -1,5 +1,5 @@ //! Explicit external logs allow history reads without adding a writable project root. -mod common; +use crate::common; use ide_host::{Host, ops::vcs}; use std::{path::Path, process::Command}; diff --git a/crates/ide-host/tests/gradle_linkage.rs b/crates/ide-host/tests/integration/gradle_linkage.rs similarity index 99% rename from crates/ide-host/tests/gradle_linkage.rs rename to crates/ide-host/tests/integration/gradle_linkage.rs index d547ed7d6f..e086d343d9 100644 --- a/crates/ide-host/tests/gradle_linkage.rs +++ b/crates/ide-host/tests/integration/gradle_linkage.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/ij_svn_roots.rs b/crates/ide-host/tests/integration/ij_svn_roots.rs similarity index 99% rename from crates/ide-host/tests/ij_svn_roots.rs rename to crates/ide-host/tests/integration/ij_svn_roots.rs index 20df7fea06..b1cdf2e9bb 100644 --- a/crates/ide-host/tests/ij_svn_roots.rs +++ b/crates/ide-host/tests/integration/ij_svn_roots.rs @@ -3,7 +3,7 @@ //! SvnExternalTest, SvnExternalCommitNoticedTest and SvnCommitTest (scenarios only); the //! working copies themselves are checked in crates/ide-svn/tests/ij_files.rs. //! Skipped when `svn` or `svnadmin` is not installed (a failure in CI). -mod common; +use crate::common; use ide_host::Host; use ide_host::ops::vcs; diff --git a/crates/ide-host/tests/java_build.rs b/crates/ide-host/tests/integration/java_build.rs similarity index 95% rename from crates/ide-host/tests/java_build.rs rename to crates/ide-host/tests/integration/java_build.rs index 4145088d2a..0af1dd5c99 100644 --- a/crates/ide-host/tests/java_build.rs +++ b/crates/ide-host/tests/integration/java_build.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_build::compile::BuildEvent; use ide_core::RequestId; @@ -26,11 +26,11 @@ async fn pom_launch_uses_dependency_classpath_without_a_java_project() { let temp = tempfile::tempdir().unwrap(); let base = dunce::canonicalize(temp.path()).unwrap(); let root = base.join("project"); - let pom = include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml") + let pom = include_str!("../../../ide-build/tests/fixtures/jbuild-maven/pom.xml") .replace("", "assembly"); write(&root, "pom.xml", &pom); - write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml")); - write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml")); + write(&root, "lib/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml")); + write(&root, "app/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml")); write( &root, "assembly/pom.xml", @@ -130,9 +130,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() { let temp = tempfile::tempdir().unwrap(); let base = dunce::canonicalize(temp.path()).unwrap(); let root = base.join("project"); - write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml")); - write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml")); - write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml")); + write(&root, "pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/pom.xml")); + write(&root, "lib/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml")); + write(&root, "app/pom.xml", include_str!("../../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml")); write( &root, "lib/src/main/java/l/L.java", diff --git a/crates/ide-host/tests/jdtls_excluded_checkout.rs b/crates/ide-host/tests/integration/jdtls_excluded_checkout.rs similarity index 100% rename from crates/ide-host/tests/jdtls_excluded_checkout.rs rename to crates/ide-host/tests/integration/jdtls_excluded_checkout.rs diff --git a/crates/ide-host/tests/light_edit.rs b/crates/ide-host/tests/integration/light_edit.rs similarity index 99% rename from crates/ide-host/tests/light_edit.rs rename to crates/ide-host/tests/integration/light_edit.rs index 5ff84092a6..decabdb2d1 100644 --- a/crates/ide-host/tests/light_edit.rs +++ b/crates/ide-host/tests/integration/light_edit.rs @@ -1,6 +1,6 @@ //! LightEdit: a window editing loose files without a project. -mod common; +use crate::common; use ide_core::{ChangeSet, Pos, Range, SymbolKind, TextChange}; use ide_host::{Host, catalogue::TrustClass, ops}; diff --git a/crates/ide-host/tests/integration/main.rs b/crates/ide-host/tests/integration/main.rs new file mode 100644 index 0000000000..21af467094 --- /dev/null +++ b/crates/ide-host/tests/integration/main.rs @@ -0,0 +1,102 @@ +#[path = "../common/mod.rs"] +mod common; + +mod agent_approvals; +mod agent_automations; +mod agent_env_secrets; +mod agent_mcp; +#[cfg(unix)] +mod agent_model_refresh; +mod attached_excludes; +mod binary_args; +#[cfg(unix)] +mod close_project; +mod container_php_real; +#[cfg(unix)] +mod container_python_real; +mod csharpier; +mod data_dirs; +mod db_consoles; +mod debug_jvm_memory_ipc; +mod directory_sync; +mod distribution; +#[cfg(unix)] +mod docker_run_targets_real; +mod external_log; +mod gradle_linkage; +mod ij_svn_roots; +mod java_build; +mod jdtls_excluded_checkout; +mod light_edit; +mod maven_external; +mod mcp; +mod mcp_secrets; +mod nav_inheritance; +#[cfg(windows)] +mod network_images; +mod open_project; +mod plugin_clipboard; +mod plugin_code_semantics; +mod plugin_commit; +mod plugin_completion_list; +mod plugin_completion_resolve; +mod plugin_data_tools; +mod plugin_database_open; +mod plugin_dependencies; +mod plugin_diagnostics; +mod plugin_hover; +mod plugin_indexing; +mod plugin_inlay_hints; +mod plugin_language_features; +mod plugin_project_view; +mod plugin_refactoring; +mod plugin_rename; +mod plugin_run_anything; +mod plugin_run_output; +mod plugin_semantic_tokens; +mod plugin_server_commands; +mod plugin_symbols; +mod plugin_syntax_decorations; +mod plugin_timers; +mod plugin_view_badge; +mod plugin_watch_paths; +mod plugin_workbench; +mod pom_encoding; +mod properties; +mod pytest_fixtures; +mod python_move; +mod python_rename_comments; +mod python_signature; +mod python_signature_ops; +#[cfg(unix)] +mod remote_daemon; +#[cfg(unix)] +mod remote_plugins; +mod replace_all; +mod roslyn_editorconfig; +mod roslyn_hints; +mod rpc; +mod run_configs; +mod search_encoding; +mod settings_sync; +mod spell_dictionary; +mod ssh_terminal; +mod svn; +#[cfg(any(unix, windows))] +mod terminal_images; +mod trust; +#[cfg(unix)] +mod trust_git_binary; +mod trust_vcs_sweep; +mod unity; +mod vcs_backends; +mod vcs_delete_added; +mod vcs_documents; +mod vcs_encoding; +mod vcs_flow; +mod vcs_roots; +mod vcs_shelf_roots; +mod vcs_watcher_moved_repository; +mod vcs_worktrees; +mod workspace_edits; +mod workspaces; diff --git a/crates/ide-host/tests/maven_external.rs b/crates/ide-host/tests/integration/maven_external.rs similarity index 99% rename from crates/ide-host/tests/maven_external.rs rename to crates/ide-host/tests/integration/maven_external.rs index c53321a62f..efe1ed02c1 100644 --- a/crates/ide-host/tests/maven_external.rs +++ b/crates/ide-host/tests/integration/maven_external.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_host::{Host, HostConfig, ops}; use ide_workspace::settings::SettingsScope; diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/integration/mcp.rs similarity index 87% rename from crates/ide-host/tests/mcp.rs rename to crates/ide-host/tests/integration/mcp.rs index 859e8efba4..7d889ce891 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/integration/mcp.rs @@ -1,8 +1,9 @@ -mod common; +use crate::common; use ide_core::{ CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest, }; +use ide_db::{DataSource, DbDriver}; use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry}; use ide_host::{Host, HostConfig}; use ide_mcp::ToolRegistry; @@ -3144,3 +3145,479 @@ async fn automation_tools_enforce_trust_mandatory_confirm_even_in_brave_mode_and assert_eq!(del_res["deletedId"], imported_id); assert!(h.host.automations.get(&imported_id).is_none()); } + +/// The project's SQLite data source `db`: `users` with 150 rows and a foreign key to itself, +/// the `users_name` unique index and the `named` view. +async fn sqlite_fixture(h: &Harness) { + std::fs::File::create(h.root.join("data.sqlite")).unwrap(); + let db = h.host.project("main").unwrap().db.clone(); + db.save_sources(vec![DataSource { + id: "db".into(), + name: "Test DB".into(), + driver: DbDriver::Sqlite, + file: Some(h.root.join("data.sqlite").into()), + ..Default::default() + }]) + .await + .unwrap(); + let c = CancellationToken::new(); + for stmt in [ + "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, manager_id INTEGER REFERENCES users(id))", + "CREATE UNIQUE INDEX users_name ON users(name)", + "CREATE VIEW named AS SELECT name FROM users", + ] { + db.execute("db", stmt, 100, &c).await.unwrap(); + } + let rows: Vec = (1..=150).map(|id| format!("({id}, 'user{id:03}')")).collect(); + db.execute("db", &format!("INSERT INTO users (id, name) VALUES {}", rows.join(", ")), 100, &c).await.unwrap(); +} + +/// Writes `.openidea/data-sources.toml` as a crafted repository might: `save_sources` rejects +/// duplicate ids, so a test of the tool boundary needs the file itself. +fn write_sources_file(root: &Path, sources: &[DataSource]) { + let tables: Vec = sources + .iter() + .map(|source| { + let mut value = toml::Value::try_from(source).unwrap(); + value.as_table_mut().unwrap().remove("global"); + value + }) + .collect(); + let doc = toml::Value::Table(toml::map::Map::from_iter([("data-source".to_owned(), toml::Value::Array(tables))])); + std::fs::create_dir_all(root.join(".openidea")).unwrap(); + std::fs::write(root.join(".openidea/data-sources.toml"), toml::to_string_pretty(&doc).unwrap()).unwrap(); +} + +/// Runs `name` in the project's window and allows the confirmation it asks there; the window +/// must be ready (`h.host.mcp_requests.set_ready("main", true)`). +async fn confirmed(h: &Harness, name: &str, args: Value) -> String { + h.events.lock().unwrap().clear(); + let call = h.call(name, args); + let allow = async { + let id = h.request().await; + h.host.mcp_requests.answer("main", id, true, None).unwrap(); + }; + let (result, ()) = tokio::join!(call, allow); + result +} + +/// Like [`confirmed`], for a call that must fail after the confirmation. +async fn confirmed_error(h: &Harness, name: &str, args: Value) -> String { + h.events.lock().unwrap().clear(); + let call = h.error(name, args); + let allow = async { + let id = h.request().await; + h.host.mcp_requests.answer("main", id, true, None).unwrap(); + }; + let (result, ()) = tokio::join!(call, allow); + result +} + +#[tokio::test(flavor = "multi_thread")] +async fn database_connections_are_listed_without_urls_hosts_or_credentials() { + let h = Harness::new(); + sqlite_fixture(&h).await; + assert!(!h.host.project("main").unwrap().is_trusted(), "the metadata tools need a trusted project"); + let refused = h.error("list_database_connections", json!({})).await; + assert!(refused.contains("Restricted Mode"), "{refused}"); + h.trust().await; + let raw = h.call("list_database_connections", json!({})).await; + let listed: Value = serde_json::from_str(&raw).unwrap(); + assert_eq!( + listed["connections"], + json!([{ "id": "db", "name": "Test DB", "driver": "sqlite", "database": "", "readOnly": false, "global": false }]) + ); + for key in ["url", "host", "user", "password"] { + assert!(!raw.contains(&format!("\"{key}\"")), "`{key}` in {raw}"); + } + // A URL-only source's URL, host and user never reach the agent either. + let db = h.host.project("main").unwrap().db.clone(); + let mut sources = db.sources().unwrap(); + sources.push(DataSource { + id: "remote".into(), + name: "Remote".into(), + driver: DbDriver::Postgres, + url_only: true, + url: "postgres://db.example.invalid:5432/app".into(), + ..Default::default() + }); + db.save_sources(sources).await.unwrap(); + let raw = h.call("list_database_connections", json!({})).await; + assert!(raw.contains("\"remote\""), "{raw}"); + for secret in ["db.example.invalid", "5432", "app"] { + assert!(!raw.contains(secret), "`{secret}` in {raw}"); + } +} + +/// Global data sources are stored app-wide and listed in every project; the list marks them. +#[tokio::test(flavor = "multi_thread")] +async fn global_data_sources_are_listed_with_a_global_flag() { + let h = Harness::new(); + sqlite_fixture(&h).await; + ide_db::source::save_global( + &h.host.data_dir, + &[DataSource { + id: "shared".into(), + name: "Shared".into(), + driver: DbDriver::Sqlite, + file: Some(h.root.join("data.sqlite").into()), + ..Default::default() + }], + ) + .unwrap(); + h.trust().await; + let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap(); + let connections = listed["connections"].as_array().unwrap(); + let project = connections.iter().find(|c| c["id"] == "db").expect("the project source"); + assert_eq!(project["global"], false, "{listed}"); + let global = connections.iter().find(|c| c["id"] == "shared").expect("the global source"); + assert_eq!(global["global"], true, "{listed}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn database_schemas_and_objects_are_listed_in_a_trusted_project() { + let h = Harness::new(); + sqlite_fixture(&h).await; + for (name, args) in [ + ("list_database_schemas", json!({"connectionId": "db"})), + ("list_schema_objects", json!({"connectionId": "db", "schema": "main"})), + ] { + let refused = h.error(name, args).await; + assert!(refused.contains("Restricted Mode"), "{name}: {refused}"); + } + h.trust().await; + let schemas = h.json("list_database_schemas", json!({"connectionId": "db"})).await; + assert_eq!(schemas["connectionId"], "db"); + assert_eq!(schemas["schemas"], json!(["main"])); + // Tables and views are objects; the unique index is not. + let all = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main"})).await; + assert_eq!(all["objects"], json!([{"kind": "view", "name": "named"}, {"kind": "table", "name": "users"}]), "{all}"); + assert!(!all.to_string().contains("users_name"), "{all}"); + let views = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main", "kind": "view"})).await; + assert_eq!(views["objects"], json!([{"kind": "view", "name": "named"}]), "{views}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn database_object_description_reads_columns_indexes_and_foreign_keys() { + let h = Harness::new(); + sqlite_fixture(&h).await; + let args = json!({"connectionId": "db", "schema": "main", "objectName": "users"}); + let refused = h.error("get_database_object_description", args.clone()).await; + assert!(refused.contains("Restricted Mode"), "{refused}"); + h.trust().await; + let described = h.json("get_database_object_description", args).await; + assert_eq!( + (&described["connectionId"], &described["schema"], &described["objectName"]), + (&json!("db"), &json!("main"), &json!("users")) + ); + let details = &described["details"]; + let columns = details["columns"].as_array().unwrap(); + let names: Vec<&str> = columns.iter().map(|c| c["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["id", "name", "manager_id"]); + assert_eq!(columns[0]["primaryKey"], true); + assert_eq!(columns[1]["nullable"], false); + let index = details["indexes"].as_array().unwrap().iter().find(|i| i["name"] == "users_name").expect("users_name"); + assert_eq!(index["unique"], true); + assert_eq!(index["columns"], json!(["name"])); + let keys = details["foreignKeys"].as_array().unwrap(); + assert_eq!(keys.len(), 1, "{described}"); + assert_eq!(keys[0]["columns"], json!(["manager_id"])); + assert_eq!(keys[0]["refSchema"], "main"); + assert_eq!(keys[0]["refTable"], "users"); + assert_eq!(keys[0]["refColumns"], json!(["id"])); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_is_a_write_tool_that_needs_trust() { + let h = Harness::new(); + sqlite_fixture(&h).await; + let untrusted = Registry::new(h.host.clone()).tools(&h.root).unwrap(); + for name in + ["list_database_connections", "list_database_schemas", "list_schema_objects", "get_database_object_description"] + { + assert!(untrusted.iter().any(|t| t.name == name && t.read_only), "{name} is a read tool"); + } + assert!(untrusted.iter().all(|t| t.name != "execute_sql_query"), "a write tool is hidden until trust"); + // The metadata tools are still listed, but their calls need trust too, not only the write tool. + for (name, args) in [ + ("list_database_connections", json!({})), + ("list_database_schemas", json!({"connectionId": "db"})), + ("list_schema_objects", json!({"connectionId": "db", "schema": "main"})), + ("get_database_object_description", json!({"connectionId": "db", "schema": "main", "objectName": "users"})), + ] { + let message = h.error(name, args).await; + assert!(message.contains("Restricted Mode"), "{name}: {message}"); + } + // Calling it directly is refused too, not only hidden from the list. + let refused = Registry::new(h.host.clone()).call( + &h.root, + "execute_sql_query", + &json!({"connectionId": "db", "sql": "SELECT 1"}).to_string(), + CancellationToken::new(), + ); + let message = match refused.expect_err("a write tool is refused in Restricted Mode") { + ide_mcp::ToolCallError::Failed(message) | ide_mcp::ToolCallError::UnknownTool(message) => message, + }; + assert!(message.contains("Restricted Mode"), "{message}"); + h.trust().await; + let trusted = Registry::new(h.host.clone()).tools(&h.root).unwrap(); + let tool = trusted.iter().find(|t| t.name == "execute_sql_query").expect("offered once trusted"); + assert!(!tool.read_only); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_pages_rows_and_cuts_long_cells() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + h.host.mcp_requests.set_ready("main", true); + + let page: Value = serde_json::from_str( + &confirmed( + &h, + "execute_sql_query", + json!({"connectionId": "db", "sql": "SELECT id, name FROM users ORDER BY id", "maxRows": 10}), + ) + .await, + ) + .unwrap(); + assert_eq!(page["rowCount"], 10, "{page}"); + assert_eq!(page["rows"].as_array().unwrap().len(), 10); + assert_eq!(page["hasMore"], true); + assert_eq!(page["rows"][0], json!(["1", "user001"])); + // The dialog showed the exact statement, not the raw arguments or a truncated form. + let detail = h + .events + .lock() + .unwrap() + .iter() + .find_map(|(_, event)| match event { + IdeEvent::McpRequest { request: McpUiRequest::Confirm { detail, .. }, .. } => { + Some(detail.clone().unwrap_or_default()) + } + _ => None, + }) + .expect("a confirmation was asked"); + assert!(detail.contains("SQL:\nSELECT id, name FROM users ORDER BY id"), "{detail}"); + assert!(detail.contains("Driver: SQLite"), "{detail}"); + let columns: Vec<&str> = page["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect(); + assert_eq!(columns, ["id", "name"]); + + // Without `maxRows` the result stops at the default of 100, and says more rows exist. + let default: Value = serde_json::from_str( + &confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT id FROM users ORDER BY id"})) + .await, + ) + .unwrap(); + assert_eq!(default["rowCount"], 100, "{default}"); + assert_eq!(default["rows"].as_array().unwrap().len(), 100); + assert_eq!(default["hasMore"], true); + + // A cell longer than 4096 UTF-16 units is cut and reported in `truncated`. + let sql = format!("SELECT '{}' AS long", "x".repeat(5000)); + let long: Value = + serde_json::from_str(&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": sql})).await) + .unwrap(); + assert_eq!(long["rows"][0][0].as_str().unwrap().chars().count(), 4096); + let truncated = long["truncated"].as_array().unwrap(); + assert_eq!(truncated.len(), 1, "{long}"); + assert_eq!(truncated[0]["length"], 5000); + assert_eq!((&truncated[0]["row"], &truncated[0]["column"]), (&json!(0), &json!(0))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_refuses_several_statements_and_writes_before_asking() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + let several = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT 1; SELECT 2"})).await; + assert!(several.contains("exactly one statement"), "{several}"); + let write = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "DELETE FROM users"})).await; + assert!(write.contains("DELETE is not allowed"), "{write}"); + assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked"); + let count = h + .host + .project("main") + .unwrap() + .db + .execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(count.rows, vec![vec![Some("150".into())]]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_refuses_a_driver_without_a_read_only_session_before_asking() { + let h = Harness::new(); + let db = h.host.project("main").unwrap().db.clone(); + db.save_sources(vec![DataSource { + id: "mssql".into(), + name: "SQL Server".into(), + driver: DbDriver::SqlServer, + host: "127.0.0.1".into(), + port: Some(1), + user: "sa".into(), + ..Default::default() + }]) + .await + .unwrap(); + h.trust().await; + h.host.mcp_requests.set_ready("main", true); + h.events.lock().unwrap().clear(); + // The refusal happens before a connection is opened, so no server is needed. + let error = h.error("execute_sql_query", json!({"connectionId": "mssql", "sql": "SELECT 1"})).await; + assert!(error.contains("SQL Server has no read-only session"), "{error}"); + assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked"); +} + +/// A statement that passes the `SELECT`/`WITH` allowlist but writes through a CTE is refused by the +/// driver-enforced read-only session (`PRAGMA query_only`), not by the keyword check. Unlike the +/// gated PostgreSQL test, this runs everywhere SQLite does. +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_refuses_a_cte_write_through_the_read_only_session() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + h.host.mcp_requests.set_ready("main", true); + let error = confirmed_error( + &h, + "execute_sql_query", + json!({"connectionId": "db", "sql": "WITH d AS (SELECT 1) DELETE FROM users"}), + ) + .await; + assert!(error.to_ascii_lowercase().contains("readonly"), "{error}"); + let count = h + .host + .project("main") + .unwrap() + .db + .execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(count.rows, vec![vec![Some("150".into())]], "the session refused the write before it ran"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_can_be_denied_without_changing_the_database() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + h.host.mcp_requests.set_ready("main", true); + let denied = + h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT name FROM users ORDER BY id"})); + let deny = async { + let id = h.request().await; + h.host.mcp_requests.answer("main", id, false, None).unwrap(); + }; + let (error, ()) = tokio::join!(denied, deny); + assert!(error.contains("denied by the user"), "{error}"); + let count = h + .host + .project("main") + .unwrap() + .db + .execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(count.rows, vec![vec![Some("150".into())]]); +} + +/// A crafted project file cannot route a tool to a plugin-owned source: its id is refused when +/// plugin-owned, a `:database` suffix is refused, and two entries with one id are refused. +#[tokio::test(flavor = "multi_thread")] +async fn database_tools_refuse_plugin_and_ambiguous_connection_ids() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + let file: ide_core::IpcPath = h.root.join("data.sqlite").into(); + let plugin = |id: &str| DataSource { + id: id.into(), + name: "Plugin source".into(), + driver: DbDriver::Sqlite, + file: Some(file.clone()), + plugin_owner: Some("sample".into()), + plugin_source_id: Some("owned".into()), + ..Default::default() + }; + let user = |id: &str| DataSource { + id: id.into(), + name: "User source".into(), + driver: DbDriver::Sqlite, + file: Some(file.clone()), + ..Default::default() + }; + write_sources_file( + &h.root, + &[ + plugin("plugin-owned"), + user("plugin-owned:database"), + // The plugin entry first: `DbManager` takes the first matching prefix. + plugin("dup"), + user("dup"), + ], + ); + + let colon = h.error("list_database_schemas", json!({"connectionId": "plugin-owned:database"})).await; + assert!(colon.contains("without a `:database` part"), "{colon}"); + let owned = h.error("list_database_schemas", json!({"connectionId": "plugin-owned"})).await; + assert!(owned.contains("no data source plugin-owned"), "{owned}"); + let duplicate = h.error("list_database_schemas", json!({"connectionId": "dup"})).await; + assert!(duplicate.contains("more than one data source"), "{duplicate}"); + // `list_database_connections` keeps its own filter: only the user entries appear. + let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap(); + let ids: Vec<&str> = listed["connections"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect(); + assert!(!ids.contains(&"plugin-owned"), "{listed}"); +} + +/// Driver and tunnel errors can name the user or the host; no database tool may pass them on. +#[tokio::test(flavor = "multi_thread")] +async fn database_tool_errors_hide_the_user_host_and_url() { + let h = Harness::new(); + let db = h.host.project("main").unwrap().db.clone(); + db.save_sources(vec![DataSource { + id: "remote".into(), + name: "Remote".into(), + driver: DbDriver::Postgres, + user: "alice".into(), + host: "127.0.0.1".into(), + url_only: true, + url: "postgres://alice:sekret@127.0.0.1:1/app".into(), + ..Default::default() + }]) + .await + .unwrap(); + let assert_hidden = |text: &str| { + for secret in ["alice", "127.0.0.1", "postgres://"] { + assert!(!text.contains(secret), "`{secret}` in {text}"); + } + }; + h.trust().await; + let listed = h.call("list_database_connections", json!({})).await; + assert_hidden(&listed); + let schemas = h.error("list_database_schemas", json!({"connectionId": "remote"})).await; + assert_hidden(&schemas); + h.host.mcp_requests.set_ready("main", true); + let query = confirmed_error(&h, "execute_sql_query", json!({"connectionId": "remote", "sql": "SELECT 1"})).await; + assert_hidden(&query); +} + +#[tokio::test(flavor = "multi_thread")] +async fn execute_sql_query_still_answers_a_select_on_a_read_only_data_source() { + let h = Harness::new(); + sqlite_fixture(&h).await; + h.trust().await; + h.host.mcp_requests.set_ready("main", true); + // The data source's own read-only setting is respected: queries still run, and it is listed as such. + let db = h.host.project("main").unwrap().db.clone(); + let mut sources = db.sources().unwrap(); + sources.iter_mut().find(|s| s.id == "db").unwrap().read_only = true; + db.save_sources(sources).await.unwrap(); + let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap(); + assert_eq!(listed["connections"][0]["readOnly"], true, "{listed}"); + let result: Value = serde_json::from_str( + &confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT count(*) AS n FROM users"})) + .await, + ) + .unwrap(); + assert_eq!(result["rows"], json!([["150"]]), "{result}"); +} diff --git a/crates/ide-host/tests/mcp_secrets.rs b/crates/ide-host/tests/integration/mcp_secrets.rs similarity index 99% rename from crates/ide-host/tests/mcp_secrets.rs rename to crates/ide-host/tests/integration/mcp_secrets.rs index a146453c9b..7fdaf2f12b 100644 --- a/crates/ide-host/tests/mcp_secrets.rs +++ b/crates/ide-host/tests/integration/mcp_secrets.rs @@ -2,7 +2,7 @@ //! credential store; `settings.toml` keeps only their names. A project's own servers keep //! their values in the project's file, where the project shares them. -mod common; +use crate::common; use ide_agent::{McpKeyValue, McpScope, McpServer, McpServerInput}; use ide_core::settings::McpTransport; diff --git a/crates/ide-host/tests/nav_inheritance.rs b/crates/ide-host/tests/integration/nav_inheritance.rs similarity index 99% rename from crates/ide-host/tests/nav_inheritance.rs rename to crates/ide-host/tests/integration/nav_inheritance.rs index e9caa10f93..5f01861473 100644 --- a/crates/ide-host/tests/nav_inheritance.rs +++ b/crates/ide-host/tests/integration/nav_inheritance.rs @@ -3,7 +3,7 @@ //! written in its source, so the UI can compute inheritance gutter markers without a //! language server's type-hierarchy provider. -mod common; +use crate::common; use ide_host::{Host, ops}; use std::path::PathBuf; diff --git a/crates/ide-host/tests/network_images.rs b/crates/ide-host/tests/integration/network_images.rs similarity index 99% rename from crates/ide-host/tests/network_images.rs rename to crates/ide-host/tests/integration/network_images.rs index 8cf889edd1..23ee18591b 100644 --- a/crates/ide-host/tests/network_images.rs +++ b/crates/ide-host/tests/integration/network_images.rs @@ -2,7 +2,6 @@ //! share signs in to its server with the user's credentials: the host reads an image from a //! share only when a project is open on it. The share here is this machine's own `C$` over //! loopback. -#![cfg(windows)] use ide_core::NullSink; use ide_host::ops::bytes::fs_read_image; diff --git a/crates/ide-host/tests/open_project.rs b/crates/ide-host/tests/integration/open_project.rs similarity index 98% rename from crates/ide-host/tests/open_project.rs rename to crates/ide-host/tests/integration/open_project.rs index d0ae18ec67..2dd39c0c27 100644 --- a/crates/ide-host/tests/open_project.rs +++ b/crates/ide-host/tests/integration/open_project.rs @@ -1,7 +1,7 @@ //! Opening the project a window is already opening reuses it: racing opens (a double //! click, a launch path and a restore) must not start a second index and language servers. -mod common; +use crate::common; use ide_host::Host; use std::sync::{Arc, Barrier}; diff --git a/crates/ide-host/tests/plugin_clipboard.rs b/crates/ide-host/tests/integration/plugin_clipboard.rs similarity index 100% rename from crates/ide-host/tests/plugin_clipboard.rs rename to crates/ide-host/tests/integration/plugin_clipboard.rs diff --git a/crates/ide-host/tests/plugin_code_semantics.rs b/crates/ide-host/tests/integration/plugin_code_semantics.rs similarity index 99% rename from crates/ide-host/tests/plugin_code_semantics.rs rename to crates/ide-host/tests/integration/plugin_code_semantics.rs index f76a10c1de..13bade1ce7 100644 --- a/crates/ide-host/tests/plugin_code_semantics.rs +++ b/crates/ide-host/tests/integration/plugin_code_semantics.rs @@ -1,6 +1,6 @@ //! API 1.21 `code.semantics`: read-only LSP semantic queries require capability & trust //! and confine non-virtual target locations to workspace roots. -mod common; +use crate::common; use ide_core::error::ErrorKind; use ide_host::plugins::{Consent, HostWorkspace, PluginHost}; diff --git a/crates/ide-host/tests/plugin_commit.rs b/crates/ide-host/tests/integration/plugin_commit.rs similarity index 100% rename from crates/ide-host/tests/plugin_commit.rs rename to crates/ide-host/tests/integration/plugin_commit.rs diff --git a/crates/ide-host/tests/plugin_completion_list.rs b/crates/ide-host/tests/integration/plugin_completion_list.rs similarity index 99% rename from crates/ide-host/tests/plugin_completion_list.rs rename to crates/ide-host/tests/integration/plugin_completion_list.rs index 5c1e1a59fb..7c270e0b58 100644 --- a/crates/ide-host/tests/plugin_completion_list.rs +++ b/crates/ide-host/tests/integration/plugin_completion_list.rs @@ -1,6 +1,6 @@ //! API 1.16 `completion-list-provider`: a plugin marks its completion incomplete, and typing on //! in the same word asks that plugin again while the language server's list is kept. -mod common; +use crate::common; use ide_core::{ChangeSet, Pos, RequestId, TextChange}; use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers}; diff --git a/crates/ide-host/tests/plugin_completion_resolve.rs b/crates/ide-host/tests/integration/plugin_completion_resolve.rs similarity index 99% rename from crates/ide-host/tests/plugin_completion_resolve.rs rename to crates/ide-host/tests/integration/plugin_completion_resolve.rs index d1bd9abe63..30dd4372d1 100644 --- a/crates/ide-host/tests/plugin_completion_resolve.rs +++ b/crates/ide-host/tests/integration/plugin_completion_resolve.rs @@ -1,6 +1,6 @@ //! API 1.21 `completion-resolve-provider`: listing items with opaque `data`, capability //! enforcement inside lazy `resolve`, and resolving detail/docs/additional_edits on focus. -mod common; +use crate::common; use ide_core::{Pos, RequestId}; use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers}; diff --git a/crates/ide-host/tests/plugin_data_tools.rs b/crates/ide-host/tests/integration/plugin_data_tools.rs similarity index 99% rename from crates/ide-host/tests/plugin_data_tools.rs rename to crates/ide-host/tests/integration/plugin_data_tools.rs index 0e0200bcc9..42a6bb6e90 100644 --- a/crates/ide-host/tests/plugin_data_tools.rs +++ b/crates/ide-host/tests/integration/plugin_data_tools.rs @@ -1,5 +1,5 @@ //! Database and MCP calls through a real sandboxed component. -mod common; +use crate::common; use ide_core::{CancellationToken, IdeEvent, event::McpUiRequest}; use ide_host::{ diff --git a/crates/ide-host/tests/plugin_database_open.rs b/crates/ide-host/tests/integration/plugin_database_open.rs similarity index 99% rename from crates/ide-host/tests/plugin_database_open.rs rename to crates/ide-host/tests/integration/plugin_database_open.rs index 076a23eb80..7a1aefea23 100644 --- a/crates/ide-host/tests/plugin_database_open.rs +++ b/crates/ide-host/tests/integration/plugin_database_open.rs @@ -1,6 +1,6 @@ //! API 1.21 `database.open-console` & `database.open-table-data`: capability gating, //! unknown source rejection, and OpenDatabaseConsole / OpenDatabaseTable event emission. -mod common; +use crate::common; use ide_core::error::ErrorKind; use ide_host::plugins::{Consent, HostWorkspace, PluginEvent, PluginHost}; diff --git a/crates/ide-host/tests/plugin_dependencies.rs b/crates/ide-host/tests/integration/plugin_dependencies.rs similarity index 100% rename from crates/ide-host/tests/plugin_dependencies.rs rename to crates/ide-host/tests/integration/plugin_dependencies.rs diff --git a/crates/ide-host/tests/plugin_diagnostics.rs b/crates/ide-host/tests/integration/plugin_diagnostics.rs similarity index 99% rename from crates/ide-host/tests/plugin_diagnostics.rs rename to crates/ide-host/tests/integration/plugin_diagnostics.rs index fb71e57aae..d6ce6000ef 100644 --- a/crates/ide-host/tests/plugin_diagnostics.rs +++ b/crates/ide-host/tests/integration/plugin_diagnostics.rs @@ -1,5 +1,5 @@ //! Real Wasm provider dispatch and the document-edit path used locally and over RPC. -mod common; +use crate::common; use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, TextChange}; use ide_host::plugins::{Consent, HostWorkspace, PluginEvent, PluginHost, set_editor_providers}; diff --git a/crates/ide-host/tests/plugin_hover.rs b/crates/ide-host/tests/integration/plugin_hover.rs similarity index 100% rename from crates/ide-host/tests/plugin_hover.rs rename to crates/ide-host/tests/integration/plugin_hover.rs diff --git a/crates/ide-host/tests/plugin_indexing.rs b/crates/ide-host/tests/integration/plugin_indexing.rs similarity index 100% rename from crates/ide-host/tests/plugin_indexing.rs rename to crates/ide-host/tests/integration/plugin_indexing.rs diff --git a/crates/ide-host/tests/plugin_inlay_hints.rs b/crates/ide-host/tests/integration/plugin_inlay_hints.rs similarity index 100% rename from crates/ide-host/tests/plugin_inlay_hints.rs rename to crates/ide-host/tests/integration/plugin_inlay_hints.rs diff --git a/crates/ide-host/tests/plugin_language_features.rs b/crates/ide-host/tests/integration/plugin_language_features.rs similarity index 99% rename from crates/ide-host/tests/plugin_language_features.rs rename to crates/ide-host/tests/integration/plugin_language_features.rs index 69c02ce918..0ef4e24cad 100644 --- a/crates/ide-host/tests/plugin_language_features.rs +++ b/crates/ide-host/tests/integration/plugin_language_features.rs @@ -1,5 +1,5 @@ //! The API 1.4 fixture exercises every kind through the real component runtime and editor ops. -mod common; +use crate::common; use ide_core::{CancellationToken, Pos, Range, RequestId}; use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers}; diff --git a/crates/ide-host/tests/plugin_project_view.rs b/crates/ide-host/tests/integration/plugin_project_view.rs similarity index 99% rename from crates/ide-host/tests/plugin_project_view.rs rename to crates/ide-host/tests/integration/plugin_project_view.rs index a39192bf93..2e0e4ccaf2 100644 --- a/crates/ide-host/tests/plugin_project_view.rs +++ b/crates/ide-host/tests/integration/plugin_project_view.rs @@ -1,5 +1,5 @@ //! API 1.21 Project view panes and Git branch menus, through the fixture plugin. -mod common; +use crate::common; use ide_core::ipc_path::to_ipc; use ide_host::plugins::commands::{plugin_project_view_modify, plugin_run_git_command}; diff --git a/crates/ide-host/tests/plugin_refactoring.rs b/crates/ide-host/tests/integration/plugin_refactoring.rs similarity index 99% rename from crates/ide-host/tests/plugin_refactoring.rs rename to crates/ide-host/tests/integration/plugin_refactoring.rs index b3073c7b4d..62f1088f6d 100644 --- a/crates/ide-host/tests/plugin_refactoring.rs +++ b/crates/ide-host/tests/integration/plugin_refactoring.rs @@ -1,5 +1,5 @@ //! Indexed names use the same preview/apply/undo commands as language-server refactorings. -mod common; +use crate::common; use ide_core::{IdeEvent, Pos, RequestId, error::ErrorKind}; use ide_host::{ diff --git a/crates/ide-host/tests/plugin_rename.rs b/crates/ide-host/tests/integration/plugin_rename.rs similarity index 99% rename from crates/ide-host/tests/plugin_rename.rs rename to crates/ide-host/tests/integration/plugin_rename.rs index 05d79c412a..3aed55880d 100644 --- a/crates/ide-host/tests/plugin_rename.rs +++ b/crates/ide-host/tests/integration/plugin_rename.rs @@ -1,6 +1,6 @@ //! API 1.21 `rename-provider`: prepare-rename, cross-file rename via Invocation, //! capability denial/grant handling, and writable-root path confinement. -mod common; +use crate::common; use ide_core::{FileEdit, Pos, RequestId, error::ErrorKind}; use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers}; diff --git a/crates/ide-host/tests/plugin_run_anything.rs b/crates/ide-host/tests/integration/plugin_run_anything.rs similarity index 100% rename from crates/ide-host/tests/plugin_run_anything.rs rename to crates/ide-host/tests/integration/plugin_run_anything.rs diff --git a/crates/ide-host/tests/plugin_run_output.rs b/crates/ide-host/tests/integration/plugin_run_output.rs similarity index 99% rename from crates/ide-host/tests/plugin_run_output.rs rename to crates/ide-host/tests/integration/plugin_run_output.rs index b4ec5e4305..73a7a9ac7e 100644 --- a/crates/ide-host/tests/plugin_run_output.rs +++ b/crates/ide-host/tests/integration/plugin_run_output.rs @@ -1,6 +1,6 @@ //! API 1.21 `run.output` & `ui.set-console-links`: capability gating, declared-command //! validation, console link snapshots/events, and live RunOutput event delivery. -mod common; +use crate::common; use ide_core::error::ErrorKind; use ide_host::plugins::{Consent, HostWorkspace, PluginEvent, PluginHost}; diff --git a/crates/ide-host/tests/plugin_semantic_tokens.rs b/crates/ide-host/tests/integration/plugin_semantic_tokens.rs similarity index 100% rename from crates/ide-host/tests/plugin_semantic_tokens.rs rename to crates/ide-host/tests/integration/plugin_semantic_tokens.rs diff --git a/crates/ide-host/tests/plugin_server_commands.rs b/crates/ide-host/tests/integration/plugin_server_commands.rs similarity index 99% rename from crates/ide-host/tests/plugin_server_commands.rs rename to crates/ide-host/tests/integration/plugin_server_commands.rs index 35c754a3a8..35c8a27547 100644 --- a/crates/ide-host/tests/plugin_server_commands.rs +++ b/crates/ide-host/tests/integration/plugin_server_commands.rs @@ -1,7 +1,7 @@ //! `[[contributes.serverCommands]]` (plugin API 1.9): a command a language server hands to the //! client runs the plugin command that claims it. The fixture's command sends its argument //! back to the server (`mock/ran`), through the real component runtime and `language-servers`. -mod common; +use crate::common; use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/plugin_symbols.rs b/crates/ide-host/tests/integration/plugin_symbols.rs similarity index 100% rename from crates/ide-host/tests/plugin_symbols.rs rename to crates/ide-host/tests/integration/plugin_symbols.rs diff --git a/crates/ide-host/tests/plugin_syntax_decorations.rs b/crates/ide-host/tests/integration/plugin_syntax_decorations.rs similarity index 99% rename from crates/ide-host/tests/plugin_syntax_decorations.rs rename to crates/ide-host/tests/integration/plugin_syntax_decorations.rs index 7a79417134..81f42a8316 100644 --- a/crates/ide-host/tests/plugin_syntax_decorations.rs +++ b/crates/ide-host/tests/integration/plugin_syntax_decorations.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{CancellationToken, Pos, Range, RequestId}; use ide_host::plugins::{Consent, PluginHost}; diff --git a/crates/ide-host/tests/integration/plugin_timers.rs b/crates/ide-host/tests/integration/plugin_timers.rs new file mode 100644 index 0000000000..b539a5b0ea --- /dev/null +++ b/crates/ide-host/tests/integration/plugin_timers.rs @@ -0,0 +1,80 @@ +//! `events.schedule` (API 1.21): one-shot timers a plugin sets for itself, fired in the +//! window that set them, replaced by id, cancelled, and dropped with the window. +use ide_host::plugins::{Consent, PluginHost}; +use ide_plugin::{Invocation, Limits}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const ID: &str = "timers"; + +fn fixture() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/timers") +} + +struct Setup { + _tmp: tempfile::TempDir, + host: PluginHost, +} + +fn setup() -> Setup { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let host = PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + host.load_all(); + host.startup_finished(); + host.install_from_dir(&fixture(), &Consent::all()).unwrap(); + Setup { _tmp: tmp, host } +} + +impl Setup { + fn run(&self, command: &str, arg: &str) -> Result, String> { + let inv = Invocation { client: Some("main".into()), ..Default::default() }; + self.host.run_command(ID, command, Some(arg), inv).map_err(|e| e.message) + } + + /// Delivers what is due `after` from now, then what the plugin received. + fn fired_after(&self, after: Duration) -> Vec { + self.host.flush_events_at(Instant::now() + after); + assert!(self.host.wait_events(Duration::from_secs(10))); + let stored = self.run("fired", "").unwrap(); + stored.map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default() + } +} + +#[test] +fn a_timer_fires_once_when_due_and_the_same_id_replaces_it() { + let s = setup(); + s.run("schedule", "retry 300").unwrap(); + s.run("schedule", "later 300").unwrap(); + s.run("schedule", "later 60000").unwrap(); + assert!(s.fired_after(Duration::ZERO).is_empty(), "nothing is due yet"); + assert_eq!(s.fired_after(Duration::from_secs(2)), ["retry"]); + assert_eq!(s.fired_after(Duration::from_secs(2)), ["retry"], "a timer fires once"); + assert_eq!(s.fired_after(Duration::from_secs(61)), ["retry", "later"]); +} + +#[test] +fn cancelled_timers_and_those_of_a_closed_window_never_fire() { + let s = setup(); + s.run("schedule", "cancelled 300").unwrap(); + s.run("cancel", "cancelled").unwrap(); + s.run("cancel", "unknown").unwrap(); + s.run("schedule", "closed 300").unwrap(); + s.host.forget_client("main"); + s.host.reopen_client("main"); + assert!(s.fired_after(Duration::from_secs(2)).is_empty()); +} + +#[test] +fn schedule_checks_its_bounds() { + let s = setup(); + for arg in ["x 249", "x 86400001", " 1000"] { + assert!(s.run("schedule", arg).unwrap_err().contains("timer"), "{arg}"); + } + for i in 0..16 { + s.run("schedule", &format!("t{i} 1000")).unwrap(); + } + assert!(s.run("schedule", "t16 1000").unwrap_err().contains("at most 16")); + s.run("schedule", "t0 2000").unwrap(); +} diff --git a/crates/ide-host/tests/plugin_view_badge.rs b/crates/ide-host/tests/integration/plugin_view_badge.rs similarity index 100% rename from crates/ide-host/tests/plugin_view_badge.rs rename to crates/ide-host/tests/integration/plugin_view_badge.rs diff --git a/crates/ide-host/tests/plugin_watch_paths.rs b/crates/ide-host/tests/integration/plugin_watch_paths.rs similarity index 100% rename from crates/ide-host/tests/plugin_watch_paths.rs rename to crates/ide-host/tests/integration/plugin_watch_paths.rs diff --git a/crates/ide-host/tests/plugin_workbench.rs b/crates/ide-host/tests/integration/plugin_workbench.rs similarity index 99% rename from crates/ide-host/tests/plugin_workbench.rs rename to crates/ide-host/tests/integration/plugin_workbench.rs index d818eae488..f0b2738d7a 100644 --- a/crates/ide-host/tests/plugin_workbench.rs +++ b/crates/ide-host/tests/integration/plugin_workbench.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{CancellationToken, Diagnostic, Pos, Range, Severity}; use ide_host::plugins::{HostWorkspace, PluginWorkspace}; diff --git a/crates/ide-host/tests/pom_encoding.rs b/crates/ide-host/tests/integration/pom_encoding.rs similarity index 99% rename from crates/ide-host/tests/pom_encoding.rs rename to crates/ide-host/tests/integration/pom_encoding.rs index 227cf62753..dc107fe3c4 100644 --- a/crates/ide-host/tests/pom_encoding.rs +++ b/crates/ide-host/tests/integration/pom_encoding.rs @@ -1,7 +1,7 @@ //! Maven's `project.build.sourceEncoding` is the encoding of the module's sources, //! without becoming a user choice or overriding EditorConfig. -mod common; +use crate::common; use ide_host::{Host, ops}; use ide_workspace::settings::SettingsScope; diff --git a/crates/ide-host/tests/properties.rs b/crates/ide-host/tests/integration/properties.rs similarity index 99% rename from crates/ide-host/tests/properties.rs rename to crates/ide-host/tests/integration/properties.rs index 9cbeabc0a4..5d39a26c9b 100644 --- a/crates/ide-host/tests/properties.rs +++ b/crates/ide-host/tests/integration/properties.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{ChangeSet, RequestId, TextChange}; use ide_host::{ diff --git a/crates/ide-host/tests/pytest_fixtures.rs b/crates/ide-host/tests/integration/pytest_fixtures.rs similarity index 99% rename from crates/ide-host/tests/pytest_fixtures.rs rename to crates/ide-host/tests/integration/pytest_fixtures.rs index b147d01d8f..914eb14c99 100644 --- a/crates/ide-host/tests/pytest_fixtures.rs +++ b/crates/ide-host/tests/integration/pytest_fixtures.rs @@ -2,7 +2,7 @@ //! on a project on disk: which files are searched, overrides left out, `pytest_plugins` //! modules, `python_files`, body reads and name clashes. -mod common; +use crate::common; use ide_core::{FileEdit, Pos}; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/python_move.rs b/crates/ide-host/tests/integration/python_move.rs similarity index 99% rename from crates/ide-host/tests/python_move.rs rename to crates/ide-host/tests/integration/python_move.rs index 441d559c8b..d7dcae0d96 100644 --- a/crates/ide-host/tests/python_move.rs +++ b/crates/ide-host/tests/integration/python_move.rs @@ -2,7 +2,7 @@ //! Python before and after, and must print the same. `#[ignore]`d: it needs `pylsp` on `PATH` //! (the helper runs with that environment's Python). -mod common; +use crate::common; use ide_core::{ChangeSet, IdeEvent, RequestId, SharedSink, TextChange}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/python_rename_comments.rs b/crates/ide-host/tests/integration/python_rename_comments.rs similarity index 99% rename from crates/ide-host/tests/python_rename_comments.rs rename to crates/ide-host/tests/integration/python_rename_comments.rs index f11658658e..790c014a50 100644 --- a/crates/ide-host/tests/python_rename_comments.rs +++ b/crates/ide-host/tests/integration/python_rename_comments.rs @@ -2,7 +2,7 @@ //! merged edit the preview shows, applying it and undoing it in one step. Needs //! `basedpyright-langserver` on PATH: //! `cargo test -p ide-host --test python_rename_comments -- --ignored` -mod common; +use crate::common; use ide_core::{IdeEvent, Pos, RequestId, WorkspaceEdit}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/python_signature.rs b/crates/ide-host/tests/integration/python_signature.rs similarity index 100% rename from crates/ide-host/tests/python_signature.rs rename to crates/ide-host/tests/integration/python_signature.rs diff --git a/crates/ide-host/tests/python_signature_ops.rs b/crates/ide-host/tests/integration/python_signature_ops.rs similarity index 99% rename from crates/ide-host/tests/python_signature_ops.rs rename to crates/ide-host/tests/integration/python_signature_ops.rs index 0f4d21831d..b133ca84b3 100644 --- a/crates/ide-host/tests/python_signature_ops.rs +++ b/crates/ide-host/tests/integration/python_signature_ops.rs @@ -2,7 +2,7 @@ //! edit it computes from the open (unsaved) buffers, applying it and undoing it. `#[ignore]`d: //! it needs `pylsp` with rope on `PATH` (`pip install python-lsp-server pylsp-rope`). -mod common; +use crate::common; use ide_core::{ChangeSet, IdeEvent, Pos, RequestId, SharedSink, TextChange, error::ErrorKind}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/remote_daemon.rs b/crates/ide-host/tests/integration/remote_daemon.rs similarity index 99% rename from crates/ide-host/tests/remote_daemon.rs rename to crates/ide-host/tests/integration/remote_daemon.rs index 1d34f82f4e..610dae0edb 100644 --- a/crates/ide-host/tests/remote_daemon.rs +++ b/crates/ide-host/tests/integration/remote_daemon.rs @@ -3,8 +3,6 @@ //! (including `stopCommand` configs such as `docker compose`) and dirty buffers //! running until a client sends `"shutdown"` or the backend has been idle long enough. -#![cfg(unix)] - use ide_host::rpc::{self, ChannelMessage, EventMessage, Invoke, ServerInfo}; use ide_jsonrpc::{Handler, Peer}; use parking_lot::Mutex; diff --git a/crates/ide-host/tests/remote_plugins.rs b/crates/ide-host/tests/integration/remote_plugins.rs similarity index 99% rename from crates/ide-host/tests/remote_plugins.rs rename to crates/ide-host/tests/integration/remote_plugins.rs index 4ca2a9833f..1a3c0858b4 100644 --- a/crates/ide-host/tests/remote_plugins.rs +++ b/crates/ide-host/tests/integration/remote_plugins.rs @@ -3,9 +3,7 @@ //! code plugins over the remote protocol; Checkstyle then checks the file on //! the server's disk when it is saved, and secrets come from the desktop. -#![cfg(unix)] - -mod common; +use crate::common; use ide_core::IdeEvent; use ide_host::plugins::remote_host::{ diff --git a/crates/ide-host/tests/replace_all.rs b/crates/ide-host/tests/integration/replace_all.rs similarity index 99% rename from crates/ide-host/tests/replace_all.rs rename to crates/ide-host/tests/integration/replace_all.rs index 7f2d2f5175..6cd88ac016 100644 --- a/crates/ide-host/tests/replace_all.rs +++ b/crates/ide-host/tests/integration/replace_all.rs @@ -1,7 +1,7 @@ //! Replace All when the search hit its match limit (#4083): every match in the //! scope is replaced, not just the listed ones. -mod common; +use crate::common; use ide_core::{Pos, RequestId}; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/roslyn_editorconfig.rs b/crates/ide-host/tests/integration/roslyn_editorconfig.rs similarity index 99% rename from crates/ide-host/tests/roslyn_editorconfig.rs rename to crates/ide-host/tests/integration/roslyn_editorconfig.rs index 1b9ab599b0..0c9cf4473e 100644 --- a/crates/ide-host/tests/roslyn_editorconfig.rs +++ b/crates/ide-host/tests/integration/roslyn_editorconfig.rs @@ -2,7 +2,7 @@ //! language server installed as Settings does. It downloads the server, so it runs only on request: //! `cargo test -p ide-host --test roslyn_editorconfig -- --ignored`; skipped without a .NET SDK. -mod common; +use crate::common; use ide_core::{DocId, IdeEvent, Pos, Range, RequestId, Severity}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/roslyn_hints.rs b/crates/ide-host/tests/integration/roslyn_hints.rs similarity index 99% rename from crates/ide-host/tests/roslyn_hints.rs rename to crates/ide-host/tests/integration/roslyn_hints.rs index 0945e10f16..bdeb817611 100644 --- a/crates/ide-host/tests/roslyn_hints.rs +++ b/crates/ide-host/tests/integration/roslyn_hints.rs @@ -2,7 +2,7 @@ //! csharp-ls and the Roslyn language server, installed as Settings does (network). Ignored by //! default: `cargo test -p ide-host --test roslyn_hints -- --ignored`; skipped without a .NET SDK. -mod common; +use crate::common; use ide_core::{DocId, Pos, Range}; use ide_host::{Host, HostConfig, ops}; diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/integration/rpc.rs similarity index 99% rename from crates/ide-host/tests/rpc.rs rename to crates/ide-host/tests/integration/rpc.rs index a66da9348e..5619c90f29 100644 --- a/crates/ide-host/tests/rpc.rs +++ b/crates/ide-host/tests/integration/rpc.rs @@ -1,7 +1,7 @@ //! The remote protocol end to end: a server on one side of an in-memory pipe, //! a JSON-RPC client on the other. -mod common; +use crate::common; use ide_host::rpc::{self, ChannelMessage, Dispatcher, EventMessage, Invoke, ServerInfo}; use ide_host::{Host, HostConfig}; diff --git a/crates/ide-host/tests/run_configs.rs b/crates/ide-host/tests/integration/run_configs.rs similarity index 99% rename from crates/ide-host/tests/run_configs.rs rename to crates/ide-host/tests/integration/run_configs.rs index 4281e2b47d..c7bc0a77a0 100644 --- a/crates/ide-host/tests/run_configs.rs +++ b/crates/ide-host/tests/integration/run_configs.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_host::{Host, ops}; use std::sync::Arc; diff --git a/crates/ide-host/tests/search_encoding.rs b/crates/ide-host/tests/integration/search_encoding.rs similarity index 99% rename from crates/ide-host/tests/search_encoding.rs rename to crates/ide-host/tests/integration/search_encoding.rs index 9831de0242..1e9a49a0ac 100644 --- a/crates/ide-host/tests/search_encoding.rs +++ b/crates/ide-host/tests/integration/search_encoding.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/settings_sync.rs b/crates/ide-host/tests/integration/settings_sync.rs similarity index 99% rename from crates/ide-host/tests/settings_sync.rs rename to crates/ide-host/tests/integration/settings_sync.rs index b89a738303..d840d24034 100644 --- a/crates/ide-host/tests/settings_sync.rs +++ b/crates/ide-host/tests/integration/settings_sync.rs @@ -1,6 +1,6 @@ //! Settings Sync between two machines through a local bare repository. -mod common; +use crate::common; use ide_host::Host; use ide_host::ops::settings_sync::{SettingsSyncMode, SettingsSyncResult, has_local_changes, sync_now}; diff --git a/crates/ide-host/tests/spell_dictionary.rs b/crates/ide-host/tests/integration/spell_dictionary.rs similarity index 100% rename from crates/ide-host/tests/spell_dictionary.rs rename to crates/ide-host/tests/integration/spell_dictionary.rs diff --git a/crates/ide-host/tests/ssh_terminal.rs b/crates/ide-host/tests/integration/ssh_terminal.rs similarity index 88% rename from crates/ide-host/tests/ssh_terminal.rs rename to crates/ide-host/tests/integration/ssh_terminal.rs index a9e08a8a47..471037cd8d 100644 --- a/crates/ide-host/tests/ssh_terminal.rs +++ b/crates/ide-host/tests/integration/ssh_terminal.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::remote_settings::{SshAuth, SshConfiguration}; use ide_core::{IdeEvent, SharedSink}; @@ -91,6 +91,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() { &host, "main", "box", + None, 100, 30, Arc::new(move |s| { @@ -116,7 +117,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() { assert!(!host.terminals.contains(info.id)); // Closing the tab hangs up a running shell. - let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", 80, 24, Arc::new(|_| {})).await.unwrap(); + let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", None, 80, 24, Arc::new(|_| {})).await.unwrap(); host.terminals.kill(info.id).unwrap(); let code = loop { match events.recv_timeout(Duration::from_secs(10)).expect("exit event") { @@ -128,6 +129,31 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() { host.shutdown().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_session_in_a_directory_starts_the_login_shell_there() { + let tmp = tempfile::tempdir().unwrap(); + let (host, _events) = host_with_ssh_box(tmp.path(), Arc::new(|cmd| (format!("ran: {cmd}\n"), 0))).await; + let (tx, output) = mpsc::channel(); + let tx = Mutex::new(tx); + ide_host::ops::term::spawn_ssh( + &host, + "main", + "box", + Some("~/my app's"), + 80, + 24, + Arc::new(move |s| { + let _ = tx.lock().unwrap().send(s); + }), + ) + .await + .unwrap(); + // The server answers the PTY request ("pty 80x24") first, in its own packet on Linux. + let out = read_until(&output, "-l\n"); + assert!(out.contains(r#"ran: cd -- ~/'my app'\''s'; exec "${SHELL:-/bin/sh}" -l"#), "{out:?}"); + host.shutdown().await; +} + /// Reads what a connection to the local end of a Docker tunnel gets back. async fn dial(port: u16) -> std::io::Result { use tokio::io::AsyncReadExt; diff --git a/crates/ide-host/tests/svn.rs b/crates/ide-host/tests/integration/svn.rs similarity index 95% rename from crates/ide-host/tests/svn.rs rename to crates/ide-host/tests/integration/svn.rs index 37310b6fbe..1256ef70bb 100644 --- a/crates/ide-host/tests/svn.rs +++ b/crates/ide-host/tests/integration/svn.rs @@ -1,7 +1,7 @@ //! Subversion working copies through the shared `vcs_*` commands and the //! `svn_*` ones, against throwaway `svnadmin` repositories (`file://` URLs). //! Skipped when `svn` or `svnadmin` is not installed. -mod common; +use crate::common; use ide_core::CancellationToken; use ide_host::Host; @@ -1306,7 +1306,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() { assert!(incoming[0].time_ms > 0.0); // 2. svn_working_copy_info returns info for all SVN roots in the project. - let infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap(); + let infos = svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap(); assert_eq!(infos.len(), 1); assert_eq!(infos[0].url, trunk_url); assert_eq!(infos[0].repository_root, fx.url); @@ -1347,7 +1347,10 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() { .await .unwrap(); assert!(reached.is_some()); - assert_eq!(svn::svn_working_copy_info(&host, "main", None).await.unwrap()[0].url, feat_url); + assert_eq!( + svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap()[0].url, + feat_url + ); std::fs::write(wc1.join("branch.txt"), "branch\n").unwrap(); fx.svn(&wc1, &["add", "-q", "branch.txt"]); @@ -1390,7 +1393,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() { ) .await .unwrap(); - let all_infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap(); + let all_infos = svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), None).await.unwrap(); assert!( all_infos.iter().any(|i| i.root == sub_dir.display().to_string() && i.is_switched), "expected switched descendant in wc info: {all_infos:?}" @@ -1402,7 +1405,7 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() { untrusted_host.open_project("restricted", &untrusted_wc).unwrap(); for err in [ svn::svn_incoming(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(), - svn::svn_working_copy_info(&untrusted_host, "restricted", None).await.unwrap_err(), + svn::svn_working_copy_info(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(), svn::svn_branch_layout(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(), svn::svn_compare_with_url(&untrusted_host, "restricted", ide_core::RequestId::next(), None, trunk_url, None) .await @@ -1419,6 +1422,29 @@ async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() { ) .await .unwrap_err(), + // The Subversion tool window's commands (review of #8212, M11). + svn::svn_incoming_revisions(&untrusted_host, "restricted", ide_core::RequestId::next(), true) + .await + .unwrap_err(), + svn::svn_revisions_between( + &untrusted_host, + "restricted", + ide_core::RequestId::next(), + untrusted_wc.clone(), + 1, + 2, + ) + .await + .unwrap_err(), + svn::svn_upgrade( + &untrusted_host, + "restricted", + ide_core::RequestId::next(), + untrusted_wc.clone(), + "1.8".into(), + ) + .await + .unwrap_err(), ] { assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable, "{err:?}"); } @@ -1690,7 +1716,7 @@ async fn incoming_revisions_of_two_working_copies() { host.trust.decide(&project_root, true, false).unwrap(); let project = host.open_project("main", &project_root).unwrap(); until("both working copies", || project.backends().len() == 2).await; - let incoming = || svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next()); + let incoming = || svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next(), false); let found = incoming().await.unwrap(); assert!(found.errors.is_empty(), "{:?}", found.errors); for name in ["boot", "antd"] { @@ -1712,3 +1738,64 @@ async fn incoming_revisions_of_two_working_copies() { let antd = project_root.join("antd").display().to_string(); assert_eq!(roots, [(antd.clone(), 4), (antd, 3)]); } + +/// Review of #8212, H5: Incoming reads under the project's requests, so taking the project's +/// trust back stops an svn still waiting on the server. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn restricted_mode_stops_an_incoming_read() { + let Some(fx) = fixture() else { return }; + let root = fx.checkout("wc"); + let real = which("svn").unwrap(); + let started = fx.base.join("started"); + // `svn status -u` (Incoming's server read) hangs; everything else is the real svn. + let svn = script( + &fx.base, + "slow-svn", + &format!( + "#!/bin/sh\ncase \"$*\" in *status*-u*) touch '{}'; exec sleep 60;; esac\nexec '{}' \"$@\"\n", + started.display(), + real.display() + ), + ); + std::fs::create_dir(root.join(".openidea")).unwrap(); + std::fs::write( + root.join(".openidea/settings.toml"), + format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()), + ) + .unwrap(); + let (host, _project) = open(&fx.base, &root).await; + let host = Arc::new(host); + let read = tokio::spawn({ + let host = host.clone(); + async move { svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next(), true).await } + }); + until("svn status -u", || started.exists()).await; + let at = std::time::Instant::now(); + host.set_project_trust(&root, false, false).await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(20), read).await.expect("the read stopped").unwrap(); + assert!(at.elapsed() < Duration::from_secs(20)); + assert!(result.is_err(), "{result:?}"); +} + +/// Review of #8212, H1: a project inside a larger checkout cannot change the checkout's format. +#[tokio::test] +async fn a_project_inside_a_checkout_cannot_change_its_format() { + let Some(fx) = fixture() else { return }; + let outer = fx.checkout("outer"); + std::fs::create_dir(outer.join("sub")).unwrap(); + std::fs::write(outer.join("sub/x.txt"), "x\n").unwrap(); + fx.svn(&outer, &["add", "-q", "sub"]); + fx.svn(&outer, &["commit", "-q", "-m", "add a folder"]); + let sub = outer.join("sub"); + let (host, _project) = open(&fx.base, &sub).await; + let infos = + svn::svn_working_copy_info(&host, "main", ide_core::RequestId::next(), Some(sub.clone())).await.unwrap(); + let newest = infos[0].formats.last().cloned().expect("the formats this svn writes"); + // `.svn/wc.db`'s SQLite user version: the format (no `svn info --show-item wc-format` before 1.10). + let format = || std::fs::read(outer.join(".svn/wc.db")).unwrap()[60..64].to_vec(); + let before = format(); + let err = svn::svn_upgrade(&host, "main", ide_core::RequestId::next(), sub, newest).await.unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput, "{err:?}"); + assert_eq!(format(), before); +} diff --git a/crates/ide-host/tests/terminal_images.rs b/crates/ide-host/tests/integration/terminal_images.rs similarity index 97% rename from crates/ide-host/tests/terminal_images.rs rename to crates/ide-host/tests/integration/terminal_images.rs index ceea03ea4b..17e2d670bd 100644 --- a/crates/ide-host/tests/terminal_images.rs +++ b/crates/ide-host/tests/integration/terminal_images.rs @@ -1,6 +1,4 @@ -#![cfg(any(unix, windows))] - -mod common; +use crate::common; use ide_core::{NullSink, TerminalId}; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/trust.rs b/crates/ide-host/tests/integration/trust.rs similarity index 99% rename from crates/ide-host/tests/trust.rs rename to crates/ide-host/tests/integration/trust.rs index d4aa89511a..48d7cb8e30 100644 --- a/crates/ide-host/tests/trust.rs +++ b/crates/ide-host/tests/integration/trust.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; #[cfg(unix)] use ide_host::ops; diff --git a/crates/ide-host/tests/trust_git_binary.rs b/crates/ide-host/tests/integration/trust_git_binary.rs similarity index 97% rename from crates/ide-host/tests/trust_git_binary.rs rename to crates/ide-host/tests/integration/trust_git_binary.rs index d26f16b427..d15bcee023 100644 --- a/crates/ide-host/tests/trust_git_binary.rs +++ b/crates/ide-host/tests/integration/trust_git_binary.rs @@ -1,7 +1,5 @@ -//! Which git executable each window's repositories run. Its own test binary: the default -//! executable (global settings) is process-wide. -#![cfg(unix)] -mod common; +//! Which git executable each window's repositories run (project-scoped `.openidea/settings.toml`). +use crate::common; use ide_host::{Host, ops}; use std::os::unix::fs::PermissionsExt; diff --git a/crates/ide-host/tests/trust_vcs_sweep.rs b/crates/ide-host/tests/integration/trust_vcs_sweep.rs similarity index 99% rename from crates/ide-host/tests/trust_vcs_sweep.rs rename to crates/ide-host/tests/integration/trust_vcs_sweep.rs index 71df600ceb..525853fd69 100644 --- a/crates/ide-host/tests/trust_vcs_sweep.rs +++ b/crates/ide-host/tests/integration/trust_vcs_sweep.rs @@ -1,7 +1,7 @@ //! Security audit lead 2: every `vcs_*` command Restricted Mode allows, run against a //! repository whose config names a program for a signed commit, an index read, an external //! diff, a clean filter and a missing object. None may run. -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{Host, catalogue::TrustClass, ops, ops::vcs}; diff --git a/crates/ide-host/tests/unity.rs b/crates/ide-host/tests/integration/unity.rs similarity index 99% rename from crates/ide-host/tests/unity.rs rename to crates/ide-host/tests/integration/unity.rs index 41f90e2701..a8a03fc078 100644 --- a/crates/ide-host/tests/unity.rs +++ b/crates/ide-host/tests/integration/unity.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/vcs_backends.rs b/crates/ide-host/tests/integration/vcs_backends.rs similarity index 99% rename from crates/ide-host/tests/vcs_backends.rs rename to crates/ide-host/tests/integration/vcs_backends.rs index 2b5fbe1309..f3d9c1de1c 100644 --- a/crates/ide-host/tests/vcs_backends.rs +++ b/crates/ide-host/tests/integration/vcs_backends.rs @@ -1,7 +1,7 @@ //! A version control system besides Git plugs in through `BackendProvider`, the way //! Perforce and Subversion do: an in-memory fake here, so nothing but `git` has to be //! installed. -mod common; +use crate::common; use ide_core::{CancellationToken, IdeError, IdeResult}; use ide_host::{ diff --git a/crates/ide-host/tests/vcs_delete_added.rs b/crates/ide-host/tests/integration/vcs_delete_added.rs similarity index 99% rename from crates/ide-host/tests/vcs_delete_added.rs rename to crates/ide-host/tests/integration/vcs_delete_added.rs index 99b4daa6ef..9558428572 100644 --- a/crates/ide-host/tests/vcs_delete_added.rs +++ b/crates/ide-host/tests/integration/vcs_delete_added.rs @@ -1,7 +1,7 @@ //! #7333: Delete of a file that was only added to Git also drops it from the index, as IDEA //! does, so it does not linger as `AD`; Undo brings the content back without touching the index. -mod common; +use crate::common; use ide_host::{Host, Project}; use std::{ diff --git a/crates/ide-host/tests/vcs_documents.rs b/crates/ide-host/tests/integration/vcs_documents.rs similarity index 99% rename from crates/ide-host/tests/vcs_documents.rs rename to crates/ide-host/tests/integration/vcs_documents.rs index ac83990157..1fda331ecb 100644 --- a/crates/ide-host/tests/vcs_documents.rs +++ b/crates/ide-host/tests/integration/vcs_documents.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{ChangeSet, TextChange}; use ide_host::{Host, Project, ops::vcs}; diff --git a/crates/ide-host/tests/vcs_encoding.rs b/crates/ide-host/tests/integration/vcs_encoding.rs similarity index 99% rename from crates/ide-host/tests/vcs_encoding.rs rename to crates/ide-host/tests/integration/vcs_encoding.rs index bf90bcb5f5..db4067c89d 100644 --- a/crates/ide-host/tests/vcs_encoding.rs +++ b/crates/ide-host/tests/integration/vcs_encoding.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{ChangeSet, TextChange}; use ide_host::{Host, Project, ops::vcs}; diff --git a/crates/ide-host/tests/vcs_flow.rs b/crates/ide-host/tests/integration/vcs_flow.rs similarity index 99% rename from crates/ide-host/tests/vcs_flow.rs rename to crates/ide-host/tests/integration/vcs_flow.rs index c142b0ae14..a2072cdb85 100644 --- a/crates/ide-host/tests/vcs_flow.rs +++ b/crates/ide-host/tests/integration/vcs_flow.rs @@ -2,7 +2,7 @@ //! marked in the gutter, Local Changes and its diff, a commit in the log, a branch, a stash, and //! a merge that conflicts, resolved and committed. Open documents follow every step. -mod common; +use crate::common; use ide_core::DocId; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/vcs_roots.rs b/crates/ide-host/tests/integration/vcs_roots.rs similarity index 99% rename from crates/ide-host/tests/vcs_roots.rs rename to crates/ide-host/tests/integration/vcs_roots.rs index a174d4f5a6..4356af976c 100644 --- a/crates/ide-host/tests/vcs_roots.rs +++ b/crates/ide-host/tests/integration/vcs_roots.rs @@ -1,5 +1,5 @@ //! Repository-scoped patch operations must never fall back to the primary root. -mod common; +use crate::common; use ide_host::{Host, ops::vcs}; use std::{path::Path, process::Command, time::Duration}; diff --git a/crates/ide-host/tests/vcs_shelf_roots.rs b/crates/ide-host/tests/integration/vcs_shelf_roots.rs similarity index 99% rename from crates/ide-host/tests/vcs_shelf_roots.rs rename to crates/ide-host/tests/integration/vcs_shelf_roots.rs index 1ddd12afcf..5d1e408312 100644 --- a/crates/ide-host/tests/vcs_shelf_roots.rs +++ b/crates/ide-host/tests/integration/vcs_shelf_roots.rs @@ -1,5 +1,5 @@ //! Shelves retain their repository even when the project root is above or below it. -mod common; +use crate::common; use ide_host::{Host, ops::vcs}; use std::{path::Path, process::Command, time::Duration}; diff --git a/crates/ide-host/tests/vcs_watcher_moved_repository.rs b/crates/ide-host/tests/integration/vcs_watcher_moved_repository.rs similarity index 99% rename from crates/ide-host/tests/vcs_watcher_moved_repository.rs rename to crates/ide-host/tests/integration/vcs_watcher_moved_repository.rs index 9d651434b5..02d8733fd2 100644 --- a/crates/ide-host/tests/vcs_watcher_moved_repository.rs +++ b/crates/ide-host/tests/integration/vcs_watcher_moved_repository.rs @@ -2,7 +2,7 @@ //! the folder brings no `.git` event of its own, so the watcher's "created path" is what the //! rescan has to answer to (the open scan already ran). -mod common; +use crate::common; use ide_host::Host; use std::{path::Path, time::Duration}; diff --git a/crates/ide-host/tests/vcs_worktrees.rs b/crates/ide-host/tests/integration/vcs_worktrees.rs similarity index 99% rename from crates/ide-host/tests/vcs_worktrees.rs rename to crates/ide-host/tests/integration/vcs_worktrees.rs index ce080f70ae..faf5107167 100644 --- a/crates/ide-host/tests/vcs_worktrees.rs +++ b/crates/ide-host/tests/integration/vcs_worktrees.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::RequestId; use ide_host::{Host, Project, ops::vcs}; diff --git a/crates/ide-host/tests/workspace_edits.rs b/crates/ide-host/tests/integration/workspace_edits.rs similarity index 97% rename from crates/ide-host/tests/workspace_edits.rs rename to crates/ide-host/tests/integration/workspace_edits.rs index 8079afc3bd..83fe23dc9e 100644 --- a/crates/ide-host/tests/workspace_edits.rs +++ b/crates/ide-host/tests/integration/workspace_edits.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{IdeEvent, SharedSink, WorkspaceEdit, error::ErrorKind}; use ide_host::{Host, HostConfig, ops}; @@ -342,11 +342,10 @@ async fn a_server_edit_may_version_files_the_editor_never_opened() { ops::lsp::lsp_execute_command(&host, "main", info.id, command) }; + // A created file takes the system line separator (CRLF on Windows). + let read = |name: &str| std::fs::read_to_string(root.join(name)).unwrap().replace("\r\n", "\n"); run("gopls.add_test", json!({})).await.unwrap(); - assert_eq!( - std::fs::read_to_string(root.join("add_test.go")).unwrap(), - "package x_test\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {}\n" - ); + assert_eq!(read("add_test.go"), "package x_test\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {}\n"); // The open file must still be at the version the server names: an edit made before the // user typed is refused. @@ -371,6 +370,6 @@ async fn a_server_edit_may_version_files_the_editor_never_opened() { ops::doc::doc_snapshot(&host, "main", info.id).await.unwrap().text, "package x\n\n// Add returns the sum.\nfunc Add(a, b int) int { return a + b }\n\n// more\n" ); - assert_eq!(std::fs::read_to_string(root.join("two.go")).unwrap(), "package x\n\nfunc Two() int { return 2 }\n"); + assert_eq!(read("two.go"), "package x\n\nfunc Two() int { return 2 }\n"); accept.abort(); } diff --git a/crates/ide-host/tests/workspaces.rs b/crates/ide-host/tests/integration/workspaces.rs similarity index 99% rename from crates/ide-host/tests/workspaces.rs rename to crates/ide-host/tests/integration/workspaces.rs index cf90e653c8..c6994f2e06 100644 --- a/crates/ide-host/tests/workspaces.rs +++ b/crates/ide-host/tests/integration/workspaces.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use ide_core::{ChangeSet, RequestId, TextChange}; use ide_host::{Host, ops}; diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 0a1765b731..c787511fac 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -1451,6 +1451,105 @@ async fn granted_agents_fork_reaches_the_core() { host.close_project_detached("main"); } +/// A real Host over `f.project` with `misbehave` granted `agents` at `engines`. +/// Hermetic HOME: the core scans the home transcript folders when forking. +fn agents_host(f: &Fixture, engines: &str) -> Arc { + // SAFETY: set before the Host reads HOME; nextest isolates this test's process. + unsafe { std::env::set_var("HOME", f._tmp.path().join("home")) }; + let host = Arc::new(Host::new(common::host_config(f._tmp.path()))); + host.trust.decide(&f.project, true, false).unwrap(); + host.open_project("main", &f.project).unwrap(); + f.host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); + let pkg = f._tmp.path().join("misbehave-agents"); + copy_dir(&misbehave_pkg(), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text + .replace("required = [\"project.read\"]", "required = [\"project.read\", \"agents\"]") + .replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engines}\"")); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + host +} + +/// A missing `agents` grant is an error the plugin can handle, not a trap (API 1.21). +#[test] +fn ungranted_agents_start_task_is_denied_not_trapped() { + let f = fixture(Limits::default()); + let pkg = f._tmp.path().join("misbehave-no-agents"); + copy_dir(&misbehave_pkg(), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.21\""); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + let err = f.host.run_command("misbehave", "start-task", Some("claude investigate this"), f.inv()).unwrap_err(); + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}"); + assert!(err.message.contains("agents"), "{err:?}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); + assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing"); +} + +/// With the `agents` grant the task is created UNSENT: Ready, no turn, nothing +/// queued, and `OpenAgentTask` carries its id and the prompt for the user to review. +#[tokio::test(flavor = "multi_thread")] +async fn granted_agents_start_task_creates_an_unsent_task() { + let f = fixture(Limits::default()); + let host = agents_host(&f, "^1.21"); + f.take_events(); + let id = f.run("misbehave", "start-task", Some("claude investigate this")).unwrap().unwrap(); + let project = host.project("main").unwrap(); + let agents = &project.agents; + let task = agents.task_snapshot(&id).expect("the task exists"); + assert_eq!(task.status, ide_agent::AgentStatus::Ready, "created unsent"); + assert_eq!((task.provider.as_str(), task.title.as_str()), ("claude", "investigate this")); + assert_eq!(task.isolation, ide_agent::Isolation::Local); + assert!(task.queue.is_empty(), "nothing is queued to send"); + assert!(agents.entries(&id, None).unwrap().is_empty(), "no turn was sent"); + let events = f.take_events(); + assert!( + events.iter().any(|(client, e)| client.as_deref() == Some("main") + && matches!(e, PluginEvent::OpenAgentTask { task_id, prompt } if task_id == &id && prompt == "investigate this")), + "OpenAgentTask emitted: {events:?}" + ); + // Detached: the blocking close joins the LSP/index workers, which can stall under nextest. + host.close_project_detached("main"); +} + +/// The `fork` variant reuses fork-session's validation: an unknown session is the +/// core's not-found, exactly as `fork-session` reports it. +#[tokio::test(flavor = "multi_thread")] +async fn granted_agents_start_task_fork_reuses_fork_validation() { + let f = fixture(Limits::default()); + let host = agents_host(&f, "^1.21"); + let session = "11111111-2222-3333-4444-555555555555"; + let arg = format!("fork claude {session} {} continue the recording", f.project.to_str().unwrap()); + let err = f.run("misbehave", "start-task", Some(&arg)).unwrap_err(); + assert!(err.contains("unknown claude session"), "{err}"); + host.close_project_detached("main"); +} + +/// API 1.21: a pre-1.21 `engines.openidea` is refused by `require_api`, not trapped. +#[test] +fn agents_start_task_requires_api_1_21() { + let f = fixture(Limits::default()); + let pkg = f._tmp.path().join("misbehave-agents-118"); + copy_dir(&misbehave_pkg(), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text + .replace("required = [\"project.read\"]", "required = [\"project.read\", \"agents\"]") + .replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\""); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + let err = f.run("misbehave", "start-task", Some("claude investigate this")).unwrap_err(); + assert!(err.contains("set engines.openidea"), "{err}"); + assert!(err.contains("1.21"), "{err}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); +} + /// A trap drops the instance, which restarts on next use after a /// backoff that doubles; only consecutive crashes stop the plugin. #[test] @@ -1734,7 +1833,7 @@ fn idle_instances_are_reclaimed_and_schedules_reactivate() { assert_eq!(f.host.instances(), 0); let info = f.host.info_of("misbehave").unwrap(); assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1)); - assert_eq!(f.command_titles("misbehave").len(), 25, "contributions stay"); + assert_eq!(f.command_titles("misbehave").len(), 26, "contributions stay"); assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y")); assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2); @@ -3366,7 +3465,13 @@ fn official_license_header_reports_fixes_and_scans() { #[test] fn official_mybatis_navigates_between_interface_and_xml() { let f = fixture(Limits::default()); + assert!(f.host.line_marker_languages_with("java").is_empty()); f.install(&official("mybatis")); + // One plugin's two declarations: a saved Kotlin file can change the XML's markers too. + let mut languages = f.host.line_marker_languages_with("kotlin"); + languages.sort(); + assert_eq!(languages, ["java", "kotlin", "xml"]); + assert!(f.host.line_marker_languages_with("markdown").is_empty()); let java_path = f.project.join("src/main/java/com/acme/UserMapper.java"); let xml_path = f.project.join("src/main/resources/mapper/UserMapper.xml"); std::fs::create_dir_all(java_path.parent().unwrap()).unwrap(); @@ -3394,7 +3499,7 @@ fn official_mybatis_navigates_between_interface_and_xml() { // skipped. The editor asks again; so does this. let deadline = Instant::now() + Duration::from_secs(10); let markers = loop { - let markers = f.host.provide_line_markers(&jdoc); + let markers = f.host.provide_line_markers(&jdoc).0; if !markers.is_empty() || Instant::now() > deadline { break markers; } @@ -3425,7 +3530,7 @@ fn official_mybatis_navigates_between_interface_and_xml() { let mut times = Vec::new(); for _ in 0..20 { let started = Instant::now(); - assert_eq!(f.host.provide_line_markers(&jdoc).len(), 1); + assert_eq!(f.host.provide_line_markers(&jdoc).0.len(), 1); times.push(started.elapsed()); } times.sort(); @@ -6476,8 +6581,8 @@ fn marker_providers_preserve_names_and_package_paths() { version: 1, text: "marker-icons\nordinary\ncustom\nlegacy".into(), }; - assert!(eventually(|| f.host.provide_line_markers(&doc).len() == 4)); - let markers = f.host.provide_line_markers(&doc); + assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 4)); + let markers = f.host.provide_line_markers(&doc).0; assert_eq!( markers.iter().map(|(_, m)| m.icon.as_deref().unwrap()).collect::>(), ["run", "database", "icons/very-long-resource-marker-icon.svg", "overriding"] @@ -7763,6 +7868,99 @@ fn styled_decorations_carry_normalized_colors() { f.run("decorations", "clear", None).unwrap(); } +/// API 1.21: a missing `project.read` grant is an error the plugin can handle, not a trap. +#[test] +fn ungranted_actionable_decoration_is_denied_not_trapped() { + let f = fixture(Limits::default()); + let pkg = f._tmp.path().join("decorations-no-project-read"); + copy_dir(&sample("decorations"), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text.replace("required = [\"project.read\"]", "required = []"); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + let err = f.host.run_command("decorations", "actionable", Some("src/notes.txt"), f.inv()).unwrap_err(); + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}"); + assert!(err.message.contains("project.read"), "{err:?}"); + let info = f.host.info_of("decorations").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); + assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing"); +} + +/// API 1.21: with the grant the actionable set reaches storage and `DecorationsChanged` +/// carries the actions, each naming a command the plugin declares. +#[test] +fn actionable_decorations_reach_storage_and_carry_actions() { + let f = fixture(Limits::default()); + f.install(&sample("decorations")); + f.take_events(); + f.run("decorations", "actionable", Some("src/notes.txt")).unwrap(); + let sets = f.host.decoration_sets(); + let set = &sets["decorations"][0]; + assert_eq!((set.set_id.as_str(), set.tree), ("example", false)); + assert_eq!(set.items.len(), 1); + assert_eq!(set.items[0].actions.len(), 1); + let action = &set.items[0].actions[0]; + assert_eq!((action.label.as_str(), action.command.as_str()), ("Continue", "continue")); + assert_eq!(action.argument.as_deref(), Some("more")); + let carried = f + .take_events() + .into_iter() + .find_map(|(_, e)| match e { + PluginEvent::DecorationsChanged { plugin_id, sets } if plugin_id == "decorations" => Some(sets), + _ => None, + }) + .expect("DecorationsChanged emitted"); + assert_eq!(carried[0].items[0].actions[0].command, "continue"); +} + +/// API 1.21: an action whose command the plugin does not declare fails the whole call. +#[test] +fn actionable_decoration_with_undeclared_command_fails() { + let f = fixture(Limits::default()); + f.install(&sample("decorations")); + let err = f.run("decorations", "actionable-bad", Some("undeclared src/notes.txt")).unwrap_err(); + assert!(err.contains("no-such-command"), "{err}"); + assert!(f.host.decoration_sets().get("decorations").is_none_or(|s| s.is_empty()), "nothing is stored"); +} + +/// API 1.21: action bounds (count, label, tooltip, argument) fail the whole call and change nothing. +#[test] +fn actionable_decoration_bounds_are_enforced() { + let f = fixture(Limits::default()); + f.install(&sample("decorations")); + for (mode, needle) in [ + ("five", "4 actions"), + ("empty-label", "label"), + ("big-label", "label"), + ("control-label", "label"), + ("big-tooltip", "tooltip"), + ("big-arg", "argument"), + ] { + let err = f.run("decorations", "actionable-bad", Some(&format!("{mode} src/notes.txt"))).unwrap_err(); + assert!(err.contains(needle), "{mode}: {err}"); + assert!(f.host.decoration_sets().get("decorations").is_none_or(|s| s.is_empty()), "{mode}: nothing is stored"); + } +} + +/// API 1.21: a pre-1.21 `engines.openidea` is refused by `require_api`, not trapped. +#[test] +fn actionable_decoration_requires_api_1_21() { + let f = fixture(Limits::default()); + let pkg = f._tmp.path().join("decorations-117"); + copy_dir(&sample("decorations"), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text.replace("engines.openidea = \"^1.21\"", "engines.openidea = \"^1.17\""); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + let err = f.run("decorations", "actionable", Some("src/notes.txt")).unwrap_err(); + assert!(err.contains("set engines.openidea"), "{err}"); + assert!(err.contains("1.21"), "{err}"); + let info = f.host.info_of("decorations").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); +} + // ─── Project window groups ──────────────────────────────────────────────────── // A group's container root holds only `.openidea` metadata; the files live in // the member projects. The plugin surface reaches them like the editor and the @@ -8634,3 +8832,123 @@ fn custom_editor_toolbar_installs_and_validates_manifest() { .contains("[[contributes.commands]]") ); } + +/// `misbehave` as `id`, a `line-markers` provider for `text`; with `spin`, also its `spin` +/// command, which keeps its instance busy until cancelled. +fn install_marker_provider(f: &Fixture, tmp: &Path, id: &str, spin: bool) { + let pkg = tmp.join(id); + copy_dir(&misbehave_pkg(), &pkg); + let command = if spin { "[[contributes.commands]]\nid = \"spin\"\ntitle = \"spin\"\n" } else { "" }; + std::fs::write( + pkg.join("plugin.toml"), + format!( + "id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\ + wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n{command}\ + [[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = [\"text\"]\n" + ), + ) + .unwrap(); + f.install(&pkg); +} + +fn markers_doc(f: &Fixture) -> ide_plugin::ProviderDocument { + ide_plugin::ProviderDocument { + path: f.project.join("markers.txt"), + language: "text".into(), + version: 1, + text: "marker-icons\nordinary\ncustom\nlegacy".into(), + } +} + +/// A call dropped by the edit-path budget is reported by plugin, not answered as "no markers"; +/// a disabled plugin is not asked, so it is not reported. +#[test] +fn line_markers_report_the_plugins_too_late_to_answer() { + let f = fixture(Limits { edit_soft: Duration::ZERO, ..Limits::default() }); + let tmp = tempfile::tempdir().unwrap(); + install_marker_provider(&f, tmp.path(), "late-a", false); + install_marker_provider(&f, tmp.path(), "late-b", false); + let (markers, mut late) = f.host.provide_line_markers(&markers_doc(&f)); + late.sort(); + assert!(markers.is_empty()); + assert_eq!(late, ["late-a", "late-b"]); + f.host.set_enabled("late-a", false).unwrap(); + assert_eq!(f.host.provide_line_markers(&markers_doc(&f)), (Vec::new(), vec!["late-b".to_owned()])); +} + +/// A call queued behind a busy instance past the budget is reported as late; the plugins that +/// answered in time keep their markers. +#[test] +fn line_markers_too_late_from_one_provider_keep_the_others() { + // A budget no runner misses, so only the call queued behind `spin` is late. + let f = fixture(Limits { + edit_soft: Duration::from_secs(1), + edit_hard: Duration::from_secs(30), + timeout: Duration::from_secs(60), + fuel: u64::MAX, + ..Limits::default() + }); + let tmp = tempfile::tempdir().unwrap(); + install_marker_provider(&f, tmp.path(), "busy", true); + install_marker_provider(&f, tmp.path(), "on-time", false); + let doc = markers_doc(&f); + assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 8)); + std::thread::scope(|scope| { + scope.spawn(|| f.run("busy", "spin", None)); + // Answered in time until `spin` runs; late from then on. + let mut answer = (Vec::new(), Vec::new()); + let late_seen = eventually(|| { + answer = f.host.provide_line_markers(&doc); + !answer.1.is_empty() + }); + f.host.cancel("busy"); + assert!(late_seen, "never late: {answer:?}"); + let (markers, late) = answer; + assert_eq!(late, ["busy"]); + assert_eq!(markers.len(), 4); + assert!(markers.iter().all(|(id, _)| id == "on-time")); + }); +} + +/// A disabled plugin's languages don't make a save ask for line markers again. +#[test] +fn line_marker_languages_leave_out_disabled_plugins() { + let f = fixture(Limits::default()); + f.install(&official("mybatis")); + assert_eq!(f.host.line_marker_languages_with("xml").len(), 3); + f.host.set_enabled("openidea.mybatis", false).unwrap(); + assert!(f.host.line_marker_languages_with("xml").is_empty()); +} + +/// Another plugin's languages don't count: only one plugin declaring both links two files. +#[test] +fn line_marker_languages_come_from_the_plugins_covering_the_saved_language() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let install = |id: &str, languages: &str| { + let pkg = tmp.path().join(id); + copy_dir(&misbehave_pkg(), &pkg); + std::fs::write( + pkg.join("plugin.toml"), + format!( + "id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\ + wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n\ + [[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = {languages}\n" + ), + ) + .unwrap(); + f.install(&pkg); + }; + install("text-markers", r#"["text"]"#); + install("md-markers", r#"["markdown"]"#); + // Another plugin's languages don't come along. + assert_eq!(f.host.line_marker_languages_with("text"), ["text"]); + assert_eq!(f.host.line_marker_languages_with("markdown"), ["markdown"]); + assert!(f.host.line_marker_languages_with("java").is_empty()); + install("any-markers", r#"["*"]"#); + // `any-markers` covers every language, so every save reaches its editors. + let mut languages = f.host.line_marker_languages_with("text"); + languages.sort(); + assert_eq!(languages, ["*", "text"]); + assert_eq!(f.host.line_marker_languages_with("java"), ["*"]); +} diff --git a/crates/ide-http/src/client.rs b/crates/ide-http/src/client.rs index 55ed999700..3545ea5580 100644 --- a/crates/ide-http/src/client.rs +++ b/crates/ide-http/src/client.rs @@ -174,9 +174,9 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned()) } -/// reqwest errors with their causes ("error sending request: … connection refused"). -pub fn describe(e: &reqwest::Error) -> String { - use std::error::Error; +/// An error with its causes ("error sending request: … connection refused"), so +/// messages surfaced to the user keep the step that actually failed. +pub fn describe(e: &(dyn std::error::Error + 'static)) -> String { let mut msg = e.to_string(); let mut source = e.source(); while let Some(s) = source { @@ -194,6 +194,51 @@ pub fn describe(e: &reqwest::Error) -> String { mod tests { use super::*; + /// The updater wraps reqwest in its own error type (`tauri-plugin-updater`'s + /// `#[error(transparent)]` variant), so `describe` must follow `source` through + /// any error, not just `reqwest::Error`. + #[derive(Debug)] + struct ConnectRefused; + impl std::fmt::Display for ConnectRefused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "tcp connect error: connection refused 127.0.0.1:55134") + } + } + impl std::error::Error for ConnectRefused {} + + #[derive(Debug)] + struct WrappedRequest { + source: ConnectRefused, + } + impl std::fmt::Display for WrappedRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json)" + ) + } + } + impl std::error::Error for WrappedRequest { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.source) + } + } + + #[test] + fn describe_keeps_the_causes_behind_a_wrapped_error() { + let error = WrappedRequest { source: ConnectRefused }; + assert_eq!( + describe(&error), + "error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json): \ + tcp connect error: connection refused 127.0.0.1:55134" + ); + } + + #[test] + fn describe_of_an_error_without_causes_is_unchanged() { + assert_eq!(describe(&ConnectRefused), "tcp connect error: connection refused 127.0.0.1:55134"); + } + #[test] fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() { static SYSTEM: Mutex = Mutex::new(String::new()); diff --git a/crates/ide-language/src/syntax/cache.rs b/crates/ide-language/src/syntax/cache.rs index 6be41c434e..8c8c605707 100644 --- a/crates/ide-language/src/syntax/cache.rs +++ b/crates/ide-language/src/syntax/cache.rs @@ -186,7 +186,8 @@ impl SyntaxCache { stats } - pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec { + /// The memoized outline, shared: a cache hit clones none of its `String`s. + pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc> { self.memoized( doc, lang, @@ -211,7 +212,8 @@ impl SyntaxCache { ) } - pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec { + /// The memoized folding ranges, shared like [`Self::outline`]. + pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc> { self.memoized( doc, lang, @@ -230,7 +232,7 @@ impl SyntaxCache { /// Highlighting from the grammar's own query; empty without one. pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights { - SyntaxHighlights::new(self.memoized( + SyntaxHighlights::new(Arc::unwrap_or_clone(self.memoized( doc, lang, version, @@ -241,10 +243,12 @@ impl SyntaxCache { }) .or_else(|| super::external::highlights(lang, text)) }, - )) + ))) } /// `compute()` once per document version; `None` (no grammar / query) is not memoized. + /// Returns the `Arc` the memo holds; a caller that must own the result uses + /// `Arc::unwrap_or_clone`. fn memoized( &self, doc: DocId, @@ -252,7 +256,7 @@ impl SyntaxCache { version: u32, slot: impl Fn(&mut Memo) -> &mut Option>>, compute: impl FnOnce() -> Option>, - ) -> Vec { + ) -> Arc> { let entry = self.entries.lock().get(&doc).cloned(); if let Some(e) = &entry { let mut e = e.lock(); @@ -260,10 +264,11 @@ impl SyntaxCache { && let Some(hit) = slot(&mut e.memo).clone() { self.hits.fetch_add(1, Ordering::Relaxed); - return (*hit).clone(); + return hit; } } - let Some(result) = compute() else { return Vec::new() }; + let Some(result) = compute() else { return Arc::new(Vec::new()) }; + let result = Arc::new(result); if let Some(e) = &entry { let mut e = e.lock(); // Containers without their own grammar memoize their web outline too. @@ -271,7 +276,7 @@ impl SyntaxCache { if e.version == version && (e.tree.is_some() || (e.lang == *lang && self.syntax.web_grammar_name(lang) == Some("html"))) { - *slot(e.memo.at(version, lang)) = Some(Arc::new(result.clone())); + *slot(e.memo.at(version, lang)) = Some(result.clone()); } } result @@ -426,7 +431,7 @@ mod tests { let mut doc = Document::new(SRC); cache.open(id, &rust(), doc.version()); let first = cache.outline(id, &rust(), 0, &doc.text()); - assert_eq!(first, cache.syntax().outline(&rust(), SRC)); + assert_eq!(first.as_ref(), &cache.syntax().outline(&rust(), SRC)); assert_eq!(cache.stats().full_parses, 1); cache.folding(id, &rust(), 0, &doc.text()); assert_eq!(cache.stats().hits, 1); @@ -444,8 +449,16 @@ mod tests { cache.edit(id, doc.version(), &edits); let text = doc.text(); let v = doc.version(); - assert_eq!(cache.outline(id, &rust(), v, &text), cache.syntax().outline(&rust(), &text), "round {round}"); - assert_eq!(cache.folding(id, &rust(), v, &text), cache.syntax().folding(&rust(), &text), "round {round}"); + assert_eq!( + cache.outline(id, &rust(), v, &text).as_ref(), + &cache.syntax().outline(&rust(), &text), + "round {round}" + ); + assert_eq!( + cache.folding(id, &rust(), v, &text).as_ref(), + &cache.syntax().folding(&rust(), &text), + "round {round}" + ); let off = seed % (doc.len_utf16() + 1); assert_eq!( cache.selection_ranges(id, &rust(), v, &text, off), @@ -481,7 +494,7 @@ mod tests { cache.edit(id, doc.version(), &edits); let text = doc.text(); let edited = cache.outline(id, &rust(), 1, &text); - assert_eq!(edited, cache.syntax().outline(&rust(), &text)); + assert_eq!(edited.as_ref(), &cache.syntax().outline(&rust(), &text)); assert_ne!(edited, outline); // Another language at the same version is not answered from the memo. assert!(cache.outline(id, &LanguageId::new("plaintext"), 1, &text).is_empty()); @@ -504,7 +517,7 @@ mod tests { cache.edit(id, doc.version(), &edits); let second = cache.outline(id, &lang, doc.version(), &doc.text()); assert_ne!(second, first); - assert_eq!(second, cache.syntax().outline(&lang, &doc.text())); + assert_eq!(second.as_ref(), &cache.syntax().outline(&lang, &doc.text())); // An older query must not replace the current version's memo. cache.outline(id, &lang, 0, ""); let hits = cache.stats().hits; @@ -528,7 +541,7 @@ mod tests { let edits = edit(&mut doc, 0, 0, "// y\n"); cache.edit(id, doc.version(), &edits); let text = doc.text(); - assert_eq!(cache.outline(id, &rust(), 2, &text), cache.syntax().outline(&rust(), &text)); + assert_eq!(cache.outline(id, &rust(), 2, &text).as_ref(), &cache.syntax().outline(&rust(), &text)); assert_eq!(cache.stats().full_parses, 2, "dropped tree re-parses from scratch"); // A query for a version the cache has not reached is answered but not stored. diff --git a/crates/ide-language/src/syntax/tests.rs b/crates/ide-language/src/syntax/tests.rs index fc17658528..ca1daf2285 100644 --- a/crates/ide-language/src/syntax/tests.rs +++ b/crates/ide-language/src/syntax/tests.rs @@ -2033,9 +2033,9 @@ fn cached_outline_matches_syntax_outline_for_web_documents() { let id = DocId::next(); let src = "\n\n"; cache.open(id, &lang("vue"), 0); - assert_eq!(cache.outline(id, &lang("vue"), 0, src), syntax().outline(&lang("vue"), src)); + assert_eq!(cache.outline(id, &lang("vue"), 0, src).as_ref(), &syntax().outline(&lang("vue"), src)); cache.open(id, &lang("html"), 0); - assert_eq!(cache.outline(id, &lang("html"), 0, src), syntax().outline(&lang("html"), src)); + assert_eq!(cache.outline(id, &lang("html"), 0, src).as_ref(), &syntax().outline(&lang("html"), src)); } #[test] @@ -2137,7 +2137,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() { let cache = SyntaxCache::new(Arc::new(Syntax::new())); cache.open(id, &language, 0); let items = cache.outline(id, &language, 0, src); - assert_eq!(items, syntax().outline(&language, src)); + assert_eq!(items.as_ref(), &syntax().outline(&language, src)); assert_eq!(items[0].name, "中文😀"); assert_eq!(items[0].selection_range, Range::new(Pos::new(1, 1), Pos::new(1, 5))); assert_eq!(items[0].children[0].name, "子章节"); @@ -2146,7 +2146,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() { assert_eq!(items[0].children[1].name, "Other"); let edited = src.replace("子章节", "新章节😀"); let updated = cache.outline(id, &language, 1, &edited); - assert_eq!(updated, syntax().outline(&language, &edited)); + assert_eq!(updated.as_ref(), &syntax().outline(&language, &edited)); assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5)); assert_ne!(items, updated); } diff --git a/crates/ide-lsp/src/caps.rs b/crates/ide-lsp/src/caps.rs index 8faa38b87c..4b05c7bc31 100644 --- a/crates/ide-lsp/src/caps.rs +++ b/crates/ide-lsp/src/caps.rs @@ -168,8 +168,13 @@ pub fn client_capabilities() -> Value { "typeHierarchy": { "dynamicRegistration": false } }, // rust-analyzer: report when the project has loaded (`quiescent`). - // java-analyzer: Spring bean markers of open documents may have changed (`spring_beans.rs`). - "experimental": { "serverStatusNotification": true, "java-analyzer/springBeanMarkersChanged": true }, + // java-analyzer: Spring bean and AOP markers of open documents may have changed + // (`spring_beans.rs`, `spring_aop.rs`). + "experimental": { + "serverStatusNotification": true, + "java-analyzer/springBeanMarkersChanged": true, + "java-analyzer/springAopMarkersChanged": true + }, // Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`). "notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } } }) diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 3f79eb78df..29e6198d47 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -783,6 +783,9 @@ impl Handler for ClientHandler { crate::spring_beans::CHANGED if self.server.is_live(self.generation) => { mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringBeanMarkers }) } + crate::spring_aop::CHANGED if self.server.is_live(self.generation) => { + mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringAopMarkers }) + } "window/showMessage" => self.show_message(&mgr, ¶ms), "window/logMessage" => { let text = params.get("message").and_then(Value::as_str).unwrap_or_default(); diff --git a/crates/ide-lsp/src/jdtls/extract_interface.rs b/crates/ide-lsp/src/jdtls/extract_interface.rs index 12d1ec2c98..7c9ab04e25 100644 --- a/crates/ide-lsp/src/jdtls/extract_interface.rs +++ b/crates/ide-lsp/src/jdtls/extract_interface.rs @@ -137,6 +137,7 @@ fn java_result_of( JavaSeverity::Warning => ProblemSeverity::Warning, }, message: p.message, + location: None, }) .collect(); // java-analyzer is stateless: no confirmation token, the client applies what it got. @@ -271,6 +272,7 @@ impl LspManager { problems: vec![RefactoringProblem { severity: ProblemSeverity::Fatal, message: "The interface could not be extracted".to_owned(), + location: None, }], edit: None, confirmation: None, diff --git a/crates/ide-lsp/src/jdtls/hierarchy.rs b/crates/ide-lsp/src/jdtls/hierarchy.rs index 1d7f341556..0748bec28e 100644 --- a/crates/ide-lsp/src/jdtls/hierarchy.rs +++ b/crates/ide-lsp/src/jdtls/hierarchy.rs @@ -3,7 +3,9 @@ //! server advertises them (`crate::phoxite`). The server checks the move and computes the edit; the UI //! shows its problems and applies the edit itself. use super::COMMAND_TIMEOUT; -use crate::types::{HierarchyChoice, HierarchyMembers, HierarchyRefactored, HierarchyRefactoring, RefactoringProblem}; +use crate::types::{ + HierarchyChoice, HierarchyMembers, HierarchyRefactored, HierarchyRefactoring, ProblemSeverity, RefactoringProblem, +}; use crate::{DocSnap, LspManager, Target, convert}; use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos}; use serde::Deserialize; @@ -29,10 +31,20 @@ fn java_analyzer(caps: &crate::caps::ServerCaps, kind: HierarchyRefactoring) -> #[derive(Default, Deserialize)] struct JavaRefactored { #[serde(default)] - problems: Vec, + problems: Vec, edit: Option, } +/// java-analyzer's problem shape: the location is an LSP location, converted to IDE +/// coordinates like the edit is. +#[derive(Deserialize)] +struct JavaProblem { + severity: ProblemSeverity, + message: String, + #[serde(default)] + location: Option, +} + /// The extension's answer: a result, or why the position can't be refactored. #[derive(Deserialize)] #[serde(untagged)] @@ -187,9 +199,15 @@ impl LspManager { } let answer = answer.unwrap_or_default(); let conv = self.conv(target.enc()); - Ok(HierarchyRefactored { - problems: answer.problems, - edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)), - }) + let problems = answer + .problems + .into_iter() + .map(|problem| RefactoringProblem { + severity: problem.severity, + message: problem.message, + location: problem.location.as_ref().and_then(|loc| conv.location(loc)), + }) + .collect(); + Ok(HierarchyRefactored { problems, edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)) }) } } diff --git a/crates/ide-lsp/src/jdtls/move_refactoring.rs b/crates/ide-lsp/src/jdtls/move_refactoring.rs index 0a62384066..5153bff963 100644 --- a/crates/ide-lsp/src/jdtls/move_refactoring.rs +++ b/crates/ide-lsp/src/jdtls/move_refactoring.rs @@ -6,12 +6,38 @@ //! arguments back unchanged. use super::COMMAND_TIMEOUT; use super::signature::{RefactorEdit, changed}; -use crate::types::ServerRefactored; -use crate::{LspManager, convert}; -use ide_core::{CancellationToken, DocId, IdeError, IdeResult}; +use crate::caps::ServerCaps; +use crate::types::{MoveChoice, MoveInfo, ProblemSeverity, RefactoringProblem, ServerRefactored}; +use crate::{DocSnap, LspManager, Target, convert}; +use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos}; +use serde::Deserialize; use serde_json::{Value, json}; const FEATURE: &str = "Move"; +/// java-analyzer's dialog-driven Move pair, advertised in `capabilities.experimental`. +const JAVA_INFO: &str = "java-analyzer/moveInfo"; +const JAVA_EDIT: &str = "java-analyzer/move"; + +fn java_analyzer(caps: &ServerCaps) -> bool { + caps.raw["experimental"][JAVA_INFO] == true && caps.raw["experimental"][JAVA_EDIT] == true +} + +#[derive(Default, Deserialize)] +struct JavaMoveResult { + #[serde(default)] + problems: Vec, + edit: Option, +} + +/// java-analyzer's problem shape: the location is an LSP location, converted to the +/// IDE's coordinates like the edit is. +#[derive(Deserialize)] +struct JavaProblem { + severity: ProblemSeverity, + message: String, + #[serde(default)] + location: Option, +} /// What `java/getMoveDestinations` and `java/move` accept as `moveKind`. const KINDS: [&str; 6] = ["moveResource", "moveInstanceMethod", "moveStaticMember", "moveTypeToNewFile", "moveTypeToClass", "moveType"]; @@ -95,6 +121,71 @@ impl LspManager { } } +impl LspManager { + async fn java_move_target(&self, doc: DocId) -> IdeResult<(DocSnap, Target)> { + let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?; + if let Some(t) = targets.iter().find(|t| java_analyzer(&t.caps())) { + return Ok((snap, t.clone())); + } + if targets.iter().any(|t| t.server.name == "java-analyzer") { + return Err(IdeError::unavailable( + "java-analyzer doesn't support Move; use the file tree's Move or the jdtls Move actions", + )); + } + Err(IdeError::unavailable(format!("{FEATURE} needs a Java language server"))) + } + + /// What can move at `pos` and where it can go (java-analyzer's `moveInfo`). + pub async fn java_move_info(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult { + let (snap, t) = self.java_move_target(doc).await?; + let params = json!({ + "textDocument": { "uri": snap.uri }, + "position": snap.position(&t, pos), + }); + let info: Option = self.call(&t, JAVA_INFO, params, Some(&cancel), COMMAND_TIMEOUT).await?; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + info.ok_or_else(|| IdeError::invalid("There is nothing movable at the caret")) + } + + /// Checks the chosen move and computes its edit (java-analyzer's `move`). + pub async fn java_move_refactor( + &self, + doc: DocId, + pos: Pos, + destination: MoveChoice, + cancel: CancellationToken, + ) -> IdeResult { + let (snap, t) = self.java_move_target(doc).await?; + let params = json!({ + "textDocument": { "uri": snap.uri }, + "position": snap.position(&t, pos), + "destination": { "kind": destination.kind, "id": destination.id }, + }); + let answer: Option = self.call(&t, JAVA_EDIT, params, Some(&cancel), COMMAND_TIMEOUT).await?; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let answer = answer.unwrap_or_default(); + let conv = self.conv(t.enc()); + let problems = answer + .problems + .into_iter() + .map(|problem| RefactoringProblem { + severity: problem.severity, + message: problem.message, + location: problem.location.as_ref().and_then(|loc| conv.location(loc)), + }) + .collect(); + Ok(ServerRefactored { + problems, + edit: answer.edit.map(|edit| convert::workspace_edit(&conv, edit)), + confirmation: None, + }) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-lsp/src/jdtls/signature.rs b/crates/ide-lsp/src/jdtls/signature.rs index 8d99f79bc7..79b0b97ca8 100644 --- a/crates/ide-lsp/src/jdtls/signature.rs +++ b/crates/ide-lsp/src/jdtls/signature.rs @@ -110,6 +110,7 @@ fn java_result_of( JavaSeverity::Warning => ProblemSeverity::Warning, }, message: p.message, + location: None, }) .collect(); // java-analyzer is stateless: no confirmation token, the client applies what it got. @@ -139,11 +140,11 @@ pub(super) fn changed( convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit, ) -> ServerRefactored { let problem = |severity| { - answer - .error_message - .as_deref() - .filter(|m| !m.trim().is_empty()) - .map(|message| RefactoringProblem { severity, message: message.trim().to_owned() }) + answer.error_message.as_deref().filter(|m| !m.trim().is_empty()).map(|message| RefactoringProblem { + severity, + message: message.trim().to_owned(), + location: None, + }) }; if let Some(token) = answer.confirmation_token { return ServerRefactored { diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 5c4a8f90ac..8c32586f20 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -40,6 +40,7 @@ mod roslyn; mod scope; mod server; mod source_actions; +mod spring_aop; mod spring_beans; mod switch_source_header; mod tcp; diff --git a/crates/ide-lsp/src/spring_aop.rs b/crates/ide-lsp/src/spring_aop.rs new file mode 100644 index 0000000000..57c5bdd271 --- /dev/null +++ b/crates/ide-lsp/src/spring_aop.rs @@ -0,0 +1,103 @@ +//! Spring AOP markers of a Java document: advised methods with the advices applied to them, and +//! advice methods with the methods they advise. The first source is java-analyzer's +//! `java-analyzer/springAopMarkers`, one request per document; its answer is turned into the +//! server-independent [`SpringAopMarker`]s the gutter shows. + +use crate::types::{SpringAopAdviceKind, SpringAopDirection, SpringAopMarker, SpringAopTarget}; +use crate::{LspManager, Target, lsp}; +use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Range}; +use serde::Deserialize; +use serde_json::json; +use std::time::Duration; + +/// `{ textDocument: { uri } }` → `{ markers: [{ range, name, direction, targets: [{ location, label, adviceKind, order }] }] }`. +pub(crate) const METHOD: &str = "java-analyzer/springAopMarkers"; +/// Sent by the server, to clients that declare it, when markers of open documents may have changed. +pub(crate) const CHANGED: &str = "java-analyzer/springAopMarkersChanged"; +/// The first answer of a large workspace pairs every advised method with its advices. +const TIMEOUT: Duration = Duration::from_secs(60); + +#[derive(Deserialize)] +struct Answer { + markers: Vec, +} + +#[derive(Deserialize)] +struct WireMarker { + range: lsp::Range, + name: String, + direction: SpringAopDirection, + targets: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WireTarget { + location: lsp::Location, + label: String, + #[serde(default)] + advice_kind: Option, + #[serde(default)] + order: Option, +} + +impl LspManager { + /// The document's Spring AOP markers; `None` when no server attached to it provides them + /// (jdtls, an older java-analyzer, a server not running yet), without asking any server. + pub async fn spring_aop_markers( + &self, + doc: DocId, + cancel: CancellationToken, + ) -> IdeResult>> { + let snap = self.snapshot(doc)?; + // Only an instance the document is open on: waiting for servers to start would hold + // every Java file of a jdtls project for a background feature. + let source = self.docs.lock().get(&doc).and_then(|d| { + d.servers.iter().find_map(|a| { + let run = a.server.running()?; + let provides = { + let caps = run.caps.read(); + // AOP markers are implementation navigation: `features` without it leave it out. + caps.restriction.implementation() && caps.raw["experimental"][METHOD] == true + }; + (provides && a.opened_gen == Some(run.generation)).then(|| Target::new(a.server.clone(), run)) + }) + }); + let Some(target) = source else { return Ok(None) }; + let answer: Option = + self.call(&target, METHOD, json!({ "textDocument": snap.ident() }), Some(&cancel), TIMEOUT).await?; + // Ranges are read against the text the request was made for. + if self.snapshot(doc)?.version != snap.version { + return Err(IdeError::cancelled()); + } + let enc = target.enc(); + let conv = self.conv(enc); + let pos = |p| snap.text.lsp_to_ide(enc, p); + let markers = answer.map_or_else(Vec::new, |a| a.markers); + Ok(Some( + markers + .into_iter() + .filter_map(|m| { + let targets: Vec<_> = m + .targets + .into_iter() + .filter_map(|t| { + Some(SpringAopTarget { + location: conv.location(&t.location)?, + label: t.label, + advice_kind: t.advice_kind, + order: t.order, + }) + }) + .collect(); + (!targets.is_empty()).then(|| SpringAopMarker { + range: Range::new(pos(m.range.start), pos(m.range.end)), + name: m.name, + direction: m.direction, + targets, + }) + }) + .collect(), + )) + } +} diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs index cbdafd4c64..c6529c75d4 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -542,6 +542,10 @@ pub enum ProblemSeverity { pub struct RefactoringProblem { pub severity: ProblemSeverity, pub message: String, + /// Where the problem was found, when the server can say. + #[serde(default)] + #[specta(optional)] + pub location: Option, } /// A checked refactoring: what the server found, and the edit unless a problem is fatal. @@ -552,6 +556,55 @@ pub struct HierarchyRefactored { pub edit: Option, } +/// The kind of element Move (F6) would move, as java-analyzer reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum MoveKind { + Type, + StaticMember, + InstanceMethod, +} + +/// One destination Move can go to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct MoveDestination { + /// `package`, `class`, `newFile`, `field` or `parameter`. + pub kind: String, + /// Server-owned identity, passed back unchanged. + pub id: String, + pub name: String, + #[serde(default)] + pub qualified_name: String, + #[serde(default)] + pub detail: String, + #[serde(default)] + pub current: bool, + /// For field/parameter destinations: the type of the field or parameter. + #[serde(default)] + pub target_type: String, + #[serde(default)] + pub is_field: bool, +} + +/// The element at a position and where Move can take it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct MoveInfo { + pub kind: MoveKind, + /// The element being moved, as the server renders it. + pub label: String, + pub destinations: Vec, +} + +/// A Move destination choice, as the dialog sends it back. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct MoveChoice { + pub kind: String, + pub id: String, +} + /// A parameter in Change Signature: its type, name, the value passed at existing calls when it is /// added, and its index in the current signature (-1 for an added one). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -787,3 +840,46 @@ pub enum SpringBeanResolution { Resolved, Candidate, } + +/// A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice +/// method (`ToAdvised`), whichever server found it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringAopMarker { + /// The method's name range. + pub range: Range, + pub name: String, + pub direction: SpringAopDirection, + /// Never empty. + pub targets: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringAopDirection { + /// On an advised method: its targets are the advices applied to it. + ToAdvice, + /// On an advice method: its targets are the methods it advises. + ToAdvised, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringAopTarget { + pub location: Location, + pub label: String, + /// Set on an advice target; `None` on an advised method. + pub advice_kind: Option, + /// The advice's Spring `order`; `None` when it has none. + pub order: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringAopAdviceKind { + Before, + After, + AfterReturning, + AfterThrowing, + Around, +} diff --git a/crates/ide-lsp/tests/integration/main.rs b/crates/ide-lsp/tests/integration/main.rs new file mode 100644 index 0000000000..39be05757d --- /dev/null +++ b/crates/ide-lsp/tests/integration/main.rs @@ -0,0 +1,5 @@ +mod mock_server; +mod real_servers; +#[cfg(unix)] +mod stdio_crash; +mod tcp_server; diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/integration/mock_server.rs similarity index 98% rename from crates/ide-lsp/tests/mock_server.rs rename to crates/ide-lsp/tests/integration/mock_server.rs index 1de6176411..ac62cb06c5 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/integration/mock_server.rs @@ -7832,7 +7832,11 @@ async fn gopls_interactive_command_validates_before_execution_and_applies_edits( .await .unwrap(); assert_eq!(created, vec![new_file.clone()]); - assert_eq!(std::fs::read_to_string(&new_file).unwrap(), "package probe_test\n\nimport \"testing\"\n"); + // A created file takes the system line separator (CRLF on Windows). + assert_eq!( + std::fs::read_to_string(&new_file).unwrap().replace("\r\n", "\n"), + "package probe_test\n\nimport \"testing\"\n" + ); } /// bash-language-server formats a whole file with `Position.create(Number.MAX_VALUE, @@ -9674,7 +9678,8 @@ async fn a_server_is_sent_the_documents_it_registers_a_selector_for() { let after = open_data("after.dt"); eventually(|| fw.docs.lock().contains_key(&uri_of(&after))).await; // Its own server keeps the documents, and one the selector doesn't name stays with it alone. - assert!(own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated))); + eventually(|| own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated))) + .await; assert!(!fw.docs.lock().contains_key(&uri_of(&unrelated))); // The server list names the language among the ones it serves. let served = h.mgr.servers().into_iter().find(|s| s.name == "fw").unwrap().languages; @@ -10923,3 +10928,173 @@ async fn initialize_sends_active_locale_and_restarts_on_locale_change() { assert_eq!(state.requested("initialize")[2]["locale"], "zh-TW"); h.mgr.shutdown_all().await; } + +#[tokio::test(flavor = "multi_thread")] +async fn move_uses_java_analyzer_when_advertised() { + let mut ja_caps = incremental_caps(); + ja_caps["positionEncoding"] = json!("utf-8"); + ja_caps["experimental"] = json!({ + "java-analyzer/moveInfo": true, + "java-analyzer/move": true, + }); + let h = harness_configured("java", "java", &[("java-analyzer", ja_caps), ("jdtls", incremental_caps())], |_| {}); + let (doc, path) = + h.open("Dog.java", "package app;\npublic class Dog extends Animal {\n int bark() { return 1; }\n}\n"); + for name in ["java-analyzer", "jdtls"] { + h.wait_status(name, ServerStatus::Ready).await; + } + let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls")); + eventually(|| !ja.notified("textDocument/didOpen").is_empty()).await; + let caret = Pos::new(2, 9); + + ja.respond( + "java-analyzer/moveInfo", + json!({ + "kind": "instanceMethod", + "label": "app.Dog.bark()", + "destinations": [{ + "kind": "parameter", "id": "parameter:target", "name": "target", + "qualifiedName": "app.Target", "targetType": "app.Target", "isField": false, + }], + }), + ); + let info = h.mgr.java_move_info(doc, caret, Default::default()).await.unwrap(); + assert_eq!(info.label, "app.Dog.bark()"); + assert_eq!(info.destinations[0].id, "parameter:target"); + assert_eq!( + ja.requested("java-analyzer/moveInfo")[0], + json!({ "textDocument": { "uri": uri_of(&path) }, "position": { "line": 2, "character": 9 } }) + ); + assert!(jdtls.requested("java/getMoveDestinations").is_empty()); + + ja.respond( + "java-analyzer/move", + json!({ + "edit": { "changes": { + uri_of(&path): [{ + "range": { "start": { "line": 2, "character": 0 }, "end": { "line": 2, "character": 0 } }, + "newText": "", + }], + } }, + "problems": [{ "severity": "warning", "message": "Review this call" }], + }), + ); + let res = h + .mgr + .java_move_refactor( + doc, + caret, + MoveChoice { kind: "parameter".to_owned(), id: "parameter:target".to_owned() }, + Default::default(), + ) + .await + .unwrap(); + assert_eq!(res.problems[0].severity, ProblemSeverity::Warning); + assert!(res.edit.is_some()); + assert!(res.confirmation.is_none()); + assert_eq!( + ja.requested("java-analyzer/move")[0], + json!({ + "textDocument": { "uri": uri_of(&path) }, + "position": { "line": 2, "character": 9 }, + "destination": { "kind": "parameter", "id": "parameter:target" }, + }) + ); + assert!(jdtls.requested("java/move").is_empty()); + h.mgr.shutdown_all().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn move_without_the_pair_on_java_analyzer_says_so() { + let h = harness_configured("java", "java", &[("java-analyzer", incremental_caps())], |_| {}); + let (doc, _) = h.open("Dog.java", "package app;\nclass Dog {\n int bark() { return 1; }\n}\n"); + h.wait_status("java-analyzer", ServerStatus::Ready).await; + let err = h.mgr.java_move_info(doc, Pos::new(2, 9), Default::default()).await.unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable); + assert!(err.message.starts_with("java-analyzer doesn't support Move"), "{}", err.message); + h.mgr.shutdown_all().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_markers_come_from_the_server_that_declares_them() { + let mut caps = incremental_caps(); + caps["positionEncoding"] = json!("utf-8"); + caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true }); + let h = harness(&[("aop", caps), ("plain", incremental_caps())]); + // "é😀" is 3 UTF-16 units and 6 bytes before `clock`. + let (doc, path) = h.open("a.mk", "é😀clock;\nclass App {}\n"); + for name in ["aop", "plain"] { + h.wait_status(name, ServerStatus::Ready).await; + } + let (aop, plain) = (h.launcher.state("aop"), h.launcher.state("plain")); + eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await; + let init = &aop.requested("initialize")[0]; + assert_eq!(init["capabilities"]["experimental"]["java-analyzer/springAopMarkersChanged"], true); + let at = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}}); + aop.respond( + "java-analyzer/springAopMarkers", + json!({ "markers": [ + { "range": at(0, 6, 11), "name": "clock", "direction": "toAdvice", "targets": [ + { "location": { "uri": uri_of(&path), "range": at(1, 6, 9) }, "label": "logBefore", "adviceKind": "before", "order": 1 }, + { "location": { "uri": uri_of(&path), "range": at(0, 0, 2) }, "label": "é", "adviceKind": "around", "order": null }, + ] }, + { "range": at(1, 6, 9), "name": "App", "direction": "toAdvised", "targets": [ + { "location": { "uri": uri_of(&path), "range": at(0, 3, 8) }, "label": "clock", "adviceKind": null, "order": null }, + ] }, + { "range": at(1, 0, 3), "name": "App", "direction": "toAdvised", "targets": [] }, + ] }), + ); + let markers = h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap().unwrap(); + assert_eq!(aop.requested("java-analyzer/springAopMarkers")[0], json!({ "textDocument": { "uri": uri_of(&path) } })); + assert!(plain.requested("java-analyzer/springAopMarkers").is_empty()); + // The marker without targets is dropped; positions are UTF-16 in every file. + assert_eq!(markers.len(), 2); + assert_eq!(markers[0].range, rng(0, 3, 0, 8)); + assert_eq!(markers[0].direction, SpringAopDirection::ToAdvice); + assert_eq!(markers[0].targets[0].location.range, rng(1, 6, 1, 9)); + assert_eq!(markers[0].targets[0].advice_kind, Some(SpringAopAdviceKind::Before)); + assert_eq!(markers[0].targets[0].order, Some(1)); + assert_eq!(markers[0].targets[1].location.range, rng(0, 0, 0, 1)); + assert_eq!(markers[0].targets[1].advice_kind, Some(SpringAopAdviceKind::Around)); + assert_eq!(markers[0].targets[1].order, None); + assert_eq!(markers[1].direction, SpringAopDirection::ToAdvised); + assert_eq!(markers[1].targets[0].advice_kind, None); + assert_eq!(markers[1].targets[0].order, None); + + let refreshes = || { + h.events + .lock() + .iter() + .filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SpringAopMarkers, .. })) + .count() + }; + aop.peer().notify("java-analyzer/springAopMarkersChanged", json!({})).unwrap(); + eventually(|| refreshes() == 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_markers_ask_no_server_without_the_capability() { + let h = harness(&[("plain", incremental_caps())]); + let (doc, _) = h.open("a.mk", "class App {}\n"); + // Not ready yet: no wait for it to start. + assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None); + h.wait_status("plain", ServerStatus::Ready).await; + let plain = h.launcher.state("plain"); + eventually(|| !plain.notified("textDocument/didOpen").is_empty()).await; + assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None); + assert!(plain.requested("java-analyzer/springAopMarkers").is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_markers_follow_the_servers_features() { + let mut caps = incremental_caps(); + caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true }); + // Used for diagnostics only: no navigation from it, AOP markers included. + let h = harness_configured("mock", "mk", &[("aop", caps)], |cfg| cfg.features = vec!["diagnostics".into()]); + let (doc, _) = h.open("a.mk", "class App {}\n"); + h.wait_status("aop", ServerStatus::Ready).await; + let aop = h.launcher.state("aop"); + eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await; + assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None); + assert!(aop.requested("java-analyzer/springAopMarkers").is_empty()); +} diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/integration/real_servers.rs similarity index 99% rename from crates/ide-lsp/tests/real_servers.rs rename to crates/ide-lsp/tests/integration/real_servers.rs index 9da3e073cf..5d6ac3d199 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/integration/real_servers.rs @@ -291,7 +291,7 @@ async fn java_searches_skip_indexed_sources_but_keep_exclusions_outside_scope() async fn lombok_generated_members_appear_in_document_symbols() { let dir = tempfile::tempdir().unwrap(); let root = dunce::canonicalize(dir.path()).unwrap(); - let source = include_str!("fixtures/LombokSymbols.java"); + let source = include_str!("../fixtures/LombokSymbols.java"); let path = root.join("src/demo/LombokSymbols.java"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, source).unwrap(); @@ -357,8 +357,8 @@ async fn lombok_generated_members_appear_in_document_symbols() { async fn intellij_java_formatter_preserves_manual_breaks_and_wraps_long_lines() { let dir = tempfile::tempdir().unwrap(); let root = dir.path().canonicalize().unwrap(); - let source = include_str!("fixtures/FormatterSample.input.java"); - let expected = include_str!("fixtures/FormatterSample.intellij.java"); + let source = include_str!("../fixtures/FormatterSample.input.java"); + let expected = include_str!("../fixtures/FormatterSample.intellij.java"); let path = root.join("src/demo/FormatterSample.java"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, source).unwrap(); @@ -911,7 +911,7 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() { } // What the settings hook writes for `alias: { '@': path.resolve(__dirname, 'src') }`. let plugin = root.join("plugin/node_modules/openidea-path-aliases"); - std::fs::write(plugin.join("index.js"), include_str!("../../ide-sdk/src/path-aliases.js")).unwrap(); + std::fs::write(plugin.join("index.js"), include_str!("../../../ide-sdk/src/path-aliases.js")).unwrap(); let src = slash(&root.join("src")); let paths = serde_json::json!({ slash(&root): { "@": [src], "@/*": [format!("{src}/*")] } }); std::fs::write(plugin.join("paths.json"), paths.to_string()).unwrap(); diff --git a/crates/ide-lsp/tests/stdio_crash.rs b/crates/ide-lsp/tests/integration/stdio_crash.rs similarity index 99% rename from crates/ide-lsp/tests/stdio_crash.rs rename to crates/ide-lsp/tests/integration/stdio_crash.rs index 4bc4ec8c05..3e260cbf13 100644 --- a/crates/ide-lsp/tests/stdio_crash.rs +++ b/crates/ide-lsp/tests/integration/stdio_crash.rs @@ -1,6 +1,5 @@ //! A stdio server that dies before the handshake: what it printed (on stderr, and //! on stdout outside the protocol, in any encoding) must reach the crash message. -#![cfg(unix)] use ide_core::event::ServerStatus; use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId}; diff --git a/crates/ide-lsp/tests/tcp_server.rs b/crates/ide-lsp/tests/integration/tcp_server.rs similarity index 100% rename from crates/ide-lsp/tests/tcp_server.rs rename to crates/ide-lsp/tests/integration/tcp_server.rs diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index c59812be5b..70e21888d3 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -419,6 +419,16 @@ pub trait HostApi: Send + Sync { /// Fork a recorded native agent session into a new task in the invoking /// window's project, returning the new task id (API 1.18). fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result; + /// Start a new agent task in the invoking window's project, unsent, and open it in + /// the Agents window for the user to review and send (API 1.21). `fork` (session id, + /// cwd) continues a recorded native session exactly like `fork_agent_session`. + fn start_agent_task( + &self, + client: &str, + provider: &str, + prompt: &str, + fork: Option<(&str, &Path)>, + ) -> Result; /// Trusted repository history. fn vcs_log( &self, @@ -683,6 +693,13 @@ pub trait HostApi: Send + Sync { Err(HostError::Failed("watching paths is unavailable here".into())) } fn unsubscribe(&self, kind: &str); + /// Wakes this plugin with a `timer` event `id` after `after`, in window `client` + /// (API 1.21); replaces a pending timer with the same id. `id` and `after` are checked. + fn schedule(&self, _client: Option<&str>, _id: &str, _after: std::time::Duration) -> Result<(), HostError> { + Err(HostError::Failed("timers are unavailable here".into())) + } + /// Cancels this plugin's pending timer `id`, if any (API 1.21). + fn cancel_schedule(&self, _id: &str) {} /// Starts `cmd` and returns the handle to it without waiting. fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result; /// Starts `cmd` with streaming options (API 1.15). @@ -1264,7 +1281,15 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event { kind: "project-closed".into(), data: serde_json::to_string(&p).expect("path serializes"), }), + WorkbenchEvent::ProjectTreeExpanded(paths) => wit_events::Event::Other(wit_types::Extension { + kind: "project-tree-expanded".into(), + data: serde_json::to_string(&paths).expect("paths serialize"), + }), WorkbenchEvent::Scheduled => wit_events::Event::Scheduled, + WorkbenchEvent::Timer(id) => wit_events::Event::Other(wit_types::Extension { + kind: "timer".into(), + data: serde_json::to_string(&id).expect("id serializes"), + }), WorkbenchEvent::ActionPerformed(a) => wit_events::Event::ActionPerformed(wit_events::ActionPerformed { action: a.action, title: a.title, diff --git a/crates/ide-plugin/src/types.rs b/crates/ide-plugin/src/types.rs index 470b059d28..bb4a9b8a2d 100644 --- a/crates/ide-plugin/src/types.rs +++ b/crates/ide-plugin/src/types.rs @@ -239,11 +239,16 @@ pub enum EventKind { ProjectClosed, /// Paths outside the project watched with `events.watch-paths` changed (API 1.18). WatchedFilesChanged, + /// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21): + /// a JSON array of absolute paths (`Event::Other`). + ProjectTreeExpanded, Scheduled, + /// A timer the plugin set with `events.schedule` fired (API 1.21); delivered without subscribing. + Timer, } impl EventKind { - pub const ALL: [Self; 22] = [ + pub const ALL: [Self; 24] = [ Self::DocumentChanged, Self::WebsocketReady, Self::FileClosed, @@ -265,7 +270,9 @@ impl EventKind { Self::ProblemsChanged, Self::ProjectClosed, Self::WatchedFilesChanged, + Self::ProjectTreeExpanded, Self::Scheduled, + Self::Timer, ]; pub fn name(self) -> &'static str { @@ -291,7 +298,9 @@ impl EventKind { Self::ProblemsChanged => "problems-changed", Self::ProjectClosed => "project-closed", Self::WatchedFilesChanged => "watched-files-changed", + Self::ProjectTreeExpanded => "project-tree-expanded", Self::Scheduled => "scheduled", + Self::Timer => "timer", } } @@ -306,6 +315,7 @@ impl EventKind { Self::ActionPerformed | Self::InputModeChanged => Some(ide_extension::Capability::InputEvents), Self::RunOutput => Some(ide_extension::Capability::RunOutput), Self::Scheduled + | Self::Timer | Self::RunStarted | Self::RunExited | Self::TerminalExited @@ -484,7 +494,11 @@ pub enum WorkbenchEvent { /// Changes to paths outside the project watched with `events.watch-paths` (API 1.18); /// `project` is the project the watch belongs to, `generation` is unset. WatchedFilesChanged(FilesChanged), + /// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21). + ProjectTreeExpanded(Vec), Scheduled, + /// A timer this plugin set with `events.schedule` fired (API 1.21): its id. + Timer(String), } impl WorkbenchEvent { @@ -511,7 +525,9 @@ impl WorkbenchEvent { Self::ProblemsChanged => EventKind::ProblemsChanged, Self::ProjectClosed(_) => EventKind::ProjectClosed, Self::WatchedFilesChanged(_) => EventKind::WatchedFilesChanged, + Self::ProjectTreeExpanded(_) => EventKind::ProjectTreeExpanded, Self::Scheduled => EventKind::Scheduled, + Self::Timer(_) => EventKind::Timer, } } } @@ -1215,6 +1231,10 @@ pub struct Decoration { /// The item's own colors (API 1.17 `set-styled`), validated `#rrggbb` / `#rrggbbaa`. #[serde(default)] pub colors: Option, + /// Hover-card actions (API 1.21 `set-actionable`); each runs one of the plugin's + /// declared commands as if from Find Action, then closes the card. + #[serde(default)] + pub actions: Vec, } /// Colors of a styled editor decoration (API 1.17). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] @@ -1222,6 +1242,17 @@ pub struct DecorationColors { pub foreground: Option, pub background: Option, } +/// A hover-card action button (API 1.21): runs one of the plugin's declared commands +/// as if the user ran it from Find Action, then closes the card. No new capability. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CardAction { + pub icon: Option, + pub label: String, + pub tooltip: Option, + pub command: String, + pub argument: Option, +} /// A tree decoration. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] pub struct FileDecoration { diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index 42ad7c9097..0ce422fe76 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -1824,7 +1824,7 @@ impl events::Host for StoreData { { return Ok(Err(to_wit(e))); } - if matches!(kind, EventKind::RunStarted | EventKind::RunOutput) + if matches!(kind, EventKind::RunStarted | EventKind::RunOutput | EventKind::ProjectTreeExpanded) && let Err(e) = self.host.require_api(kind.name(), 21) { return Ok(Err(to_wit(e))); @@ -1895,6 +1895,32 @@ impl events::Host for StoreData { Ok(()) } + fn schedule(&mut self, id: String, after_ms: u32) -> Fallible<()> { + if let Err(e) = self.host.require_api("events.schedule", 21) { + return Ok(Err(to_wit(e))); + } + if id.is_empty() || id.len() > 128 || id.chars().any(char::is_control) { + return Ok(Err(wit::Error::Invalid("timer id must be 1-128 bytes without control characters".into()))); + } + if !(MIN_TIMER_MS..=MAX_TIMER_MS).contains(&after_ms) { + return Ok(Err(wit::Error::Invalid(format!( + "a timer fires {MIN_TIMER_MS} ms to {MAX_TIMER_MS} ms from now" + )))); + } + let client = self.client().map(str::to_owned); + Ok(self + .host + .schedule(client.as_deref(), &id, std::time::Duration::from_millis(u64::from(after_ms))) + .map_err(to_wit)) + } + + fn cancel_schedule(&mut self, id: String) -> wasmtime::Result<()> { + if self.host.require_api("events.schedule", 21).is_ok() { + self.host.cancel_schedule(&id); + } + Ok(()) + } + fn watch_paths(&mut self, paths: Vec) -> Fallible<()> { if let Err(e) = self.require(Capability::Events) { return Ok(Err(e)); @@ -1934,6 +1960,9 @@ impl events::Host for StoreData { /// The most paths one plugin watches outside one project (`events.watch-paths`). const MAX_WATCHED_PATHS: usize = 32; +/// Bounds of `events.schedule`: the event loop's own period, and a day. +const MIN_TIMER_MS: u32 = 250; +const MAX_TIMER_MS: u32 = 24 * 60 * 60 * 1000; impl tasks::Host for StoreData { fn begin(&mut self, title: String, cancellable: bool) -> wasmtime::Result> { @@ -3522,6 +3551,7 @@ impl bindings::openidea::plugin::decorations::Host for StoreData { after: d.after, markdown_hover: None, colors: None, + actions: vec![], }) .collect(); self.replace_decorations(path, set_id, items) @@ -3541,6 +3571,7 @@ impl bindings::openidea::plugin::decorations::Host for StoreData { after: d.after, markdown_hover: d.markdown_hover, colors: None, + actions: vec![], }) .collect(); self.replace_decorations(path, set_id, items) @@ -3562,6 +3593,42 @@ impl bindings::openidea::plugin::decorations::Host for StoreData { colors: d .colors .map(|c| crate::DecorationColors { foreground: c.foreground, background: c.background }), + actions: vec![], + }) + .collect(); + self.replace_decorations(path, set_id, items) + } + fn set_actionable( + &mut self, + path: String, + set_id: String, + items: Vec, + ) -> Fallible<()> { + if let Err(e) = self.host.require_api("decorations.set-actionable", 21) { + return Ok(Err(to_wit(e))); + } + let items = items + .into_iter() + .map(|d| crate::Decoration { + range: core_range(d.range), + style: d.style, + hover: d.hover, + after: d.after, + markdown_hover: d.markdown_hover, + colors: d + .colors + .map(|c| crate::DecorationColors { foreground: c.foreground, background: c.background }), + actions: d + .actions + .into_iter() + .map(|a| crate::CardAction { + icon: a.icon, + label: a.label, + tooltip: a.tooltip, + command: a.command, + argument: a.argument, + }) + .collect(), }) .collect(); self.replace_decorations(path, set_id, items) @@ -4159,6 +4226,20 @@ impl bindings::openidea::plugin::agents::Host for StoreData { let client = self.invocation.client.clone().unwrap_or_default(); Ok(self.host.fork_agent_session(&client, &agent, &session_id, Path::new(&cwd)).map_err(to_wit)) } + fn start_task(&mut self, task: bindings::openidea::plugin::agents::NewTask) -> Fallible { + if let Err(e) = self.host.require_api("agents.start-task", 21) { + return Ok(Err(to_wit(e))); + } + if let Err(e) = self.require(Capability::Agents) { + return Ok(Err(e)); + } + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let client = self.invocation.client.clone().unwrap_or_default(); + let fork = task.fork.as_ref().map(|f| (f.session_id.as_str(), Path::new(&f.cwd))); + Ok(self.host.start_agent_task(&client, &task.provider, &task.prompt, fork).map_err(to_wit)) + } } pub(crate) mod mcp_bindings { diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index db24c4138d..bbafa4d1f5 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index fb3231a414..ece9ddd598 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -9d593a5ff4185d1e0a8bdaca546c82dcb2e79effd81dd025654237540c43a380 +b8be10102efb9a73945b342e1077130e3ae259d318a1328aa449f3fc6d33c95d diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm index 45f23bd3d8..e097552c81 100644 Binary files a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources index c52dc424e5..810153b2b3 100644 --- a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources @@ -1 +1 @@ -9b3ef215237f68ee53dbeefb8f2c12bdce0f4cd911038c6afdaa307558363c34 +75910c8950f19404d2b389c31250b38e94e0845b8406fd65086d801c3b7beb42 diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm index fe21db7665..37033f8b6c 100644 Binary files a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources index 21b5131dbe..efc110dcae 100644 --- a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources @@ -1 +1 @@ -c1e82db13b8779b83f0de375d79275a97778b7a868b22dd8e542bc2b414f9c91 +4dd181187bc087ad2155ac92d304f50cda4fededc63b02ad57cf012f01eef3f6 diff --git a/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm index 8dce7bc5ea..71502daa55 100644 Binary files a/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm.sources index d1dc771504..7743b4eb2f 100644 --- a/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/code-semantics/dist/plugin.wasm.sources @@ -1 +1 @@ -20b0ee40fd00f4b88f82228d93ebba835978336cc5fe60b834af2e431268c2aa +99dbde69e800adbb3277f78b0a7ffbf6c86b387995c7cf7f7701a5cc7175f87d diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 257968cf97..764cd88c4f 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 6e82245385..fec9c2509f 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -3a805f4d8296f5110ceaff05b7ef34bd6ebce394aba62ba68623c30cdf7e11b7 +4d795c1074d4be794c7327c623b0e366e1daab50778f918a42a2d38439542a12 diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm index 939f0cfb1a..ea48387785 100644 Binary files a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources index 1fd6d08646..11328421e0 100644 --- a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources @@ -1 +1 @@ -5d2db9abab7b9c7c3ce88a420ff0263bb2d2493e19723597276422a7a3ddb7ec +b85013d2dac330df156621e610bcb7b529761f34891ccb0a43139caff9b806e6 diff --git a/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm index 4d6e43bf0e..6eff8ac44d 100644 Binary files a/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm.sources index a0d248ad41..85af4f95bf 100644 --- a/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/completion-resolve/dist/plugin.wasm.sources @@ -1 +1 @@ -5732ca5ad9fa1aa8f3569cc046bc14c37b5f483d8861ecc95aee9c9d1f00d4d0 +6742d26393161e0858d7a672969d861493f36e28ae122fd3606aee570bf154f7 diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm index 5fafeae946..cb3225c75a 100644 Binary files a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources index 10b64e0aa4..be4b2c9c8b 100644 --- a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources @@ -1 +1 @@ -4a255f1746018ee5e01883f794ecca102909c993a0ee1d7c3679fdd19a131256 +31fec64f6ce288e5514d93dd2d451ec5e00c25ca5fd6568bde636765bc980168 diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm index 05347b6c7d..45fcad65a2 100644 Binary files a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources index 0b9b7792f9..0541332c3d 100644 --- a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -ac2354a040ab01663d680b282482415fe8698d37c5aa01ff7adc58097cd66669 +24fb126861d1398a19a4b9a9167dc253f4f03760428013050986f94391ed4c79 diff --git a/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm index 92b7cdb168..b19d474fbf 100644 Binary files a/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm.sources index d027a5b96a..8e98b779ed 100644 --- a/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/database-open/dist/plugin.wasm.sources @@ -1 +1 @@ -c02ff4e7e39457d8df55f71f9067c4fd5e2481b8a37531f770d2fc302443a054 +65c6e23c92a58ecb73518445eaf2f95decdd3ee434d2ba34101cd7b122881d1c diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm index 03e407993b..eb28584dce 100644 Binary files a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources index 18f59ed036..d2766c6489 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources @@ -1 +1 @@ -940ba84068829add9b8db39adbd5f719613e2bcdaf78637fd6958bc03f17173c +2f5ce9268f54296994835c650667142893574c96b707410024897242370d522f diff --git a/crates/ide-plugin/tests/fixtures/decorations/plugin.toml b/crates/ide-plugin/tests/fixtures/decorations/plugin.toml index c1077c9c37..38c61b560c 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/decorations/plugin.toml @@ -1,10 +1,10 @@ id = "decorations" name = "Decoration example" version = "0.1.0" -description = "Minimal plugin API 1.17 example: line-end labels with Markdown hover cards and their own colors." +description = "Minimal plugin API 1.21 example: line-end labels with Markdown hover cards, their own colors and hover-card actions." authors = ["OpenIDEA contributors"] license = "Apache-2.0" -engines.openidea = "^1.17" +engines.openidea = "^1.21" wasm = "dist/plugin.wasm" activation = ["on-command:*"] @@ -19,6 +19,18 @@ title = "Decorations: Publish" id = "styled" title = "Decorations: Publish Styled" +[[contributes.commands]] +id = "actionable" +title = "Decorations: Publish Actionable" + +[[contributes.commands]] +id = "actionable-bad" +title = "Decorations: Publish Invalid Actionable" + +[[contributes.commands]] +id = "continue" +title = "Decorations: Continue" + [[contributes.commands]] id = "clear" title = "Decorations: Clear" diff --git a/crates/ide-plugin/tests/fixtures/decorations/src/lib.rs b/crates/ide-plugin/tests/fixtures/decorations/src/lib.rs index 915ff71eb9..bf37dfef1b 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/decorations/src/lib.rs @@ -1,9 +1,10 @@ -//! Minimal plugin API 1.17 example: push a line-end label whose hover is Markdown, -//! and ranges painted in the plugin's own colors. +//! Minimal plugin API 1.21 example: push a line-end label whose hover is Markdown, +//! ranges painted in the plugin's own colors, and hover-card actions that run a +//! declared command. use openidea_plugin::{ - DecorationColors, Error, Invocation, MarkdownDecoration, Plugin, Position, Range, StyledDecoration, host, - register_plugin, + ActionableDecoration, CardAction, DecorationColors, Error, Invocation, MarkdownDecoration, Plugin, Position, Range, + StyledDecoration, host, register_plugin, }; #[derive(Default)] @@ -50,6 +51,69 @@ impl Plugin for Decorations { )?; Ok(None) } + "actionable" => { + let path = arg.ok_or_else(|| Error::Invalid("a project file path is required".into()))?; + host::set_actionable_decorations( + path, + "example", + &[ActionableDecoration { + range: Range::new(Position::new(0, 0), Position::new(0, 1)), + style: "highlight".into(), + hover: Some("model-x generated this line".into()), + after: Some(" + model-x".into()), + markdown_hover: Some("**model-x** generated this line".into()), + colors: None, + actions: vec![CardAction { + icon: None, + label: "Continue".into(), + tooltip: Some("Ask model-x to continue".into()), + command: "continue".into(), + argument: Some("more".into()), + }], + }], + )?; + Ok(None) + } + // Publishes an actionable set the host must refuse: ` `. + "actionable-bad" => { + let arg = arg.ok_or_else(|| Error::Invalid("expected ".into()))?; + let (mode, path) = + arg.split_once(' ').ok_or_else(|| Error::Invalid("expected ".into()))?; + let action = |command: &str, label: &str, argument: Option| CardAction { + icon: None, + label: label.into(), + tooltip: None, + command: command.into(), + argument, + }; + let actions = match mode { + "undeclared" => vec![action("no-such-command", "Go", None)], + "five" => (0..5).map(|i| action("continue", &format!("A{i}"), None)).collect(), + "empty-label" => vec![action("continue", "", None)], + "big-label" => vec![action("continue", &"x".repeat(65), None)], + "control-label" => vec![action("continue", "Go\u{85}", None)], + "big-tooltip" => { + vec![CardAction { tooltip: Some("t".repeat(257)), ..action("continue", "Go", None) }] + } + "big-arg" => vec![action("continue", "Go", Some("x".repeat(5 * 1024)))], + other => return Err(Error::Invalid(format!("unknown mode {other}"))), + }; + host::set_actionable_decorations( + path, + "example", + &[ActionableDecoration { + range: Range::new(Position::new(0, 0), Position::new(0, 1)), + style: "highlight".into(), + hover: None, + after: None, + markdown_hover: None, + colors: None, + actions, + }], + )?; + Ok(None) + } + "continue" => Ok(Some("continued".into())), "clear" => { host::clear_decorations("example")?; Ok(None) diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index 4f749d0b47..58dfe392c9 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index e62c8ebf80..70d6365c5b 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -cd1864953a21f839de35f4465b10d6ba46a95e1376ea95f8b4830fd1386249bd +1a1ab54e7c5939167cb5f18da6107ec812ed4ba6ff60b69b985675996cbda5a5 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index eff6c8dc55..a772b96ea9 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index ea6a39438a..314f543c30 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -864f1352536a133d58eece4b838fda0858a9146834c126f3749d224f5b072f45 +8775c5084031dfdda65492a10dc1c3dda4de82f02121f99c4dbeb989e21d5c2f diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index eea6229fb4..cf97dc7d7b 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index 9e478da5cb..0636f78b30 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -b6161800bc9b0f051a0150066b98d5492879cc3e7e108d6a5f8830510f4d739b +e54e38958b56dea794b7c625c6d91465bb5f6f34c83433a5f3e0c72fdb568fec diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm index 83e52b958e..fe06287074 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources index 2d27911785..e265f404fc 100644 --- a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources @@ -1 +1 @@ -88c5e2cd1c6fccfeabd4ac40e678d502a12d36b989bf73d9b37947871d1dd7ff +9986a416ae0286ef587fb068afa4017344e60e6fc798cf4b041330e223570c71 diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index de2f1f6888..f2541e187b 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index 7192f4f176..bb6a77cd0f 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -3a5444071ccd5b41e479e61f22e12305b14d74c029a92776e42cda56b100413f +650b01742cb7a9879a121df7fc3d49d478e4e9ead6b28bd1a7773fd3112c0579 diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm index dfa3af91c7..a899814d1f 100644 Binary files a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources index 3eae9246f7..d21df5fd1d 100644 --- a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources @@ -1 +1 @@ -80df228d526926ed7787e8f0419f07b621f3e772171ec89aba8f9258a56b8d13 +4e6dde5d4ca82690739916b859c738bb1d445c5406ad8f907376206c1c0d5a04 diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index 0196051bd4..9a800529aa 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index d19a130269..6934ae09b1 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -e006c711d732ef5cc4777858ba67c75736e8d48c97637d8a0788827c3db2a7bb +0d2992306e79a9ff042d7d15bd9690d12fcc3b658055f9f629ad534c4c6f72f0 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index f2d231bef6..73b574ec60 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 8552548b3a..66a166b87e 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -60e15b40a0dafaf2232c83c2ab62df8eb138fae023be46be288f05a80aa64d06 +0586a531e1c85c314960d7ac066179458ab4c20a5923c6738c3501c913452da9 diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index 17d35e9cf0..f58fe00762 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index fc0058a9e4..bd17279d0d 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -c6a449dcad76d15c044f171c0c8b89a439df31b9e9c5e1cc2de02c0318b68825 +10562a15fc5f231b8a68108653133c91e96e32b8c2ca1625d340151930a85081 diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index 46cd1d5fab..da97382729 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index c4f5724c1b..50a779a04b 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -39752f332187a22f2f76f462ab0055e6d620088590ca83b3875e2491937819c5 +f3232db563dcf0e08325425382014713bf96f60e17f307dbc568f1facf72948c diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm index 6e99078ab4..0dcfea536a 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources index 45f622b987..496cdabfdc 100644 --- a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources @@ -1 +1 @@ -55a61700fa710aac8d6e40150ab0e61d8b255f81cc2a749ef792a2e329a93b9b +c788f1a863f7efc73efe4611dca5ad0215c5a8c1da129a6158cf681b39fa18c3 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 22473d5850..85eed44e24 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index e2c95f413f..511b1f3067 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -42d724c96a1aceaff7f5e77304865fe1bb1c4b19790652050893cf3f8bbbc1f7 +d8c589d3f62c538e194b0f5a2e5db4f1be2812498a4f05f87e779535dd5ddde9 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index 76d80a5430..a6b54502bf 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index 37a4ce3e5e..18e8be950c 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -14388f08e0c6059e434d85e2d587824c215f2d9db40e1d01c482b2263c9fdf48 +dafa503be1dd67478e8bfc309c4c485e000a9b75cb3719df56683c86f1b68564 diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index 1dcdff1bb9..fb61dcdbb6 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index 5c68853c9f..22cc0402f5 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -0d7cc1362d3a4abe014b63ff734a3a6dcd41865ac801c518ffdfba94c40f2b5c +31381b6a31660cefaefe8b938c217711f1513bfb2445460787a4e9827407bb6e diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index b3bf9d612b..aa5d8e987d 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 5647ad4773..1ba1cf819a 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -26e64a2d30feb3586912b3c1fde5710c4098c90cbe9664fe2683f1ee9b39f1d5 +856991e10d441a6044f3952e94be581b83180497cd10026b88c0221bb446d644 diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm index 68c709de27..016dc16c16 100644 Binary files a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources index 89dd9936f0..b006cf0d0f 100644 --- a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources @@ -1 +1 @@ -4e4b99e638d824516f354325c73a6a3f48f75a460c27c9b912c46b0b604314af +b5e27b340ea81a792f5f2ec45b0b1aa3e529bcc4e94827fbb6c5aaf09edbcf7a diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm index a59d664d73..b63061e30e 100644 Binary files a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources index c66ecad1cf..6afc24d51a 100644 --- a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources @@ -1 +1 @@ -ca70d2fb1c37cfbb52d4849af9777fa00ae5bfff6575dd8cecadbb5728c99cd8 +48dddfe2f5126c9e4cfe4b5694c2e9218e4a82a29f0039ffcd2e093c0a15814a diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index f9a366deb5..cc11c919a5 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index ca64e0a33f..dbf34721a0 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -e6c4ab73ae15aa217143d889f83e28d46964b7f92d62987d93d0ecfe907558e1 +8bb50006dc5afe0f767a435d7f1a22c2b74fb9b84fb6b9c18213d322dce93eed diff --git a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml index b079823331..51278982c9 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml @@ -58,6 +58,10 @@ title = "insert" id = "fork-session" title = "fork-session" +[[contributes.commands]] +id = "start-task" +title = "start-task" + [[contributes.commands]] id = "cancel" title = "cancel" diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index 8a55060baa..c2df4cdb17 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -220,6 +220,30 @@ impl commands::Guest for Misbehave { let cwd = parts.next().unwrap_or_default(); openidea::plugin::agents::fork_session(agent, session_id, cwd).map(Some) } + // `agents.start-task`: arg is "provider prompt…", or "fork provider + // session-id cwd prompt…" to continue a recorded session. Without the + // `agents` grant this is `denied`, not a trap. + "start-task" => { + use openidea::plugin::agents::{NewTask, RecordedSession}; + let arg = arg.unwrap_or_default(); + let (provider, prompt, fork) = if let Some(rest) = arg.strip_prefix("fork ") { + let mut parts = rest.splitn(4, ' '); + let provider = parts.next().unwrap_or_default(); + let session_id = parts.next().unwrap_or_default(); + let cwd = parts.next().unwrap_or_default(); + let prompt = parts.next().unwrap_or_default(); + (provider, prompt, Some(RecordedSession { session_id: session_id.into(), cwd: cwd.into() })) + } else { + let mut parts = arg.splitn(2, ' '); + (parts.next().unwrap_or_default(), parts.next().unwrap_or_default(), None) + }; + openidea::plugin::agents::start_task(&NewTask { + provider: provider.into(), + prompt: prompt.into(), + fork, + }) + .map(Some) + } // The user gave up: not the plugin failing. "cancel" => Err(types::Error::Cancelled), // Event kinds are names: one this IDE doesn't know is refused. diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm index ef45a24579..d89f15a89a 100644 Binary files a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources index fa4b8d4d0e..89b57a43d7 100644 --- a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources @@ -1 +1 @@ -18b5a5595de9d7e1b3958a1421681f1592cd012395f0fe66d36d07f6d36ed291 +e68e7444837b2b55611407bc8a3c37cc0e8d210f502b79db2cf3a671534ce36b diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index f2cc718a58..4d7bfbc651 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index 6e900d5501..40be547614 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -d681e87d863a0ec6b8589326c5c3e9b0d846ec1593e3aa4493c6d8c5ec08c39a +84f8be0119ec2ada0e319f7162abd22ea6a64d7959fd2d342074687f3ab26fde diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 93e948e9bd..2d4188d0c0 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index 454888d782..51ff713e2b 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -5a090b8b6d2c31943affd5a4b7ec4b529f189a022a657519bfd6ef3957be81dc +31619ef14a44f347b01419a4851499fb0e1ed2c55a751b4d139e88914307e011 diff --git a/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm index 57f9709522..2cdfa6b986 100644 Binary files a/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm.sources index 561bddc625..3c8f1dd5a6 100644 --- a/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/project-view/dist/plugin.wasm.sources @@ -1 +1 @@ -f762dfe0a8b321b8430644ae6bea76b9d57e6cc2bb69b639cc407349c76745e2 +3a7908caa2ac93d57004e9a4dba72ae6d161a4183e921d393f9cedbe792ac839 diff --git a/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm index e3edff0063..9b7d575ba6 100644 Binary files a/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm.sources index d653e1d9f5..5a0eb3f0f0 100644 --- a/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/rename/dist/plugin.wasm.sources @@ -1 +1 @@ -5f041b939904dfdf2c6ab68eef35cd0ab9dd81227862f9481218f598ea260cc8 +4a9c229a681273e77e8ca3c429637899aa7187c855e85c668e2290c8773883ea diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm index a499c140e3..1cac213fa7 100644 Binary files a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources index 92e71abd4d..93721f488c 100644 --- a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources @@ -1 +1 @@ -dacde8dabebbcd6516c77620c446b7ebad543b2cd488cbca607c74bafcda8d83 +755b57c427ae48315cbadd252d7e8995c05af13c8cfb30cd8b0fa9d0c8d71338 diff --git a/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm index becc7b66fa..afc2483f34 100644 Binary files a/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm.sources index 1a46950422..ff7bb26dbc 100644 --- a/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/run-output/dist/plugin.wasm.sources @@ -1 +1 @@ -abb4745156f1527c40d8e403f6a274dc48c726ec255a98fbca58211b3117da46 +cc94a2dc87a04ebffae275445374290a6ff917b04ee10b21fbd1a696b79c1fe7 diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm index f12463abcd..d13fca8014 100644 Binary files a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources index 6571b86f04..e57a52cf9f 100644 --- a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources @@ -1 +1 @@ -5eb3e4bda1cbb7f611416e2112171c17786cc1fd66df261793f3674d17986ec3 +073e5322210532b3cd8f53701295a378b316c5e6f02479106d85d85757f03d42 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index a6d0481c5f..277e2e4df0 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index 10bd404087..b3deb03fce 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -fecf837130572c940185d4155ea3a256c6a5a159cba82bbb94f75406e9abc188 +16365c383dafd031032e7451c926bf27b4b92101cf7297487489b0effaee3c5a diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index ea44597054..0bab2ed126 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index f769ae467f..e9b4e7b36a 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -83e975431a728c18ade6f2fd273250b98135a40f6780977caa628514c584ff55 +581577464194e51034512aa56c4185e4dbe56ec6a1211227edea3e1a91b33f6b diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 884c19f96c..01be66c211 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index e825b6bb8d..c7e09eb582 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -8b3f32553a8cd4816fc068f00fbe5c38d3a1e9aa413cc44f75e961fb06ff5bbc +59075f549052aeaa82bdca52c95105d80d662518b7941ce12b8776475efed921 diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index cc1206c6f4..e640b8e86b 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index b2f1b8d917..c47668dde5 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -fff4074c3fc9fe829add39f510012e109618369ab35e5753df7a08dfeff19450 +610f8d6efffa69fabd5cc8518ff2e480dba39c89329df7b4ebbd09a364c5e15a diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm index 28f9474627..f0cc5417de 100644 Binary files a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources index f77ee46a77..8449e46364 100644 --- a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources @@ -1 +1 @@ -193e957ca658751a085c73ba81a222d8789f96e476c1385a23eef4844ee221ab +c8555859b237b5269a6e04e3c7bfbfd6fa087ba5edbeb78c9ffd5662983ffae3 diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index 374109b95c..5982d1dd70 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index 1bd0afa08f..2f09e059f8 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -8a9e6f773448a400881e18fc71d8788c5e66ca7a492dc9e636a111ac744d4dd9 +765f1a11c340593ed2101395fe98b68344cc1a68f9028ff6f6f422d2e9e0276f diff --git a/crates/ide-plugin/tests/fixtures/timers/Cargo.lock b/crates/ide-plugin/tests/fixtures/timers/Cargo.lock new file mode 100644 index 0000000000..70de0a5c1f --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/timers/Cargo.lock @@ -0,0 +1,337 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "wit-bindgen", +] + +[[package]] +name = "openidea-test-timers" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/timers/Cargo.toml b/crates/ide-plugin/tests/fixtures/timers/Cargo.toml new file mode 100644 index 0000000000..74937e4a25 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/timers/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-test-timers" +version = "0.1.0" +edition = "2024" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm new file mode 100644 index 0000000000..86c5ab7f5d Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm.sources new file mode 100644 index 0000000000..ab8f598dd1 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/timers/dist/plugin.wasm.sources @@ -0,0 +1 @@ +dfa4038456ddf3186642fb509b3fe6be3debc349356bc01d8717946723fa8bf8 diff --git a/crates/ide-plugin/tests/fixtures/timers/plugin.toml b/crates/ide-plugin/tests/fixtures/timers/plugin.toml new file mode 100644 index 0000000000..ebdbda4ce9 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/timers/plugin.toml @@ -0,0 +1,21 @@ +id = "timers" +name = "Timers test" +version = "0.1.0" +engines.openidea = "^1.21" +wasm = "dist/plugin.wasm" +activation = ["on-command:*"] + +[capabilities] +required = ["storage"] + +[[contributes.commands]] +id = "schedule" +title = "Set the timer given as ` `" + +[[contributes.commands]] +id = "cancel" +title = "Cancel the timer given" + +[[contributes.commands]] +id = "fired" +title = "Read the ids of the timers that fired" diff --git a/crates/ide-plugin/tests/fixtures/timers/src/lib.rs b/crates/ide-plugin/tests/fixtures/timers/src/lib.rs new file mode 100644 index 0000000000..076efa7926 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/timers/src/lib.rs @@ -0,0 +1,35 @@ +use openidea_plugin::{Error, Event, Invocation, Plugin, host, register_plugin}; + +#[derive(Default)] +struct Timers; + +impl Plugin for Timers { + fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result, Error> { + match id { + "schedule" => { + let (timer, ms) = arg.unwrap_or_default().split_once(' ').ok_or(Error::Invalid(" ".into()))?; + host::schedule(timer, ms.parse().map_err(|_| Error::Invalid(ms.into()))?)?; + Ok(None) + } + "cancel" => { + host::cancel_schedule(arg.unwrap_or_default()); + Ok(None) + } + "fired" => host::storage::get("fired"), + _ => Err(Error::NotFound(id.into())), + } + } + + fn handle_events(&mut self, events: &[Event], _ctx: &Invocation) { + let mut fired: Vec = + host::storage::get("fired").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default(); + for event in events { + if let Event::Timer(id) = event { + fired.push(id.clone()); + } + } + host::storage::set("fired", &serde_json::to_string(&fired).unwrap()).unwrap(); + } +} + +register_plugin!(Timers); diff --git a/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm index b94f31245c..63377d25d1 100644 Binary files a/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm.sources index 2984323ba4..cdcf285d93 100644 --- a/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/view-badge/dist/plugin.wasm.sources @@ -1 +1 @@ -32e8fb7a4962a2068fc03da748a5185fe1bb1a86ad8f904e0518f03dcabfb8bd +4fa2ff39fc10ac3855eb9eb17c2c8f9702306046cb63ddf9f0fd5891b772f9f5 diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm index 0dc62b2cf9..29a4cceb12 100644 Binary files a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources index b96665ef4f..7ce5caa584 100644 --- a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources @@ -1 +1 @@ -ecf50976d7bff093071dd9e681c962adc474b416a3ea87006e8b350c1201de4b +67c5a1fb2752dfb684f14bdb3e99a8afa47db8f77abeb8a9a6991d776846e3da diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index 5e22456bc6..563f357170 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 327ccdfaf2..b9bee79ad8 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -1a0c5aeb00d95297584b5d06a122b364a5f249b391d3cf9ffd5118d162d9da1c +76f6490d223bed1bac0a4f5847a18f5970e087ca1e724409ceaabe2254f7dbd2 diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index 05bdf1ba7d..472b20bc78 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index d6a3cf2378..d5c8fb21fc 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -69a618e8e44698bd9cb19f1947091bc30358b62c8043cfbeb95102c8c8c470ba +4748143f3c002ab6764095aa989aac68d64111a5dbb45d62cd893a22f40e87ec diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index 54cbfc0f9a..ebad414dfb 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index 9e8599235e..fac16cb216 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -e72d0edf256538b297fdad74e10d13b69379093ad8286268e1de42803a3ee7cf +1725d6ac5f25a224921693c170b9b8e1ff4d894562e5811936cb40cbb308d863 diff --git a/crates/ide-run/src/detect/cmake/mod.rs b/crates/ide-run/src/detect/cmake/mod.rs index 87626225ad..64d8e5acee 100644 --- a/crates/ide-run/src/detect/cmake/mod.rs +++ b/crates/ide-run/src/detect/cmake/mod.rs @@ -327,11 +327,19 @@ fn targets( return; } let canonical_root = dunce::canonicalize(&source_root).unwrap_or(source_root); + let matched_name = profile.and_then(|profile| { + let names = model.configurations.iter().map(|configuration| configuration.name.as_str()); + names.clone().find(|&name| name == profile.build_type).or_else(|| { + let mut matching = names.filter(|name| name.eq_ignore_ascii_case(&profile.build_type)); + let name = matching.next()?; + matching.next().is_none().then_some(name) + }) + }); for (index, configuration) in model.configurations.iter().enumerate() { let name = configuration.name.as_str(); // The profile's configuration; with CLion's "Default" build type (empty), the first one. let wanted = |p: &CMakeProfile| { - if p.build_type.is_empty() { index == 0 } else { name.is_empty() || name == p.build_type } + if p.build_type.is_empty() { index == 0 } else { name.is_empty() || Some(name) == matched_name } }; if profile.is_some_and(|p| !wanted(p)) { continue; @@ -731,6 +739,59 @@ mod tests { assert!(root.path().join("out/dev/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file()); } + #[test] + fn preset_targets_match_the_codemodel_configuration() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + fs::write(root.join("CMakeLists.txt"), "project(app)").unwrap(); + fs::write( + root.join("CMakePresets.json"), + r#"{"version":3,"configurePresets":[{"name":"dev","binaryDir":"out","cacheVariables":{"CMAKE_BUILD_TYPE":"Debug"}}]}"#, + ) + .unwrap(); + let settings = ide_core::settings::CMakeSettings { enabled_presets: vec!["dev".into()], ..Default::default() }; + let profiles = presets::profiles(root, &settings, &[]).unwrap(); + assert_eq!(profiles[0].build_type, "Debug"); + + for (names, expected) in [ + (&["Release", "debug"][..], Some("debug")), + (&["debug", "DEBUG", "Debug"][..], Some("Debug")), + (&["debug", "DEBUG"][..], None), + (&["Release"][..], None), + (&["Release", ""][..], Some("Debug")), + ] { + let configurations: Vec<_> = names + .iter() + .map(|name| serde_json::json!({"name": name, "targets": [{"jsonFile": "app.json"}]})) + .collect(); + file_api::tests::write_reply( + &root.join("out"), + &[( + "codemodel", + 2, + "model.json", + serde_json::json!({"paths": {"source": root}, "configurations": configurations}), + )], + &[( + "app.json", + serde_json::json!({"name": "app", "type": "EXECUTABLE", "artifacts": [{"path": "app"}]}), + )], + ); + let mut configs = Vec::new(); + detect(root, Some(&profiles), &mut configs); + let target_ids: Vec<_> = + configs.iter().filter(|c| c.id.starts_with("cmake:profile:target:")).map(|c| c.id.as_str()).collect(); + if let Some(expected) = expected { + let id = "cmake:profile:target:app:build"; + assert_eq!(target_ids, [id, "cmake:profile:target:app"], "{names:?}"); + let build = configs.iter().find(|c| c.id == id).unwrap(); + assert_eq!(build.args[..6], ["--build", "out", "--target", "app", "--config", expected]); + } else { + assert!(target_ids.is_empty(), "{names:?}"); + } + } + } + #[test] fn the_default_build_type_passes_no_configuration() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/ide-run/src/detect/dotnet.rs b/crates/ide-run/src/detect/dotnet.rs index 33b50cb680..5458bde9f5 100644 --- a/crates/ide-run/src/detect/dotnet.rs +++ b/crates/ide-run/src/detect/dotnet.rs @@ -2,7 +2,7 @@ use crate::{ RunConfig, - dotnet::{is_project_file, parse_project, profiles, solution_projects}, + dotnet::{is_project_file, parse_project_file, profiles, solution_projects}, }; use std::{ collections::{BTreeMap, BTreeSet}, @@ -68,7 +68,7 @@ pub(crate) fn detect(root: &Path, out: &mut Vec) { let root = dunce::canonicalize(root).unwrap_or_else(|_| root.into()); let projects: BTreeSet<_> = projects.into_iter().filter_map(|p| dunce::canonicalize(p).ok()).collect(); for path in projects { - let Some(project) = fs::read_to_string(&path).ok().and_then(|s| parse_project(&s)) else { continue }; + let Some(project) = parse_project_file(&path, &root) else { continue }; let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); let name = path.file_stem().unwrap_or_default().to_string_lossy(); let profiles = profiles(&path); @@ -111,7 +111,7 @@ fn detected(project: &str, name: &str, profile: &str, params: BTreeMap Option> { pub fn parse_project(xml: &str) -> Option { let tags = elements(xml)?; + parse_project_tags(&tags) +} + +/// Parses a project file together with ancestor `Directory.Build.props` files under `root` +/// (following MSBuild's rule: stop at the nearest `Directory.Build.props` unless it chains upward +/// with `GetPathOfFileAbove`). +pub fn parse_project_file(path: &Path, root: &Path) -> Option { + let xml = fs::read_to_string(path).ok()?; + let project_tags = elements(&xml)?; + if project_tags.first()?.name != "Project" { + return None; + } + let mut props = Vec::new(); + let mut dir = path.parent(); + while let Some(d) = dir { + if !d.starts_with(root) { + break; + } + let candidate = d.join("Directory.Build.props"); + if let Ok(src) = fs::read_to_string(&candidate) { + let chains = src.contains("GetPathOfFileAbove"); + if let Some(tags) = elements(&src) { + props.push(tags); + } + if !chains { + break; + } + } + dir = d.parent(); + } + if props.is_empty() { + return parse_project_tags(&project_tags); + } + let mut combined = Vec::new(); + for tags in props.into_iter().rev() { + combined.extend(tags); + } + combined.extend(project_tags); + parse_project_tags(&combined) +} + +fn parse_project_tags(tags: &[Element]) -> Option { if tags.first()?.name != "Project" { return None; } diff --git a/crates/ide-run/src/gradle_jvm.rs b/crates/ide-run/src/gradle_jvm.rs index 44f90292c8..4e9875de93 100644 --- a/crates/ide-run/src/gradle_jvm.rs +++ b/crates/ide-run/src/gradle_jvm.rs @@ -21,18 +21,35 @@ fn groovy_string(s: &str) -> String { out } +const HEADER: &str = r#"// Written by OpenIDEA: VM options of the run configuration. +import org.gradle.util.GradleVersion +// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. +def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +"#; + /// The init script adding `jvm_args` (one argument each) to the forked JVMs. pub fn init_script(jvm_args: &[String]) -> String { let list = jvm_args.iter().map(|a| groovy_string(a)).collect::>().join(", "); format!( - "// Written by OpenIDEA: VM options of the run configuration.\n\ - import org.gradle.util.GradleVersion\n\ - // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\ - def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \ - tasks.configureEach(action) : tasks.all(action) }}\n\ - allprojects {{\n \ - each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \ - each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\ + "{HEADER}eachProject {{ p ->\n \ + each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \ + each(p.tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\ }}\n" ) } @@ -79,8 +96,8 @@ mod tests { fn adds_each_argument_to_java_exec_and_test_tasks() { let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"])); let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']"; - assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); - assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); + assert!(script.contains(&format!("each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); + assert!(script.contains(&format!("each(p.tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); // Gradle before 4.9 has no `configureEach` (#3864). assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}"); } diff --git a/crates/ide-run/tests/config.rs b/crates/ide-run/tests/integration/config.rs similarity index 100% rename from crates/ide-run/tests/config.rs rename to crates/ide-run/tests/integration/config.rs diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/integration/detect.rs similarity index 100% rename from crates/ide-run/tests/detect.rs rename to crates/ide-run/tests/integration/detect.rs diff --git a/crates/ide-run/tests/dotnet.rs b/crates/ide-run/tests/integration/dotnet.rs similarity index 91% rename from crates/ide-run/tests/dotnet.rs rename to crates/ide-run/tests/integration/dotnet.rs index 80eb731263..e5fce59166 100644 --- a/crates/ide-run/tests/dotnet.rs +++ b/crates/ide-run/tests/integration/dotnet.rs @@ -155,7 +155,7 @@ fn detection_deduplicates_projects_and_generates_commands() { let test = configs.iter().find(|c| c.is_test).unwrap(); assert_eq!(test.kind, "dotnet-test"); assert_eq!(test.args, ["test", "src/Test/Test.csproj", "--framework", "net10.0"]); - assert!(test.debug_adapter.is_none()); + assert_eq!(test.debug_adapter.as_deref(), Some("netcoredbg")); let mut edited = app.clone(); edited.env.insert("DEMO".into(), "override".into()); let resolved = resolve(root, edited.clone()).unwrap(); @@ -195,6 +195,34 @@ fn an_xunit_v3_testing_platform_project_gets_a_test_configuration() { assert_eq!(configs[0].args, ["test", "tests/App.Tests/App.Tests.csproj", "--framework", "net11.0"]); } +#[test] +fn directory_build_props_supplies_inherited_framework_and_test_metadata() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + write( + root, + "Directory.Build.props", + r#"net8.0"#, + ); + write( + root, + "tests/Directory.Build.props", + r#"true"#, + ); + write( + root, + "tests/Domain.Tests/Domain.Tests.csproj", + r#"Domain.Tests"#, + ); + let configs = detect(root); + assert_eq!(configs.len(), 1); + assert_eq!(configs[0].kind, "dotnet-test"); + assert!(configs[0].is_test); + assert_eq!(configs[0].debug_adapter.as_deref(), Some("netcoredbg")); + assert_eq!(configs[0].extras.params["framework"], "net8.0"); + assert_eq!(configs[0].args, ["test", "tests/Domain.Tests/Domain.Tests.csproj", "--framework", "net8.0"]); +} + /// The project files `dotnet new` writes for F# and Visual Basic (SDK 11), by kind. fn templates(lang: &str) -> [(&'static str, String, bool, bool); 5] { let exe = r#"Exenet11.0"#; @@ -230,7 +258,7 @@ fn fsharp_and_vb_projects_follow_the_csharp_rules() { assert_eq!(own.len(), usize::from(run || test), "{ext} {kind}"); for c in own { assert_eq!(c.kind, if test { "dotnet-test" } else { "dotnet" }, "{ext} {kind}"); - assert_eq!(c.debug_adapter.is_some(), run, "{ext} {kind}"); + assert_eq!(c.debug_adapter.as_deref(), Some("netcoredbg"), "{ext} {kind}"); } } let multi = configs.iter().find(|c| c.name == "WinExe (.NET Project)").unwrap(); diff --git a/crates/ide-run/tests/dotnet_cli.rs b/crates/ide-run/tests/integration/dotnet_cli.rs similarity index 100% rename from crates/ide-run/tests/dotnet_cli.rs rename to crates/ide-run/tests/integration/dotnet_cli.rs diff --git a/crates/ide-run/tests/integration/gradle_init_scripts.rs b/crates/ide-run/tests/integration/gradle_init_scripts.rs new file mode 100644 index 0000000000..5c8ea847e7 --- /dev/null +++ b/crates/ide-run/tests/integration/gradle_init_scripts.rs @@ -0,0 +1,201 @@ +//! The init scripts of Gradle run, debug and test launches on a real Gradle, with and without +//! Isolated Projects (#8261). Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else +//! `gradle` on the search path); skipped without them, like ide-build's Gradle tests. +use std::path::{Path, PathBuf}; +use std::process::Command; + +const RUN: &str = include_str!("../../../../src/features/run/gradleRun.gradle"); +const BOOT: &str = include_str!("../../../../src/features/run/gradleBoot.gradle"); +const TESTS: &str = include_str!("../../../../src/features/run/gradleTests.gradle"); + +const MAIN: &str = r#"package a; +public class Main { + public static void main(String[] args) { + String token = ""; + for (String a : java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments()) + if (a.startsWith("-Dopenidea.")) token += " " + a; + System.out.println("APP " + String.join(",", args) + " enc=" + System.getProperty("file.encoding") + " vm=" + System.getProperty("openidea.vm") + token); + } +} +"#; + +const TEST: &str = r#"package l; +class LTest { + @org.junit.jupiter.api.Test + void ok() { + System.out.println("TEST vm=" + System.getProperty("openidea.vm") + " late=" + System.getProperty("openidea.late")); + } +} +"#; + +const JUNIT: &str = "org.junit.jupiter:junit-jupiter:5.11.0"; + +fn gradle() -> Option { + std::env::var_os("JAVA_HOME")?; + std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())) +} + +fn write(root: &Path, files: &[(&str, &str)]) { + for (rel, text) in files { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } +} + +/// Runs `tasks` with every init script; the output, or the failure with it. +fn run(gradle: &Path, root: &Path, tasks: &[&str]) -> Result { + let scripts = root.parent().unwrap().join("scripts"); + let mut args = vec!["--console=plain".to_owned()]; + for name in ["jvm", "encoding", "run", "boot", "tests"] { + args.extend(["--init-script".to_owned(), scripts.join(format!("{name}.init.gradle")).display().to_string()]); + } + args.extend( + [ + "-Dopenidea.run.project=:app", + "-Dopenidea.run.main=a.Main", + r#"-Dopenidea.run.args=["openidea"]"#, + "-Dopenidea.run.token=t1", + ] + .map(String::from), + ); + args.extend(tasks.iter().map(|t| t.to_string())); + let out = Command::new(gradle).args(&args).current_dir(root).output().unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + if out.status.success() { Ok(text) } else { Err(text) } +} + +/// The test-events script reported the test, with its output, from a test JVM given the VM options. +fn assert_test_events(out: &str) { + for event in [ + "##teamcity[testStarted name='ok()' className='l.LTest'", + "##teamcity[testStdOut name='ok()' className='l.LTest' reportName='ok()' out='TEST vm=1", + "##teamcity[testFinished name='ok()' className='l.LTest'", + ] { + assert!(out.contains(event), "no `{event}`:\n{out}"); + } +} + +fn app_line<'a>(out: &'a str, arg: &str) -> &'a str { + let prefix = format!("APP {arg} "); + out.lines().find(|l| l.starts_with(&prefix)).unwrap_or_else(|| panic!("no `{prefix}` line:\n{out}")) +} + +/// Gradle's version, as (major, minor). +fn version(gradle: &Path) -> (u32, u32) { + let out = Command::new(gradle).arg("--version").output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + let v = text.lines().find_map(|l| l.strip_prefix("Gradle ")).expect("a `Gradle x.y` line"); + let mut parts = v.trim().split('.').map(|p| p.parse::().unwrap_or(0)); + (parts.next().unwrap(), parts.next().unwrap_or(0)) +} + +#[test] +fn run_debug_and_test_scripts_configure_each_project() { + let Some(gradle) = gradle() else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let jvm = ide_run::gradle_jvm::init_script(&["-Dopenidea.vm=1".to_owned()]); + write( + &base, + &[ + ("scripts/jvm.init.gradle", &jvm), + ("scripts/encoding.init.gradle", ide_core::output_encoding::GRADLE_FILE_ENCODING_SCRIPT), + ("scripts/run.init.gradle", RUN), + ("scripts/boot.init.gradle", BOOT), + ("scripts/tests.init.gradle", TESTS), + ], + ); + + // Without Isolated Projects, in the Groovy DSL: the build's own setting still wins over the + // scripts' UTF-8 default, also when the root configures its subprojects. + let plain = base.join("plain"); + write( + &plain, + &[ + ("gradle.properties", "org.gradle.daemon=false\n"), + ("settings.gradle", "rootProject.name = 'plain'\ninclude 'app', 'lib'\n"), + ( + "build.gradle", + "subprojects { tasks.withType(JavaExec).configureEach { defaultCharacterEncoding = 'ISO-8859-1' } }\n", + ), + ( + "app/build.gradle", + "plugins { id 'application' }\napplication { mainClass = 'a.Main' }\ntasks.named('run') { args 'run' }\n\ + tasks.register('bootRun', JavaExec) { mainClass = 'a.Main'; classpath = sourceSets.main.runtimeClasspath; args 'boot' }\n", + ), + ("app/src/main/java/a/Main.java", MAIN), + ( + "lib/build.gradle", + &format!( + "plugins {{ id 'java' }}\nrepositories {{ mavenCentral() }}\n\ + dependencies {{ testImplementation '{JUNIT}'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }}\n\ + test {{ useJUnitPlatform() }}\n" + ), + ), + ("lib/src/test/java/l/LTest.java", TEST), + ], + ); + let out = run(&gradle, &plain, &[":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]).unwrap(); + assert_eq!(app_line(&out, "run"), "APP run enc=ISO-8859-1 vm=1 -Dopenidea.vm=1"); + assert_eq!(app_line(&out, "boot"), "APP boot enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + assert_eq!(app_line(&out, "openidea"), "APP openidea enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + assert_test_events(&out); + + // With Isolated Projects, in the Kotlin DSL, on a configuration cache miss and then a hit. + let isolated = base.join("isolated"); + write( + &isolated, + &[ + ( + "gradle.properties", + "org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\ + org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ("settings.gradle.kts", "rootProject.name = \"isolated\"\ninclude(\"app\", \"lib\")\n"), + ("build.gradle.kts", ""), + ( + "app/build.gradle.kts", + "plugins { application }\napplication { mainClass.set(\"a.Main\") }\n\ + tasks.named(\"run\") { args(\"run\"); defaultCharacterEncoding = \"ISO-8859-1\"; jvmArgs(\"-Dopenidea.vm=build\") }\n\ + tasks.register(\"bootRun\") { mainClass.set(\"a.Main\"); classpath = sourceSets[\"main\"].runtimeClasspath; args(\"boot\") }\n\ + afterEvaluate { tasks.named(\"bootRun\") { setJvmArgs(listOf(\"-Dopenidea.late=1\")) } }\n", + ), + ("app/src/main/java/a/Main.java", MAIN), + ( + "lib/build.gradle.kts", + &format!( + "plugins {{ java }}\nrepositories {{ mavenCentral() }}\n\ + dependencies {{ testImplementation(\"{JUNIT}\"); testRuntimeOnly(\"org.junit.platform:junit-platform-launcher\") }}\n\ + tasks.test {{ useJUnitPlatform() }}\n\ + afterEvaluate {{ tasks.named(\"test\") {{ systemProperty(\"openidea.late\", \"1\") }} }}\n" + ), + ), + ("lib/src/test/java/l/LTest.java", TEST), + ], + ); + let tasks = [":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]; + if version(&gradle) < (8, 8) { + // Before Gradle 8.8 the scripts keep reading every project, as the build above checked. + return; + } + for pass in ["miss", "hit"] { + let out = run(&gradle, &isolated, &tasks).unwrap_or_else(|e| panic!("cache {pass}:\n{e}")); + assert_eq!(out.contains("Reusing configuration cache."), pass == "hit", "{out}"); + // The build's own charset and VM option win over the scripts' values. + let run = app_line(&out, "run"); + assert!(run.starts_with("APP run enc=ISO-8859-1 vm=build "), "{run}"); + // The token comes after the build's own `afterEvaluate`, which replaced the JVM arguments. + assert_eq!(app_line(&out, "boot"), "APP boot enc=UTF-8 vm=null -Dopenidea.late=1 -Dopenidea.run.token=t1"); + assert_eq!(app_line(&out, "openidea"), "APP openidea enc=UTF-8 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + // Test tasks always run, also on a cache hit. + assert_test_events(&out); + // The test task the build configures in its own `afterEvaluate` ran with that setting. + assert!(out.contains("out='TEST vm=1 late=1"), "{out}"); + } +} diff --git a/crates/ide-run/tests/import_jetbrains.rs b/crates/ide-run/tests/integration/import_jetbrains.rs similarity index 100% rename from crates/ide-run/tests/import_jetbrains.rs rename to crates/ide-run/tests/integration/import_jetbrains.rs diff --git a/crates/ide-run/tests/import_vscode.rs b/crates/ide-run/tests/integration/import_vscode.rs similarity index 100% rename from crates/ide-run/tests/import_vscode.rs rename to crates/ide-run/tests/integration/import_vscode.rs diff --git a/crates/ide-run/tests/integration/main.rs b/crates/ide-run/tests/integration/main.rs new file mode 100644 index 0000000000..59421043d2 --- /dev/null +++ b/crates/ide-run/tests/integration/main.rs @@ -0,0 +1,16 @@ +mod config; +mod detect; +mod dotnet; +mod dotnet_cli; +mod gradle_init_scripts; +mod import_jetbrains; +mod import_vscode; +#[cfg(unix)] +mod process; +#[cfg(unix)] +mod stop_group; +#[cfg(windows)] +mod stop_tree; +mod tomcat_artifact; +#[cfg(windows)] +mod windows_output; diff --git a/crates/ide-run/tests/process.rs b/crates/ide-run/tests/integration/process.rs similarity index 99% rename from crates/ide-run/tests/process.rs rename to crates/ide-run/tests/integration/process.rs index ee57a65b3b..d757cccc6b 100644 --- a/crates/ide-run/tests/process.rs +++ b/crates/ide-run/tests/integration/process.rs @@ -1,5 +1,3 @@ -#![cfg(unix)] - use ide_core::{IdeEvent, RunId, SharedSink}; use ide_run::junit::ReportSnapshot; use ide_run::{OutputChunk, ProcessManager, RunConfig, StartOptions}; diff --git a/crates/ide-run/tests/stop_group.rs b/crates/ide-run/tests/integration/stop_group.rs similarity index 99% rename from crates/ide-run/tests/stop_group.rs rename to crates/ide-run/tests/integration/stop_group.rs index ebf7c842f3..fb58c6bb23 100644 --- a/crates/ide-run/tests/stop_group.rs +++ b/crates/ide-run/tests/integration/stop_group.rs @@ -1,6 +1,5 @@ //! A stopped run reports its exit only once the whole process group is gone, so the next //! start cannot meet a port the previous process still holds. -#![cfg(unix)] use ide_core::{IdeEvent, RunId, SharedSink}; use ide_run::{ProcessManager, RunConfig, StartOptions}; diff --git a/crates/ide-run/tests/stop_tree.rs b/crates/ide-run/tests/integration/stop_tree.rs similarity index 99% rename from crates/ide-run/tests/stop_tree.rs rename to crates/ide-run/tests/integration/stop_tree.rs index 6cac1a6f61..48265546e6 100644 --- a/crates/ide-run/tests/stop_tree.rs +++ b/crates/ide-run/tests/integration/stop_tree.rs @@ -2,7 +2,6 @@ //! launch reaches what a launcher started even when the launcher exited first (where a //! `taskkill /T /F` from the tracked pid no longer finds the orphan), and the run only //! reports its exit once the port the tree held is free again. -#![cfg(windows)] use ide_core::{IdeEvent, RunId, SharedSink}; use ide_run::{OutputChunk, ProcessManager, RunConfig, StartOptions}; diff --git a/crates/ide-run/tests/tomcat_artifact.rs b/crates/ide-run/tests/integration/tomcat_artifact.rs similarity index 100% rename from crates/ide-run/tests/tomcat_artifact.rs rename to crates/ide-run/tests/integration/tomcat_artifact.rs diff --git a/crates/ide-run/tests/windows_output.rs b/crates/ide-run/tests/integration/windows_output.rs similarity index 96% rename from crates/ide-run/tests/windows_output.rs rename to crates/ide-run/tests/integration/windows_output.rs index 747e13e7a7..112d99ba35 100644 --- a/crates/ide-run/tests/windows_output.rs +++ b/crates/ide-run/tests/integration/windows_output.rs @@ -1,69 +1,67 @@ -#![cfg(windows)] - -use ide_core::{IdeEvent, SharedSink}; -use ide_run::{OutputChunk, ProcessManager, RunConfig, StartOptions}; -use parking_lot::Mutex; -use std::collections::BTreeMap; -use std::sync::Arc; -use std::sync::mpsc; -use std::time::Duration; - -/// Stdout and stderr of a shell command line run on pipes in a UTF-8 console. -fn run(command: &str) -> String { - let (tx, events) = mpsc::channel(); - let tx = Mutex::new(tx); - let sink: SharedSink = Arc::new(move |e: IdeEvent| { - let _ = tx.lock().send(e); - }); - let root = tempfile::tempdir().unwrap(); - let config = RunConfig { - id: "t:out".into(), - name: "t:out".into(), - kind: "shell".into(), - command: command.into(), - args: Vec::new(), - cwd: None, - env: BTreeMap::new(), - detected: false, - is_test: false, - debug_adapter: None, - allow_parallel: false, - extras: Default::default(), - }; - let chunks: Arc>> = Arc::default(); - let out = chunks.clone(); - let pm = ProcessManager::new(); - let info = pm - .start(root.path(), &config, &StartOptions::default(), sink, Box::new(move |c| out.lock().push(c))) - .expect("start"); - loop { - match events.recv_timeout(Duration::from_secs(20)).expect("RunExited event") { - IdeEvent::RunExited { run, .. } if run == info.id => break, - _ => {} - } - } - chunks - .lock() - .iter() - .filter_map(|c| match c { - OutputChunk::Stdout { text } | OutputChunk::Stderr { text } => Some(text.as_str()), - _ => None, - }) - .collect() -} - -/// `cmd`'s own messages reach the pipe in the console code page (GBK, Shift_JIS, EUC-KR, -/// 437…, by the system's language), and still read right in a UTF-8 console. -#[test] -fn native_messages_in_the_console_code_page_are_decoded() { - let text = run(r"dir C:\openidea-no-such-dir"); - assert!(text.trim().lines().count() >= 2, "{text:?}"); - assert!(!text.contains('\u{FFFD}'), "{text:?}"); -} - -/// `cmd /u` writes UTF-16LE, as `wsl.exe` does; it reads right whatever the system's language. -#[test] -fn utf16_output_is_decoded() { - let text = run("cmd /u /c echo 中文 한국어 OK"); - assert_eq!(text, "中文 한국어 OK\r\n"); -} +use ide_core::{IdeEvent, SharedSink}; +use ide_run::{OutputChunk, ProcessManager, RunConfig, StartOptions}; +use parking_lot::Mutex; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::mpsc; +use std::time::Duration; + +/// Stdout and stderr of a shell command line run on pipes in a UTF-8 console. +fn run(command: &str) -> String { + let (tx, events) = mpsc::channel(); + let tx = Mutex::new(tx); + let sink: SharedSink = Arc::new(move |e: IdeEvent| { + let _ = tx.lock().send(e); + }); + let root = tempfile::tempdir().unwrap(); + let config = RunConfig { + id: "t:out".into(), + name: "t:out".into(), + kind: "shell".into(), + command: command.into(), + args: Vec::new(), + cwd: None, + env: BTreeMap::new(), + detected: false, + is_test: false, + debug_adapter: None, + allow_parallel: false, + extras: Default::default(), + }; + let chunks: Arc>> = Arc::default(); + let out = chunks.clone(); + let pm = ProcessManager::new(); + let info = pm + .start(root.path(), &config, &StartOptions::default(), sink, Box::new(move |c| out.lock().push(c))) + .expect("start"); + loop { + match events.recv_timeout(Duration::from_secs(20)).expect("RunExited event") { + IdeEvent::RunExited { run, .. } if run == info.id => break, + _ => {} + } + } + chunks + .lock() + .iter() + .filter_map(|c| match c { + OutputChunk::Stdout { text } | OutputChunk::Stderr { text } => Some(text.as_str()), + _ => None, + }) + .collect() +} + +/// `cmd`'s own messages reach the pipe in the console code page (GBK, Shift_JIS, EUC-KR, +/// 437…, by the system's language), and still read right in a UTF-8 console. +#[test] +fn native_messages_in_the_console_code_page_are_decoded() { + let text = run(r"dir C:\openidea-no-such-dir"); + assert!(text.trim().lines().count() >= 2, "{text:?}"); + assert!(!text.contains('\u{FFFD}'), "{text:?}"); +} + +/// `cmd /u` writes UTF-16LE, as `wsl.exe` does; it reads right whatever the system's language. +#[test] +fn utf16_output_is_decoded() { + let text = run("cmd /u /c echo 中文 한국어 OK"); + assert_eq!(text, "中文 한국어 OK\r\n"); +} diff --git a/crates/ide-scaffold/src/engine.rs b/crates/ide-scaffold/src/engine.rs index 7b3f0e7844..c3f6b34b92 100644 --- a/crates/ide-scaffold/src/engine.rs +++ b/crates/ide-scaffold/src/engine.rs @@ -44,6 +44,39 @@ fn search_path() -> OsString { ide_core::process::host_var_os("PATH").unwrap_or_default() } +/// Where a generator's programs are found, and what they run with. +pub(crate) struct Toolchain { + search: OsString, + goroot: Option, +} + +impl Toolchain { + /// The host `PATH`. A generator that needs `go` gets the GOROOT chosen in Settings first on + /// it and as `GOROOT`, as Run and gopls do, while that GOROOT still holds a `go`. + fn new(def: &Def, values: &Values, goroot: Option<&Path>) -> Self { + let search = search_path(); + let needs_go = needs(def, values, "go"); + let usable = |g: &&Path| ide_core::tool_path::find_command("go", g.join("bin").as_os_str(), g).is_some(); + match goroot.filter(|_| needs_go).filter(usable) { + Some(goroot) => Toolchain { + search: std::env::join_paths(std::iter::once(goroot.join("bin")).chain(std::env::split_paths(&search))) + .unwrap_or(search), + goroot: Some(goroot.to_path_buf()), + }, + None => Toolchain { search, goroot: None }, + } + } + + fn command(&self, program: &Path) -> Command { + let mut cmd = Command::new(program); + cmd.env("PATH", &self.search); + if let Some(goroot) = &self.goroot { + cmd.env("GOROOT", goroot); + } + cmd + } +} + /// `values` plus every field's rendered default it lacks, `name` included. fn with_defaults(def: &Def, name: &str, values: &Values) -> Values { let mut out = values.clone(); @@ -96,16 +129,16 @@ pub(crate) fn version_at_least(a: &str, b: &str) -> bool { true } -fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requirement { +fn requirement(r: &RequireDef, values: &Values, tools: &Toolchain) -> Requirement { let program = render(&r.program, values); let min = r.min.clone(); - let found_path = ide_core::process::find_executable(&program, search); + let found_path = ide_core::process::find_executable(&program, &tools.search); let found = found_path.as_ref().and_then(|path| { if r.version_args.is_empty() { return Some(String::new()); } - let mut cmd = Command::new(path); - cmd.args(&r.version_args).env("PATH", search); + let mut cmd = tools.command(path); + cmd.args(&r.version_args); let (ok, out) = run_quiet(cmd, std::time::Duration::from_secs(20))?; // A failing version command (`dotnet` without an SDK) reports no version. Some(if ok { parse_version(&out).unwrap_or_default() } else { String::new() }) @@ -118,14 +151,23 @@ fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requiremen Requirement { program, min, found: found.filter(|v| !v.is_empty()), satisfied, hint: r.hint.clone() } } +fn needs(def: &Def, values: &Values, program: &str) -> bool { + def.requires.iter().any(|r| matches(&r.when, values) && render(&r.program, values) == program) +} + +/// Whether generator `id` runs `program` for `values`. +pub fn needs_program(id: &str, values: &Values, program: &str) -> bool { + def(id).is_some_and(|def| needs(def, &with_defaults(def, "app", values), program)) +} + /// The programs `id` needs for `values`, and whether this machine has them. -pub fn requirements(id: &str, values: &Values) -> IdeResult> { +pub fn requirements(id: &str, values: &Values, goroot: Option<&Path>) -> IdeResult> { let def = def(id).ok_or_else(|| unknown(id))?; let values = with_defaults(def, "app", values); - let search = search_path(); + let tools = Toolchain::new(def, &values, goroot); let mut out: Vec = Vec::new(); for r in def.requires.iter().filter(|r| matches(&r.when, &values)) { - let req = requirement(r, &values, &search); + let req = requirement(r, &values, &tools); if !out.iter().any(|o| o.program == req.program) { out.push(req); } @@ -243,13 +285,13 @@ fn run_step( step: &StepDef, values: &Values, project: &Path, - search: &OsString, + tools: &Toolchain, cancel: &CancellationToken, emit: Emit, ) -> IdeResult<()> { let argv = argv(step, values); emit(ScaffoldEvent::Step { text: step.label.clone() }); - let Some(program) = ide_core::process::find_executable(&argv[0], search) else { + let Some(program) = ide_core::process::find_executable(&argv[0], &tools.search) else { if step.optional { emit(ScaffoldEvent::Line { text: format!("`{}` is not installed; skipped", argv[0]) }); return Ok(()); @@ -260,8 +302,8 @@ fn run_step( Cwd::Project => project.to_path_buf(), Cwd::Parent => project.parent().unwrap_or(project).to_path_buf(), }; - let mut cmd = Command::new(program); - cmd.args(&argv[1..]).current_dir(cwd).env("PATH", search); + let mut cmd = tools.command(&program); + cmd.args(&argv[1..]).current_dir(cwd); // Official CLIs take their defaults instead of asking when they see a CI run. cmd.env("CI", "1").env("NO_COLOR", "1").env("FORCE_COLOR", "0").env("npm_config_yes", "true"); for (key, value) in &step.env { @@ -396,14 +438,20 @@ fn download_service( } /// Creates the project `req` describes and returns its directory. -pub fn create(req: &CreateRequest, cancel: &CancellationToken, emit: Emit) -> IdeResult { +pub fn create( + req: &CreateRequest, + goroot: Option<&Path>, + cancel: &CancellationToken, + emit: Emit, +) -> IdeResult { let def = def(&req.generator).ok_or_else(|| unknown(&req.generator))?; - create_with(def, req, cancel, emit) + create_with(def, req, goroot, cancel, emit) } pub(crate) fn create_with( def: &Def, req: &CreateRequest, + goroot: Option<&Path>, cancel: &CancellationToken, emit: Emit, ) -> IdeResult { @@ -431,12 +479,12 @@ pub(crate) fn create_with( return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display()))); } - let search = search_path(); + let tools = Toolchain::new(def, &values, goroot); let mut missing = def .requires .iter() .filter(|r| matches(&r.when, &values)) - .map(|r| requirement(r, &values, &search)) + .map(|r| requirement(r, &values, &tools)) .filter(|r| !r.satisfied); if let Some(r) = missing.next() { let need = r.min.as_ref().map(|m| format!(" {m} or later")).unwrap_or_default(); @@ -460,7 +508,7 @@ pub(crate) fn create_with( if step.cwd == Cwd::Project { std::fs::create_dir_all(&project)?; } - run_step(step, &values, &project, &search, cancel, emit)?; + run_step(step, &values, &project, &tools, cancel, emit)?; } if !project.is_dir() { return Err(IdeError::internal(format!("the generator did not create {}", project.display()))); @@ -474,7 +522,7 @@ pub(crate) fn create_with( if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - run_step(step, &values, &project, &search, cancel, emit)?; + run_step(step, &values, &project, &tools, cancel, emit)?; } let git_dir = project.join(".git"); if !(req.git && def.git) && git_dir.is_dir() { diff --git a/crates/ide-scaffold/src/engine/tests.rs b/crates/ide-scaffold/src/engine/tests.rs index 5d6a6b161f..3a1550a6d6 100644 --- a/crates/ide-scaffold/src/engine/tests.rs +++ b/crates/ide-scaffold/src/engine/tests.rs @@ -43,7 +43,7 @@ fn create_template(generator: &str, name: &str, values: &[(&str, &str)]) -> (tem def.after.clear(); def.requires.clear(); let req = request(generator, tmp.path(), name, values); - let path = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap(); + let path = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap(); (tmp, path) } @@ -92,7 +92,8 @@ fn php_namespace_is_escaped_in_json() { def.requires.clear(); def.after.clear(); let tmp = tempfile::tempdir().unwrap(); - let dir = create_with(&def, &request("php", tmp.path(), "shop", &[]), &CancellationToken::new(), &|_| {}).unwrap(); + let dir = + create_with(&def, &request("php", tmp.path(), "shop", &[]), None, &CancellationToken::new(), &|_| {}).unwrap(); let composer: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).unwrap()).unwrap(); assert_eq!(composer.pointer("/autoload/psr-4/Acme\\Shop\\").unwrap(), "src/"); @@ -244,13 +245,13 @@ fn dotnet_templates_see_the_selected_sdk_before_running() { step.program = def.requires[0].program.clone(); } let req = request("dotnet", tmp.path(), "Shop", &[("sdk", "10.0.400")]); - let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap(); + let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap(); let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap(); assert_eq!(pin["sdk"]["version"], "10.0.400"); assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited); // A solution named apart from the project names the folder. let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]); - let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap(); + let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap(); assert_eq!(project, tmp.path().join("Store")); assert!(project.join("global.json").is_file()); } @@ -264,7 +265,7 @@ fn a_failing_version_command_does_not_meet_a_minimum() { let tool = bin.path().join("fake-dotnet"); std::fs::write(&tool, "#!/bin/sh\necho 'No .NET SDKs were found. Install 8.0 from the site.'\nexit 145\n").unwrap(); std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); - let search = bin.path().as_os_str().to_owned(); + let search = Toolchain { search: bin.path().as_os_str().to_owned(), goroot: None }; let def = |min: &str| -> RequireDef { toml::from_str(&format!("program = \"fake-dotnet\"\n{min}")).unwrap() }; let req = requirement(&def(r#"min = "8.0""#), &Values::new(), &search); assert!(!req.satisfied); @@ -299,7 +300,8 @@ label = "Fail" program = "definitely-not-a-program-openidea" "#, ); - let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).unwrap_err(); + let err = + create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).unwrap_err(); assert!(err.message.contains("not installed"), "{}", err.message); assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); } @@ -316,7 +318,7 @@ optional = true "#, ); let lines = Mutex::new(Vec::new()); - let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|e| { + let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|e| { lines.lock().unwrap().push(format!("{e:?}")) }) .unwrap(); @@ -330,7 +332,7 @@ fn cancelling_leaves_nothing_behind() { let cancel = CancellationToken::new(); cancel.cancel(); let def = failing_def(""); - let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &cancel, &|_| {}).unwrap_err(); + let err = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &cancel, &|_| {}).unwrap_err(); assert_eq!(err.kind, ErrorKind::Cancelled); assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); } @@ -341,14 +343,14 @@ fn refuses_a_non_empty_target_and_bad_names() { std::fs::create_dir(tmp.path().join("p")).unwrap(); std::fs::write(tmp.path().join("p/x"), "").unwrap(); let def = failing_def(""); - assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).is_err()); + assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).is_err()); assert!(std::fs::read_dir(tmp.path().join("p")).unwrap().count() == 1); for bad in ["", " ", "a/b", "..", ".hidden"] { assert!(name_error(bad).is_some(), "{bad:?}"); } // An existing empty folder is used. std::fs::create_dir(tmp.path().join("q")).unwrap(); - let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), &CancellationToken::new(), &|_| {}).unwrap(); + let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), None, &CancellationToken::new(), &|_| {}).unwrap(); assert_eq!(tree(&dir), ["a.txt"]); } @@ -637,3 +639,74 @@ fn xcode_builds_and_tests_apple_projects() { } } } + +/// A GOROOT holding a fake `go` that fails, like a real one, under another installation's GOROOT. +#[cfg(unix)] +fn fake_goroot(dir: &Path) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let goroot = dir.join("go-sdk"); + std::fs::create_dir_all(goroot.join("bin")).unwrap(); + let go = goroot.join("bin/go"); + std::fs::write( + &go, + format!( + "#!/bin/sh\n[ \"$GOROOT\" = '{}' ] || exit 2\n\ + if [ \"$1\" = version ]; then echo 1.99.0; exit 0; fi\n\ + printf 'module %s\\n' \"$3\" > go.mod\n", + goroot.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&go, std::fs::Permissions::from_mode(0o755)).unwrap(); + goroot +} + +/// Go installed outside the login shell's `PATH`, chosen as GOROOT in Settings. +#[cfg(unix)] +#[test] +fn the_go_chosen_in_settings_is_found_and_runs_the_steps() { + let tmp = tempfile::tempdir().unwrap(); + let goroot = fake_goroot(tmp.path()); + let reqs = requirements("go", &Values::new(), Some(&goroot)).unwrap(); + assert_eq!(reqs[0].found.as_deref(), Some("1.99.0")); + // A Go on `PATH` would write a `go` line too. + let req = request("go", tmp.path(), "hello", &[]); + let project = create(&req, Some(&goroot), &CancellationToken::new(), &|_| {}).unwrap(); + assert_eq!(std::fs::read_to_string(project.join("go.mod")).unwrap(), "module example.com/hello\n"); +} + +#[cfg(unix)] +#[test] +fn the_go_chosen_in_settings_stays_out_of_other_generators() { + let tmp = tempfile::tempdir().unwrap(); + let goroot = fake_goroot(tmp.path()); + let node = source_def("node"); + let tools = Toolchain::new(&node, &with_defaults(&node, "app", &Values::new()), Some(&goroot)); + assert_eq!(tools.search, search_path()); + assert_eq!(tools.goroot, None); +} + +/// A GOROOT whose `go` was removed, or lost its execute bit, leaves the `go` on `PATH` to run +/// on its own. +#[cfg(unix)] +#[test] +fn an_unusable_go_chosen_in_settings_is_ignored() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let go = source_def("go"); + let values = with_defaults(&go, "app", &Values::new()); + let tools = Toolchain::new(&go, &values, Some(&tmp.path().join("go1.25"))); + assert_eq!((tools.search, tools.goroot), (search_path(), None)); + let goroot = fake_goroot(tmp.path()); + std::fs::set_permissions(goroot.join("bin/go"), std::fs::Permissions::from_mode(0o644)).unwrap(); + let tools = Toolchain::new(&go, &values, Some(&goroot)); + assert_eq!((tools.search, tools.goroot), (search_path(), None)); +} + +/// New Project asks for a discovered Go only for the generators that run `go`. +#[test] +fn only_go_generators_need_go() { + assert!(needs_program("go", &Values::new(), "go")); + assert!(!needs_program("node", &Values::new(), "go")); + assert!(!needs_program("no-such-generator", &Values::new(), "go")); +} diff --git a/crates/ide-scaffold/src/lib.rs b/crates/ide-scaffold/src/lib.rs index 3884a9e34b..1764542e37 100644 --- a/crates/ide-scaffold/src/lib.rs +++ b/crates/ide-scaffold/src/lib.rs @@ -10,7 +10,7 @@ mod providers; mod template; pub use catalog::catalog; -pub use engine::{Emit, create, free_name, name_error, options, requirements, target_taken}; +pub use engine::{Emit, create, free_name, name_error, needs_program, options, requirements, target_taken}; pub use model::{ ChoiceOption, CreateRequest, Dependency, DependencyGroup, Field, FieldKind, GeneratorInfo, Requirement, ScaffoldEvent, Values, diff --git a/crates/ide-scaffold/tests/scaffold_smoke.rs b/crates/ide-scaffold/tests/scaffold_smoke.rs index 42dc64e089..9ee3b312af 100644 --- a/crates/ide-scaffold/tests/scaffold_smoke.rs +++ b/crates/ide-scaffold/tests/scaffold_smoke.rs @@ -17,7 +17,7 @@ fn smoke(generator: &str, values: &[(&str, &str)], build: &[&str]) { git: true, values: values.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), }; - let dir = create(&req, &CancellationToken::new(), &|e| match e { + let dir = create(&req, None, &CancellationToken::new(), &|e| match e { ScaffoldEvent::Step { text } => eprintln!("== {text}"), ScaffoldEvent::Line { text } => eprintln!(" {text}"), }) diff --git a/crates/ide-ssh/Cargo.toml b/crates/ide-ssh/Cargo.toml index 125c71fcdc..5f6b0ed911 100644 --- a/crates/ide-ssh/Cargo.toml +++ b/crates/ide-ssh/Cargo.toml @@ -32,5 +32,5 @@ tokio-rustls = { version = "0.26", default-features = false } testing = ["keyring-core/sample"] [dev-dependencies] -tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } +tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net", "io-util"] } keyring-core = { workspace = true, features = ["sample"] } diff --git a/crates/ide-ssh/src/ftp.rs b/crates/ide-ssh/src/ftp.rs index 6b30f32efc..a0b21c1043 100644 --- a/crates/ide-ssh/src/ftp.rs +++ b/crates/ide-ssh/src/ftp.rs @@ -84,6 +84,19 @@ fn mfmt_time(seconds: u32) -> String { format!("{year:04}{month:02}{day:02}{:02}{:02}{:02}", rem / 3600, rem / 60 % 60, rem % 60) } +/// A folder known only to exist: no size, time or permissions. +fn folder(name: &str, path: &str) -> RemoteEntry { + RemoteEntry { + name: name.to_owned(), + path: path.to_owned(), + is_dir: true, + is_symlink: false, + size: 0, + mtime: None, + permissions: String::new(), + } +} + /// One logged-in FTP control connection; operations take turns on it. pub struct FtpFs { ftp: tokio::sync::Mutex, @@ -172,19 +185,18 @@ impl FtpFs { pub async fn stat(&self, path: &str) -> IdeResult> { let path = path.trim_end_matches('/'); let Some(dir) = parent(path) else { - return Ok(self.is_dir("/").await.then(|| RemoteEntry { - name: "/".into(), - path: "/".into(), - is_dir: true, - is_symlink: false, - size: 0, - mtime: None, - permissions: String::new(), - })); + return Ok(self.is_dir("/").await.then(|| folder("/", "/"))); }; let name = &path[dir.len()..].trim_start_matches('/'); + // The login folder's parent is often off limits, and a refused listing can leave the + // server unable to open the next data connection (bunny.net over FTPS). + if path == self.home.trim_end_matches('/') { + return Ok(self.is_dir(path).await.then(|| folder(name, path))); + } match self.list(dir).await { Ok(entries) => Ok(entries.into_iter().find(|e| e.name == *name)), + // Servers that lock the user into a folder may refuse to list its parent. + Err(_) if self.is_dir(path).await => Ok(Some(folder(name, path))), Err(e) if e.kind == ErrorKind::NotFound => Ok(None), Err(e) => Err(e), } @@ -192,9 +204,12 @@ impl FtpFs { /// Entries of `dir`, folders first, then by name; symlinks to folders count as folders. pub async fn list(&self, dir: &str) -> IdeResult> { + // Some servers (bunny.net Storage) list a folder only when its path ends with `/`. + let target = if dir.ends_with('/') { dir.to_owned() } else { format!("{dir}/") }; let lines = { let mut ftp = self.ftp.lock().await; - if self.mlsd { ftp.mlsd(Some(dir)).await } else { ftp.list(Some(dir)).await }.map_err(|e| err(dir, e))? + if self.mlsd { ftp.mlsd(Some(&target)).await } else { ftp.list(Some(&target)).await } + .map_err(|e| err(dir, e))? }; let mut out = Vec::new(); for line in lines { @@ -393,4 +408,99 @@ mod tests { assert_eq!(mfmt_time(951_782_400), "20000229000000"); assert_eq!(mfmt_time(1_794_484_245), "20261112115045"); } + + /// A server that locks the user into `/zone/` but shows its real path (bunny.net Storage): + /// it refuses `LIST /` and folder paths without a trailing `/`, and answers `LIST /locked/` with `550`. + async fn locked_in_server() -> (u16, Arc>>) { + use tokio::io::{AsyncBufReadExt, BufReader}; + use tokio::net::TcpListener; + + let control = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = control.local_addr().unwrap().port(); + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + tokio::spawn(async move { + let (stream, _) = control.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut lines = BufReader::new(read).lines(); + let mut data: Option = None; + write.write_all(b"220 Service Ready.\r\n").await.unwrap(); + while let Ok(Some(line)) = lines.next_line().await { + log.lock().unwrap().push(line.clone()); + let (cmd, arg) = line.split_once(' ').unwrap_or((line.as_str(), "")); + let reply: String = match (cmd.to_ascii_uppercase().as_str(), arg) { + ("USER", _) => "331 Password required\r\n".into(), + ("PASS", _) => "230 User logged in\r\n".into(), + ("TYPE", _) => "200 Type set\r\n".into(), + ("PWD", _) => "257 \"/zone/\" is current directory.\r\n".into(), + ("FEAT", _) => "211-Extensions supported:\r\n UTF8\r\n211 End\r\n".into(), + ("CWD", "/zone" | "/zone/" | "/zone/data" | "/shared" | "/locked/home") => "250 OK\r\n".into(), + ("CWD", _) => "550 No such folder\r\n".into(), + ("PASV", _) => { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let p = listener.local_addr().unwrap().port(); + data = Some(listener); + format!("227 Entering Passive Mode (127,0,0,1,{},{})\r\n", p >> 8, p & 0xff) + } + ("LIST", target) => { + let (mut conn, _) = data.take().unwrap().accept().await.unwrap(); + match target { + "/zone/" => { + write.write_all(b"150 Opening Ascii mode data transfer for LIST\r\n").await.unwrap(); + conn.write_all(b"drwxr-xr-x 1 zone zone 0 Jan 01 00:00 data\r\n").await.unwrap(); + drop(conn); + "226 Transfer complete\r\n".into() + } + "/locked/" => "550 Permission denied\r\n".into(), + _ => "450 Requested file action not taken\r\n".into(), + } + } + ("QUIT", _) => { + write.write_all(b"221 Bye\r\n").await.unwrap(); + break; + } + _ => "502 Command not implemented\r\n".into(), + }; + write.write_all(reply.as_bytes()).await.unwrap(); + } + }); + (port, seen) + } + + #[tokio::test] + async fn stat_falls_back_to_cwd_when_the_parent_cannot_be_listed() { + let (port, seen) = locked_in_server().await; + let connection = + FtpConnection { host: "127.0.0.1".into(), port: Some(port), user: "zone".into(), passive: true }; + let fs = FtpFs::connect(&connection, false, Some("pw".into())).await.unwrap(); + + // The login folder: `CWD` only, its parent is never listed. + let home = fs.stat("/zone/").await.unwrap().expect("the login folder"); + assert!(home.is_dir); + assert_eq!((home.name.as_str(), home.path.as_str()), ("zone", "/zone")); + assert_eq!((home.size, home.mtime, home.permissions.as_str()), (0, None, "")); + assert!(!seen.lock().unwrap().iter().any(|c| c == "LIST /")); + + // Another folder whose parent is refused. + let shared = fs.stat("/shared").await.unwrap().expect("a folder found with CWD"); + assert!(shared.is_dir); + assert_eq!((shared.name.as_str(), shared.path.as_str()), ("shared", "/shared")); + + // The parent listing works: no `CWD` fallback. + let data = fs.stat("/zone/data").await.unwrap().expect("a listed folder"); + assert!(data.is_dir); + assert!(!seen.lock().unwrap().iter().any(|c| c == "CWD /zone/data")); + + // Both fail: the listing error, not the `CWD` one. + let missing = fs.stat("/missing").await.unwrap_err(); + assert_eq!(missing.message, "/: 450 Requested file action not taken"); + + // A parent answered with `550`: the fallback runs, and without it the path doesn't exist. + assert!(fs.stat("/locked/home").await.unwrap().is_some_and(|e| e.is_dir)); + assert!(fs.stat("/locked/none").await.unwrap().is_none()); + + let names: Vec<_> = fs.list("/zone").await.unwrap().into_iter().map(|e| e.name).collect(); + assert_eq!(names, ["data"]); + fs.close().await; + } } diff --git a/crates/ide-svn/src/cli.rs b/crates/ide-svn/src/cli.rs index 9c58590464..15107e2090 100644 --- a/crates/ide-svn/src/cli.rs +++ b/crates/ide-svn/src/cli.rs @@ -190,6 +190,22 @@ thread_local! { /// The last svn this thread stopped had to be killed: it could not release a working-copy /// lock it held. Read (and cleared) by [`take_killed`]. static KILLED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Set by [`quietly`]: svn asks nothing, and a missing login fails the command. + static QUIET: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with this thread's svn commands non-interactive and without the login dialog: a +/// read the IDE starts by itself (Incoming on opening) reports a missing login as an error +/// instead of asking for it. +pub fn quietly(f: impl FnOnce() -> T) -> T { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + QUIET.with(|q| q.set(self.0)); + } + } + let _restore = Restore(QUIET.with(|q| q.replace(true))); + f() } /// Whether the last svn command this thread stopped (cancelled, timed out) was killed before @@ -398,7 +414,7 @@ impl Svn { result => return result, }; let handler = self.ctx.prompts.read().clone(); - let signing_in = CREDENTIALS.with(|c| c.borrow().is_some()); + let signing_in = CREDENTIALS.with(|c| c.borrow().is_some()) || QUIET.with(|q| q.get()); let (Some(handler), false, false) = (handler, interactive(&self.ctx.settings()), signing_in) else { return Err(error); }; @@ -444,7 +460,8 @@ impl Svn { // svn reads the line up to APR's line end, CRLF on Windows (an LF would stay in it). stdin = Some(format!("{password}{}", if cfg!(windows) { "\r\n" } else { "\n" })); } - let prompts = self.ctx.prompts.read().clone().filter(|_| interactive(&settings) && stdin.is_none()); + let quiet = QUIET.with(|q| q.get()); + let prompts = self.ctx.prompts.read().clone().filter(|_| interactive(&settings) && stdin.is_none() && !quiet); argv.push(if prompts.is_some() { "--force-interactive" } else { "--non-interactive" }.into()); let split = args.len().min(1); let argv: Vec = diff --git a/crates/ide-svn/src/lib.rs b/crates/ide-svn/src/lib.rs index cb4a1d1996..dd2ad5142b 100644 --- a/crates/ide-svn/src/lib.rs +++ b/crates/ide-svn/src/lib.rs @@ -14,7 +14,7 @@ mod xml; pub use cli::{ BranchConfig, MIN_VERSION, Prompt, PromptHandler, Settings, SvnContext, detect as detected_executable, - is_login_required, with_credentials, + is_login_required, quietly, with_credentials, }; pub use ops::{ BranchCompareEntry, BranchEntry, BranchLayout, CleanupOptions, Depth, EligibleRevision, EligibleRevisionsPage, diff --git a/crates/ide-svn/src/ops.rs b/crates/ide-svn/src/ops.rs index 214f0a9ec8..0cb656974d 100644 --- a/crates/ide-svn/src/ops.rs +++ b/crates/ide-svn/src/ops.rs @@ -187,32 +187,120 @@ impl Depth { } } -/// The items an `svn update` changed: its lines of four status columns (contents, -/// properties, lock, tree conflict) and a path, as `U a.txt`, ` U dir`, ` C b.txt`. -/// A broken lock alone (` B a.txt`) changes nothing in the working copy. +/// The most revisions Incoming, or Update Info grouped by changelist, reads at once: the newest. +pub const REVISIONS_LIMIT: u64 = 500; + +/// The lines of `svn update`'s output an [`UpdateResult`] keeps; all of them are streamed. +const UPDATE_OUTPUT_LINES: usize = 1000; + +/// One `svn update`'s output, split: the files and folders of the working copy itself and, per +/// external svn fetched in the same run, the external's own (IntelliJ's `UpdateEventHandler` binds +/// those to the external's revision). +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct UpdateOutput { + pub items: Vec, + pub externals: Vec<(PathBuf, Vec, Option)>, +} + +/// `Fetching external item into '/wc/ext':` starts an external's block. +fn external_start(line: &str) -> Option<&str> { + line.strip_prefix("Fetching external item into '")?.strip_suffix("':") +} + +/// The line that ends an external's block, with the revision it reached: `External at revision 12.`, +/// `Updated external to revision 3.`, `Checked out external at revision 3.`, `External export complete.` +fn external_end(line: &str) -> Option> { + let line = line.trim(); + let rev = |n: &str| n.strip_suffix('.').and_then(|n| n.parse().ok()); + if let Some(n) = line + .strip_prefix("External at revision ") + .or_else(|| line.strip_prefix("Updated external to revision ")) + .or_else(|| line.strip_prefix("Checked out external at revision ")) + { + return Some(rev(n)); + } + line.starts_with("External export complete").then_some(None) +} + +/// The path in `Restored 'a b.txt'`, `Skipped 'it's.txt' -- Node remains in conflict`, `Skipped +/// missing target: 'x'`: from the first quote to the last one, a quote inside the name kept. +fn quoted_path(rest: &str) -> Option<&str> { + let start = rest.find('\'')? + 1; + let rest = &rest[start..]; + match rest.rfind("' -- ") { + Some(end) => Some(&rest[..end]), + None => rest.strip_suffix('\''), + } +} + /// The files and folders `svn update` printed, with their action (see [`ide_vcs::UpdatedItem`]): -/// its status lines, `Restored 'x'` and `Skipped 'x'`. A relative path is under `root`. -pub(crate) fn update_items(output: &str, root: &Path) -> Vec { +/// its lines of four status columns (contents, properties, lock, tree conflict) and a path, as +/// `U a.txt`, ` U dir`, ` C b.txt`, and `Restored 'x'`, `Skipped 'x'`. A relative path is +/// under `root`; a path is kept as svn printed it (a name may start or end with a space). +pub(crate) fn parse_update(output: &str, root: &Path) -> UpdateOutput { let path_of = |p: &str| { - let p = PathBuf::from(p.trim()); + let p = PathBuf::from(p); if p.is_absolute() { p } else { root.join(p) } }; - let quoted = |rest: &str| rest.split('\'').nth(1).map(str::to_owned); - output - .lines() - .filter_map(|line| { - if let Some(path) = line.strip_prefix("Restored ").and_then(quoted) { - return Some(ide_vcs::UpdatedItem { path: path_of(&path), action: "restored".into() }); + let item = |line: &str| -> Option { + let item = |path: &str, action: &str| ide_vcs::UpdatedItem { + path: path_of(path), + action: action.to_owned(), + ..Default::default() + }; + if let Some(rest) = line.strip_prefix("Restored ") { + return quoted_path(rest).map(|p| item(p, "restored")); + } + if line.starts_with("Skipped") { + return quoted_path(line).map(|p| item(p, "skipped")); + } + (updated_items(line) == 1 && !line[5..].trim().is_empty()).then(|| item(&line[5..], &line[..4])) + }; + let mut out = UpdateOutput::default(); + let mut external: Option<(PathBuf, Vec)> = None; + for line in output.lines() { + if let Some(path) = external_start(line) { + if let Some((root, items)) = external.take() { + out.externals.push((root, items, None)); } - if line.starts_with("Skipped") { - return quoted(line).map(|p| ide_vcs::UpdatedItem { path: path_of(&p), action: "skipped".into() }); + external = Some((path_of(path), Vec::new())); + } else if let Some(reached) = external_end(line) { + if let Some((root, items)) = external.take() { + out.externals.push((root, items, reached)); } - if updated_items(line) == 1 { - return Some(ide_vcs::UpdatedItem { path: path_of(&line[5..]), action: line[..4].to_owned() }); + } else if let Some(found) = item(line) { + match &mut external { + Some((_, items)) => items.push(found), + None => out.items.push(found), } - None - }) - .collect() + } + } + if let Some((root, items)) = external { + out.externals.push((root, items, None)); + } + out +} + +/// How many files and folders Update Info shows for `items`: each path once (a replaced file is +/// deleted and added), `E` (a file svn found already there, which IntelliJ leaves out) not at all. +fn shown_items(items: &[ide_vcs::UpdatedItem]) -> usize { + items.iter().filter(|i| !i.action.starts_with('E')).map(|i| &i.path).collect::>().len() +} + +/// Gives each item under `root` its path in the repository (`/trunk/src/a.txt`), `root` being at +/// `root_path` (`/trunk`): its diffs read the repository, which still has a deleted file. +fn with_repo_paths(items: &mut [ide_vcs::UpdatedItem], root: &Path, root_path: &str) { + for item in items { + item.repo_path = item.path.strip_prefix(root).ok().map(|rel| { + let rel: Vec = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); + let base = root_path.trim_end_matches('/'); + if rel.is_empty() { + if base.is_empty() { "/".to_owned() } else { base.to_owned() } + } else { + format!("{base}/{}", rel.join("/")) + } + }); + } } pub(crate) fn updated_items(output: &str) -> usize { @@ -292,19 +380,31 @@ fn parse_update_output(lines: Vec) -> UpdateResult { res } -/// The revision `svn update` / `switch` / `checkout` reports reaching: `At -/// revision 7.`, `Updated to revision 7.`, `Checked out revision 7.`, and per -/// target `Updated 'a' to r7.` +/// The revision `svn update` / `switch` / `checkout` reports reaching: `At revision 7.`, `Updated +/// to revision 7.`, `Checked out revision 7.`, and per target `Updated 'a' to r7.` An external's +/// block (`Fetching external item into …` to `External at revision 12.`) is its own repository's +/// revision, and a file name that holds "revision 9" is not a summary. pub(crate) fn reached_revision(output: &str) -> Option { + let mut in_external = false; output .lines() - // An external reports its own repository's revision. - .filter(|line| !line.contains("external")) .filter_map(|line| { - let line = line.trim().trim_end_matches('.'); - line.rsplit_once(" revision ") - .map(|(_, n)| n) - .or_else(|| line.rsplit_once(" to r").map(|(_, n)| n)) + if external_start(line).is_some() { + in_external = true; + return None; + } + if external_end(line).is_some() { + in_external = false; + return None; + } + if in_external { + return None; + } + let line = line.trim().strip_suffix('.')?; + line.strip_prefix("At revision ") + .or_else(|| line.strip_prefix("Updated to revision ")) + .or_else(|| line.strip_prefix("Checked out revision ")) + .or_else(|| line.strip_prefix("Updated '").and_then(|r| r.rsplit_once("' to r")).map(|(_, n)| n)) .and_then(|n| n.parse().ok()) }) .max() @@ -413,17 +513,49 @@ impl WorkingCopy { on_line: &dyn Fn(String), ) -> IdeResult<(u64, ide_vcs::UpdateSummary)> { let from = self.current_repository().revision; - let mut argv = args(["update", "--accept", "postpone", "-r", revision.unwrap_or("HEAD")]); - argv.extend(targets(&self.paths_or_root(paths)?)); + let targets_of = self.paths_or_root(paths)?; + // Update File / Update Directory: each target's own BASE (`svn info`, no server), which in + // a mixed-revision working copy is not the root's. Update Info's "Before update" side. + let bases: Vec<(PathBuf, u64)> = if paths.is_empty() { + Vec::new() + } else { + let out = self.run(&[args(["info", "--xml", "--"]), targets(&targets_of)].concat())?; + xml::info(&out)?.into_iter().filter_map(|i| Some((self.abs(&i.path), i.revision?))).collect() + }; + let mut argv = args(["update", "--accept", "postpone", "-r", revision.unwrap_or("HEAD"), "--"]); + argv.extend(targets(&targets_of)); let out = String::from_utf8_lossy(&self.remote_streaming(&argv, Some(cancel), on_line)?).into_owned(); let _ = self.refresh(); let reached = reached_revision(&out) .ok_or_else(|| IdeError::internal(format!("unexpected `svn update` output: {out}")))?; + let parsed = parse_update(&out, self.root()); + let externals: Vec = parsed + .externals + .into_iter() + .filter(|(_, items, _)| !items.is_empty()) + .map(|(root, mut items, reached)| { + // The external's own repository location, read from its working copy (no server). + let info = self.run(&[args(["info", "--xml", "--"]), vec![target(&root)]].concat()).ok(); + let repo = info.and_then(|out| xml::info(&out).ok()?.first().map(crate::workspace::repository)); + if let Some(repo) = repo { + with_repo_paths(&mut items, &root, &repo.path); + } + ide_vcs::ExternalUpdate { root, items, to_revision: reached.map(|r| r.to_string()) } + }) + .collect(); + let mut items = parsed.items; + with_repo_paths(&mut items, self.root(), &self.repository().path); + for item in &mut items { + // The innermost target holding it. + let base = bases.iter().filter(|(t, _)| item.path.starts_with(t)).max_by_key(|(t, _)| t.as_os_str().len()); + item.from_revision = base.map(|(_, r)| *r).filter(|r| Some(*r) != from).map(|r| r.to_string()); + } let summary = ide_vcs::UpdateSummary { - changed: updated_items(&out), - items: update_items(&out, self.root()), + changed: shown_items(&items) + externals.iter().map(|e| shown_items(&e.items)).sum::(), + items, from_revision: from.map(|r| r.to_string()), to_revision: Some(reached.to_string()), + externals, }; Ok((reached, summary)) } @@ -449,6 +581,7 @@ impl WorkingCopy { if opts.ignore_externals { argv.push("--ignore-externals".into()); } + argv.push("--".into()); argv.extend(targets(&self.paths_or_root(paths)?)); let collected = parking_lot::Mutex::new(Vec::new()); let tee = |line: String| { @@ -457,7 +590,10 @@ impl WorkingCopy { }; self.remote_streaming(&argv, Some(cancel), &tee)?; let _ = self.refresh(); - Ok(parse_update_output(collected.into_inner())) + let mut result = parse_update_output(collected.into_inner()); + // Each line already went to `on_line` (the console); the result keeps the first ones only. + result.output.truncate(UPDATE_OUTPUT_LINES); + Ok(result) } /// `svn cleanup`: finishes or rolls back an interrupted operation and releases its lock. @@ -1380,26 +1516,89 @@ impl WorkingCopy { }) } - /// Reads structured working copy metadata (`svn info --xml`) for Working Copies Info view. - /// The revisions committed to the working copy's URL after its BASE revision, newest first, - /// with their files (`svn log -v` from BASE+1 to HEAD): IntelliJ's Incoming changes. + /// The revisions the server has for this working copy and it does not, newest first, with + /// their files: IntelliJ's Incoming changes. `svn status -u` names the files and folders that + /// are out of date, each at its own BASE (after a commit only the committed files move on, so a + /// working copy has mixed revisions); a revision counts when it changed one of them after its + /// BASE. At most [`REVISIONS_LIMIT`] revisions, the newest. pub fn incoming_revisions(&self, cancel: &CancellationToken) -> IdeResult> { - let repo = self.current_repository(); - let base = match repo.revision { - Some(base) => base, - None => return Ok(Vec::new()), + let argv = [args(["status", "-u", "--xml", "--"]), vec![target(self.root())]].concat(); + let (entries, head) = xml::status_with_against(&self.remote(&argv, Some(cancel))?)?; + let head = head.ok_or_else(|| IdeError::internal("unexpected `svn status -u` output: no HEAD revision"))?; + let root = self.root(); + let root_base = self.current_repository().revision.unwrap_or(0); + let abs = |p: &str| { + let path = PathBuf::from(p); + if path.is_absolute() { path } else { root.join(path) } }; - let head_argv = [args(["info", "--show-item", "revision", "-r", "HEAD", "--"]), vec![url_target(&repo.url)]]; - let head = String::from_utf8_lossy(&self.remote(&head_argv.concat(), Some(cancel))?).trim().parse::(); - let head = head.map_err(|_| IdeError::internal("unexpected `svn info` output for HEAD"))?; - if head <= base { - return Ok(Vec::new()); + // Folders switched to another URL: IntelliJ's mapping lists each as a location of its own + // (`NestedCopyType.switched`), and so does Incoming, from that URL's log. + let mut switched: Vec = + entries.iter().filter(|e| e.switched).map(|e| abs(&e.path)).filter(|p| p != root).collect(); + switched.sort(); + switched.dedup(); + // The location a path belongs to: its innermost switched folder, or the root (`None`). + let owner = |path: &Path| switched.iter().filter(|s| path.starts_with(s)).max_by_key(|s| s.as_os_str().len()); + // (path, its BASE, a remote add / delete / replace that takes what is below it along) + let stale: Vec<(PathBuf, u64, bool)> = entries + .iter() + .filter_map(|e| { + let item = e.repos_item.as_deref().filter(|s| *s != "none" && *s != "normal"); + let props = e.repos_props.as_deref().is_some_and(|s| s != "none" && s != "normal"); + if item.is_none() && !props { + return None; + } + let path = abs(&e.path); + // svn marks a location's folder `modified` whenever anything below it is newer: + // only a property change of its own is the folder's. + if (path == root || switched.contains(&path)) && !props { + return None; + } + let whole = matches!(item, Some("added" | "deleted" | "replaced")); + Some((path, e.revision.unwrap_or(root_base), whole)) + }) + .collect(); + let mut out: Vec = Vec::new(); + for location in std::iter::once(None).chain(switched.iter().map(Some)) { + let mine: Vec<&(PathBuf, u64, bool)> = stale.iter().filter(|(p, ..)| owner(p) == location).collect(); + let Some(from) = mine.iter().map(|(_, base, _)| *base).min() else { continue }; + let found = match location { + None => self.newest_revisions(from + 1, head, REVISIONS_LIMIT, cancel)?, + Some(folder) => { + let out = self.run(&[args(["info", "--xml", "--"]), vec![target(folder)]].concat())?; + let Some(info) = xml::info(&out)?.into_iter().next() else { continue }; + let repo = crate::workspace::repository(&info); + self.log_of(&repo.url, &repo.path, folder, from + 1, head, REVISIONS_LIMIT, cancel)? + } + }; + for mut r in found { + // A path of this location's log that is in another location is that one's. + let counts = r.paths.iter().filter_map(|p| p.local.as_deref()).any(|local| { + owner(local) == location + && mine.iter().any(|(path, base, whole)| { + *base < r.revision && (local == path || (*whole && local.starts_with(path))) + }) + }); + if !counts { + continue; + } + match out.iter_mut().find(|o| o.revision == r.revision) { + // One revision committed to the trunk and a branch: one row, both its files. + Some(same) => { + r.paths.retain(|p| !same.paths.contains(p)); + same.paths.append(&mut r.paths); + } + None => out.push(r), + } + } } - self.revisions_between(base + 1, head, cancel) + out.sort_by_key(|a| std::cmp::Reverse(a.revision)); + Ok(out) } /// The revisions `from` to `to` committed to the working copy's URL, newest first, with their - /// files (`svn log -v`): Incoming, and Update Info grouped by changelist. + /// files (`svn log -v`): Incoming, and Update Info grouped by changelist. At most + /// [`REVISIONS_LIMIT`], the newest. pub fn revisions_between( &self, from: u64, @@ -1409,19 +1608,55 @@ impl WorkingCopy { if from > to { return Ok(Vec::new()); } + self.newest_revisions(from, to, REVISIONS_LIMIT, cancel) + } + + /// [`revisions_between`](Self::revisions_between), at most `limit` of them: the newest. + pub fn newest_revisions( + &self, + from: u64, + to: u64, + limit: u64, + cancel: &CancellationToken, + ) -> IdeResult> { let repo = self.current_repository(); - let range = format!("{from}:{to}"); - let argv = [args(["log", "--xml", "-v", "-r", &range, "--"]), vec![url_target(&repo.url)]].concat(); + self.log_of(&repo.url, &repo.path, self.root(), from, to, limit, cancel) + } + + /// The newest `limit` revisions `from` to `to` of `url` (at `repo_path` in the repository), + /// with their files; a file under `repo_path` is also given as its place under `local_root`. + #[allow(clippy::too_many_arguments)] + fn log_of( + &self, + url: &str, + repo_path: &str, + local_root: &Path, + from: u64, + to: u64, + limit: u64, + cancel: &CancellationToken, + ) -> IdeResult> { + if from > to || limit == 0 { + return Ok(Vec::new()); + } + // Newest first, so the limit keeps the newest. + let range = format!("{to}:{from}"); + let limit = limit.to_string(); + let argv = + [args(["log", "--xml", "-v", "-r", &range, "--limit", &limit, "--"]), vec![url_target(url)]].concat(); let entries = xml::log(&self.remote(&argv, Some(cancel))?)?; - // The working copy root's repository path: `/trunk`, percent-decoded as log paths are. - let prefix = repo.path.trim_end_matches('/').to_owned(); + // The location's repository path: `/trunk`, percent-decoded as log paths are. + let prefix = repo_path.trim_end_matches('/').to_owned(); let local = |path: &str| -> Option { let rest = if prefix.is_empty() { Some(path) } else { path.strip_prefix(&prefix) }?; if !(rest.is_empty() || rest.starts_with('/')) { return None; } - let rel = rest.trim_start_matches('/'); - Some(if rel.is_empty() { self.root().to_path_buf() } else { self.root().join(rel) }) + // Segment by segment: the platform's separators (`C:\wc\src\a.txt` on Windows, as + // `svn update` prints it), and never a `..` out of the working copy. + rest.split('/').filter(|s| !s.is_empty()).try_fold(local_root.to_path_buf(), |dir, segment| { + (segment != "." && segment != "..").then(|| dir.join(segment)) + }) }; let mut out: Vec = entries .into_iter() @@ -1433,7 +1668,13 @@ impl WorkingCopy { paths: e .paths .into_iter() - .map(|p| IncomingPath { local: local(&p.path), action: p.action, path: p.path, kind: p.kind }) + .map(|p| IncomingPath { + local: local(&p.path), + action: p.action, + path: p.path, + kind: p.kind, + copy_from: p.copy_from, + }) .collect(), }) .collect(); @@ -1451,14 +1692,31 @@ impl WorkingCopy { } } - /// Working Copies Information › Format › Change: `svn upgrade` of the working copy to the - /// format `version` (`--compatible-version`). - pub fn upgrade(&self, version: &str, cancel: &CancellationToken) -> IdeResult<()> { - if !version.chars().all(|c| c.is_ascii_digit() || c == '.') || version.is_empty() { - return Err(IdeError::invalid(format!("invalid working copy format: {version}"))); + /// Working Copies Information › Format › Change: `svn upgrade` of the working copy at `path` + /// to the format `version`, one [`supported_formats`](Self::supported_formats) names. Only the + /// checkout's own root: svn upgrades a whole checkout, and a format cannot go back, so a + /// project inside a larger checkout does not upgrade the folders around it. + pub fn upgrade(&self, path: &Path, version: &str, cancel: &CancellationToken) -> IdeResult<()> { + if path != self.root() || self.root() != self.wc_root() { + return Err(IdeError::invalid(format!( + "{} is not the root of its working copy ({}); only a working copy root can change its format", + path.display(), + self.wc_root().display() + ))); } - let argv = [args(["upgrade", "--compatible-version", version, "--"]), vec![target(self.wc_root())]].concat(); - self.remote(&argv, Some(cancel)).map(|_| ()) + if !self.supported_formats().iter().any(|f| f == version) { + return Err(IdeError::invalid(format!("this svn cannot write the working copy format {version}"))); + } + let mut argv = args(["upgrade"]); + // `--compatible-version` came with 1.15; before it, `svn upgrade` writes 1.8's format. + if self.context().version().is_ok_and(|v| v >= (1, 15)) { + argv.extend(args(["--compatible-version", version])); + } + argv.push("--".into()); + argv.push(target(path)); + self.remote(&argv, Some(cancel))?; + let _ = self.refresh(); + Ok(()) } pub fn working_copy_info(&self) -> IdeResult { @@ -1479,19 +1737,17 @@ impl WorkingCopy { } /// Reads metadata for this working copy root plus any switched descendant subtrees within it. - pub fn working_copy_infos(&self) -> IdeResult> { + /// The working copy and its switched folders (Working Copies Information). The switched ones + /// come from the Changes view's last status when the working copy is unchanged since, else + /// from a scan `cancel` stops. + pub fn working_copy_infos(&self, cancel: &CancellationToken) -> IdeResult> { let root_info = self.working_copy_info()?; let shared_format = root_info.format.clone(); let mut out = vec![root_info]; - let raw = self.run(&[args(["status", "--xml", "--"]), vec![target(self.root())]].concat())?; - let mut switched_paths: Vec = xml::status(&raw)? + let mut switched_paths: Vec = self + .switched_paths(cancel)? .into_iter() - .filter(|e| e.switched) - .map(|e| { - let raw_path = PathBuf::from(&e.path); - let abs = if raw_path.is_absolute() { raw_path } else { self.root().join(raw_path) }; - dunce::canonicalize(&abs).unwrap_or(abs) - }) + .map(|p| dunce::canonicalize(&p).unwrap_or(p)) .filter(|p| p != self.root() && p.starts_with(self.root())) .collect(); switched_paths.sort(); @@ -1731,6 +1987,8 @@ pub struct IncomingPath { pub local: Option, /// `file`, `dir`, or empty from old servers. pub kind: String, + /// The path and revision it was copied from (`svn copy`, or the new half of a move). + pub copy_from: Option<(String, u64)>, } /// Working copy metadata returned by [`WorkingCopy::working_copy_info`]. @@ -2207,6 +2465,77 @@ fn read_wc_format(wc_root: &Path) -> Option { mod tests { use super::*; + fn actions(items: &[ide_vcs::UpdatedItem]) -> Vec<(String, String)> { + items.iter().map(|i| (i.path.display().to_string(), i.action.clone())).collect() + } + + /// Review of #8212, H8: svn 1.15's output with an external at a newer revision than the + /// working copy, and a file name holding a quote. + #[test] + fn an_external_at_a_newer_revision_is_not_the_working_copys() { + let out = "Updating '/w/wc':\nSkipped '/w/wc/don't.txt' -- Node remains in conflict\n\nFetching external item into '/w/wc/ext':\nExternal at revision 12.\n\nAt revision 4.\nSummary of conflicts:\n Skipped paths: 1\n"; + assert_eq!(reached_revision(out), Some(4)); + let parsed = parse_update(out, Path::new("/w/wc")); + assert_eq!(actions(&parsed.items), [("/w/wc/don't.txt".to_owned(), "skipped".to_owned())]); + assert_eq!(parsed.externals, [(PathBuf::from("/w/wc/ext"), Vec::new(), Some(12))]); + } + + /// H8: an external's files are its own, at its own revision, not the working copy's. + #[test] + fn an_externals_files_are_kept_apart() { + let out = "Updating '/w/wc':\nU /w/wc/a.txt\n\nFetching external item into '/w/wc/ext':\nU /w/wc/ext/ext_file.txt\nUpdated external to revision 3.\n\nUpdated to revision 5.\n"; + assert_eq!(reached_revision(out), Some(5)); + let parsed = parse_update(out, Path::new("/w/wc")); + assert_eq!(actions(&parsed.items), [("/w/wc/a.txt".to_owned(), "U ".to_owned())]); + let (root, items, reached) = &parsed.externals[0]; + assert_eq!( + (root.as_path(), actions(items), *reached), + (Path::new("/w/wc/ext"), vec![("/w/wc/ext/ext_file.txt".to_owned(), "U ".to_owned())], Some(3)) + ); + } + + /// H8, M4: quotes and spaces of a name are kept; a name holding "revision 9" is no summary. + #[test] + fn names_with_quotes_spaces_and_revision_words() { + let out = "Restored '/w/o'connor/it's.txt'\nSkipped missing target: '/w/a b'\nU /w/ lead.txt\nU /w/trail.txt \nU /w/see revision 999\nE /w/existed.txt\nU \nAt revision 4.\n"; + assert_eq!(reached_revision(out), Some(4)); + assert_eq!( + actions(&parse_update(out, Path::new("/w")).items), + [ + ("/w/o'connor/it's.txt", "restored"), + ("/w/a b", "skipped"), + ("/w/ lead.txt", "U "), + ("/w/trail.txt ", "U "), + ("/w/see revision 999", "U "), + ("/w/existed.txt", "E "), + ] + .map(|(p, a)| (p.to_owned(), a.to_owned())) + ); + } + + /// M2, M11: property and tree conflicts, merges and updated properties keep their columns; + /// Update Info counts what it shows (all but `E`). + #[test] + fn conflicts_and_counts() { + let out = " C /w/props.txt\n C /w/tree.txt\nCC /w/both.txt\nGU /w/gu.txt\nE /w/e.txt\nD /w/r.txt\nA /w/r.txt\nUpdated to revision 3.\n"; + let items = parse_update(out, Path::new("/w")).items; + assert_eq!( + items.iter().map(|i| i.action.as_str()).collect::>(), + [" C ", " C", "CC ", "GU ", "E ", "D ", "A "] + ); + assert_eq!(shown_items(&items), 5, "r.txt replaced is one"); + } + + #[test] + fn repository_paths_of_updated_items() { + let mut items = parse_update("U /w/src/a.txt\nU /w\nAt revision 2.\n", Path::new("/w")).items; + with_repo_paths(&mut items, Path::new("/w"), "/trunk"); + assert_eq!( + items.iter().map(|i| i.repo_path.as_deref()).collect::>(), + [Some("/trunk/src/a.txt"), Some("/trunk")] + ); + } + #[test] fn escapes_repository_paths_for_urls() { assert_eq!(escape_path("/branches/a%20b"), "/branches/a%2520b"); diff --git a/crates/ide-svn/src/workspace.rs b/crates/ide-svn/src/workspace.rs index 91c720c446..93ac69d669 100644 --- a/crates/ide-svn/src/workspace.rs +++ b/crates/ide-svn/src/workspace.rs @@ -159,6 +159,9 @@ pub struct WorkingCopy { /// The last `svn status` of the whole working copy and the time `.svn/wc.db` had then: /// the Changes view asks for the status and then for the changelists ([`recent_entries`](Self::recent_entries)). last_status: parking_lot::Mutex>, + /// The switched folders and files, with `.svn/wc.db`'s time then: only an svn that writes the + /// database switches one ([`switched_paths`](Self::switched_paths)). + switched: parking_lot::Mutex, Vec)>>, } impl WorkingCopy { @@ -194,6 +197,7 @@ impl WorkingCopy { repository_db: Default::default(), lines_cache: Default::default(), last_status: Default::default(), + switched: Default::default(), })); } Ok(None) @@ -382,6 +386,11 @@ impl WorkingCopy { entries.dedup_by(|a, b| a.path == b.path); if paths.is_empty() && flags.is_empty() { *self.last_status.lock() = Some((std::time::Instant::now(), db, entries.clone())); + // The Changes view's status lists the switched ones too: Working Copies needs no scan. + // Keyed by the database's time after the status, which may have written it (svn + // records the timestamps of files it found unchanged); only a switch changes these. + *self.switched.lock() = + Some((self.db_time(), entries.iter().filter(|e| e.switched).map(|e| PathBuf::from(&e.path)).collect())); } Ok(entries) } @@ -400,6 +409,25 @@ impl WorkingCopy { self.entries(&[]) } + /// The switched folders and files of the working copy (Working Copies Information): from the + /// last whole status (the Changes view's) while `.svn/wc.db` is unchanged since, else from + /// `svn status -q` (no unversioned files, no externals), which `cancel` stops. + pub(crate) fn switched_paths(&self, cancel: &CancellationToken) -> IdeResult> { + let now = self.db_time(); + if let Some((at, paths)) = self.switched.lock().as_ref() + && now.is_some() + && *at == now + { + return Ok(paths.clone()); + } + let argv = [args(["status", "--xml", "-q", "--ignore-externals", "--"]), vec![target(&self.root)]].concat(); + let out = self.svn.run(&argv, LOCAL, Some(cancel))?; + let paths: Vec = + xml::status(&out)?.into_iter().filter(|e| e.switched).map(|e| normalize(&self.abs(&e.path))).collect(); + *self.switched.lock() = Some((self.db_time(), paths.clone())); + Ok(paths) + } + fn db_time(&self) -> Option { std::fs::metadata(self.wc_root.join(".svn").join("wc.db")).and_then(|m| m.modified()).ok() } @@ -662,7 +690,7 @@ fn property_text(out: &[u8]) -> IdeResult> { Ok(text.into_bytes()) } -fn repository(info: &xml::Info) -> Repository { +pub(crate) fn repository(info: &xml::Info) -> Repository { let path = info.relative_url.strip_prefix('^').unwrap_or(&info.relative_url); Repository { url: info.url.clone(), diff --git a/crates/ide-svn/tests/feedback.rs b/crates/ide-svn/tests/integration/feedback.rs similarity index 99% rename from crates/ide-svn/tests/feedback.rs rename to crates/ide-svn/tests/integration/feedback.rs index 8e7e67b4eb..94039e406a 100644 --- a/crates/ide-svn/tests/feedback.rs +++ b/crates/ide-svn/tests/integration/feedback.rs @@ -1,6 +1,4 @@ -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_vcs::{Backend, LogQuery}; diff --git a/crates/ide-svn/tests/ij_auth.rs b/crates/ide-svn/tests/integration/ij_auth.rs similarity index 96% rename from crates/ide-svn/tests/ij_auth.rs rename to crates/ide-svn/tests/integration/ij_auth.rs index b64e93bdea..708ab4e507 100644 --- a/crates/ide-svn/tests/ij_auth.rs +++ b/crates/ide-svn/tests/integration/ij_auth.rs @@ -11,9 +11,7 @@ //! `svn+ssh://` through a stand-in `SVN_SSH` running `svnserve -t`; version output //! through stand-in `svn` scripts. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_core::error::ErrorKind; use ide_svn::{Depth, Prompt, PromptHandler, Settings, SvnContext, WorkingCopy}; @@ -785,3 +783,31 @@ fn reads_of_a_server_that_refuses_the_repository_root() { let lines: Vec = wc.lines(&CancellationToken::new()).unwrap().into_iter().map(|b| b.name).collect(); assert_eq!(lines, ["trunk", "branches/b1"]); } + +/// Review of #8212, H6: Incoming read by the IDE on its own (`quietly`) asks for no login, in +/// interactive mode or through the login dialog; the error says a login is needed. A Refresh +/// the user asks for still signs in. +#[test] +fn a_quiet_read_asks_for_no_login() { + if !have(&["svnserve"]) { + return; + } + let Some(repo) = repo() else { return }; + let (_server, url) = serve(&repo.base.join("repo"), true); + let cancel = CancellationToken::new(); + for interactive in [true, false] { + if interactive && cfg!(windows) { + continue; + } + let user = User::new(&[]); + let ctx = context(config(&repo.base, &format!("config-{interactive}"), false), interactive, &user); + let dest = repo.base.join(format!("wc-{interactive}")); + let wc = WorkingCopy::checkout(&format!("{url}/trunk"), None, &dest, Depth::Infinity, ctx, &cancel).unwrap(); + let asked = user.asked.lock().len(); + let err = ide_svn::quietly(|| wc.incoming_revisions(&cancel)).unwrap_err(); + assert!(ide_svn::is_login_required(&err), "{err:?}"); + assert_eq!(user.asked.lock().len(), asked, "nothing asked: {:?}", user.asked.lock()); + wc.incoming_revisions(&cancel).unwrap(); + assert!(user.asked.lock().len() > asked, "a Refresh signs in"); + } +} diff --git a/crates/ide-svn/tests/ij_changelists.rs b/crates/ide-svn/tests/integration/ij_changelists.rs similarity index 99% rename from crates/ide-svn/tests/ij_changelists.rs rename to crates/ide-svn/tests/integration/ij_changelists.rs index 3246701871..600f5ff122 100644 --- a/crates/ide-svn/tests/ij_changelists.rs +++ b/crates/ide-svn/tests/integration/ij_changelists.rs @@ -9,9 +9,7 @@ //! default one, so here the files are moved to a named list, as the Commit window does for a //! list that is not the default one. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::{Backend, ChangeKind}; diff --git a/crates/ide-svn/tests/ij_committed.rs b/crates/ide-svn/tests/integration/ij_committed.rs similarity index 99% rename from crates/ide-svn/tests/ij_committed.rs rename to crates/ide-svn/tests/integration/ij_committed.rs index 4fbc3206be..42e5465f04 100644 --- a/crates/ide-svn/tests/ij_committed.rs +++ b/crates/ide-svn/tests/integration/ij_committed.rs @@ -3,9 +3,7 @@ //! OpenIDEA shows a revision's files in the Log (`commit_files`) and diffs each one against //! the revision before (`commits_changes`, `file_at`). Skipped without `svn` locally. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::Backend; diff --git a/crates/ide-svn/tests/ij_externals.rs b/crates/ide-svn/tests/integration/ij_externals.rs similarity index 99% rename from crates/ide-svn/tests/ij_externals.rs rename to crates/ide-svn/tests/integration/ij_externals.rs index f31f5f76b0..8f5eb86b75 100644 --- a/crates/ide-svn/tests/ij_externals.rs +++ b/crates/ide-svn/tests/integration/ij_externals.rs @@ -6,9 +6,7 @@ //! working copy updated, and the external looked for at the folder IntelliJ expects. //! Skipped without `svn` locally. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::Backend; diff --git a/crates/ide-svn/tests/ij_files.rs b/crates/ide-svn/tests/integration/ij_files.rs similarity index 99% rename from crates/ide-svn/tests/ij_files.rs rename to crates/ide-svn/tests/integration/ij_files.rs index c4f06d493b..648c504200 100644 --- a/crates/ide-svn/tests/ij_files.rs +++ b/crates/ide-svn/tests/integration/ij_files.rs @@ -5,9 +5,7 @@ //! root is checked in crates/ide-host/tests/ij_svn_roots.rs. Skipped without //! `svn` locally; required in CI. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::{Backend, LogQuery}; diff --git a/crates/ide-svn/tests/ij_history.rs b/crates/ide-svn/tests/integration/ij_history.rs similarity index 99% rename from crates/ide-svn/tests/ij_history.rs rename to crates/ide-svn/tests/integration/ij_history.rs index 3c0a049fd2..b3313d912f 100644 --- a/crates/ide-svn/tests/ij_history.rs +++ b/crates/ide-svn/tests/integration/ij_history.rs @@ -4,9 +4,7 @@ //! repositories through the IDE's operations. The editor side of the annotation //! scenarios is `src/features/vcs/__tests__/ijAnnotations.test.ts`. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::{Backend, ChangeKind, LogQuery}; diff --git a/crates/ide-svn/tests/ij_merge.rs b/crates/ide-svn/tests/integration/ij_merge.rs similarity index 99% rename from crates/ide-svn/tests/ij_merge.rs rename to crates/ide-svn/tests/integration/ij_merge.rs index 0116758000..adc561f5c7 100644 --- a/crates/ide-svn/tests/ij_merge.rs +++ b/crates/ide-svn/tests/integration/ij_merge.rs @@ -5,9 +5,7 @@ //! Changes view shows the merged file and the working copy's root (its new mergeinfo). //! Skipped without `svn` locally. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::Backend; diff --git a/crates/ide-svn/tests/ij_rename_rollback.rs b/crates/ide-svn/tests/integration/ij_rename_rollback.rs similarity index 99% rename from crates/ide-svn/tests/ij_rename_rollback.rs rename to crates/ide-svn/tests/integration/ij_rename_rollback.rs index dc39102eef..0ada978aa3 100644 --- a/crates/ide-svn/tests/ij_rename_rollback.rs +++ b/crates/ide-svn/tests/integration/ij_rename_rollback.rs @@ -5,9 +5,7 @@ //! `files_deleted`); an undo is the IDE moving the file back the same way. Rollback in the //! Changes view discards the rows chosen, a folder taking the rows below it. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::WorkingCopy; use ide_vcs::{Backend, ChangeKind, LogQuery}; diff --git a/crates/ide-svn/tests/incoming_and_branches.rs b/crates/ide-svn/tests/integration/incoming_and_branches.rs similarity index 99% rename from crates/ide-svn/tests/incoming_and_branches.rs rename to crates/ide-svn/tests/integration/incoming_and_branches.rs index 591653d22a..5d7bb714cc 100644 --- a/crates/ide-svn/tests/incoming_and_branches.rs +++ b/crates/ide-svn/tests/integration/incoming_and_branches.rs @@ -1,7 +1,6 @@ //! Incoming remote status, working copy metadata, branch layout, branch comparison, and custom switch tests. -mod common; -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::Depth; use ide_vcs::Backend; @@ -174,7 +173,7 @@ fn per_root_branch_config_and_switched_descendants() { let alpha_url = format!("{}/mod-a/feature-lines/alpha", repo.url); wc_a.switch_path_with_options(Some(&sub_dir), &alpha_url, None, None, true, &cancel).unwrap(); - let infos = wc_a.working_copy_infos().unwrap(); + let infos = wc_a.working_copy_infos(&cancel).unwrap(); assert_eq!(infos.len(), 2, "expected root and switched descendant: {infos:?}"); assert_eq!(infos[0].url, mod_a_trunk); assert!(!infos[0].is_switched); diff --git a/crates/ide-svn/tests/integration/main.rs b/crates/ide-svn/tests/integration/main.rs new file mode 100644 index 0000000000..183fe0af62 --- /dev/null +++ b/crates/ide-svn/tests/integration/main.rs @@ -0,0 +1,20 @@ +#[path = "../common/mod.rs"] +mod common; + +mod feedback; +mod ij_auth; +mod ij_changelists; +mod ij_committed; +mod ij_externals; +mod ij_files; +mod ij_history; +mod ij_merge; +mod ij_rename_rollback; +mod incoming_and_branches; +mod matrix; +mod merge_ui; +mod remote_browser; +mod settings; +mod shelf; +mod wc_ops; +mod working_copy; diff --git a/crates/ide-svn/tests/matrix.rs b/crates/ide-svn/tests/integration/matrix.rs similarity index 99% rename from crates/ide-svn/tests/matrix.rs rename to crates/ide-svn/tests/integration/matrix.rs index bc109b1dbb..a809669ce5 100644 --- a/crates/ide-svn/tests/matrix.rs +++ b/crates/ide-svn/tests/integration/matrix.rs @@ -4,9 +4,7 @@ //! (`subversion/tests/cmdline/*.py`); scenarios also come from IntelliJ's //! svn4idea tests. Skipped without `svn` locally; required in CI. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_vcs::{Backend, ChangeKind, CommitOptions, LogQuery, TextEncoding}; use std::path::{Path, PathBuf}; diff --git a/crates/ide-svn/tests/merge_ui.rs b/crates/ide-svn/tests/integration/merge_ui.rs similarity index 99% rename from crates/ide-svn/tests/merge_ui.rs rename to crates/ide-svn/tests/integration/merge_ui.rs index d06cf2fa26..42978b587d 100644 --- a/crates/ide-svn/tests/merge_ui.rs +++ b/crates/ide-svn/tests/integration/merge_ui.rs @@ -1,5 +1,5 @@ //! Integration tests for Subversion merge options, eligible revisions, and reverse merge. -mod common; +use crate::common; use ide_core::CancellationToken; use ide_svn::{Depth, MergeOptions, WorkingCopy}; diff --git a/crates/ide-svn/tests/remote_browser.rs b/crates/ide-svn/tests/integration/remote_browser.rs similarity index 99% rename from crates/ide-svn/tests/remote_browser.rs rename to crates/ide-svn/tests/integration/remote_browser.rs index 93f862212e..a2c57fef92 100644 --- a/crates/ide-svn/tests/remote_browser.rs +++ b/crates/ide-svn/tests/integration/remote_browser.rs @@ -1,7 +1,6 @@ //! Repository browser, export, and checkout option operations in `ide_svn`. -mod common; -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_svn::{ Depth, WorkingCopy, cat_url, export_url, list_url, remote_copy, remote_delete, remote_log, remote_mkdir, diff --git a/crates/ide-svn/tests/settings.rs b/crates/ide-svn/tests/integration/settings.rs similarity index 99% rename from crates/ide-svn/tests/settings.rs rename to crates/ide-svn/tests/integration/settings.rs index a75d67dd5f..c01a934840 100644 --- a/crates/ide-svn/tests/settings.rs +++ b/crates/ide-svn/tests/integration/settings.rs @@ -2,9 +2,9 @@ //! throwaway `svnserve` with a password database, and their scope: one //! project's context. Skipped when `svn`, `svnadmin` or `svnserve` is not installed. -mod common; +use crate::common; -use common::{Svnserve, svnserve}; +use crate::common::{Svnserve, svnserve}; use ide_core::CancellationToken; use ide_core::error::ErrorKind; use ide_svn::{Depth, Prompt, PromptHandler, Settings, SvnContext, WorkingCopy}; diff --git a/crates/ide-svn/tests/shelf.rs b/crates/ide-svn/tests/integration/shelf.rs similarity index 98% rename from crates/ide-svn/tests/shelf.rs rename to crates/ide-svn/tests/integration/shelf.rs index 31c806205e..43a55b4bd1 100644 --- a/crates/ide-svn/tests/shelf.rs +++ b/crates/ide-svn/tests/integration/shelf.rs @@ -1,7 +1,6 @@ //! Shelve Changes in a working copy: the patch the shelf keeps and the rollback after it. -mod common; -use common::{repo, write}; +use crate::common::{repo, write}; /// A file changed between saving its patch on the shelf and rolling it back is left alone. #[test] diff --git a/crates/ide-svn/tests/wc_ops.rs b/crates/ide-svn/tests/integration/wc_ops.rs similarity index 99% rename from crates/ide-svn/tests/wc_ops.rs rename to crates/ide-svn/tests/integration/wc_ops.rs index b54639899d..80c1714f72 100644 --- a/crates/ide-svn/tests/wc_ops.rs +++ b/crates/ide-svn/tests/integration/wc_ops.rs @@ -1,5 +1,5 @@ //! Integration tests for Subversion working copy operations (ignore, property diffs, cleanup, update options, URL lookup). -mod common; +use crate::common; use ide_core::CancellationToken; use ide_svn::{CleanupOptions, Depth, PropertyDiff, UpdateOptions, WorkingCopy}; diff --git a/crates/ide-svn/tests/working_copy.rs b/crates/ide-svn/tests/integration/working_copy.rs similarity index 99% rename from crates/ide-svn/tests/working_copy.rs rename to crates/ide-svn/tests/integration/working_copy.rs index 53ab80baa2..1a83726418 100644 --- a/crates/ide-svn/tests/working_copy.rs +++ b/crates/ide-svn/tests/integration/working_copy.rs @@ -2,9 +2,7 @@ //! `file://` URLs): no server involved. Skipped when `svn` or `svnadmin` is //! not installed. -mod common; - -use common::*; +use crate::common::*; use ide_core::CancellationToken; use ide_core::error::ErrorKind; use ide_svn::{ResolveAccept, WorkingCopy}; diff --git a/crates/ide-svn/tests/tool_window.rs b/crates/ide-svn/tests/tool_window.rs new file mode 100644 index 0000000000..230299c8a6 --- /dev/null +++ b/crates/ide-svn/tests/tool_window.rs @@ -0,0 +1,265 @@ +//! The Subversion tabs of the version control tool window (review of #8212): Incoming of a +//! mixed-revision working copy, the newest revisions under a limit, Format › Change, Depth › Fix, +//! and an update's report of an external. +mod common; + +use common::*; +use ide_core::CancellationToken; +use ide_svn::{Depth, IncomingRevision, UpdateOptions, WorkingCopy}; +use ide_vcs::Backend; +use std::process::Command; + +fn revisions(found: &[IncomingRevision]) -> Vec { + found.iter().map(|r| r.revision).collect() +} + +fn add_and_commit(wc: &WorkingCopy, rel: &str, text: &str, message: &str) -> String { + let path = write(wc, rel, text); + wc.files_added(std::slice::from_ref(&path)).unwrap(); + commit(wc, &[path], message) +} + +/// H10: a commit moves only the committed files to the new revision; their folder stays at the +/// older one. The commit is not incoming; another client's commit is. +#[test] +fn a_commit_of_ones_own_is_not_incoming() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "a.txt", "one\n", "add a"); + let a = write(&wc, "a.txt", "two\n"); + assert_eq!(commit(&wc, &[a], "change a"), "3"); + assert_eq!(wc.current_repository().revision, Some(1), "the root stays at its revision"); + assert!(wc.incoming_revisions(&cancel).unwrap().is_empty()); + + let other = repo.checkout("other"); + assert_eq!(add_and_commit(&other, "b.txt", "b\n", "add b"), "4"); + assert_eq!(revisions(&wc.incoming_revisions(&cancel).unwrap()), [4]); +} + +/// H10: a file updated back to an older revision than its folder still has its newer ones coming. +#[test] +fn a_file_behind_its_folder_is_incoming() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "a.txt", "one\n", "add a"); + let a = write(&wc, "a.txt", "two\n"); + commit(&wc, &[a], "change a"); + repo.svn(wc.root(), &["update", "-q"]); + repo.svn(wc.root(), &["update", "-q", "-r", "2", "a.txt"]); + let found = wc.incoming_revisions(&cancel).unwrap(); + assert_eq!(revisions(&found), [3]); + assert_eq!(found[0].paths[0].local.as_deref(), Some(wc.root().join("a.txt").as_path())); +} + +/// H7: a range read keeps the newest revisions when it has more than the limit. +#[test] +fn the_newest_revisions_under_a_limit() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "a.txt", "1\n", "r2"); + for n in 3..=5 { + let a = write(&wc, "a.txt", &format!("{n}\n")); + commit(&wc, &[a], &format!("r{n}")); + } + assert_eq!(revisions(&wc.newest_revisions(2, 5, 2, &cancel).unwrap()), [5, 4]); + assert_eq!(revisions(&wc.revisions_between(2, 5, &cancel).unwrap()), [5, 4, 3, 2]); +} + +/// The working copy's format: `.svn/wc.db`'s SQLite user version (svn before 1.10 has no +/// `svn info --show-item wc-format`). +fn wc_format(path: &std::path::Path) -> String { + let db = std::fs::read(path.join(".svn/wc.db")).unwrap(); + u32::from_be_bytes([db[60], db[61], db[62], db[63]]).to_string() +} + +/// H1: svn upgrades a whole checkout and a format cannot go back. A project inside a checkout, +/// or a folder that is not a working copy root, does not change the checkout's format. +#[test] +fn only_a_working_copy_root_changes_its_format() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "sub/x.txt", "x\n", "add sub"); + let before = wc_format(wc.root()); + let newest = wc.supported_formats().last().cloned().unwrap(); + + let sub = WorkingCopy::discover(&wc.root().join("sub"), ctx()).unwrap().unwrap(); + assert_eq!((sub.root(), sub.wc_root()), (wc.root().join("sub").as_path(), wc.root())); + assert!(sub.upgrade(sub.root(), &newest, &cancel).is_err(), "a project inside the checkout"); + assert!(wc.upgrade(&wc.root().join("sub"), &newest, &cancel).is_err(), "a folder of it"); + assert!(wc.upgrade(wc.root(), "1.99", &cancel).is_err(), "a format this svn cannot write"); + assert_eq!(wc_format(wc.root()), before); + + wc.upgrade(wc.root(), &newest, &cancel).unwrap(); + if newest == "1.15" { + assert_eq!(wc_format(wc.root()), "32"); + } +} + +/// Depth › Fix: `svn update --set-depth infinity` brings the files a shallow checkout left out. +#[test] +fn depth_fix_brings_the_whole_tree() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let seed = repo.checkout("seed"); + add_and_commit(&seed, "dir/deep.txt", "deep\n", "add deep"); + let shallow = repo.base.join("shallow"); + repo.svn( + &repo.base, + &["checkout", "-q", "--depth", "empty", &format!("{}/trunk", repo.url), shallow.to_str().unwrap()], + ); + let wc = WorkingCopy::discover(&shallow, ctx()).unwrap().unwrap(); + let lines = parking_lot::Mutex::new(Vec::new()); + let options = UpdateOptions { + revision: Some("HEAD".into()), + depth: Some(Depth::Infinity), + set_depth: true, + ignore_externals: false, + }; + let result = wc.update_with_options(&[], &options, &cancel, &|line| lines.lock().push(line)).unwrap(); + assert!(shallow.join("dir/deep.txt").is_file()); + assert_eq!(result.added, 2, "{:?}", lines.lock()); + assert!(lines.lock().iter().any(|l| l.ends_with("deep.txt")), "streamed: {:?}", lines.lock()); + assert_eq!(wc.working_copy_info().unwrap().depth, "infinity"); +} + +/// H8: an external at a newer revision of its own repository does not move the working copy's +/// reached revision, and its files are reported apart, at the external's revision; each file of +/// the working copy has its repository path. +#[test] +fn an_update_reports_an_external_apart() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let ext_repo = repo.base.join("ext-repo"); + assert!(Command::new("svnadmin").arg("create").arg(&ext_repo).status().unwrap().success()); + let ext_url = file_url(&ext_repo); + let ext_seed = repo.base.join("ext-seed"); + repo.svn(&repo.base, &["checkout", "-q", &ext_url, ext_seed.to_str().unwrap()]); + std::fs::write(ext_seed.join("ext_file.txt"), "0\n").unwrap(); + repo.svn(&ext_seed, &["add", "-q", "ext_file.txt"]); + for n in 0..8 { + std::fs::write(ext_seed.join("ext_file.txt"), format!("{n}\n")).unwrap(); + repo.svn(&ext_seed, &["commit", "-q", "-m", "ext"]); + } + + let seed = repo.checkout("seed"); + add_and_commit(&seed, "it's here.txt", "one\n", "add"); + repo.svn(seed.root(), &["update", "-q"]); + repo.svn(seed.root(), &["propset", "-q", "svn:externals", &format!("{ext_url} ext"), "."]); + repo.svn(seed.root(), &["commit", "-q", "-m", "externals"]); + let wc = repo.checkout("wc"); + assert!(wc.root().join("ext/ext_file.txt").is_file()); + + std::fs::write(ext_seed.join("ext_file.txt"), "new\n").unwrap(); + repo.svn(&ext_seed, &["commit", "-q", "-m", "ext again"]); + repo.svn(seed.root(), &["update", "-q"]); + std::fs::write(seed.root().join("it's here.txt"), "two\n").unwrap(); + repo.svn(seed.root(), &["commit", "-q", "-m", "change"]); + + let (reached, summary) = wc.update_reporting(&[], None, &cancel, &|_| {}).unwrap(); + assert_eq!(reached, 4); + assert_eq!(summary.to_revision.as_deref(), Some("4")); + let items: Vec<_> = summary.items.iter().map(|i| (i.path.clone(), i.repo_path.clone())).collect(); + assert_eq!(items, [(wc.root().join("it's here.txt"), Some("/trunk/it's here.txt".to_owned()))]); + let [external] = summary.externals.as_slice() else { panic!("{:?}", summary.externals) }; + assert_eq!(external.root, wc.root().join("ext")); + assert_eq!(external.to_revision.as_deref(), Some("9")); + assert_eq!( + external.items.iter().map(|i| (i.path.clone(), i.repo_path.clone())).collect::>(), + [(wc.root().join("ext/ext_file.txt"), Some("/ext_file.txt".to_owned()))] + ); + assert_eq!(summary.changed, 2); +} + +/// #8220 (3): a move keeps where it came from, so Incoming compares the file with its old path. +#[test] +fn incoming_keeps_where_a_moved_file_came_from() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "a.txt", "one\n", "add a"); + let other = repo.checkout("other"); + repo.svn(other.root(), &["mv", "-q", "a.txt", "b.txt"]); + repo.svn(other.root(), &["commit", "-q", "-m", "rename"]); + let found = wc.incoming_revisions(&cancel).unwrap(); + assert_eq!(revisions(&found), [3]); + let mut paths: Vec<_> = + found[0].paths.iter().map(|p| (p.action.as_str(), p.path.as_str(), p.copy_from.clone())).collect(); + paths.sort(); + assert_eq!(paths, [("A", "/trunk/b.txt", Some(("/trunk/a.txt".to_owned(), 2))), ("D", "/trunk/a.txt", None)]); +} + +/// #8220 (4): a folder switched to a branch has the branch's new revisions incoming, read from +/// the branch's log; a trunk commit to the folder's trunk path is not the folder's. +#[test] +fn a_switched_folder_has_its_branchs_revisions_incoming() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "sub/x.txt", "x\n", "add sub"); + let branch = format!("{}/branches/b", repo.url); + repo.svn(&repo.base, &["copy", "-q", "-m", "branch", &format!("{}/trunk", repo.url), &branch]); + repo.svn(wc.root(), &["update", "-q"]); + repo.svn(wc.root(), &["switch", "-q", &format!("{branch}/sub"), "sub"]); + + let on_branch = repo.base.join("on-branch"); + repo.svn(&repo.base, &["checkout", "-q", &branch, on_branch.to_str().unwrap()]); + std::fs::write(on_branch.join("sub/x.txt"), "branch\n").unwrap(); + repo.svn(&on_branch, &["commit", "-q", "-m", "on the branch"]); + let trunk = repo.checkout("trunk"); + std::fs::write(trunk.root().join("sub/x.txt"), "trunk\n").unwrap(); + repo.svn(trunk.root(), &["commit", "-q", "-m", "on the trunk"]); + + let found = wc.incoming_revisions(&cancel).unwrap(); + assert_eq!(found.iter().map(|r| (r.revision, r.message.as_str())).collect::>(), [(4, "on the branch")]); + assert_eq!(found[0].paths[0].local.as_deref(), Some(wc.root().join("sub/x.txt").as_path())); +} + +/// #8220 (5): the switched folders come from the Changes view's last status while the working +/// copy is unchanged (no scan, so a cancelled request still lists them); else the scan runs, and +/// a cancelled one stops. +#[test] +fn switched_folders_from_the_last_status_else_a_scan_that_stops() { + let Some(repo) = repo() else { return }; + let wc = repo.checkout("wc"); + add_and_commit(&wc, "sub/x.txt", "x\n", "add sub"); + let branch = format!("{}/branches/b", repo.url); + repo.svn(&repo.base, &["copy", "-q", "-m", "branch", &format!("{}/trunk", repo.url), &branch]); + repo.svn(wc.root(), &["update", "-q"]); + repo.svn(wc.root(), &["switch", "-q", &format!("{branch}/sub"), "sub"]); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + + let cold = WorkingCopy::discover(wc.root(), ctx()).unwrap().unwrap(); + let err = cold.working_copy_infos(&cancelled).unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled, "{err:?}"); + + cold.status().unwrap(); + let infos = cold.working_copy_infos(&cancelled).unwrap(); + assert_eq!( + infos.iter().map(|i| (i.root.clone(), i.is_switched)).collect::>(), + [(wc.root().display().to_string(), false), (wc.root().join("sub").display().to_string(), true)] + ); +} + +/// #8220 (6): Update File of a file at another revision than its folder (after a commit) reports +/// the file's own revision as the one it was at. +#[test] +fn update_file_reports_the_files_own_base() { + let Some(repo) = repo() else { return }; + let cancel = CancellationToken::new(); + let wc = repo.checkout("wc"); + add_and_commit(&wc, "a.txt", "one\n", "add a"); + assert_eq!(wc.current_repository().revision, Some(1), "the folder stays at r1, a.txt is at r2"); + let other = repo.checkout("other"); + std::fs::write(other.root().join("a.txt"), "two\n").unwrap(); + repo.svn(other.root(), &["commit", "-q", "-m", "change a"]); + + let (_, summary) = wc.update_reporting(&[wc.root().join("a.txt")], None, &cancel, &|_| {}).unwrap(); + assert_eq!(summary.from_revision.as_deref(), Some("1")); + let [item] = summary.items.as_slice() else { panic!("{:?}", summary.items) }; + assert_eq!((item.action.as_str(), item.from_revision.as_deref()), ("U ", Some("2"))); +} diff --git a/crates/ide-vcs/src/backend.rs b/crates/ide-vcs/src/backend.rs index 7eec9e186d..5d31c87246 100644 --- a/crates/ide-vcs/src/backend.rs +++ b/crates/ide-vcs/src/backend.rs @@ -44,14 +44,31 @@ pub struct UpdateSummary { /// The working copy's revision before and after the update. pub from_revision: Option, pub to_revision: Option, + /// Externals the same update fetched, each at its own repository's revision. + pub externals: Vec, +} + +/// The files of an external an update fetched (`svn:externals`): another repository, so its +/// revisions are not the working copy's. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExternalUpdate { + pub root: PathBuf, + pub items: Vec, + /// The revision the external reached; the one it was at is not printed. + pub to_revision: Option, } /// One file or folder of an [`UpdateSummary`]: `action` is svn's four status columns as it /// prints them (`U `, ` U `, `C `, ` C`), or `restored` / `skipped`. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct UpdatedItem { pub path: PathBuf, pub action: String, + /// Its path in the repository (`/trunk/src/a.txt`), when known: a deleted file is read there. + pub repo_path: Option, + /// The revision it was at before the update, when that is not the working copy's: an + /// update of a file whose BASE differs from its folder's (a mixed-revision working copy). + pub from_revision: Option, } /// Finds the working copies of one non-Git version control system. Registered diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 57aaffc1cf..427fc2236e 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1084,7 +1084,7 @@ pub use submodules::SubmoduleRollbackSource; mod text_encoding; mod write; -pub use backend::{Backend, BackendProvider, UpdateSummary, UpdatedItem}; +pub use backend::{Backend, BackendProvider, ExternalUpdate, UpdateSummary, UpdatedItem}; pub use cherry_pick_plan::CherryPickOptions; pub use cli::{ GitCommandObserver, askpass_env, detected_git_executable, filter_overrides_from, git_version, restrict, diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index 31b85d47f0..50c3600fdc 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -739,6 +739,33 @@ mod tests { assert!(cmd.status().unwrap().success(), "{cmd:?}"); } + /// The Git Log filters a short name that is both a tag and a local branch by git's own + /// disambiguated forms (`git rev-parse --abbrev-ref=strict`): `tags/`, `heads/`, + /// or the full ref when another ref takes those. + #[test] + fn resolves_disambiguated_short_names_of_a_tag_and_branch_sharing_a_name() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("repo"); + run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root)); + let git = |args: &[&str]| { + let out = Command::new("git").current_dir(&root).args(args).output().unwrap(); + assert!(out.status.success(), "{args:?}"); + String::from_utf8(out.stdout).unwrap().trim().to_owned() + }; + for message in ["one", "two"] { + git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", message]); + } + git(&["tag", "release"]); + git(&["branch", "release", "HEAD~1"]); + let tag = git(&["rev-parse", "refs/tags/release"]); + let branch = git(&["rev-parse", "refs/heads/release"]); + assert_ne!(tag, branch); + let repo = discover(&root).unwrap().unwrap().gix().unwrap(); + assert_eq!(resolve(&repo, "tags/release").unwrap().to_string(), tag); + assert_eq!(resolve(&repo, "heads/release").unwrap().to_string(), branch); + assert_eq!(resolve(&repo, "refs/heads/release").unwrap().to_string(), branch); + } + /// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The /// owner can't be changed in a test, so this pins that discovery opens with slots sized by the /// pack directory: objects in every pack stay readable through the cached handle. diff --git a/crates/ide-vcs/tests/blame_ignore.rs b/crates/ide-vcs/tests/integration/blame_ignore.rs similarity index 100% rename from crates/ide-vcs/tests/blame_ignore.rs rename to crates/ide-vcs/tests/integration/blame_ignore.rs diff --git a/crates/ide-vcs/tests/block_history.rs b/crates/ide-vcs/tests/integration/block_history.rs similarity index 100% rename from crates/ide-vcs/tests/block_history.rs rename to crates/ide-vcs/tests/integration/block_history.rs diff --git a/crates/ide-vcs/tests/case_rename.rs b/crates/ide-vcs/tests/integration/case_rename.rs similarity index 100% rename from crates/ide-vcs/tests/case_rename.rs rename to crates/ide-vcs/tests/integration/case_rename.rs diff --git a/crates/ide-vcs/tests/git_workflows.rs b/crates/ide-vcs/tests/integration/git_workflows.rs similarity index 100% rename from crates/ide-vcs/tests/git_workflows.rs rename to crates/ide-vcs/tests/integration/git_workflows.rs diff --git a/crates/ide-vcs/tests/history_ops.rs b/crates/ide-vcs/tests/integration/history_ops.rs similarity index 100% rename from crates/ide-vcs/tests/history_ops.rs rename to crates/ide-vcs/tests/integration/history_ops.rs diff --git a/crates/ide-vcs/tests/ignore.rs b/crates/ide-vcs/tests/integration/ignore.rs similarity index 100% rename from crates/ide-vcs/tests/ignore.rs rename to crates/ide-vcs/tests/integration/ignore.rs diff --git a/crates/ide-vcs/tests/lfs.rs b/crates/ide-vcs/tests/integration/lfs.rs similarity index 100% rename from crates/ide-vcs/tests/lfs.rs rename to crates/ide-vcs/tests/integration/lfs.rs diff --git a/crates/ide-vcs/tests/log_lock.rs b/crates/ide-vcs/tests/integration/log_lock.rs similarity index 99% rename from crates/ide-vcs/tests/log_lock.rs rename to crates/ide-vcs/tests/integration/log_lock.rs index e14622842e..d0ac54764e 100644 --- a/crates/ide-vcs/tests/log_lock.rs +++ b/crates/ide-vcs/tests/integration/log_lock.rs @@ -1,6 +1,5 @@ //! A long file history walk must not hold the log index while Git runs: commit details and //! one-commit queries (inline blame, the blame popup) share that index. -#![cfg(unix)] use ide_vcs::{LogQuery, Repo}; use std::os::unix::fs::PermissionsExt; diff --git a/crates/ide-vcs/tests/log_projection.rs b/crates/ide-vcs/tests/integration/log_projection.rs similarity index 100% rename from crates/ide-vcs/tests/log_projection.rs rename to crates/ide-vcs/tests/integration/log_projection.rs diff --git a/crates/ide-vcs/tests/log_shape.rs b/crates/ide-vcs/tests/integration/log_shape.rs similarity index 100% rename from crates/ide-vcs/tests/log_shape.rs rename to crates/ide-vcs/tests/integration/log_shape.rs diff --git a/crates/ide-vcs/tests/integration/main.rs b/crates/ide-vcs/tests/integration/main.rs new file mode 100644 index 0000000000..fe3f4b3a6c --- /dev/null +++ b/crates/ide-vcs/tests/integration/main.rs @@ -0,0 +1,17 @@ +mod blame_ignore; +mod block_history; +mod case_rename; +mod git_workflows; +mod history_ops; +mod ignore; +mod lfs; +#[cfg(unix)] +mod log_lock; +mod log_projection; +mod log_shape; +mod partial_clone; +mod repo; +mod stash_paths; +mod submodule_update; +#[cfg(target_os = "macos")] +mod volume_loss; diff --git a/crates/ide-vcs/tests/partial_clone.rs b/crates/ide-vcs/tests/integration/partial_clone.rs similarity index 100% rename from crates/ide-vcs/tests/partial_clone.rs rename to crates/ide-vcs/tests/integration/partial_clone.rs diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/integration/repo.rs similarity index 100% rename from crates/ide-vcs/tests/repo.rs rename to crates/ide-vcs/tests/integration/repo.rs diff --git a/crates/ide-vcs/tests/stash_paths.rs b/crates/ide-vcs/tests/integration/stash_paths.rs similarity index 100% rename from crates/ide-vcs/tests/stash_paths.rs rename to crates/ide-vcs/tests/integration/stash_paths.rs diff --git a/crates/ide-vcs/tests/submodule_update.rs b/crates/ide-vcs/tests/integration/submodule_update.rs similarity index 100% rename from crates/ide-vcs/tests/submodule_update.rs rename to crates/ide-vcs/tests/integration/submodule_update.rs diff --git a/crates/ide-vcs/tests/volume_loss.rs b/crates/ide-vcs/tests/integration/volume_loss.rs similarity index 99% rename from crates/ide-vcs/tests/volume_loss.rs rename to crates/ide-vcs/tests/integration/volume_loss.rs index b1e469dce9..9e55c1ece8 100644 --- a/crates/ide-vcs/tests/volume_loss.rs +++ b/crates/ide-vcs/tests/integration/volume_loss.rs @@ -1,8 +1,6 @@ //! Status after the repository's volume disappears. A stale memory-mapped pack index raises //! SIGBUS there, which kills the process instead of failing the call. -#![cfg(target_os = "macos")] - use ide_vcs::Repo; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 6581182bec..b447b128c8 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -578,7 +578,7 @@ pub struct JetBrainsSettings { } const JETBRAINS_MARKER: &str = "IntelliJ IDEA Global Settings"; -const JETBRAINS_OPTIONS: [&str; 9] = [ +const JETBRAINS_OPTIONS: [&str; 13] = [ "options/editor-font.xml", "options/terminal-font.xml", "options/colors.scheme.xml", @@ -589,6 +589,18 @@ const JETBRAINS_OPTIONS: [&str; 9] = [ "options/mac/keymap.xml", "options/windows/keymap.xml", "options/linux/keymap.xml", + // JDKs, and the build tool settings for new projects. + "options/jdk.table.xml", + "options/project.default.xml", + "options/gradle.default.xml", + "options/gradle.settings.xml", +]; +/// Options files whose paths use `$USER_HOME$`, replaced by this machine's home folder when read. +const JETBRAINS_HOME_PATHS: [&str; 4] = [ + "options/jdk.table.xml", + "options/project.default.xml", + "options/gradle.default.xml", + "options/gradle.settings.xml", ]; /// Folders whose files are all read: (folder, extension). const JETBRAINS_READ_DIRS: [(&str, &str); 5] = [ @@ -603,7 +615,20 @@ const JETBRAINS_MAX_TEXT: u64 = 4 << 20; /// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder /// (`options/`, `colors/`, … as an installed IDE keeps them). pub fn read_jetbrains_settings(path: &Path) -> IdeResult { - if path.is_dir() { read_jetbrains_folder(path) } else { read_jetbrains_archive(path) } + let mut settings = if path.is_dir() { read_jetbrains_folder(path) } else { read_jetbrains_archive(path) }?; + if let Some(home) = std::env::home_dir() { + expand_user_home(&mut settings.files, &home.to_string_lossy()); + } + Ok(settings) +} + +fn expand_user_home(files: &mut BTreeMap, home: &str) { + let home = home.trim_end_matches(['/', '\\']); + for name in JETBRAINS_HOME_PATHS { + if let Some(text) = files.get_mut(name) { + *text = text.replace("$USER_HOME$", home); + } + } } /// Plugin ids, one per line: installed from the marketplace (an export writes it), and disabled. @@ -1499,6 +1524,27 @@ mod tests { assert!(read_jetbrains_settings(&empty).is_err(), "a folder without options/ is not a settings folder"); } + #[test] + fn reads_jdks_and_maven_defaults_with_this_machines_home() { + let tmp = tempfile::tempdir().unwrap(); + let options = tmp.path().join("options"); + std::fs::create_dir_all(&options).unwrap(); + std::fs::write(options.join("jdk.table.xml"), r#""#).unwrap(); + std::fs::write( + options.join("project.default.xml"), + r#" diff --git a/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java new file mode 100644 index 0000000000..af3200982b --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java @@ -0,0 +1,37 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.core.Ordered; +import org.springframework.stereotype.Component; + +/** + * Order from {@link Ordered#getOrder()}, so {@code audit} is second in {@code place}'s chooser. + * {@code trace} matches {@code @annotation} on the method and {@code @within} on the class, and + * references {@link LoggingAspect}'s pointcut by its qualified name. + */ +@Aspect +@Component +public class AuditAspect implements Ordered { + + @Pointcut("execution(* com.example.shop.OrderService.place(..))") + public void orderPlacement() {} + + @Override + public int getOrder() { + return 2; + } + + @After("orderPlacement()") + public void audit(JoinPoint joinPoint) { + System.out.println("audit " + joinPoint.getSignature().toShortString()); + } + + @Before("com.example.shop.LoggingAspect.serviceLayer() && (@annotation(com.example.shop.Audited) || @within(com.example.shop.Audited))") + public void trace(JoinPoint joinPoint) { + System.out.println("traced " + joinPoint.getSignature().toShortString()); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Audited.java b/fixtures/spring-app/src/main/java/com/example/shop/Audited.java new file mode 100644 index 0000000000..be766afb38 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Audited.java @@ -0,0 +1,15 @@ +package com.example.shop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Method-level {@code @annotation} and type-level {@code @within} target for AOP navigation: + * {@link OrderService#place(String)} and {@link Inventory#reconcile()} carry it on the method, + * {@link Checkout} on the class. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +public @interface Audited {} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java b/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java index 713ad83f7f..0cc49e8cc5 100644 --- a/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java +++ b/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java @@ -10,7 +10,10 @@ import org.springframework.stereotype.Component; * Bean navigation: each injection point has a gutter icon to its bean, and each bean one back to * where it is injected. Remove {@code @Qualifier("sms")} and both notifiers become candidates for * {@code channel}; remove {@code @Component} from SmsNotifier and its icons go away. + * AOP navigation: the class-level {@code @Audited} makes {@code checkout} an {@code @within} + * target of AuditAspect.trace. */ +@Audited @Component public class Checkout { @Autowired diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java b/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java new file mode 100644 index 0000000000..fc1222ccaf --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java @@ -0,0 +1,17 @@ +package com.example.shop; + +import org.springframework.stereotype.Component; + +/** + * Negation demo with {@link NegationAspect}: {@code stock} carries no {@code @Audited}, so that + * aspect's advice matches it; {@code reconcile} is annotated, so {@code !@annotation} excludes it. + */ +@Component +public class Inventory { + public String stock(String item) { + return "stock:" + item; + } + + @Audited + public void reconcile() {} +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java new file mode 100644 index 0000000000..d7d226002f --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java @@ -0,0 +1,39 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * AOP navigation: {@code place} is advised by four advices (the chooser), {@code checkout} by + * two, {@code SmsNotifier.send} by one (a direct jump). {@code serviceLayer} is the named + * pointcut another aspect references; the after advices use Spring's {@code pointcut} alias. + */ +@Aspect +@Component +@Order(1) +public class LoggingAspect { + + @Pointcut("within(com.example.shop..*)") + public void serviceLayer() {} + + @Before("serviceLayer() && execution(* com.example.shop.OrderService.*(..))") + public void beforeOrder(JoinPoint joinPoint) { + System.out.println("before " + joinPoint.getSignature().toShortString()); + } + + @AfterReturning(pointcut = "execution(* com.example.shop.Checkout.checkout(..))", returning = "order") + public void afterCheckout(Object order) { + System.out.println("checkout returned " + order); + } + + @AfterThrowing(pointcut = "execution(* com.example.shop.EmailNotifier.send(..))", throwing = "error") + public void afterSendFailure(Throwable error) { + System.out.println("email failed: " + error); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java new file mode 100644 index 0000000000..72530ad738 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java @@ -0,0 +1,22 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +/** + * Negation: {@code !@annotation(com.example.shop.Audited)} excludes {@link Inventory#reconcile()} + * from this advice, while {@link Inventory#stock(String)} carries no annotation and is matched: + * the advice method's icon navigates to {@code stock} only, and {@code reconcile} shows just + * {@link AuditAspect#trace}, the {@code @annotation} advice it still matches. + */ +@Aspect +@Component +public class NegationAspect { + + @Before("execution(* com.example.shop.Inventory.*(..)) && !@annotation(com.example.shop.Audited)") + public void beforeUnannotated(JoinPoint joinPoint) { + System.out.println("unannotated " + joinPoint.getSignature().toShortString()); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java new file mode 100644 index 0000000000..cb12fcd736 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java @@ -0,0 +1,20 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +/** + * No order, so its rows show the advice kind only. {@code Notifier+} matches both + * implementations: the advice's chooser has two targets, and each notifier has this one advice. + */ +@Aspect +@Component +public class NotificationAspect { + + @After("execution(* com.example.shop.Notifier+.send(..))") + public void afterEverySend(JoinPoint joinPoint) { + System.out.println("sent " + joinPoint.getSignature().toShortString()); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java b/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java index e19b3a97e2..1e28dce289 100644 --- a/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java +++ b/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java @@ -4,6 +4,8 @@ import org.springframework.stereotype.Service; @Service public class OrderService { + /** {@code @annotation(Audited)} in AuditAspect.trace matches this method. */ + @Audited public String place(String item) { return "order:" + item; } diff --git a/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java new file mode 100644 index 0000000000..da53367483 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java @@ -0,0 +1,27 @@ +package com.example.shop; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * {@code execution} with {@code *} (return type and method) and {@code ..} (package and + * arguments), and {@code @Order(3)}: its advice is last in {@code place}'s chooser. + */ +@Aspect +@Component +@Order(3) +public class TimingAspect { + + @Around("execution(* com.example.shop..*Service.*(..))") + public Object timed(ProceedingJoinPoint joinPoint) throws Throwable { + long start = System.nanoTime(); + try { + return joinPoint.proceed(); + } finally { + System.out.println(joinPoint.getSignature().toShortString() + " took " + (System.nanoTime() - start) + " ns"); + } + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java new file mode 100644 index 0000000000..51be25af6c --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java @@ -0,0 +1,20 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +/** + * {@code args(...)} is outside the first slice: this advice contributes no AOP marker, and its + * advice method shows no icon. + */ +@Aspect +@Component +public class UnsupportedAspect { + + @Before("execution(* com.example.shop..*.*(..)) && args(java.lang.String)") + public void logArgument(JoinPoint joinPoint) { + System.out.println("argument " + joinPoint.getArgs()[0]); + } +} diff --git a/patches/@codemirror__view.patch b/patches/@codemirror__view.patch index 90baf1015b..b5ee183b11 100644 --- a/patches/@codemirror__view.patch +++ b/patches/@codemirror__view.patch @@ -1,8 +1,58 @@ diff --git a/dist/index.cjs b/dist/index.cjs -index a16387f..19fd403 100644 +index a16387f..5dd5c4e 100644 --- a/dist/index.cjs +++ b/dist/index.cjs -@@ -6699,6 +6699,14 @@ class ViewState { +@@ -4886,6 +4886,15 @@ class MouseSelection { + this.mustSelect = mustSelect; + this.scrollSpeed = { x: 0, y: 0 }; + this.scrolling = -1; ++ this.moveFrame = -1; ++ this.pendingMove = false; ++ this.finishFrame = () => { ++ this.moveFrame = -1; ++ if (this.pendingMove) { ++ this.pendingMove = false; ++ this.move(this.lastEvent); ++ } ++ }; + this.lastEvent = startEvent; + this.scrollParents = scrollableParents(view.contentDOM); + this.atoms = view.state.facet(atomicRanges).map(f => f(view)); +@@ -4907,7 +4916,15 @@ class MouseSelection { + return this.destroy(); + if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) + return; +- this.select(this.lastEvent = event); ++ // Track the first move immediately. Of the moves arriving before the next ++ // paint, only the most recent needs hit testing, selection and autoscroll. ++ this.lastEvent = event; ++ if (this.moveFrame >= 0) { ++ this.pendingMove = true; ++ return; ++ } ++ this.moveFrame = this.view.win.requestAnimationFrame(this.finishFrame); ++ this.select(event); + let sx = 0, sy = 0; + let left = 0, top = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight; + if (this.scrollParents.x) +@@ -4926,13 +4943,15 @@ class MouseSelection { + this.setScrollSpeed(sx, sy); + } + up(event) { +- if (this.dragging == null) ++ if (this.dragging == null || this.pendingMove && !this.dragging) + this.select(this.lastEvent); + if (!this.dragging) + event.preventDefault(); + this.destroy(); + } + destroy() { ++ if (this.moveFrame >= 0) ++ this.view.win.cancelAnimationFrame(this.moveFrame); + this.setScrollSpeed(0, 0); + let doc = this.view.contentDOM.ownerDocument; + doc.removeEventListener("mousemove", this.move); +@@ -6699,6 +6718,14 @@ class ViewState { } gaps.push(gap); }; @@ -17,7 +67,7 @@ index a16387f..19fd403 100644 let checkLine = (line) => { if (line.length < doubleMargin || line.type != exports.BlockType.Text) return; -@@ -6735,11 +6743,10 @@ class ViewState { +@@ -6735,11 +6762,10 @@ class ViewState { } let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset; let left, right; @@ -33,7 +83,7 @@ index a16387f..19fd403 100644 } else { left = (pxLeft - marginWidth) / totalWidth; -@@ -9840,7 +9847,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({ +@@ -9840,7 +9866,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({ "& :focus": { caretColor: "initial !important", ...drawMainRange ? { @@ -45,10 +95,60 @@ index a16387f..19fd403 100644 } } : {} diff --git a/dist/index.js b/dist/index.js -index 66dd7d5..77eb3b9 100644 +index 66dd7d5..8155d9a 100644 --- a/dist/index.js +++ b/dist/index.js -@@ -6694,6 +6694,14 @@ class ViewState { +@@ -4882,6 +4882,15 @@ class MouseSelection { + this.mustSelect = mustSelect; + this.scrollSpeed = { x: 0, y: 0 }; + this.scrolling = -1; ++ this.moveFrame = -1; ++ this.pendingMove = false; ++ this.finishFrame = () => { ++ this.moveFrame = -1; ++ if (this.pendingMove) { ++ this.pendingMove = false; ++ this.move(this.lastEvent); ++ } ++ }; + this.lastEvent = startEvent; + this.scrollParents = scrollableParents(view.contentDOM); + this.atoms = view.state.facet(atomicRanges).map(f => f(view)); +@@ -4903,7 +4912,15 @@ class MouseSelection { + return this.destroy(); + if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) + return; +- this.select(this.lastEvent = event); ++ // Track the first move immediately. Of the moves arriving before the next ++ // paint, only the most recent needs hit testing, selection and autoscroll. ++ this.lastEvent = event; ++ if (this.moveFrame >= 0) { ++ this.pendingMove = true; ++ return; ++ } ++ this.moveFrame = this.view.win.requestAnimationFrame(this.finishFrame); ++ this.select(event); + let sx = 0, sy = 0; + let left = 0, top = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight; + if (this.scrollParents.x) +@@ -4922,13 +4939,15 @@ class MouseSelection { + this.setScrollSpeed(sx, sy); + } + up(event) { +- if (this.dragging == null) ++ if (this.dragging == null || this.pendingMove && !this.dragging) + this.select(this.lastEvent); + if (!this.dragging) + event.preventDefault(); + this.destroy(); + } + destroy() { ++ if (this.moveFrame >= 0) ++ this.view.win.cancelAnimationFrame(this.moveFrame); + this.setScrollSpeed(0, 0); + let doc = this.view.contentDOM.ownerDocument; + doc.removeEventListener("mousemove", this.move); +@@ -6694,6 +6713,14 @@ class ViewState { } gaps.push(gap); }; @@ -63,7 +163,7 @@ index 66dd7d5..77eb3b9 100644 let checkLine = (line) => { if (line.length < doubleMargin || line.type != BlockType.Text) return; -@@ -6730,11 +6738,10 @@ class ViewState { +@@ -6730,11 +6757,10 @@ class ViewState { } let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset; let left, right; @@ -79,7 +179,7 @@ index 66dd7d5..77eb3b9 100644 } else { left = (pxLeft - marginWidth) / totalWidth; -@@ -9835,7 +9842,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th +@@ -9835,7 +9861,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th "& :focus": { caretColor: "initial !important", ...drawMainRange ? { diff --git a/patches/@replit__codemirror-vim-core@0.1.0.patch b/patches/@replit__codemirror-vim-core@0.1.0.patch index 930848ddcf..ef044729dc 100644 --- a/patches/@replit__codemirror-vim-core@0.1.0.patch +++ b/patches/@replit__codemirror-vim-core@0.1.0.patch @@ -1,7 +1,8 @@ diff --git a/vim.js b/vim.js +index 3cafa6bcf0c99f2ae25a5da8936d3f29445f2d6d..64c9c9bbf2bfa5fd6313d36ac6495b605a8a79d7 100644 --- a/vim.js +++ b/vim.js -@@ -236,6 +236,8 @@ +@@ -236,6 +236,8 @@ export function initVim(CM) { { keys: '"', type: 'action', action: 'setRegister' }, { keys: '', type: 'action', action: 'insertRegister', context: 'insert', isEdit: true }, { keys: '', type: 'action', action: 'oneNormalCommand', context: 'insert' }, @@ -10,7 +11,7 @@ diff --git a/vim.js b/vim.js { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, -@@ -248,6 +250,11 @@ +@@ -248,6 +250,11 @@ export function initVim(CM) { { keys: '', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' }, { keys: '', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' }, // Text object motions @@ -22,7 +23,7 @@ diff --git a/vim.js b/vim.js { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, // Search -@@ -1974,6 +1981,8 @@ +@@ -1974,6 +1981,8 @@ export function initVim(CM) { if (command.type == 'keyToEx') { // Handle user defined Ex to Ex mappings exCommandDispatcher.processCommand(cm, command.exArgs.input); @@ -31,7 +32,7 @@ diff --git a/vim.js b/vim.js } else { /**@type{import("./types").PromptOptions} */ var promptOptions = { -@@ -2582,6 +2591,8 @@ +@@ -2582,6 +2591,8 @@ export function initVim(CM) { if (head.sticky == "before") head.ch--; return head; }, @@ -40,7 +41,7 @@ diff --git a/vim.js b/vim.js textObjectManipulation: function(cm, head, motionArgs, vim) { // TODO: lots of possible exceptions that can be thrown here. Try da( // outside of a () block. -@@ -3423,6 +3434,8 @@ +@@ -3423,6 +3434,8 @@ export function initVim(CM) { cm.replaceSelection(text); } }, @@ -49,3 +50,19 @@ diff --git a/vim.js b/vim.js oneNormalCommand: function(cm, actionArgs, vim) { exitInsertMode(cm, true); vim.insertModeReturn = true; +@@ -5870,6 +5883,15 @@ export function initVim(CM) { + }; + } + } else { ++ // OpenIDEA: IdeaVim's `(id)` right-hand side runs the IDE action, as rc mappings do. ++ var ideAction = /^\(([^)\s]+)\)$/i.exec(rhs); ++ if (ideAction) { ++ /**@type {any} */ ++ var exMapping = { keys: lhs, type: 'keyToEx', exArgs: { input: 'action ' + ideAction[1] } }; ++ if (ctx) { exMapping.context = ctx; } ++ _mapCommand(exMapping); ++ return; ++ } + // Key to key or ex mapping + /**@type {vimKey} */ + var mapping = { diff --git a/plugins/README.md b/plugins/README.md index b241478ec0..2f75bb62b0 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -355,37 +355,37 @@ installing (or when a new version asks for more). Low-risk capabilities are listed; high-risk ones are called out as equivalent to running code on the machine. Users can revoke optional capabilities in Settings › Plugins. -| Capability | Risk | Unlocks today | -| ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. | -| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. | -| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations | -| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included | -| `fs.read:` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | -| `fs.write:` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | -| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` | -| `editor.write` | medium | `TextEditor::apply_edits` | -| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks | -| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` | -| `build.read` | low | API 1.10 (`build_dependencies`), API 1.21 (`sdks`, `artifacts`): Maven / Gradle dependency graph, installed SDKs/toolchains, and Project Structure artifacts; trusted projects only | -| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) | -| `events` | low | file opened/saved, editor focused, repository changed events | -| `events.input` | medium | `action-performed` and `input-mode-changed` events | -| `process:` | high | `Project::run_process`, language servers, debug adapters, runs | -| `lsp:` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only | -| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed | -| `net:` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | -| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 | -| `net.http:` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | -| `net:setting:` | medium | API 1.18: the host of the plugin's `string` setting `` over HTTPS (also loopback HTTP), approved when the user applies the value in Settings; bare host or URL | -| `net.http:setting:` | medium | API 1.18: the same setting's host over unencrypted HTTP, approved the same way | -| `ipc:` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 | -| `secrets` | medium | `{{secret:}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | -| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | -| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran | -| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only | -| `code.semantics` | low | API 1.21: `Project::lsp_definition`, `lsp_type_definition`, `lsp_implementations`, `lsp_references`, `lsp_hover_info`, `lsp_document_symbols`; trusted projects only | -| `run.output` | medium | API 1.21: `run-output` events with the stdout and stderr of runs and debug sessions; trusted projects only | +| Capability | Risk | Unlocks today | +| ------------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. | +| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. | +| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations | +| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included | +| `fs.read:` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | +| `fs.write:` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | +| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` | +| `editor.write` | medium | `TextEditor::apply_edits` | +| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks | +| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` | +| `build.read` | low | API 1.10 (`build_dependencies`), API 1.21 (`sdks`, `artifacts`): Maven / Gradle dependency graph, installed SDKs/toolchains, and Project Structure artifacts; trusted projects only | +| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) | +| `events` | low | file opened/saved, editor focused, repository changed events | +| `events.input` | medium | `action-performed` and `input-mode-changed` events | +| `process:` | high | `Project::run_process`, language servers, debug adapters, runs | +| `lsp:` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only | +| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed | +| `net:` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | +| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 | +| `net.http:` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | +| `net:setting:` | medium | API 1.18: the host of the plugin's `string` setting `` over HTTPS (also loopback HTTP), approved when the user applies the value in Settings; bare host or URL | +| `net.http:setting:` | medium | API 1.18: the same setting's host over unencrypted HTTP, approved the same way | +| `ipc:` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 | +| `secrets` | medium | `{{secret:}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | +| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | +| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran | +| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; API 1.21: `host::start_agent_task`, create an unsent task the user reviews and sends; trusted projects only | +| `code.semantics` | low | API 1.21: `Project::lsp_definition`, `lsp_type_definition`, `lsp_implementations`, `lsp_references`, `lsp_hover_info`, `lsp_document_symbols`; trusted projects only | +| `run.output` | medium | API 1.21: `run-output` events with the stdout and stderr of runs and debug sessions; trusted projects only | `process:` capabilities are also derived from what the contributions start: a language's `language-servers` and `debugger` commands and a run detector's @@ -487,6 +487,18 @@ matching SDK. Plugins for 1.20 and earlier keep working. New in 1.21: opens the IDE's Query Console with `sql` filled in, not run, and `Project::database_open_table_data(&table)` (`database.query`) opens a table's data grid; both only from a command the user invoked. +- **Hover-card actions (`decorations.set-actionable`).** + `host::set_actionable_decorations` draws the same items as + `set_styled_decorations` with up to 4 `actions` on each Markdown hover card. + An action runs one of the plugin's declared commands as if from Find Action + (the same budget and grants, no new capability) and closes the card. + Requires `project.read`. See [Editor decorations](#editor-and-project-snapshots-api-14). +- **Starting agent tasks (`agents.start-task`).** + `host::start_agent_task` creates a new task in the invoking window's project + and returns its id, unsent: it opens in the Agents window with the prompt + prefilled, focused, for the user to review and send. An optional `fork` + continues a recorded native session exactly like `fork_agent_session`. + Requires the `agents` capability and a trusted project. See _Forking agent sessions_. ### API 1.19 @@ -988,6 +1000,7 @@ then run `openidea-plugin check`. | `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | | `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. | | `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. | +| `host::set_actionable_decorations` | `decorations.set-actionable` | API 1.21: those items with up to 4 hover-card `actions` per item; each runs one of the plugin's declared commands as if from Find Action and closes the card. Shares set ids and limits with `set_decorations`. Requires `project.read`. | | `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | | `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. | | `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. | @@ -1066,6 +1079,7 @@ then run `openidea-plugin check`. | `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | | `host::open_settings(page)`, `open_permissions()` | `settings.open`, `settings.open-permissions` | API 1.19: Settings at the plugin's node (`None`) or one of its pages; at its permissions in Settings › Plugins. Commands and events only. | | `host::fork_agent_session(agent, session_id, cwd)` → `String` | `agents.fork-session` | API 1.18: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project, returning the new task id. Requires the `agents` capability and project trust; the session must belong to the project and have been recorded in `cwd`. The host builds the fork invocation; Claude forks under a host-chosen id, while Codex and Copilot assign their own. See _Forking agent sessions_. | +| `host::start_agent_task(task)` → `String` | `agents.start-task` | API 1.21: create a new task in the invoking window's project, returning its id. The task is unsent: it opens in the Agents window with the provider selected and the prompt prefilled, focused, for the user to review and send. `task.fork` continues a recorded session exactly like `fork-session`. Requires the `agents` capability and project trust. See _Forking agent sessions_. | `Project::symbols` reads the current in-memory index: results may be partial while indexing, and locations can lag unsaved edits. Normal saves and filesystem @@ -1382,6 +1396,15 @@ its purpose) and a trusted project. Without the grant the call returns `error::d An unknown session, a malformed id, a session another task already holds, or a `cwd` that does not match the recording is an invalid or not-found error, not a fork. +API 1.21 adds `host::start_agent_task(&NewTask)` (`agents.start-task`): a new task in the +invoking window's project, returning its id. The host does not send the prompt. The task is +created unsent and opens in the Agents window with the provider selected and the prompt in +its message field, focused, for the user to review and send. `NewTask` carries `provider`, +`prompt` and an optional `fork` (`RecordedSession { session_id, cwd }`); with `fork`, the +recorded session is validated and continued exactly as `fork_agent_session` does, the host +building the invocation itself. The same `agents` capability and a trusted project are +required; without the grant the call returns `error::denied`. + ### Database table menus and schema inspection (API 1.20) With `engines.openidea = "^1.20"`, contribute a command to @@ -1591,6 +1614,16 @@ labels when a file is opened or focused should subscribe to `file-opened`/`editor-focused` and call `clear_decorations` when its data no longer applies; the host already bounds what a set can carry. +API 1.21 adds `set_actionable_decorations`: those items plus `actions`, up to 4 buttons on +the Markdown hover card. Each action names one of the plugin's declared commands and runs it +exactly as if the user ran it from Find Action — the same budget and already-granted +capabilities, no new capability — then closes the card; an action whose document, project or +plugin snapshot changed since the card was placed (or last republished) does not run, and an +undeclared command fails the call. A `label` is 1–64 bytes without control characters, a +`tooltip` at most 256 bytes, an `argument` at most 4 KiB; `icon` is a registered icon name or +a declared manifest SVG path. Set ids, limits and `clear_decorations` are shared with +`set_decorations`. + The new Git reads run on the project machine, require a trusted open project and `vcs.read`, and disable repository-configured helpers, textconv and external diff programs. `vcs_log` returns commit ids, author/email, Unix seconds, subject/body @@ -1602,23 +1635,24 @@ log/blame return empty lists and diff returns `None`. ### Events -| Kind | Capability | Delivered | -| ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| `document-changed` | `events` | API 1.6: a committed local edit as versioned UTF-16 replacements; `subscribe-paths` only, also needs `project.read` and `editor.read` | -| `websocket-ready` | `events` | API 1.6: a bounded host-owned WebSocket has frames or a final close state to drain | -| `file-opened` | `events` | a file opens in an editor | -| `file-closed` | `events` | API 1.4, `Event::Other`: JSON path string | -| `settings-changed` | `events` | API 1.4, `Event::Other`: JSON array of this plugin's changed setting keys (effective values) | -| `extensions-changed` | — | API 1.5, `Event::Other`: JSON array of this plugin's extension points whose contributions changed | -| `input-mode-changed` | `events.input` | API 1.4, `Event::Other`: JSON `{path, mode, sub}` on focused Vim mode changes; `ctx.editor()` includes the document and current selections | -| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) | -| `file-saved` | `events` | after the file is written | -| `editor-focused` | `events` | the focused editor changes (path, or none) | -| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) | -| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut | -| `project-closed` | `events` | API 1.18: a project was closed or detached; JSON root path string (`Event::ProjectClosed`) | -| `watched-files-changed` | `events` | API 1.18: paths watched with `host::watch_paths` changed; JSON like `files-changed` with absolute paths (`Event::WatchedFilesChanged`) | -| `scheduled` | — | the `on-schedule` period elapsed | +| Kind | Capability | Delivered | +| ----------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `document-changed` | `events` | API 1.6: a committed local edit as versioned UTF-16 replacements; `subscribe-paths` only, also needs `project.read` and `editor.read` | +| `websocket-ready` | `events` | API 1.6: a bounded host-owned WebSocket has frames or a final close state to drain | +| `file-opened` | `events` | a file opens in an editor | +| `file-closed` | `events` | API 1.4, `Event::Other`: JSON path string | +| `settings-changed` | `events` | API 1.4, `Event::Other`: JSON array of this plugin's changed setting keys (effective values) | +| `extensions-changed` | — | API 1.5, `Event::Other`: JSON array of this plugin's extension points whose contributions changed | +| `input-mode-changed` | `events.input` | API 1.4, `Event::Other`: JSON `{path, mode, sub}` on focused Vim mode changes; `ctx.editor()` includes the document and current selections | +| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) | +| `file-saved` | `events` | after the file is written | +| `editor-focused` | `events` | the focused editor changes (path, or none) | +| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) | +| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut | +| `project-closed` | `events` | API 1.18: a project was closed or detached; JSON root path string (`Event::ProjectClosed`) | +| `watched-files-changed` | `events` | API 1.18: paths watched with `host::watch_paths` changed; JSON like `files-changed` with absolute paths (`Event::WatchedFilesChanged`) | +| `project-tree-expanded` | `events` | API 1.21: Project view folders expanded, as a JSON array of absolute paths (`Event::Other`); once with the folders already open when the plugin subscribes | +| `scheduled` | — | the `on-schedule` period elapsed | Events are batched: a running plugin gets them within a fraction of a second, an idle one collects them for 2 s before it is woken, so frequent events @@ -1900,7 +1934,13 @@ the tool that found them (`source`) and be `unnecessary` (faded) or `deprecated` (struck through). Editor providers run under the edit-path budget: 50 ms, after which the result is dropped, and an interruption at 500 ms. Every plugin providing a -kind is asked at the same time, so each has the whole budget. +kind is asked at the same time, so each has the whole budget. When a +plugin's `line-markers` call is dropped, the editor keeps the markers it +shows from that plugin until the next edit or plugin event asks it again. Saving +a file also asks `line-markers` again in the visible editors of the same +project root whose language a plugin declares along with the saved file's +(hidden tabs ask once shown), so markers built from other files follow their +saved changes. Providers run in the plugin's one instance, with its commands, events and views: they see the same memory (Checkstyle answers quick fixes from the diff --git a/plugins/indexing.md b/plugins/indexing.md index 9231d690db..5cb0a8a369 100644 --- a/plugins/indexing.md +++ b/plugins/indexing.md @@ -98,7 +98,7 @@ needed. Unindexed names continue through the normal language-server path. `crates/ide-plugin/tests/fixtures/indexer` uses a tiny line-oriented `.idx` language to exercise definitions, references, aliases, markers and host syntax symbols without framework-specific parsing. Run -`cargo test -p ide-host --test plugin_indexing` for the real-component contract +`cargo test -p ide-host --test integration plugin_indexing::` for the real-component contract checks. Framework plugins (MyBatis mappers, Rails routes) belong in their authors' diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 78041f906a..87e5612313 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index d0a2d90b43..4d2de62c27 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -3e7866964f867ec4fd847e7b696effd49c8f36fb31a12876b7668806d59ca8a6 +7c966d74c4758df4e9fb065d4735e8c3e75d5b4848cd62e5da0a0de86e1e02e3 diff --git a/plugins/official/blame-annotations/dist/plugin.wasm b/plugins/official/blame-annotations/dist/plugin.wasm index dd16f0ea46..cbcbc92e8a 100644 Binary files a/plugins/official/blame-annotations/dist/plugin.wasm and b/plugins/official/blame-annotations/dist/plugin.wasm differ diff --git a/plugins/official/blame-annotations/dist/plugin.wasm.sources b/plugins/official/blame-annotations/dist/plugin.wasm.sources index dfe497b7f1..3bf5352599 100644 --- a/plugins/official/blame-annotations/dist/plugin.wasm.sources +++ b/plugins/official/blame-annotations/dist/plugin.wasm.sources @@ -1 +1 @@ -f9c4ef18dee0bc1ef6f10ee7de914086f48955bb7c8c766bf7d5f820fc00ee6b +f1608c285cc7b05c7f87c11c3ccd6c081ea6b2d672be74ba5d33de7c02f0b4d2 diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index f53a052c0b..47a2f5a7b2 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index 6dadc7d969..4f21d06cde 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -7adb53310d5c347dccf65945536ca825562ea486706f79b62364e7026bb4e074 +49c55c6fc5c7d744f98b8245cd0621468065ddc5dbebe5830a19296580c0b992 diff --git a/plugins/official/container-runner/dist/plugin.wasm b/plugins/official/container-runner/dist/plugin.wasm index b581f94065..9146463721 100644 Binary files a/plugins/official/container-runner/dist/plugin.wasm and b/plugins/official/container-runner/dist/plugin.wasm differ diff --git a/plugins/official/container-runner/dist/plugin.wasm.sources b/plugins/official/container-runner/dist/plugin.wasm.sources index 9525590b7c..5e8f5776df 100644 --- a/plugins/official/container-runner/dist/plugin.wasm.sources +++ b/plugins/official/container-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -ed98a4280a18048ba20e585dd9ea1e3a192731c8e519de94c1432b215b49b89f +4233471bbcd4894562bae6f42a15d673ecefd0cef594c56a0cd9d72271858f52 diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index 8398657f05..0dbd3d8070 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index 6dcfe209d7..69ccd0afc9 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -e2a86c551d861792fa9e7b9568ad99b84ad3f09c55d759612a9260cf3d7efba5 +5b8703f5da0a33ad0067132c43048589e509f3db7b64a386922f0cd944ea45ea diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 2472ee21eb..4db1bc89eb 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 80f0930522..6b9147e9a7 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -a74e3a2c4dae028d8409f8163351406b24f3c121ba4507f8fd0ce01c194d4847 +29b302395d35f62c49e5420385a5757115f7c24305942f3728f880c3dd1b3d0b diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index 2b2d4f675f..bbf2ad46c9 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index a43f01c5cd..5d308f7f75 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -f288d0ad1b1400b9f2c815228beff8158a13a9dd14bf7cf16c2c9602f0dc7056 +e3f81f6af307310cb7bf85ee638d56d3658bb1ba5e04f193d79e7e1281090a50 diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 3a22b0eec2..4fc297203a 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 2a5c53b1bc..80275fd832 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -8a1e60ab4709ddd8fe5cb1a8fa314a557f08c9522a7572531d396b31d7eb0a22 +eaf8ab48e906e76be9c8429eeadd8d78fb7db008945f607a2a79888801d80b5c diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index a7e0d32745..be02fde1f3 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index 1f3a2e8283..4cdf5ab8df 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -c8b61627920cb28a08d119479344e566c248d903a74c14334d3d6d0ab3a64468 +ab57c636f84e2a05188212dac8850e027cdfaf9a3381d496fe782bfc323fda6a diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index 90b4e51bcc..1427a28047 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index ba47b5591a..30695f7bbe 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -9553096b2a5b19ea4e618d41b81aab6a8747050086e5564a83aecfb6de7c712f +04e1c8b82dd47b3508fdb9127b6d2383d3c6f9b373d3e246234d310388eb40ed diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index 2048c12cbe..e989c5343f 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index c39b8d8cc7..3e7dd62fb8 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -5980d1198ab329b7b6d3334731edae5d50ffce97808cf9b75f16632e59f695ec +0a85e5ea65161bf383ca65d9da77bd79605fe918b447ce4d95e3cd33216c2787 diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index 428def233c..a869df6318 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index 0aa839e494..50ea6c2952 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -191e8a8ba6cd999a4710213614d16181b758a5df558660fe675224e30edc31a1 +0cc683874a8a88d3dc44716226b5a1d78ddec8eb901594d88c672d54af4e86de diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 907ad5e98c..2e6f720260 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index 397fe97b81..492a0e0d21 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -2bdcbe047cdd07e3c8975b0e05e7ea78c6518fe94d3142dfa33373bcb30c0e51 +b00539a0cef710e9feaf8cc139d66cd5acdefe1dab44f64c562754424bbdaa31 diff --git a/plugins/official/test-runner/dist/plugin.wasm b/plugins/official/test-runner/dist/plugin.wasm index 9d40b91083..8afabfdcbc 100644 Binary files a/plugins/official/test-runner/dist/plugin.wasm and b/plugins/official/test-runner/dist/plugin.wasm differ diff --git a/plugins/official/test-runner/dist/plugin.wasm.sources b/plugins/official/test-runner/dist/plugin.wasm.sources index 6a042f6b46..62a2291b98 100644 --- a/plugins/official/test-runner/dist/plugin.wasm.sources +++ b/plugins/official/test-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -63b437b09447b7f04ba9b485933f57a6f51f5fe3357ea7b9b7230f16f3e1c2b3 +f5eba6aa5baafc58a0ae991f4fd9578dea711471776668b32662d627e56a0c83 diff --git a/plugins/official/todo-finder/dist/plugin.wasm b/plugins/official/todo-finder/dist/plugin.wasm index dc1c9385f1..d35b09901d 100644 Binary files a/plugins/official/todo-finder/dist/plugin.wasm and b/plugins/official/todo-finder/dist/plugin.wasm differ diff --git a/plugins/official/todo-finder/dist/plugin.wasm.sources b/plugins/official/todo-finder/dist/plugin.wasm.sources index c0bcb02093..f134cfeff3 100644 --- a/plugins/official/todo-finder/dist/plugin.wasm.sources +++ b/plugins/official/todo-finder/dist/plugin.wasm.sources @@ -1 +1 @@ -d2e1849d41277e3dbda7b2775ebf5da6d122ab5e766ddcf004000be7ba75d39c +9e12617c9b036e9be4a9024ea70d6aaff05fed104e1d02267a9d73ede3b24b9f diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a22fe42c57..ab51f4f900 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,9 +9,9 @@ overrides: patchedDependencies: '@codemirror/language@6.13.1': eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc - '@codemirror/view': bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589 + '@codemirror/view': 3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e '@lezer/lr': 1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8 - '@replit/codemirror-vim-core@0.1.0': 9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263 + '@replit/codemirror-vim-core@0.1.0': e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f importers: @@ -73,7 +73,7 @@ importers: version: 6.7.6 '@codemirror/view': specifier: ^6.44.2 - version: 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + version: 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@floating-ui/react-dom': specifier: ^2.1.9 version: 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -109,7 +109,7 @@ importers: version: 1.2.0 '@replit/codemirror-vim': specifier: 6.4.0 - version: 6.4.0(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc))(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589)) + version: 6.4.0(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc))(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e)) '@tanstack/react-virtual': specifier: ^3.14.21 version: 3.14.21(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -2982,14 +2982,14 @@ snapshots: dependencies: '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@codemirror/commands@6.11.1': dependencies: '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@codemirror/lang-angular@0.1.4': @@ -3029,7 +3029,7 @@ snapshots: '@codemirror/lang-javascript': 6.2.5 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/css': 1.3.9 '@lezer/html': 1.3.13 @@ -3045,7 +3045,7 @@ snapshots: '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/lint': 6.9.7 '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/javascript': 1.5.6 @@ -3055,7 +3055,7 @@ snapshots: '@codemirror/lang-html': 6.4.12 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8) @@ -3079,7 +3079,7 @@ snapshots: '@codemirror/lang-html': 6.4.12 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8) @@ -3090,7 +3090,7 @@ snapshots: '@codemirror/lang-html': 6.4.12 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/markdown': 1.8.0 @@ -3153,7 +3153,7 @@ snapshots: '@codemirror/autocomplete': 6.20.3 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/xml': 1.0.6 @@ -3197,7 +3197,7 @@ snapshots: dependencies: '@codemirror/state': 6.7.6 '@codemirror/streamparser': 6.0.0 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/common': 1.5.6 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8) @@ -3210,21 +3210,21 @@ snapshots: '@codemirror/lint@6.9.7': dependencies: '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) crelt: 1.0.7 '@codemirror/merge@6.12.2': dependencies: '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) '@lezer/highlight': 1.2.5 style-mod: 4.1.4 '@codemirror/search@6.7.2': dependencies: '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) crelt: 1.0.7 '@codemirror/state@6.7.6': @@ -3233,7 +3233,7 @@ snapshots: '@codemirror/streamparser@6.0.0': {} - '@codemirror/view@6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589)': + '@codemirror/view@6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e)': dependencies: '@codemirror/state': 6.7.6 crelt: 1.0.7 @@ -3752,16 +3752,16 @@ snapshots: '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8) - '@replit/codemirror-vim-core@0.1.0(patch_hash=9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263)': {} + '@replit/codemirror-vim-core@0.1.0(patch_hash=e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f)': {} - '@replit/codemirror-vim@6.4.0(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc))(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589))': + '@replit/codemirror-vim@6.4.0(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc))(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e))': dependencies: '@codemirror/commands': 6.11.1 '@codemirror/language': 6.13.1(patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc) '@codemirror/search': 6.7.2 '@codemirror/state': 6.7.6 - '@codemirror/view': 6.44.2(patch_hash=bcc394e0b3a7448b934ebb02620609bd95feb4ef66112bc6aad0a23ef0af3589) - '@replit/codemirror-vim-core': 0.1.0(patch_hash=9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263) + '@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e) + '@replit/codemirror-vim-core': 0.1.0(patch_hash=e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f) '@rolldown/binding-android-arm-eabi@1.2.14': optional: true diff --git a/scripts/smoke-paths.test.ts b/scripts/smoke-paths.test.ts index 38e4670d6c..6b3138691c 100644 --- a/scripts/smoke-paths.test.ts +++ b/scripts/smoke-paths.test.ts @@ -9,6 +9,7 @@ import { describeUnselected, filterPattern, importClosure, + matchesPathFilters, readWorkflow, rustSmokeInputs, selectedLanguages, @@ -130,6 +131,19 @@ describe("GitHub path filters", () => { expect(filterPattern("package.json").test("packageXjson")).toBe(false); }); + it("evaluates negated filters in order like GitHub Actions", () => { + const globs = [ + "src/platform/**", + "!src/platform/locales/text/**", + "!src/platform/locales/*.json", + "src/platform/locales/en.json", + ]; + expect(matchesPathFilters(globs, "src/platform/ipc.ts")).toBe(true); + expect(matchesPathFilters(globs, "src/platform/locales/text/en.json")).toBe(false); + expect(matchesPathFilters(globs, "src/platform/locales/zh.json")).toBe(false); + expect(matchesPathFilters(globs, "src/platform/locales/en.json")).toBe(true); + }); + it("refuse syntax the check does not model", () => { expect(() => filterPattern("!src/**")).toThrow(); expect(() => filterPattern("src/?.ts")).toThrow(); diff --git a/scripts/smoke-paths.ts b/scripts/smoke-paths.ts index 0fc55a8ada..a43475733d 100644 --- a/scripts/smoke-paths.ts +++ b/scripts/smoke-paths.ts @@ -242,6 +242,17 @@ export function filterPattern(glob: string): RegExp { ); } +/** GitHub Actions evaluates `paths` in order: positive globs include, `!` globs exclude. */ +export function matchesPathFilters(globs: string[], path: string): boolean { + let matched = false; + for (const glob of globs) { + const negated = glob.startsWith("!"); + const pattern = filterPattern(negated ? glob.slice(1) : glob); + if (pattern.test(path)) matched = !negated; + } + return matched; +} + /** The test files the workflow's `pnpm smoke` steps run. */ export function smokeTestFiles(workflow: Workflow): string[] { const files = new Set(); @@ -346,9 +357,9 @@ export async function unselected(workflow: Workflow, paths: string[]): Promise(); const flag = (path: string, reason: string) => reasons.set(path, [...(reasons.get(path) ?? []), reason]); for (const event of ["pull_request", "push"]) { - const filters = workflow.on[event]?.paths?.map(filterPattern); - if (!filters) continue; - for (const path of paths) if (!filters.some((filter) => filter.test(path))) flag(path, `not in on.${event}.paths`); + const globs = workflow.on[event]?.paths; + if (!globs) continue; + for (const path of paths) if (!matchesPathFilters(globs, path)) flag(path, `not in on.${event}.paths`); } const { all, smoke, unused } = await changesPatterns(workflow, paths); @@ -408,6 +419,16 @@ export async function smokeInputs(root: string, workflow: Workflow): Promise(); @@ -495,9 +516,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1] const workflow = readWorkflow(root); const asked = process.argv.slice(2); if (asked.length) { - const filters = workflow.on.pull_request?.paths?.map(filterPattern); + const globs = workflow.on.pull_request?.paths; for (const [path, languages] of await selectedLanguages(workflow, asked)) { - const triggered = !filters || filters.some((filter) => filter.test(path)); + const triggered = !globs || matchesPathFilters(globs, path); console.log(`${path}: ${triggered ? languages.join(" ") || "no language" : "not in on.pull_request.paths"}`); } } else { diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 2850de09c5..83a22be0a1 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -527,6 +527,34 @@ mod imp { .collect::>(); wit::decorations::set_styled(path, set, &items).map_err(error) } + pub fn set_actionable_decorations(path: &str, set: &str, items: &[ActionableDecoration]) -> Result<(), Error> { + let items = items + .iter() + .map(|d| wit::decorations::ActionableDecoration { + range: range_out(d.range), + style: d.style.clone(), + hover: d.hover.clone(), + after: d.after.clone(), + markdown_hover: d.markdown_hover.clone(), + colors: d.colors.as_ref().map(|c| wit::decorations::DecorationColors { + foreground: c.foreground.clone(), + background: c.background.clone(), + }), + actions: d + .actions + .iter() + .map(|a| wit::types::CardAction { + icon: a.icon.clone(), + label: a.label.clone(), + tooltip: a.tooltip.clone(), + command: a.command.clone(), + argument: a.argument.clone(), + }) + .collect(), + }) + .collect::>(); + wit::decorations::set_actionable(path, set, &items).map_err(error) + } pub fn clear_decorations(set: &str) -> Result<(), Error> { wit::decorations::clear(set).map_err(error) } @@ -685,6 +713,14 @@ mod imp { wit::events::unsubscribe(k.name()) } + pub fn schedule(id: &str, after_ms: u32) -> Result<(), Error> { + wit::events::schedule(id, after_ms).map_err(error) + } + + pub fn cancel_schedule(id: &str) { + wit::events::cancel_schedule(id) + } + pub fn begin_task(title: &str, cancellable: bool) -> TaskRes { wit::tasks::begin(title, cancellable) } @@ -1421,6 +1457,17 @@ mod imp { pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result { wit::agents::fork_session(agent, session_id, cwd).map_err(error) } + pub fn start_agent_task(task: &NewTask) -> Result { + wit::agents::start_task(&wit::agents::NewTask { + provider: task.provider.clone(), + prompt: task.prompt.clone(), + fork: task + .fork + .as_ref() + .map(|f| wit::agents::RecordedSession { session_id: f.session_id.clone(), cwd: f.cwd.clone() }), + }) + .map_err(error) + } pub fn run_process( program: &str, @@ -2457,6 +2504,24 @@ pub fn watch_paths(paths: &[&str]) -> Result<(), Error> { imp::watch_paths(paths) } +/// Wakes this plugin once, `after_ms` milliseconds from now (API 1.21): an +/// [`crate::Event::Timer`] with `id` arrives in the window of the call that set it. +/// Setting an `id` again replaces it, so backoff is the plugin's own: set the next +/// delay when the timer fires. An idle plugin is activated for it. +/// +/// `after_ms` is 250 to 86,400,000 (a day); `id` is 1-128 bytes without control +/// characters; at most 16 timers are pending per plugin (`Invalid` past that). Timers +/// end when they fire, on [`cancel_schedule`], when the window closes, or when the +/// plugin stops; idle reclaim keeps them. Needs no capability. +pub fn schedule(id: &str, after_ms: u32) -> Result<(), Error> { + imp::schedule(id, after_ms) +} + +/// Cancels the pending [`schedule`] timer `id` (API 1.21); an unknown id does nothing. +pub fn cancel_schedule(id: &str) { + imp::cancel_schedule(id) +} + /// Files outside the open projects, for a program the plugin integrates with /// or a tool installed elsewhere. Outside [`fs::plugin_dir`] and the plugin's /// install directory (read-only), paths need an `fs.read:` (reading) or @@ -2718,6 +2783,13 @@ pub fn set_markdown_decorations(path: &str, set: &str, items: &[MarkdownDecorati pub fn set_styled_decorations(path: &str, set: &str, items: &[StyledDecoration]) -> Result<(), Error> { imp::set_styled_decorations(path, set, items) } +/// Replace a file's editor decorations with items whose Markdown hover cards carry action +/// buttons (API 1.21). Each action runs one of this plugin's declared commands as if from +/// Find Action and closes the card; an undeclared command fails the call. +/// Requires project.read; the same limits and set ids as [`set_decorations`]. +pub fn set_actionable_decorations(path: &str, set: &str, items: &[ActionableDecoration]) -> Result<(), Error> { + imp::set_actionable_decorations(path, set, items) +} /// Clear this plugin's editor decoration set in all projects. Requires project.read. pub fn clear_decorations(set: &str) -> Result<(), Error> { imp::clear_decorations(set) @@ -2852,3 +2924,14 @@ pub fn extension_contributions(point: &str) -> Result, pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result { imp::fork_agent_session(agent, session_id, cwd) } +/// Start a new agent task in the invoking window's project, returning its id (API 1.21). +/// Requires the `agents` capability and an invoking window. The host does NOT send the +/// prompt: the task opens in the Agents window with the provider selected and the prompt +/// in its message field, focused, for the user to review and send. With `fork`, the +/// recorded session is validated and continued exactly as [`fork_agent_session`] does; +/// the host builds the invocation, so a plugin never supplies the agent's command line. +/// Without `fork`, the prompt must be non-empty. +/// Needs `engines.openidea = "^1.21"`. +pub fn start_agent_task(task: &NewTask) -> Result { + imp::start_agent_task(task) +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index 84af0aa527..a48de5d2a0 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -144,6 +144,8 @@ struct State { project_generations: BTreeMap, debounce_ms: BTreeMap, watched_paths: Vec, + /// Pending [`crate::host::schedule`] timers: id → delay in milliseconds. + timers: BTreeMap, tasks: Vec, vcs: Option, repositories: Vec, @@ -180,6 +182,7 @@ struct State { decorations: BTreeMap<(String, String), Vec>, markdown_decorations: BTreeMap<(String, String), Vec>, styled_decorations: BTreeMap<(String, String), Vec>, + actionable_decorations: BTreeMap<(String, String), Vec>, file_decorations: BTreeMap<(String, String), FileDecoration>, file_notes: BTreeMap<(String, String), (String, Option)>, file_icons: BTreeMap<(String, String), (String, Option)>, @@ -241,6 +244,8 @@ struct State { opened_edit_configs: Vec>, /// `(agent, session_id, cwd)` of each `fork_agent_session` call. agent_forks: Vec<(String, String, String)>, + /// Each `start_agent_task` call's task (API 1.21). + agent_tasks: Vec, log_tabs: Vec, locations: Vec<(String, u32, u32)>, settings: BTreeMap, @@ -419,6 +424,9 @@ impl MockHost { pub fn styled_decorations(&self) -> BTreeMap<(String, String), Vec> { self.state.borrow().styled_decorations.clone() } + pub fn actionable_decorations(&self) -> BTreeMap<(String, String), Vec> { + self.state.borrow().actionable_decorations.clone() + } /// Tree decoration snapshots keyed by (set id, absolute path). pub fn file_decorations(&self) -> BTreeMap<(String, String), FileDecoration> { self.state.borrow().file_decorations.clone() @@ -658,6 +666,17 @@ impl MockHost { self.state.borrow().watched_paths.clone() } + /// The pending [`crate::host::schedule`] timers: id → the delay they were set with. + pub fn timers(&self) -> BTreeMap { + self.state.borrow().timers.clone() + } + + /// Fires timer `id` as the IDE would: it is no longer pending, and the event to hand + /// to the plugin's handler is returned (`None` when no such timer is pending). + pub fn fire_timer(&self, id: &str) -> Option { + self.state.borrow_mut().timers.remove(id).map(|_| crate::Event::Timer(id.to_owned())) + } + pub fn subscriptions(&self) -> BTreeSet { self.state.borrow().subscriptions.clone() } @@ -928,6 +947,10 @@ impl MockHost { pub fn agent_forks(&self) -> Vec<(String, String, String)> { self.state.borrow().agent_forks.clone() } + /// Recorded `start_agent_task` calls (API 1.21). + pub fn agent_tasks(&self) -> Vec { + self.state.borrow().agent_tasks.clone() + } /// Makes the language server `server` run and answer `method` with `result` (JSON). /// A server with no answer set is not running: requests to it are not-found. pub fn set_language_server_response(&self, server: &str, method: &str, result: &str) { @@ -2161,8 +2184,8 @@ pub mod current { | "muted" ) } - /// Plain, Markdown and styled sets share the set-id namespace and the per-file limit: the last - /// call for a (set, path) replaces whichever kind was there. + /// Plain, Markdown, styled and actionable sets share the set-id namespace and the per-file + /// limit: the last call for a (set, path) replaces whichever kind was there. fn replace_decorations( s: &mut State, set: &str, @@ -2173,22 +2196,30 @@ pub mod current { map.iter().filter(|((_, p), _)| p == path).map(|(_, i)| i.len()).sum() } let key = (set.to_owned(), path.to_owned()); - let saved = (s.decorations.clone(), s.markdown_decorations.clone(), s.styled_decorations.clone()); + let saved = ( + s.decorations.clone(), + s.markdown_decorations.clone(), + s.styled_decorations.clone(), + s.actionable_decorations.clone(), + ); s.decorations.remove(&key); s.markdown_decorations.remove(&key); s.styled_decorations.remove(&key); + s.actionable_decorations.remove(&key); insert(s, key); let names = (s.decorations.keys()) .chain(s.markdown_decorations.keys()) .chain(s.styled_decorations.keys()) + .chain(s.actionable_decorations.keys()) .map(|(set, _)| set) .collect::>() .len(); let count = per_file(&s.decorations, path) + per_file(&s.markdown_decorations, path) - + per_file(&s.styled_decorations, path); + + per_file(&s.styled_decorations, path) + + per_file(&s.actionable_decorations, path); if set.is_empty() || set.len() > 128 || names > 50 || count > 10_000 { - (s.decorations, s.markdown_decorations, s.styled_decorations) = saved; + (s.decorations, s.markdown_decorations, s.styled_decorations, s.actionable_decorations) = saved; return Err(Error::Invalid("decoration limit".into())); } Ok(()) @@ -2243,12 +2274,53 @@ pub mod current { }) }) } + /// The host's checks, except that the commands are declared (the mock has no manifest). + pub fn set_actionable_decorations(path: &str, set: &str, items: &[ActionableDecoration]) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + let path = decoration_path(s, path)?; + let mut kept = Vec::new(); + for item in items { + let mut item = item.clone(); + if let Some(c) = &mut item.colors { + c.foreground = c.foreground.as_deref().map(color).transpose()?; + c.background = c.background.as_deref().map(color).transpose()?; + } + item.colors = item.colors.filter(|c| c.foreground.is_some() || c.background.is_some()); + check_card_actions(&item.actions)?; + if style(&item.style) || (item.style.is_empty() && item.colors.is_some()) { + kept.push(item); + } + } + replace_decorations(s, set, &path, |s, key| { + s.actionable_decorations.insert(key, kept); + }) + }) + } + fn check_card_actions(actions: &[CardAction]) -> Result<(), Error> { + if actions.len() > 4 { + return Err(Error::Invalid("at most 4 actions per decoration".into())); + } + for a in actions { + if a.label.is_empty() || a.label.len() > 64 || a.label.chars().any(char::is_control) { + return Err(Error::Invalid("action label must be 1-64 bytes without control characters".into())); + } + if a.tooltip.as_ref().is_some_and(|t| t.len() > 256) { + return Err(Error::Invalid("action tooltip is at most 256 bytes".into())); + } + if a.argument.as_ref().is_some_and(|s| s.len() > 4096) { + return Err(Error::Invalid("action argument is at most 4 KiB".into())); + } + } + Ok(()) + } pub fn clear_decorations(set: &str) -> Result<(), Error> { with(|s| { require(s, "project.read")?; s.decorations.retain(|(id, _), _| id != set); s.markdown_decorations.retain(|(id, _), _| id != set); s.styled_decorations.retain(|(id, _), _| id != set); + s.actionable_decorations.retain(|(id, _), _| id != set); Ok(()) }) } @@ -2619,6 +2691,28 @@ pub mod current { }); } + pub fn schedule(id: &str, after_ms: u32) -> Result<(), Error> { + with(|s| { + if id.is_empty() || id.len() > 128 || id.chars().any(char::is_control) { + return Err(Error::Invalid("timer id must be 1-128 bytes without control characters".into())); + } + if !(250..=86_400_000).contains(&after_ms) { + return Err(Error::Invalid("a timer fires 250 ms to 86400000 ms from now".into())); + } + if !s.timers.contains_key(id) && s.timers.len() >= 16 { + return Err(Error::Invalid("at most 16 timers may be pending: cancel one first".into())); + } + s.timers.insert(id.to_owned(), after_ms); + Ok(()) + }) + } + + pub fn cancel_schedule(id: &str) { + with(|s| { + s.timers.remove(id); + }); + } + pub fn project_find(p: &ProjectRes, glob: &str, limit: u32) -> Result, Error> { with(|s| { require(s, "project.read")?; @@ -3335,6 +3429,14 @@ pub mod current { Ok(id) }) } + pub fn start_agent_task(task: &NewTask) -> Result { + with(|s| { + require(s, "agents")?; + let id = format!("mock-agent-task-{}", s.agent_tasks.len()); + s.agent_tasks.push(task.clone()); + Ok(id) + }) + } pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> { register_run_target_with_overrides(project, &target.clone().into()) diff --git a/sdk/rust/openidea-plugin/src/types.rs b/sdk/rust/openidea-plugin/src/types.rs index 693f32cba7..b68a4ab298 100644 --- a/sdk/rust/openidea-plugin/src/types.rs +++ b/sdk/rust/openidea-plugin/src/types.rs @@ -440,6 +440,9 @@ pub enum EventKind { ProjectClosed, /// Paths watched with [`crate::host::watch_paths`] changed (`Event::WatchedFilesChanged`, API 1.18). WatchedFilesChanged, + /// Project tree folders newly expanded, or already expanded when the plugin subscribes + /// (`Event::Other` `"project-tree-expanded"`, a JSON array of absolute paths; API 1.21). + ProjectTreeExpanded, } impl EventKind { @@ -467,6 +470,7 @@ impl EventKind { Self::ProblemsChanged => "problems-changed", Self::ProjectClosed => "project-closed", Self::WatchedFilesChanged => "watched-files-changed", + Self::ProjectTreeExpanded => "project-tree-expanded", Self::Scheduled => "scheduled", } } @@ -616,6 +620,8 @@ pub enum Event { VcsChanged(String), /// The `on-schedule` period elapsed. Scheduled, + /// A timer set with [`crate::host::schedule`] fired (API 1.21): its id. + Timer(String), /// A project was closed (or its window closed): the project root path. ProjectClosed(String), /// Paths watched with [`crate::host::watch_paths`] changed (API 1.18): absolute @@ -903,6 +909,11 @@ impl Event { { return Self::WatchedFilesChanged(batch); } + if kind == "timer" + && let Ok(id) = serde_json::from_str(&data) + { + return Self::Timer(id); + } Self::Other { kind, data } } } @@ -978,6 +989,45 @@ pub struct StyledDecoration { pub markdown_hover: Option, pub colors: Option, } +/// A hover-card action button (API 1.21): runs one of this plugin's declared commands +/// as if the user ran it from Find Action, then closes the card. No new capability. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CardAction { + pub icon: Option, + pub label: String, + pub tooltip: Option, + pub command: String, + pub argument: Option, +} +/// An editor annotation with its own colors and hover-card actions (API 1.21). +/// Like [`StyledDecoration`], with buttons rendered on the Markdown hover card. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActionableDecoration { + pub range: Range, + pub style: String, + pub hover: Option, + pub after: Option, + pub markdown_hover: Option, + pub colors: Option, + pub actions: Vec, +} +/// A recorded native session to continue as a fork (API 1.21). The host validates it and +/// builds the fork invocation itself, like `fork_agent_session`; a plugin never puts +/// tokens on an agent's command line. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordedSession { + pub session_id: String, + pub cwd: String, +} +/// A new task a plugin starts (API 1.21). The host does NOT send the prompt: the task opens +/// in the Agents window with the provider selected and the prompt in its message field, +/// focused, for the user to review and send. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NewTask { + pub provider: String, + pub prompt: String, + pub fork: Option, +} /// A project-tree annotation. Badge is at most two Unicode characters. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FileDecoration { diff --git a/sdk/rust/openidea-plugin/tests/api21_card_actions.rs b/sdk/rust/openidea-plugin/tests/api21_card_actions.rs new file mode 100644 index 0000000000..ba9b32dfef --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api21_card_actions.rs @@ -0,0 +1,114 @@ +use openidea_plugin::{ActionableDecoration, CardAction, Error, Range, StyledDecoration, host, mock::MockHost}; + +fn actionable(command: &str) -> ActionableDecoration { + ActionableDecoration { + range: Range::default(), + style: "highlight".into(), + hover: None, + after: None, + markdown_hover: Some("**recorded**".into()), + colors: None, + actions: vec![CardAction { + icon: None, + label: "Continue".into(), + tooltip: None, + command: command.into(), + argument: None, + }], + } +} + +#[test] +fn actionable_decorations_carry_card_actions_and_need_project_read() { + let mock = MockHost::install(); + host::set_actionable_decorations("a.txt", "handoff", &[actionable("continue")]).unwrap(); + let items = mock.actionable_decorations().into_values().next().unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(items[0].actions[0].command, "continue"); + assert_eq!(items[0].actions[0].label, "Continue"); + assert_eq!(items[0].markdown_hover.as_deref(), Some("**recorded**")); + let _mock = mock.with_capabilities(&[]); + assert!(matches!( + host::set_actionable_decorations("a.txt", "handoff", &[]), + Err(Error::Denied(c)) if c == "project.read" + )); +} + +#[test] +fn actionable_decoration_bounds_are_enforced() { + let mock = MockHost::install(); + host::set_actionable_decorations("a.txt", "handoff", &[actionable("continue")]).unwrap(); + let before = mock.actionable_decorations(); + + let base = actionable("continue"); + let mut five = base.clone(); + five.actions = vec![base.actions[0].clone(); 5]; + let mut empty_label = base.clone(); + empty_label.actions[0].label = String::new(); + let mut big_label = base.clone(); + big_label.actions[0].label = "x".repeat(65); + let mut wide_label = base.clone(); + wide_label.actions[0].label = "é".repeat(33); // 66 bytes, 33 chars: the bound is bytes + let mut control_label = base.clone(); + control_label.actions[0].label = "Go\u{85}".into(); + let mut big_tooltip = base.clone(); + big_tooltip.actions[0].tooltip = Some("t".repeat(257)); + let mut big_arg = base.clone(); + big_arg.actions[0].argument = Some("x".repeat(4097)); + for bad in [five, empty_label, big_label, wide_label, control_label, big_tooltip, big_arg] { + assert!(host::set_actionable_decorations("a.txt", "handoff", &[bad]).is_err()); + assert_eq!(mock.actionable_decorations(), before, "a rejected call changes nothing"); + } + + // A rejected call must not withdraw another kind sharing the set id either. + let styled = StyledDecoration { + range: Range::default(), + style: "highlight".into(), + hover: None, + after: None, + markdown_hover: None, + colors: None, + }; + host::set_styled_decorations("a.txt", "todo", &[styled]).unwrap(); + let mut bad = base.clone(); + bad.actions[0].label = String::new(); + assert!(host::set_actionable_decorations("a.txt", "todo", &[bad]).is_err()); + assert_eq!(mock.styled_decorations().len(), 1); + + // Exactly at the bounds is accepted: 4 actions, 64 label bytes, 256 tooltip bytes, 4 KiB argument. + let mut max = base; + max.actions = vec![ + CardAction { + icon: None, + label: "é".repeat(32), + tooltip: Some("t".repeat(256)), + command: "continue".into(), + argument: Some("x".repeat(4096)), + }; + 4 + ]; + host::set_actionable_decorations("a.txt", "handoff", &[max]).unwrap(); +} + +#[test] +fn actionable_sets_share_ids_and_limits_with_other_sets() { + let mock = MockHost::install(); + let styled = StyledDecoration { + range: Range::default(), + style: "highlight".into(), + hover: None, + after: None, + markdown_hover: None, + colors: None, + }; + host::set_styled_decorations("a.txt", "todo", &[styled]).unwrap(); + host::set_actionable_decorations("a.txt", "todo", &[actionable("continue")]).unwrap(); + assert!(mock.styled_decorations().is_empty(), "the last call for a set id wins"); + assert_eq!(mock.actionable_decorations().len(), 1); + for i in 0..49 { + host::set_decorations("a.txt", &format!("set{i}"), &[]).unwrap(); + } + assert!(host::set_actionable_decorations("a.txt", "overflow", &[]).is_err()); + host::clear_decorations("todo").unwrap(); + assert!(mock.actionable_decorations().is_empty()); +} diff --git a/sdk/rust/openidea-plugin/tests/api21_schedule.rs b/sdk/rust/openidea-plugin/tests/api21_schedule.rs new file mode 100644 index 0000000000..8e4a57a4e2 --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api21_schedule.rs @@ -0,0 +1,33 @@ +use openidea_plugin::{Error, Event, host, mock::MockHost}; + +#[test] +fn schedule_replaces_cancels_and_fires_once() { + let mock = MockHost::install(); + // No capability: a plugin only wakes itself. + host::schedule("retry", 2_000).unwrap(); + host::schedule("poll", 250).unwrap(); + // The same id again replaces it: the plugin paces its own backoff. + host::schedule("retry", 4_000).unwrap(); + assert_eq!(mock.timers(), [("poll".to_owned(), 250), ("retry".to_owned(), 4_000)].into()); + + host::cancel_schedule("poll"); + host::cancel_schedule("unknown"); + assert_eq!(mock.timers().len(), 1); + assert_eq!(mock.fire_timer("retry"), Some(Event::Timer("retry".into()))); + assert_eq!(mock.fire_timer("retry"), None, "a timer fires once"); + assert_eq!(Event::from_other("timer".into(), "\"retry\"".into()), Event::Timer("retry".into())); +} + +#[test] +fn schedule_bounds() { + let mock = MockHost::install(); + for (id, after) in [("", 1_000), ("a\nb", 1_000), (&*"x".repeat(129), 1_000), ("ok", 249), ("ok", 86_400_001)] { + assert!(matches!(host::schedule(id, after), Err(Error::Invalid(_))), "{id:?} {after}"); + } + for i in 0..16 { + host::schedule(&format!("t{i}"), 1_000).unwrap(); + } + assert!(matches!(host::schedule("t16", 1_000), Err(Error::Invalid(_)))); + host::schedule("t0", 86_400_000).unwrap(); + assert_eq!(mock.timers().len(), 16); +} diff --git a/sdk/rust/openidea-plugin/tests/api21_start_task.rs b/sdk/rust/openidea-plugin/tests/api21_start_task.rs new file mode 100644 index 0000000000..d5ca073721 --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api21_start_task.rs @@ -0,0 +1,34 @@ +use openidea_plugin::{Error, NewTask, RecordedSession, host, mock::MockHost}; + +#[test] +fn start_task_needs_agents_and_returns_a_task_id() { + let mock = MockHost::install().with_capabilities(&[]); + let task = NewTask { provider: "claude".into(), prompt: "investigate this".into(), fork: None }; + assert!(matches!(host::start_agent_task(&task), Err(Error::Denied(c)) if c == "agents")); + let mock = mock.with_capabilities(&["agents"]); + let id = host::start_agent_task(&task).unwrap(); + assert!(!id.is_empty(), "start-task returns the new task id"); + let recorded = mock.agent_tasks(); + assert_eq!(recorded.len(), 1); + assert_eq!(recorded[0].provider, "claude"); + assert_eq!(recorded[0].prompt, "investigate this"); + assert!(recorded[0].fork.is_none()); +} + +#[test] +fn start_task_carries_a_recorded_session_fork() { + let mock = MockHost::install(); + let task = NewTask { + provider: "claude".into(), + prompt: "continue the recording".into(), + fork: Some(RecordedSession { + session_id: "11111111-1111-4111-8111-111111111111".into(), + cwd: "/project".into(), + }), + }; + host::start_agent_task(&task).unwrap(); + let recorded = mock.agent_tasks(); + let fork = recorded[0].fork.as_ref().unwrap(); + assert_eq!(fork.session_id, "11111111-1111-4111-8111-111111111111"); + assert_eq!(fork.cwd, "/project"); +} diff --git a/sdk/rust/openidea-plugin/wit/agents.wit b/sdk/rust/openidea-plugin/wit/agents.wit index b5d9918262..86684d3f78 100644 --- a/sdk/rust/openidea-plugin/wit/agents.wit +++ b/sdk/rust/openidea-plugin/wit/agents.wit @@ -11,4 +11,28 @@ interface agents { /// new task id. `cwd` must be where the session was recorded. The first /// turn continues the recording as the agent's own fork. fork-session: func(agent: string, session-id: string, cwd: string) -> result; + /// A recorded native session to continue as a fork (API 1.21). The host validates + /// it and builds the fork invocation itself, like `fork-session`; a plugin never + /// puts tokens on an agent's command line. + record recorded-session { + /// The recorded session's id; the task's provider must be the agent that recorded it. + session-id: string, + /// Where it was recorded (same rule as fork-session). + cwd: string, + } + /// A new task a plugin starts (API 1.21). The host does NOT send the prompt: the + /// task opens in the Agents window with the provider selected and the prompt in + /// its message field, focused, for the user to review and send. + record new-task { + provider: string, + /// Without `fork`, must be non-empty; the host rejects an empty prompt. + prompt: string, + /// Continue a recorded native session as a fork, like fork-session. + fork: option, + } + /// Start a new task in the invoking window's project and return its id (API 1.21). + /// Requires the `agents` capability. The task is created unsent; the user reviews + /// the prompt in the Agents window and sends it. With `fork`, the recorded session + /// is validated and continued exactly as `fork-session` does. + start-task: func(task: new-task) -> result; } \ No newline at end of file diff --git a/sdk/rust/openidea-plugin/wit/decorations.wit b/sdk/rust/openidea-plugin/wit/decorations.wit index 90e3ea0d00..419331a878 100644 --- a/sdk/rust/openidea-plugin/wit/decorations.wit +++ b/sdk/rust/openidea-plugin/wit/decorations.wit @@ -7,7 +7,7 @@ package openidea:plugin@1.21.0; /// typo, weak, underline, strikethrough, muted. Unknown styles are ignored. Theme tokens only, /// except for the colors a `set-styled` item gives (API 1.17). interface decorations { - use types.{error, range}; + use types.{error, range, card-action}; /// An editor annotation; after is plain text shown after the range. record decoration { range: range, style: string, hover: option, after: option } /// An editor annotation whose hover is rendered as Markdown (API 1.16). @@ -37,6 +37,18 @@ interface decorations { markdown-hover: option, colors: option, } + /// An editor annotation with its own colors and hover-card actions (API 1.21). + /// Like `styled-decoration`, with buttons on the Markdown hover card. + record actionable-decoration { + range: range, + style: string, + hover: option, + after: option, + markdown-hover: option, + colors: option, + /// At most 4 actions; each command must be one this plugin declares. + actions: list, + } /// A project-tree annotation; badge is at most two Unicode characters. record file-decoration { badge: option, style: string, tooltip: option } /// Replace this set for a file. At most 10,000 items/file and 50 editor sets/plugin. @@ -50,6 +62,10 @@ interface decorations { /// assigns, such as one color per marked variable. Colors apply only to the item's range /// and after label; an invalid color fails the call. Same limits and set-id rules as `set`. set-styled: func(path: string, set-id: string, items: list) -> result<_, error>; + /// Like `set-styled`, with each item's hover-card actions (API 1.21). An action + /// runs this plugin's declared command as if from Find Action and closes the + /// card; an undeclared command fails the call. Same limits and set-id rules as `set`. + set-actionable: func(path: string, set-id: string, items: list) -> result<_, error>; /// Remove this editor set from every file/project. clear: func(set-id: string) -> result<_, error>; /// Replace this set's tree annotation for a file; at most 50 tree sets/plugin. diff --git a/sdk/rust/openidea-plugin/wit/events.wit b/sdk/rust/openidea-plugin/wit/events.wit index 24a5681289..87097f2191 100644 --- a/sdk/rust/openidea-plugin/wit/events.wit +++ b/sdk/rust/openidea-plugin/wit/events.wit @@ -45,13 +45,18 @@ interface events { /// whenever one of this plugin's configurations starts (whether launched by the plugin /// or by the user), `run-exited` for user-launched plugin configurations, and `run-output` /// (JSON {runId, configId, stream, text}) when subscribing with `run.output` in a trusted project. + /// `project-tree-expanded` (API 1.21) is also delivered through `other`: a JSON array of the + /// absolute paths of Project tree folders the user newly expanded (one batch per expand, + /// multi-level expands included), and once with the folders already expanded when a plugin + /// subscribes; it requires `events`. /// Kinds: `file-opened`, `file-saved`, `document-changed` (versioned UTF-16 /// replacements from explicit path subscriptions), `websocket-ready` /// (a host-owned connection has messages to drain), `caret-moved`, `files-changed` (batched disk changes /// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor /// changed), `vcs-changed` (a repository's state changed: commit, /// checkout, fetch…), `action-performed` (an IDE action ran), - /// `project-closed` (a project closed), `run-started`, `run-exited`, and + /// `project-closed` (a project closed), `project-tree-expanded` (Project tree folders expanded), + /// `run-started`, `run-exited`, and /// `scheduled` (the `on-schedule` period elapsed); later IDEs add more, /// and an IDE that doesn't know one fails with `invalid`. /// Requires `events` (`events.input` for `action-performed`). @@ -90,6 +95,17 @@ interface events { /// that serves a window's project (a command or event). watch-paths: func(paths: list) -> result<_, error>; unsubscribe: func(kind: string); + /// Wakes this plugin once, `after-ms` milliseconds from now (API 1.21), for retries, + /// backoff and polling the plugin paces itself: a `timer` event (JSON string: `id`) + /// arrives through `other`, in the window of the call that scheduled it. Scheduling an + /// `id` again replaces it, so the next delay is the plugin's own choice. An idle plugin + /// is activated for it. `after-ms` is 250 ms to 24 h; `id` is 1-128 bytes; at most 16 + /// timers are pending per plugin. They end when they fire, on `cancel-schedule`, when + /// the window closes, or when the plugin stops (disabled, updated, uninstalled); idle + /// reclaim keeps them. No capability: a plugin only wakes itself. + schedule: func(id: string, after-ms: u32) -> result<_, error>; + /// Cancels the pending `schedule` with this `id` (API 1.21); an unknown id does nothing. + cancel-schedule: func(id: string); } /// Long-running work with a progress indicator. While a task is open, the diff --git a/sdk/rust/openidea-plugin/wit/types.wit b/sdk/rust/openidea-plugin/wit/types.wit index 90eca253a9..285966098d 100644 --- a/sdk/rust/openidea-plugin/wit/types.wit +++ b/sdk/rust/openidea-plugin/wit/types.wit @@ -52,6 +52,24 @@ interface types { range: range, } + /// An action button on a plugin's hover card (API 1.21). It runs one of the + /// plugin's declared commands exactly as if the user ran it from Find Action: + /// the same budget and already-granted capabilities, no new capability. The + /// card closes when the action runs; an action whose document, project or + /// plugin snapshot changed since the card was placed (or last republished) + /// does not run. + record card-action { + /// Optional icon: a registered icon name or a declared manifest SVG path. + icon: option, + /// Text shown when no icon resolves; an icon makes the button icon-only, + /// with this as its accessible name and fallback tooltip. + label: string, + tooltip: option, + /// This plugin's declared command. + command: string, + argument: option, + } + /// A case added after 1.0, carried by the `other` case of a variant that /// grows (events, view bodies, view events, form fields): its kind and its /// data as JSON. Whoever doesn't know the kind ignores it or shows a diff --git a/src-tauri/src/commands/ssh.rs b/src-tauri/src/commands/ssh.rs index 87a8cc300b..f56c4ea242 100644 --- a/src-tauri/src/commands/ssh.rs +++ b/src-tauri/src/commands/ssh.rs @@ -49,6 +49,7 @@ pub async fn ssh_open_terminal( window: tauri::Window, state: State<'_, AppState>, id: String, + cwd: Option, cols: u16, rows: u16, on_output: tauri::ipc::Channel, @@ -58,6 +59,7 @@ pub async fn ssh_open_terminal( &host, window.label(), &id, + cwd.as_deref(), cols, rows, std::sync::Arc::new(move |chunk| { diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index ecbaf3177f..0a300d0257 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -755,7 +755,7 @@ pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeRe let update = tokio::time::timeout(std::time::Duration::from_secs(60), updater.check()) .await .map_err(|e| IdeError::unavailable(e.to_string()))? - .map_err(|e| IdeError::unavailable(e.to_string()))?; + .map_err(|e| IdeError::unavailable(ide_http::client::describe(&e)))?; Ok(UpdateCheck { enabled: true, update: update.map(|u| UpdateInfo { diff --git a/src-tauri/src/commands/window_drag.rs b/src-tauri/src/commands/window_drag.rs index 3de4480e70..d33f25901f 100644 --- a/src-tauri/src/commands/window_drag.rs +++ b/src-tauri/src/commands/window_drag.rs @@ -9,6 +9,10 @@ use tauri::WebviewWindow; /// /// macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run /// its drag loop with no release left to end it, and the window follows the pointer until the next click. +/// +/// On Windows, `start_dragging` posts `WM_NCLBUTTONDOWN`/`HTCAPTION`. If the button is already up +/// (a short click that only activated a background window, after an async invoke), Win32's move loop +/// follows the pointer until the next click (#7142). #[desktop_command(trust = always)] #[tauri::command] #[specta::specta] @@ -17,10 +21,31 @@ pub fn window_start_drag(window: WebviewWindow) -> IdeResult { if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 { return Ok(false); } + #[cfg(windows)] + if !primary_mouse_button_down() { + return Ok(false); + } window.start_dragging().map_err(|e| IdeError::internal(e.to_string()))?; Ok(true) } +#[cfg(windows)] +fn primary_button_vk(swapped: bool) -> u16 { + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_LBUTTON, VK_RBUTTON}; + if swapped { VK_RBUTTON } else { VK_LBUTTON } +} + +#[cfg(windows)] +fn primary_mouse_button_down() -> bool { + use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; + use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SWAPBUTTON}; + // GetAsyncKeyState reads physical buttons; map logical primary when left-handed swap is active. + let swapped = unsafe { GetSystemMetrics(SM_SWAPBUTTON) != 0 }; + let vk = primary_button_vk(swapped); + // High-order bit is set while the button is down. + unsafe { GetAsyncKeyState(i32::from(vk)) as u16 & 0x8000 != 0 } +} + /// Drags `paths` (local files and folders) out of `window` while the primary mouse button is /// still down, so the app they are dropped on copies them (#2867). Resolves when the drag ends, /// with whether a target took the files. @@ -59,3 +84,15 @@ pub async fn window_drag_files(window: WebviewWindow, paths: Vec) -> Id } ide_command::desktop_domain!(window_start_drag, window_drag_files); + +#[cfg(all(test, windows))] +mod tests { + use super::primary_button_vk; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_LBUTTON, VK_RBUTTON}; + + #[test] + fn primary_button_vk_respects_swapped_setting() { + assert_eq!(primary_button_vk(false), VK_LBUTTON); + assert_eq!(primary_button_vk(true), VK_RBUTTON); + } +} diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 16c18f977f..4cba0b7029 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -195,10 +195,11 @@ pub(crate) async fn download_update( mut progress: impl FnMut(u64, Option), ) -> IdeResult { let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?; - let update = - cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) }) - .await? - .ok_or_else(|| IdeError::not_found("no update available"))?; + let update = cancellable(token, async { + updater.check().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error))) + }) + .await? + .ok_or_else(|| IdeError::not_found("no update available"))?; let directory = app .path() .app_cache_dir() diff --git a/src-tauri/src/updates/download.rs b/src-tauri/src/updates/download.rs index eff0369bca..732aa26102 100644 --- a/src-tauri/src/updates/download.rs +++ b/src-tauri/src/updates/download.rs @@ -47,7 +47,8 @@ pub(crate) async fn fetch( if offset > 0 { request = request.header(RANGE, format!("bytes={offset}-")); } - let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?; + let response = + request.send().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error)))?; let status = response.status(); if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 { @@ -171,7 +172,7 @@ async fn append_body( progress(downloaded, total); } Ok(None) => break Ok(()), - Err(error) => break Err(IdeError::unavailable(error.to_string())), + Err(error) => break Err(IdeError::unavailable(ide_http::client::describe(&error))), } }; // tokio writes in the background: flush even when the body broke off, so the bytes diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 3d1873e05d..662a6b033a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -478,6 +478,8 @@ lsp_java_source_types trusted project_host bin lsp_library_source_origin trusted project_host bindings async lsp_library_sources trusted project_host bindings async lsp_message_request_answer trusted project_host bindings sync +lsp_move_edit trusted project_host bindings async +lsp_move_info trusted project_host bindings async lsp_move_to_file_targets trusted project_host bindings async lsp_open_typescript_file trusted project_host bindings async lsp_prepare_rename trusted project_host bindings async @@ -499,6 +501,7 @@ lsp_snapshot_completion trusted project_host bin lsp_snapshot_diagnostics trusted project_host bindings async lsp_source_action_text trusted project_host bindings async lsp_source_definition trusted project_host bindings async +lsp_spring_aop_markers trusted project_host bindings async lsp_spring_bean_markers trusted project_host bindings async lsp_stop trusted project_host bindings async lsp_switch_source_header trusted project_host bindings async @@ -587,6 +590,7 @@ plugin_grant outside_restricted desktop bin plugin_install_dir outside_restricted desktop bindings async plugin_installed_intellij_themes always desktop bindings async plugin_language_visuals trusted project_host bindings async +plugin_line_marker_languages trusted project_host bindings async plugin_line_markers trusted project_host bindings async plugin_link trusted desktop bindings async plugin_list always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 39272ec744..28e23156ca 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1270,6 +1270,10 @@ export const commands = { * language server runs: the question waits in that process, a remote project's server included. */ lspMessageRequestAnswer: (id: number, choice: string | null) => typedError(__TAURI_INVOKE("lsp_message_request_answer", { id, choice })), + /** Checks the chosen move and computes its edit (java-analyzer's `move`). */ + lspMoveEdit: (request: RequestId, doc: DocId, pos: Pos, destination: MoveChoice) => typedError(__TAURI_INVOKE("lsp_move_edit", { request, doc, pos, destination })), + /** What can move at `pos` and where it can go (java-analyzer's `moveInfo`). */ + lspMoveInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_move_info", { request, doc, pos })), /** * The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with * `cancel_request(request)`. @@ -1345,6 +1349,12 @@ export const commands = { * instead of its `.d.ts`. Cancel with `cancel_request(request)`. */ lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })), + /** + * The document's Spring AOP markers (advised methods with their advices, advice methods with + * the methods they advise); `None` when no server attached to it provides them. Cancel with + * `cancel_request(request)`. + */ + lspSpringAopMarkers: (request: RequestId, doc: DocId) => typedError(__TAURI_INVOKE("lsp_spring_aop_markers", { request, doc })), /** * The document's Spring bean markers (injection points and bean declarations with their * targets); `None` when no server attached to it provides them. Cancel with `cancel_request(request)`. @@ -1649,8 +1659,14 @@ export const commands = { /** Theme plugins installed in the JetBrains IDEs of this user, the ones in use first. */ pluginInstalledIntellijThemes: () => typedError(__TAURI_INVOKE("plugin_installed_intellij_themes")), pluginLanguageVisuals: (doc: DocId) => typedError(__TAURI_INVOKE("plugin_language_visuals", { doc })), + /** + * The languages whose plugin line markers a save of `path` can change: those a plugin declares for + * `line-markers` along with the file's language (`"*"` for every language). Does not load plugin + * code. By path, not document: closing a tab saves it and then closes its document. + */ + pluginLineMarkerLanguages: (path: string) => typedError(__TAURI_INVOKE("plugin_line_marker_languages", { path })), /** Gutter markers of plugin `line-markers` providers for an open document. */ - pluginLineMarkers: (doc: DocId) => typedError(__TAURI_INVOKE("plugin_line_markers", { doc })), + pluginLineMarkers: (doc: DocId) => typedError(__TAURI_INVOKE("plugin_line_markers", { doc })), /** Links a development plugin folder (`openidea-plugin link` does the same from a terminal). */ pluginLink: (path: string) => typedError(__TAURI_INVOKE("plugin_link", { path })), /** @@ -2456,7 +2472,7 @@ export const commands = { * Tools › Start SSH Session: a shell on configuration `id` in a terminal tab, through the * built-in client with the configuration's saved credentials. */ - sshOpenTerminal: (id: string, cols: number, rows: number, onOutput: Channel) => typedError(__TAURI_INVOKE("ssh_open_terminal", { id, cols, rows, onOutput })), + sshOpenTerminal: (id: string, cwd: string | null, cols: number, rows: number, onOutput: Channel) => typedError(__TAURI_INVOKE("ssh_open_terminal", { id, cwd, cols, rows, onOutput })), /** Whether a password is saved under `key` (an FTP deployment server's). */ sshPasswordSaved: (key: string) => __TAURI_INVOKE("ssh_password_saved", { key }), /** Remembers the password / passphrase of configuration `id` (`None` forgets it). */ @@ -2508,10 +2524,12 @@ export const commands = { /** Lists incoming remote updates for a Subversion working copy (`svn status -u --xml`). */ svnIncoming: (request: RequestId, repo: string | null) => typedError(__TAURI_INVOKE("svn_incoming", { request, repo })), /** - * Incoming: for each Subversion working copy, the revisions committed to its URL after its - * BASE revision, from BASE+1 to HEAD, as IntelliJ's Incoming tab lists them. + * Incoming: for each Subversion working copy, the revisions the server has that it does not, as + * IntelliJ's Incoming tab lists them. The working copies are read side by side, so one whose + * server does not answer does not hold up the others. `quiet` (the tab reading by itself, not a + * Refresh) asks for no login: a working copy that needs one shows the error instead. */ - svnIncomingRevisions: (request: RequestId) => typedError(__TAURI_INVOKE("svn_incoming_revisions", { request })), + svnIncomingRevisions: (request: RequestId, quiet: boolean) => typedError(__TAURI_INVOKE("svn_incoming_revisions", { request, quiet })), /** Repository URL of `path` inside a Subversion working copy. */ svnItemUrl: (path: string) => typedError(__TAURI_INVOKE("svn_item_url", { path })), /** Lists direct child entries of a remote repository URL (`svn list --xml`). */ @@ -2569,8 +2587,11 @@ export const commands = { * project's choosing runs only in a trusted project (as Git's Test does). */ svnVersion: (executable: string) => typedError(__TAURI_INVOKE("svn_version", { executable })), - /** Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project. */ - svnWorkingCopyInfo: (repo: string | null) => typedError(__TAURI_INVOKE("svn_working_copy_info", { repo })), + /** + * Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project, + * with their switched folders; `request` stops the scan for those. + */ + svnWorkingCopyInfo: (request: RequestId, repo: string | null) => typedError(__TAURI_INVOKE("svn_working_copy_info", { request, repo })), /** `ERROR` / `MISSING` nodes (e.g. a missing `;`) in document order. */ syntaxErrors: (doc: DocId, request: number | null) => typedError(__TAURI_INVOKE("syntax_errors", { doc, request })), /** @@ -3139,6 +3160,10 @@ export const commands = { * * macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run * its drag loop with no release left to end it, and the window follows the pointer until the next click. + * + * On Windows, `start_dragging` posts `WM_NCLBUTTONDOWN`/`HTCAPTION`. If the button is already up + * (a short click that only activated a background window, after an async invoke), Win32's move loop + * follows the pointer until the next click (#7142). */ windowStartDrag: () => typedError(__TAURI_INVOKE("window_start_drag")), /** What this window was opened for (taken once). */ @@ -4219,11 +4244,13 @@ export type AgentPluginCapabilities_Deserialize = { commandCount: number, hookFiles?: string[], stdioCommands?: string[], + /** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */ + lspCommands?: string[], hasLsp?: boolean, hasCanvasOrApp?: boolean, /** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */ nativeHarnesses?: string[], - /** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents). */ + /** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents). */ capabilityHash?: string | null, requiresConsent?: boolean, }; @@ -4239,11 +4266,13 @@ export type AgentPluginCapabilities_Serialize = { commandCount: number, hookFiles?: string[], stdioCommands?: string[], + /** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */ + lspCommands?: string[], hasLsp: boolean, hasCanvasOrApp: boolean, /** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */ nativeHarnesses?: string[], - /** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents). */ + /** Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents). */ capabilityHash?: string | null, requiresConsent: boolean, }; @@ -6354,6 +6383,18 @@ export type CapabilityInfo = { reasonLocales?: { [key in string]: string }, }; +/** + * A hover-card action button (API 1.21): runs one of the plugin's declared commands + * as if the user ran it from Find Action, then closes the card. No new capability. + */ +export type CardAction = { + icon: string | null, + label: string, + tooltip: string | null, + command: string, + argument: string | null, +}; + /** * The caret moved in the focused editor. Positions are 0-based; `col` counts * UTF-16 code units, as everywhere in the plugin API. @@ -8364,6 +8405,11 @@ export type Decoration = { markdownHover: string | null, /** The item's own colors (API 1.17 `set-styled`), validated `#rrggbb` / `#rrggbbaa`. */ colors?: DecorationColors | null, + /** + * Hover-card actions (API 1.21 `set-actionable`); each runs one of the plugin's + * declared commands as if from Find Action, then closes the card. + */ + actions?: CardAction[], }; /** Colors of a styled editor decoration (API 1.17). */ @@ -9599,7 +9645,14 @@ export type EventKind = "document-changed" | "websocket-ready" | "file-closed" | /** A project was closed (or its window closed): the project root path. */ "project-closed" | /** Paths outside the project watched with `events.watch-paths` changed (API 1.18). */ -"watched-files-changed" | "scheduled"; +"watched-files-changed" | +/** + * Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21): + * a JSON array of absolute paths (`Event::Other`). + */ +"project-tree-expanded" | "scheduled" | +/** A timer the plugin set with `events.schedule` fired (API 1.21); delivered without subscribing. */ +"timer"; export type ExceptionClassBreakpoint = { id: string, @@ -9757,6 +9810,13 @@ export type ExternalTool = { openConsole?: boolean, }; +/** The files of an external an update fetched: another repository, at its own revision. */ +export type ExternalUpdateReport = { + root: string, + items: UpdatedItemReport[], + toRevision: string | null, +}; + /** * What Extract Interface starts from: the file's class, the members the interface can declare and * the packages it can go to (as JSON, passed back unchanged). @@ -12749,6 +12809,16 @@ export type LineMarkerInfo = { target: Location | null, }; +/** The answer of the `line-markers` providers for a document. */ +export type LineMarkers = { + markers: LineMarkerInfo[], + /** + * Plugins whose call ran past the edit-path budget and was dropped: they gave no answer, + * so the editor keeps the markers it shows from them. + */ + late: string[], +}; + export type LineMatch = { /** 0-based line. */ line: number, @@ -12963,7 +13033,9 @@ export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" | /** The Dart server published a document's Flutter outline. */ "flutterOutline" | /** Spring bean markers of open documents may have changed. */ -"springBeanMarkers"; +"springBeanMarkers" | +/** Spring AOP markers of open documents may have changed. */ +"springAopMarkers"; export type MainToolbarSettings = { left?: string[], @@ -13830,6 +13902,38 @@ export type ModuleStructureSettings = { dependencies?: ModuleDependency[], }; +/** A Move destination choice, as the dialog sends it back. */ +export type MoveChoice = { + kind: string, + id: string, +}; + +/** One destination Move can go to. */ +export type MoveDestination = { + /** `package`, `class`, `newFile`, `field` or `parameter`. */ + kind: string, + /** Server-owned identity, passed back unchanged. */ + id: string, + name: string, + qualifiedName?: string, + detail?: string, + current?: boolean, + /** For field/parameter destinations: the type of the field or parameter. */ + targetType?: string, + isField?: boolean, +}; + +/** The element at a position and where Move can take it. */ +export type MoveInfo = { + kind: MoveKind, + /** The element being moved, as the server renders it. */ + label: string, + destinations: MoveDestination[], +}; + +/** The kind of element Move (F6) would move, as java-analyzer reports it. */ +export type MoveKind = "type" | "staticMember" | "instanceMethod"; + /** * A named set of files: `file:src//*.ts && !file:*.test.ts` (project-relative path patterns * joined with `||`, `&&`, `!` and parentheses). @@ -14391,6 +14495,11 @@ export type PluginEvent_Deserialize = ({ type: "openDatabaseConsole"; pluginId: string; sourceId: string; sql: string | null; schema: string | null }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; selection?: never; sets?: never; table?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Open the IDE's native table data grid in the invoking window (API 1.21). */ ({ type: "openDatabaseTable"; pluginId: string; sourceId: string; catalog: string | null; schema: string; table: string }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; selection?: never; sets?: never; sql?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | +/** + * Open a plugin-started task in the invoking window's Agents window (API 1.21): + * created unsent, with `prompt` in its message field for the user to review and send. + */ +({ type: "openAgentTask"; taskId: string; prompt: string }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; pluginId?: never; program?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; schema?: never; selection?: never; sets?: never; sourceId?: never; sql?: never; table?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Complete replacement of one plugin's clickable console link rules (API 1.21). */ ({ type: "consoleLinksChanged"; pluginId: string; rules: ConsoleLinkRule[] }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; schema?: never; selection?: never; sets?: never; sourceId?: never; sql?: never; table?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Open a file in the invoking window; `as_text` in the text editor even when a custom editor claims it. */ @@ -14514,6 +14623,11 @@ export type PluginEvent_Serialize = ({ type: "openDatabaseConsole"; pluginId: string; sourceId: string; sql: string | null; schema: string | null }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; selection?: never; sets?: never; table?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Open the IDE's native table data grid in the invoking window (API 1.21). */ ({ type: "openDatabaseTable"; pluginId: string; sourceId: string; catalog: string | null; schema: string; table: string }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; selection?: never; sets?: never; sql?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | +/** + * Open a plugin-started task in the invoking window's Agents window (API 1.21): + * created unsent, with `prompt` in its message field for the user to review and send. + */ +({ type: "openAgentTask"; taskId: string; prompt: string }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; pluginId?: never; program?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; rules?: never; schema?: never; selection?: never; sets?: never; sourceId?: never; sql?: never; table?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Complete replacement of one plugin's clickable console link rules (API 1.21). */ ({ type: "consoleLinksChanged"; pluginId: string; rules: ConsoleLinkRule[] }) & { actions?: never; arg?: never; args?: never; asText?: never; badge?: never; body?: never; cancellable?: never; capabilities?: never; catalog?: never; chain?: never; channel?: never; column?: never; connection?: never; cwd?: never; diff?: never; directory?: never; done?: never; fileName?: never; focus?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; page?: never; path?: never; permissions?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; schema?: never; selection?: never; sets?: never; sourceId?: never; sql?: never; table?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never; viewId?: never } | /** Open a file in the invoking window; `as_text` in the text editor even when a custom editor claims it. */ @@ -15844,6 +15958,8 @@ export type RedirectHop = { export type RefactoringProblem = { severity: ProblemSeverity, message: string, + /** Where the problem was found, when the server can say. */ + location?: Location | null, }; export type ReferenceAccess = "read" | "write" | "readWrite" | "unknown"; @@ -17462,6 +17578,36 @@ export type SpellingSettings = { defaultDictionary?: string | null, }; +export type SpringAopAdviceKind = "before" | "after" | "afterReturning" | "afterThrowing" | "around"; + +export type SpringAopDirection = +/** On an advised method: its targets are the advices applied to it. */ +"toAdvice" | +/** On an advice method: its targets are the methods it advises. */ +"toAdvised"; + +/** + * A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice + * method (`ToAdvised`), whichever server found it. + */ +export type SpringAopMarker = { + /** The method's name range. */ + range: Range, + name: string, + direction: SpringAopDirection, + /** Never empty. */ + targets: SpringAopTarget[], +}; + +export type SpringAopTarget = { + location: Location, + label: string, + /** Set on an advice target; `None` on an advised method. */ + adviceKind: SpringAopAdviceKind | null, + /** The advice's Spring `order`; `None` when it has none. */ + order: number | null, +}; + export type SpringBeanDirection = "toBean" | "toInjectionPoint"; /** @@ -17932,6 +18078,9 @@ export type SvnIncomingPath = { /** The file in the working copy, for a path under the working copy's URL. */ local: string | null, kind: string, + /** The repository path it was copied from (`svn copy`, or the new half of a move). */ + copyFrom?: string | null, + copyFromRevision?: number | null, }; /** A revision committed after a working copy's BASE: a row of the Incoming tab. */ @@ -18898,6 +19047,8 @@ export type UpdateReport = { /** The working copy's revision before and after the update. */ fromRevision?: string | null, toRevision?: string | null, + /** Externals the update fetched, each with its own revision. */ + externals?: ExternalUpdateReport[], }; export type UpdateSource = "github" | "cnb"; @@ -18915,6 +19066,10 @@ export type UpdateStatus = { export type UpdatedItemReport = { path: string, action: string, + /** Its path in the repository (`/trunk/src/a.txt`), when known. */ + repoPath?: string | null, + /** Its own revision before the update, when not the working copy's (`from_revision`). */ + fromRevision?: string | null, }; export type UpstreamTracking = { @@ -19293,7 +19448,11 @@ export type WorkbenchEvent = { kind: "documentChanged"; value: DocumentChanged } * Changes to paths outside the project watched with `events.watch-paths` (API 1.18); * `project` is the project the watch belongs to, `generation` is unset. */ -{ kind: "watchedFilesChanged"; value: FilesChanged } | { kind: "scheduled" }; +{ kind: "watchedFilesChanged"; value: FilesChanged } | +/** Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21). */ +{ kind: "projectTreeExpanded"; value: string[] } | { kind: "scheduled" } | +/** A timer this plugin set with `events.schedule` fired (API 1.21): its id. */ +{ kind: "timer"; value: string }; export type WorkingTreeChange = { path: string, diff --git a/src/editor/TextField.test.tsx b/src/editor/TextField.test.tsx new file mode 100644 index 0000000000..719f13438c --- /dev/null +++ b/src/editor/TextField.test.tsx @@ -0,0 +1,223 @@ +/** The editor-based text field: Vim goes first on Escape, the field stays controlled. */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render } from "@testing-library/react"; +import { useRef, useState } from "react"; +import { EditorView } from "@codemirror/view"; +import { activate as activateVim } from "@/features/vim"; +import { useVimSettings } from "@/features/vim/settings"; +import { TextField, type TextFieldHandle } from "./TextField"; + +const contentOf = (label: string) => { + const el = document.querySelector(`[aria-label="${label}"]`); + if (!el) throw new Error("field not rendered"); + return el; +}; + +const viewOf = (label: string): EditorView => { + const view = EditorView.findFromDOM(contentOf(label)); + if (!view) throw new Error("not an editor field"); + return view; +}; + +/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */ +const untilVim = async (label: string): Promise => { + const view = viewOf(label); + await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 }); + return view; +}; + +/** Parent stores the text, like the commit message store does. */ +function renderControlled(label: string, initial: string) { + const onChange = vi.fn(); + function Holder() { + const [text, setText] = useState(initial); + return ( + { + onChange(t); + setText(t); + }} + /> + ); + } + render(); + return { onChange }; +} + +/** Parent owns the value outright: rerender replaces it from the outside. */ +function renderStatic(label: string, initial: string) { + const onChange = vi.fn(); + function Holder({ text }: { text: string }) { + return ; + } + const { rerender } = render(); + return { rerender: (next: string) => rerender() }; +} + +/** A controlled field exposing the handle, for focus and view assertions. */ +function renderHandleField(label: string, initial: string) { + function Holder() { + const [text, setText] = useState(initial); + const ref = useRef(null); + return ( + <> + + + + ); + } + render(); +} + +afterEach(() => { + useVimSettings.setState({ enabled: false, handlers: {} }, true); +}); + +describe("TextField", () => { + it("is a focusable editor textbox that reports typed text", () => { + const { onChange } = renderControlled("Field", ""); + const view = viewOf("Field"); + expect(contentOf("Field").getAttribute("role")).toBe("textbox"); + act(() => { + view.focus(); + view.dispatch(view.state.replaceSelection("typed"), { userEvent: "input.type" }); + }); + expect(view.state.doc.toString()).toBe("typed"); + expect(onChange).toHaveBeenLastCalledWith("typed"); + }); + + it("follows an external value change", () => { + const { rerender } = renderStatic("Field", "first"); + const view = viewOf("Field"); + expect(view.state.doc.toString()).toBe("first"); + rerender("second"); + expect(view.state.doc.toString()).toBe("second"); + }); + + it("keeps the focus in the field while Vim is off and Esc still leaves it", () => { + renderHandleField("Field", "text"); + const view = viewOf("Field"); + act(() => view.focus()); + expect(document.activeElement).toBe(view.contentDOM); + fireEvent.keyDown(view.contentDOM, { key: "Escape" }); + expect(document.activeElement).not.toBe(view.contentDOM); + }); + + it("with Vim mode on, Esc leaves Insert mode and keeps the focus in the field", async () => { + useVimSettings.setState({ enabled: true, handlers: {} }, true); + const disposeVim = activateVim(); + try { + renderHandleField("Field", "hello"); + const view = await untilVim("Field"); + act(() => view.focus()); + fireEvent.keyDown(view.contentDOM, { key: "i" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("insert"); + fireEvent.keyDown(view.contentDOM, { key: "Escape" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("normal"); + expect(document.activeElement).toBe(view.contentDOM); + } finally { + disposeVim(); + } + }); + + it("with Vim mode on, a further Esc in Normal mode returns the focus (explicit)", async () => { + useVimSettings.setState({ enabled: true, handlers: {} }, true); + const disposeVim = activateVim(); + try { + renderHandleField("Field", "hello"); + const view = await untilVim("Field"); + act(() => view.focus()); + fireEvent.keyDown(view.contentDOM, { key: "i" }); + fireEvent.keyDown(view.contentDOM, { key: "Escape" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("normal"); + fireEvent.keyDown(view.contentDOM, { key: "Escape" }); + expect(document.activeElement).not.toBe(view.contentDOM); + } finally { + disposeVim(); + } + }); + + it("with Vim mode on, operators edit the field's text (dd)", async () => { + useVimSettings.setState({ enabled: true, handlers: {} }, true); + const disposeVim = activateVim(); + try { + const { onChange } = renderControlled("Field", "subject\nbody"); + const view = await untilVim("Field"); + act(() => { + view.focus(); + view.dispatch({ selection: { anchor: 0 } }); + }); + fireEvent.keyDown(view.contentDOM, { key: "d" }); + fireEvent.keyDown(view.contentDOM, { key: "d" }); + expect(view.state.doc.toString()).toBe("body"); + expect(onChange).toHaveBeenLastCalledWith("body"); + } finally { + disposeVim(); + } + }); + + it("takes no edits while read-only, and reports caret moves that don't change the text", () => { + const onSelectionChange = vi.fn(); + function Holder({ readOnly }: { readOnly: boolean }) { + const [text, setText] = useState("hello"); + return ( + + ); + } + const { rerender } = render(); + const view = viewOf("Field"); + act(() => view.dispatch({ selection: { anchor: 2 } })); + expect(onSelectionChange).toHaveBeenCalledWith(2, view); + rerender(); + expect(view.state.readOnly).toBe(true); + expect(contentOf("Field").getAttribute("contenteditable")).toBe("false"); + rerender(); + expect(view.state.readOnly).toBe(false); + }); + + it("with Vim mode on, gives a key to onKeyDownFirst before Vim and to onKeyDown after it", async () => { + useVimSettings.setState({ enabled: true, handlers: {} }, true); + const disposeVim = activateVim(); + const first = vi.fn((e: KeyboardEvent) => e.key === "ArrowDown"); + const after = vi.fn((_e: KeyboardEvent) => false); + try { + function Holder() { + const [text, setText] = useState("one\ntwo"); + return ( + + ); + } + render(); + const view = await untilVim("Field"); + act(() => view.focus()); + act(() => view.dispatch({ selection: { anchor: 0 } })); + fireEvent.keyDown(view.contentDOM, { key: "ArrowDown" }); + expect(first).toHaveBeenCalledTimes(1); + expect(view.state.selection.main.head).toBe(0); + fireEvent.keyDown(view.contentDOM, { key: "i" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("insert"); + fireEvent.keyDown(view.contentDOM, { key: "Escape" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("normal"); + expect(after.mock.calls.some(([e]) => e.key === "Escape" && !e.defaultPrevented)).toBe(false); + } finally { + disposeVim(); + } + }); +}); diff --git a/src/editor/TextField.tsx b/src/editor/TextField.tsx new file mode 100644 index 0000000000..b1fe926414 --- /dev/null +++ b/src/editor/TextField.tsx @@ -0,0 +1,224 @@ +/** + * A multi-line text field built on the code editor: Vim and every other `embedded` + * editor contribution apply through the shared embedded-editor mechanism + * (`embeddedEditorExtensions`) and are reconfigured live, so with Vim mode on + * `Esc` goes to Vim first and only moves the focus when Vim does not use it. + * The commit message field is the first user (#7024). + */ +import { forwardRef, useImperativeHandle, useLayoutEffect, useRef, type CSSProperties, type RefObject } from "react"; +import { Annotation, Compartment, EditorState, Prec } from "@codemirror/state"; +import { EditorView, keymap, placeholder as cmPlaceholder } from "@codemirror/view"; +import { defaultKeymap, history } from "@codemirror/commands"; +import { embeddedEditorExtensions } from "./api"; + +/** Marks a transaction the field itself made (an external value or a host echo): no `onChange`. */ +export const fieldEcho = Annotation.define(); + +/** Created once: every `EditorView.theme` call mounts new CSS rules into the document. */ +const FIELD_THEME = EditorView.theme({ + "&": { height: "100%", backgroundColor: "transparent" }, + ".cm-scroller": { + backgroundColor: "transparent", + fontFamily: "inherit", + fontWeight: "inherit", + lineHeight: "inherit", + }, + ".cm-content": { padding: "6px var(--pad, 10px)" }, + ".cm-line": { padding: "0" }, + ".cm-placeholder": { + color: "var(--fg-subtle)", + fontFamily: "var(--font-ui)", + fontSize: "var(--fs-ui)", + }, +}); + +const readOnlyExtension = (readOnly: boolean) => + readOnly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []; + +export interface TextFieldHandle { + focus(): void; + /** The live editor view, null before mount and after unmount. */ + view(): EditorView | null; +} + +export interface TextFieldProps { + value: string; + /** Text typed or deleted in the field; not called for the field's own echo transactions. */ + onChange: (text: string, view: EditorView) => void; + /** A stable pseudo document path; embedded editor contributions and their events use it. */ + path: string; + placeholder?: string; + ariaLabel?: string; + spellCheck?: boolean; + /** Marks the editor as its tool window's late-focus target (`data-autofocus`). */ + autoFocus?: boolean; + /** Whether long lines wrap (a textarea-like field always does). */ + wrap?: boolean; + /** Reported on the editor as `aria-invalid` (a failed check at the field). */ + invalid?: boolean; + /** The editor's content lost the focus. */ + onBlur?: () => void; + /** Runs after Vim has had the key; return true when the key was handled. */ + onKeyDown?: (event: KeyboardEvent, view: EditorView) => boolean | void; + /** Runs before Vim and the editor's keys (a completion list open at the field); true when handled. */ + onKeyDownFirst?: (event: KeyboardEvent, view: EditorView) => boolean | void; + /** The caret moved without the text changing. */ + onSelectionChange?: (head: number, view: EditorView) => void; + /** No editing (a request in flight); the text stays selectable. */ + readOnly?: boolean; + className?: string; + style?: CSSProperties; + /** Receives the host element, to anchor popups at the field. */ + hostRef?: RefObject; +} + +/** A controlled editor field; see the module comment. */ +export const TextField = forwardRef(function TextField( + { + value, + onChange, + path, + placeholder, + ariaLabel, + spellCheck, + autoFocus, + wrap = true, + invalid, + onBlur, + onKeyDown, + onKeyDownFirst, + onSelectionChange, + readOnly = false, + className, + style, + hostRef, + }, + ref, +) { + const host = useRef(null); + const view = useRef(null); + const wrapCompartment = useRef(new Compartment()); + const readOnlyCompartment = useRef(new Compartment()); + // The handlers change every render; the view is built once and reads them through refs. + const onChangeRef = useRef(onChange); + onChangeRef.current = onChange; + const onKeyDownRef = useRef(onKeyDown); + onKeyDownRef.current = onKeyDown; + const onKeyDownFirstRef = useRef(onKeyDownFirst); + onKeyDownFirstRef.current = onKeyDownFirst; + const onSelectionChangeRef = useRef(onSelectionChange); + onSelectionChangeRef.current = onSelectionChange; + const onBlurRef = useRef(onBlur); + onBlurRef.current = onBlur; + const valueRef = useRef(value); + valueRef.current = value; + + useLayoutEffect(() => { + if (!host.current) return; + const editor = new EditorView({ + parent: host.current, + state: EditorState.create({ + doc: valueRef.current, + extensions: [ + FIELD_THEME, + history(), + keymap.of(defaultKeymap), + wrapCompartment.current.of(wrap ? EditorView.lineWrapping : []), + readOnlyCompartment.current.of(readOnlyExtension(readOnly)), + Prec.highest( + EditorView.domEventHandlers({ + keydown: (event, current) => onKeyDownFirstRef.current?.(event, current) === true, + }), + ), + ...(placeholder ? [cmPlaceholder(placeholder)] : []), + embeddedEditorExtensions(path), + EditorView.updateListener.of((update) => { + if (!update.docChanged) { + if (update.selectionSet) onSelectionChangeRef.current?.(update.state.selection.main.head, update.view); + return; + } + if (update.transactions.some((tr) => tr.annotation(fieldEcho))) return; + onChangeRef.current?.(update.state.doc.toString(), update.view); + }), + EditorView.domEventHandlers({ + keydown(event, current) { + if (onKeyDownRef.current && onKeyDownRef.current(event, current) === true) return true; + // Vim had the key first (its handlers run at highest precedence); + // only an Escape Vim does not use moves the focus, as the textarea's did. + if (event.key === "Escape" && !event.defaultPrevented && !current.composing) { + current.contentDOM.blur(); + return true; + } + return false; + }, + blur(_event, current) { + // A view being destroyed (unmount, or React re-running the effect) blurs on removal: + // only the live field's blur counts. + if (view.current === current) onBlurRef.current?.(); + return false; + }, + }), + EditorView.contentAttributes.of({ + "aria-label": ariaLabel ?? "", + "aria-multiline": "true", + role: "textbox", + spellcheck: spellCheck ? "true" : "false", + }), + ], + }), + }); + view.current = editor; + return () => { + view.current = null; + editor.destroy(); + }; + // The field is created once; `path` identifies it for its lifetime. + // eslint-disable-next-line react-hooks/exhaustive-deps -- placeholder/aria are stable per field + }, []); + + useLayoutEffect(() => { + view.current?.dispatch({ effects: wrapCompartment.current.reconfigure(wrap ? EditorView.lineWrapping : []) }); + }, [wrap]); + + useLayoutEffect(() => { + view.current?.dispatch({ effects: readOnlyCompartment.current.reconfigure(readOnlyExtension(readOnly)) }); + }, [readOnly]); + + useLayoutEffect(() => { + const editor = view.current; + if (!editor || editor.state.doc.toString() === value) return; + editor.dispatch({ + changes: { from: 0, to: editor.state.doc.length, insert: value }, + selection: { anchor: value.length }, + annotations: fieldEcho.of(true), + }); + }, [value]); + + // `data-autofocus` moves at runtime (the Commit window takes the activation focus + // only when Commit… asked for the message), like the textarea attribute did. Set before + // paint: the tool window looks for it in the next animation frame. + useLayoutEffect(() => { + const el = view.current?.contentDOM; + if (!el) return; + if (invalid) el.setAttribute("aria-invalid", "true"); + else el.removeAttribute("aria-invalid"); + if (autoFocus) el.setAttribute("data-autofocus", "true"); + else el.removeAttribute("data-autofocus"); + }, [invalid, autoFocus]); + + useImperativeHandle(ref, () => ({ + focus: () => view.current?.focus(), + view: () => view.current, + })); + + return ( +
{ + host.current = el; + if (hostRef) hostRef.current = el; + }} + className={className} + style={style} + /> + ); +}); diff --git a/src/editor/core/clipboardHistory.ts b/src/editor/core/clipboardHistory.ts index d44218685f..ed56ebda1f 100644 --- a/src/editor/core/clipboardHistory.ts +++ b/src/editor/core/clipboardHistory.ts @@ -96,7 +96,12 @@ function selectCopiedLines(view: EditorView, lines: ReturnType) { const state = view.state; const spans: Array<[first: number, last: number]> = []; @@ -113,12 +118,13 @@ function cutCaretLines(view: EditorView, lines: ReturnType { - const target = doc.lineAt(changes.mapPos(line.from, -1)); - return { - line: line.number, - range: EditorSelection.cursor(target.from + Math.min(pos - line.from, target.length)), - }; + const mapped = lines.map(({ line }) => { + const last = spans.find(([first, end]) => line.number >= first && line.number <= end)![1]; + const target = + last < state.doc.lines + ? changes.mapPos(state.doc.line(last + 1).from, 1) + : doc.lineAt(changes.mapPos(line.from, -1)).from; + return { line: line.number, range: EditorSelection.cursor(target) }; }); const unique = mapped.filter(({ range }, i) => mapped.findIndex((other) => other.range.head === range.head) === i); const mainLine = state.doc.lineAt(state.selection.main.head).number; diff --git a/src/editor/core/cm/clipboard.test.ts b/src/editor/core/cm/clipboard.test.ts index 18b188c478..27751411dc 100644 --- a/src/editor/core/cm/clipboard.test.ts +++ b/src/editor/core/cm/clipboard.test.ts @@ -360,7 +360,7 @@ describe("line-wise paste", () => { const view = make("one\ntwo", [5]); expect(copy(view, "cut")).toBe("two"); expect(view.state.doc.toString()).toBe("one"); - expect(view.state.selection.main.head).toBe(1); + expect(view.state.selection.main.head).toBe(0); expect(clipboardHistory()[0]).toEqual({ text: "two", linewise: true }); }); @@ -401,7 +401,7 @@ describe("line-wise paste", () => { const view = make("one\ntwo\nthree\nfour\nfive", [1, 2, 15]); expect(copy(view, "cut")).toBe("one\nfour"); expect(view.state.doc.toString()).toBe("two\nthree\nfive"); - expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1, 5]); + expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0, 10]); expect(clipboardHistory()[0]).toEqual({ text: "one\nfour", linewise: true }); }); @@ -409,7 +409,16 @@ describe("line-wise paste", () => { const view = make("one\ntwo\nthree\nfour", [1, 2, 5, 9]); expect(copy(view, "cut")).toBe("one\ntwo\nthree"); expect(view.state.doc.toString()).toBe("four"); - expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1]); + expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0]); + }); + + it("keeps the caret on the cut line's number, at the start of the line moved up, so repeated cuts go down", () => { + const view = make("one\n two\nthree", [6]); + expect(copy(view, "cut")).toBe(" two"); + expect(view.state.doc.toString()).toBe("one\nthree"); + expect(view.state.selection.main.head).toBe(4); + expect(copy(view, "cut")).toBe("three"); + expect(view.state.doc.toString()).toBe("one"); }); it("allows line copy but not deletion in a read-only editor", () => { diff --git a/src/editor/core/focusedCell.test.ts b/src/editor/core/focusedCell.test.ts index d713dfbfec..bb04b30a11 100644 --- a/src/editor/core/focusedCell.test.ts +++ b/src/editor/core/focusedCell.test.ts @@ -16,6 +16,7 @@ vi.mock("./fileAttributes", async (original) => ({ })); const ctrl = editorController(); +const cells: EditorView[] = []; let disposeActions: () => void; beforeAll(() => { disposeActions = registerEditorActions(); @@ -30,6 +31,12 @@ afterEach(() => { useEditorStatus.setState({ status: null }); useContextKeys.setState({}, true); _setFocusedCellEditor(null); + // A live view's pending focus timer would run after jsdom is torn down. + for (const view of cells.splice(0)) { + const host = view.dom.parentElement; + view.destroy(); + host?.remove(); + } toggleReadOnlyMock.mockClear(); }); @@ -39,32 +46,23 @@ function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } { document.body.appendChild(host); // `columnModeField`: what a cell editor carries through its own extension list. const view = new EditorView({ doc, parent: host, extensions: columnModeField }); + cells.push(view); view.focus(); if (!view.hasFocus) throw new Error("the jsdom view did not take focus"); _setFocusedCellEditor(view); return { view, clear: () => _setFocusedCellEditor(null) }; } -function disposeView(cell: { view: EditorView }): void { - cell.view.destroy(); - cell.view.dom.remove(); -} - describe("editor context keys with a focused notebook cell", () => { it("keeps the keys on while a cell editor has focus, with no text editor open", () => { - const cell = focusedCell(); - try { - ctrl.publishContext(); - expect(getContext().textEditorActive).toBe(true); - expect(getContext().editorTextFocus).toBe(true); - // Republishing (tab churn, pane focus) must not drop the keys. - ctrl.publishContext(); - expect(getContext().textEditorActive).toBe(true); - expect(getContext().editorTextFocus).toBe(true); - } finally { - cell.clear(); - disposeView(cell); - } + focusedCell(); + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); + // Republishing (tab churn, pane focus) must not drop the keys. + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); }); it("lets a focused cell editor win over the mounted but unfocused text editor", async () => { @@ -75,12 +73,10 @@ describe("editor context keys with a focused notebook cell", () => { try { const textView = slot.mount(host); ctrl.onMounted(slot); - const cell = focusedCell(); + focusedCell(); ctrl.publishContext(); expect(getContext().editorTextFocus).toBe(true); expect(textView.hasFocus).toBe(false); - cell.clear(); - disposeView(cell); } finally { host.remove(); } @@ -88,16 +84,12 @@ describe("editor context keys with a focused notebook cell", () => { it("drops the keys once no cell editor has focus", () => { const cell = focusedCell(); - try { - ctrl.publishContext(); - expect(getContext().textEditorActive).toBe(true); - cell.clear(); - ctrl.publishContext(); - expect(getContext().textEditorActive).toBe(false); - expect(getContext().editorTextFocus).toBe(false); - } finally { - disposeView(cell); - } + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + cell.clear(); + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(false); + expect(getContext().editorTextFocus).toBe(false); }); it("keeps a text tab's own keys when no cell editor is focused", async () => { @@ -132,8 +124,6 @@ describe("editor actions in a focused notebook cell", () => { await executeAction("editor.toggleColumnSelection"); expect(isColumnMode(cell.view.state)).toBe(true); expect(isColumnMode(textView.state)).toBe(false); - cell.clear(); - disposeView(cell); } finally { host.remove(); } @@ -183,8 +173,6 @@ describe("editor actions in a focused notebook cell", () => { } finally { uninstall(); disposeStub(); - cell.clear(); - disposeView(cell); } }); }); @@ -211,13 +199,9 @@ describe("Copy Path with a notebook tab", () => { }, }, })); - const cell = focusedCell(); - try { - ctrl.publishContext(); - expect(ctrl.activePath()).toBe("/p/a.ipynb"); - expect(evaluateWhen("textEditorActive", getContext())).toBe(true); - } finally { - cell.clear(); - } + focusedCell(); + ctrl.publishContext(); + expect(ctrl.activePath()).toBe("/p/a.ipynb"); + expect(evaluateWhen("textEditorActive", getContext())).toBe(true); }); }); diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index df4a08ded5..87892ffdf1 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -51,6 +51,7 @@ import { implementationGutter, pythonStubGutter, registerNavigationActions, + springAopGutter, springBeanGutter, } from "@/editor/navigation"; import { @@ -140,6 +141,7 @@ export function activate(): () => void { registerEditorContribution({ id: "lsp.lineMarkers", order: 56, extensions: implementationGutter }), registerEditorContribution({ id: "lsp.pythonStubs", order: 57, extensions: pythonStubGutter }), registerEditorContribution({ id: "lsp.springBeans", order: 58, extensions: springBeanGutter }), + registerEditorContribution({ id: "lsp.springAop", order: 59, extensions: springAopGutter }), // After the templates (order 90): live template / postfix expansion keeps ⇥ first. registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }), registerOverlay({ id: "editor-lsp.popups", component: LspPopups }), diff --git a/src/editor/lsp/signature.test.ts b/src/editor/lsp/signature.test.ts index b5a2e0a9fc..18a7c25e3d 100644 --- a/src/editor/lsp/signature.test.ts +++ b/src/editor/lsp/signature.test.ts @@ -224,6 +224,71 @@ describe("parameter info replies", () => { await vi.waitFor(() => expect(shown(a)).toBe("f")); expect(shown(b)).toBe("g"); }); + + const escape = (view: EditorView) => + view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + + it("stays closed after Escape while the refresh for the last keystroke is pending", async () => { + lspSignatureHelp.mockResolvedValueOnce(named("f") as never); + const view = editor(); + triggerSignatureHelp(view, true); + await vi.waitFor(() => expect(shown(view)).toBe("f")); + typeChar(view, ","); + escape(view); + expect(shown(view)).toBeNull(); + await new Promise((r) => setTimeout(r, 300)); + expect(shown(view)).toBeNull(); + triggerSignatureHelp(view, true); + await vi.waitFor(() => expect(shown(view)).not.toBeNull()); + }); + + it("stays closed after the editor loses focus while a refresh is pending", async () => { + lspSignatureHelp.mockResolvedValueOnce(named("f") as never); + const view = editor(); + view.focus(); + triggerSignatureHelp(view, true); + await vi.waitFor(() => expect(shown(view)).toBe("f")); + typeChar(view, ","); + view.contentDOM.blur(); + await vi.waitFor(() => expect(shown(view)).toBeNull()); + await new Promise((r) => setTimeout(r, 300)); + expect(shown(view)).toBeNull(); + }); + + it("doesn't open the auto-popup once the editor lost focus before it showed", async () => { + const view = editor("f", 1); + view.focus(); + typeChar(view, "("); + view.contentDOM.blur(); + await new Promise((r) => setTimeout(r, 1200)); + expect(lspSignatureHelp).not.toHaveBeenCalled(); + expect(shown(view)).toBeNull(); + }); + + it("doesn't open parameter info after a completed call once Escape was pressed before the reply", async () => { + const inside = pending(); + lspSignatureHelp.mockReturnValueOnce(inside.promise as never); + const view = editor(); + const left = parameterInfoOrLeave(view, 2); + escape(view); + inside.resolve(named("f")); + await left; + expect(shown(view)).toBeNull(); + expect(view.state.selection.main.head).toBe(2); + }); + + it("stays closed after Escape when an automatic reply was already on its way", async () => { + const late = pending(); + lspSignatureHelp.mockResolvedValueOnce(named("f") as never).mockReturnValueOnce(late.promise as never); + const view = editor(); + triggerSignatureHelp(view, true); + await vi.waitFor(() => expect(shown(view)).toBe("f")); + triggerSignatureHelp(view, false); + escape(view); + late.resolve(named("f2")); + await settle(); + expect(shown(view)).toBeNull(); + }); }); describe("C# parameter info", () => { diff --git a/src/editor/lsp/signature.ts b/src/editor/lsp/signature.ts index 288e0c6ceb..006f81a57c 100644 --- a/src/editor/lsp/signature.ts +++ b/src/editor/lsp/signature.ts @@ -188,10 +188,13 @@ function signatureTooltip(s: SigState): Tooltip { }; } -/** Per view: requests sent, and the tooltip value the newest shown reply set, with the document and caret it was asked at. */ +/** + * Per view: requests sent, the newest request sent before the user closed the tooltip, + * and the tooltip value the newest shown reply set, with the document and caret it was asked at. + */ const requests = new WeakMap< EditorView, - { sent: number; shown?: { id: number; value: SigState; doc: Text; head: number } } + { sent: number; dismissed?: number; shown?: { id: number; value: SigState; doc: Text; head: number } } >(); async function fetchSignature(view: EditorView, explicit: boolean) { @@ -204,6 +207,8 @@ async function fetchSignature(view: EditorView, explicit: boolean) { const head = state.selection.main.head; // A late reply asked at another caret never overrides what a newer request still shows for this one. const superseded = () => { + // The user closed the tooltip after this automatic request was sent: its reply must not reopen it. + if (!explicit && id <= (order.dismissed ?? 0)) return true; const shown = order.shown; return ( !!shown && @@ -244,12 +249,17 @@ async function fetchSignature(view: EditorView, explicit: boolean) { export async function parameterInfoOrLeave(view: EditorView, inside: number) { const doc = docOf(view); const state = view.state; + // An automatic request: Escape or leaving the editor before the reply drops it. + let order = requests.get(view); + if (!order) requests.set(view, (order = { sent: 0 })); + const id = ++order.sent; let help: SignatureHelp | null = null; try { if (doc) help = await lspRequest(() => commands.lspSignatureHelp(doc.doc, offsetToPos(state.doc, inside))); } catch { // No signature help: treated as nothing to fill in. } + if (id <= (order.dismissed ?? 0)) return; if (view.state.doc !== state.doc || view.state.selection.main.head !== inside) return; if (help?.signatures.some((sig) => sig.parameters.length)) view.dispatch({ effects: setSignature.of({ pos: inside, help }) }); @@ -273,7 +283,16 @@ const signaturePlugin = ViewPlugin.fromClass( clearTimeout(this.popupTimer); this.popupTimer = setTimeout(() => void fetchSignature(this.view, false), Math.max(0, p.parameterInfoDelay)); } + /** The user closed the tooltip: automatic requests already scheduled or sent don't reopen it. */ + dismiss() { + clearTimeout(this.popupTimer); + this.refresh.cancel(); + const order = requests.get(this.view); + if (order) order.dismissed = order.sent; + } update(u: ViewUpdate) { + // Leaving the editor closes the tooltip like Escape does (`focusChangeEffect` below), and nothing pending opens it. + if (u.focusChanged && !u.view.hasFocus) this.dismiss(); const active = u.state.field(signatureField, false); let typedTrigger = false; if ( @@ -409,6 +428,8 @@ export function signatureExtension(): Extension { { key: "Escape", run: (view) => { + // Also before the popup shows: an automatic one on its way stays away, and Escape goes on. + view.plugin(signaturePlugin)?.dismiss(); if (!view.state.field(signatureField, false)) return false; view.dispatch({ effects: setSignature.of(null) }); return true; diff --git a/src/editor/navigation/index.ts b/src/editor/navigation/index.ts index e54fe2a938..46eb830520 100644 --- a/src/editor/navigation/index.ts +++ b/src/editor/navigation/index.ts @@ -348,5 +348,6 @@ export function registerNavigationActions(): () => void { } export { implementationGutter } from "./implementationGutter"; +export { springAopGutter } from "./springAopGutter"; export { springBeanGutter } from "./springBeanGutter"; export { pythonStubGutter } from "./pythonStubs"; diff --git a/src/editor/navigation/lspMarkerGutter.ts b/src/editor/navigation/lspMarkerGutter.ts new file mode 100644 index 0000000000..5dba69cf96 --- /dev/null +++ b/src/editor/navigation/lspMarkerGutter.ts @@ -0,0 +1,235 @@ +/** + * Per-document gutter markers answered by one language-server request: Spring bean and Spring + * AOP navigation (`lspSpringBeanMarkers`, `lspSpringAopMarkers`). One cancellable request per + * document and 500 ms debounce; late answers are dropped. The markers follow their lines through + * edits, and are asked again when the server says they changed, when it settles, and when a + * source server stops or is removed. Library sources and documents without Gutter Icons ask + * nothing; a navigation the user waits for is served first. + */ +import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; +import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea"; +import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance"; +import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api"; +import { debounce, lspRequest } from "@/editor/lsp/lsp"; +import { onLspRefresh, onServerSettled } from "@/editor/lsp/availability"; +import { inForeground, onForeground } from "@/editor/lsp/foreground"; +import { + commands, + isCancelled, + nextRequestId, + onIdeEvent, + type IdeError, + type LspRefreshKind, + type RequestId, +} from "@/platform/ipc"; +import { editorPrefs } from "@/platform/editorSettings"; +import { useProject } from "@/platform/project"; + +const DEBOUNCE_MS = 500; + +export interface PlacedMarker { + marker: M; + /** Start of the marker's line in the current state. */ + pos: number; +} + +export interface MarkerGutterOptions { + /** Ask the server for this document's markers; `null` when no attached server provides them. */ + request: ( + request: RequestId, + doc: number, + ) => Promise<{ status: "ok"; data: M[] | null } | { status: "error"; error: IdeError }>; + /** The refresh kind the server sends when these markers may have changed. */ + refreshKind: LspRefreshKind; + /** Markers to show, left to right within a line. */ + place: (doc: Text, markers: readonly M[]) => PlacedMarker[]; + /** The gutter icon (a button) for one placed marker. */ + marker: (value: M) => GutterMarker; + /** Position in the shared icon area, after the inheritance icons (50). */ + order: number; +} + +interface LivePlugin { + readonly refreshKind: LspRefreshKind; + refreshSoon(): void; + yieldToNavigation(): void; + resumeAfterNavigation(): void; +} + +const live = new Set(); +const watchedKinds = new Set(); +let watching = false; + +function refreshAll(kind?: LspRefreshKind) { + for (const plugin of live) if (kind === undefined || plugin.refreshKind === kind) plugin.refreshSoon(); +} + +function watchChanges(kind: LspRefreshKind) { + if (!watchedKinds.has(kind)) { + watchedKinds.add(kind); + // The server's own "markers changed" (another file edited, a re-import). + onLspRefresh(kind, () => refreshAll(kind)); + } + if (watching) return; + watching = true; + // Answers given while a server was importing may be incomplete. + onServerSettled(() => refreshAll()); + // A stopped or removed source must not leave icons that navigate to old targets. + onIdeEvent("languageServer", (e) => { + if (e.status === "stopped" || e.status === "crashed") refreshAll(); + }); + onIdeEvent("languageServerRemoved", () => refreshAll()); + // Requests the user waits for go first (Go to Declaration, a refactoring), as for the inheritance icons. + onForeground((foreground) => { + for (const plugin of live) { + if (foreground) plugin.yieldToNavigation(); + else plugin.resumeAfterNavigation(); + } + }); +} + +/** Gutter markers of `ctx`'s document, placed as `options` says and drawn by its `marker` factory. */ +export function lspMarkerGutter(ctx: EditorDocContext, options: MarkerGutterOptions): Extension { + const setPlaced = StateEffect.define[]>(); + + const field = StateField.define[]>({ + create: () => [], + update(value, tr) { + for (const e of tr.effects) if (e.is(setPlaced)) return e.value; + if (!tr.docChanged || !value.length) return value; + return value.map((p) => ({ ...p, pos: mapLineStart(tr, p.pos) })); + }, + }); + + /** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */ + const markerSets = new WeakMap[], RangeSet>(); + + function placedSet(placed: readonly PlacedMarker[]): RangeSet { + let set = markerSets.get(placed); + if (!set) { + set = RangeSet.of( + placed.map(({ marker, pos }) => options.marker(marker).range(pos)), + true, + ); + markerSets.set(placed, set); + } + return set; + } + + class MarkerPlugin implements LivePlugin { + readonly refreshKind = options.refreshKind; + private refresh = debounce(() => void this.run(), DEBOUNCE_MS); + private generation = 0; + private skipped = false; + private request: RequestId | null = null; + /** A pass was cancelled or held back by a navigation: run again once it is done. */ + private yielded = false; + private offSettings: () => void; + + constructor(private view: EditorView) { + live.add(this); + watchChanges(options.refreshKind); + this.refresh(); + // Turning Gutter Icons back on asks again. + this.offSettings = useProject.subscribe((s, prev) => { + if (s.settings !== prev.settings) this.refresh(); + }); + } + + /** The markers on screen may be stale: an answer already on its way is dropped. */ + refreshSoon() { + this.generation++; + this.cancelRequest(); + this.refresh(); + } + + yieldToNavigation() { + if (this.request === null) return; + this.generation++; + this.cancelRequest(); + this.yielded = true; + } + + resumeAfterNavigation() { + if (!this.yielded) return; + this.yielded = false; + this.refresh(); + } + + update(u: ViewUpdate) { + if (u.docChanged) { + this.generation++; + this.cancelRequest(); + this.refresh(); + } else if (this.skipped && shownAgain(u)) this.refresh(); + // A local Gutter Icons override can turn the icons on. + else if (u.startState.field(localAppearanceField, false) !== u.state.field(localAppearanceField, false)) + this.refresh(); + } + + private cancelRequest() { + if (this.request === null) return; + void commands.cancelRequest(this.request).catch(() => {}); + this.request = null; + } + + private show(placed: PlacedMarker[]) { + const current = this.view.state.field(field); + if (current.length || placed.length) this.view.dispatch({ effects: setPlaced.of(placed) }); + } + + private async run() { + const view = this.view; + this.skipped = !view.dom.isConnected; + if (this.skipped) return; + if (inForeground()) { + this.yielded = true; + return; + } + const gen = ++this.generation; + this.cancelRequest(); + // Checked on every pass, as Code Vision does: excluding or including a folder changes it. + if (isLibrarySource(ctx) || !gutterIconsOn(view.state, undefined, editorPrefs())) { + this.show([]); + return; + } + const text = view.state.doc; + const stale = () => gen !== this.generation || view.state.doc !== text; + const request = (this.request = nextRequestId()); + try { + const markers = await lspRequest( + () => options.request(request, ctx.doc), + () => !stale(), + ); + if (stale()) return; + this.show(options.place(text, markers ?? [])); + } catch (e) { + if (stale()) return; + // A failed answer leaves no icon that could navigate to an old target. + this.show([]); + if (!isCancelled(e)) console.debug("[lspMarkers]", e); + } finally { + if (this.request === request) this.request = null; + } + } + + destroy() { + this.refresh.cancel(); + this.cancelRequest(); + this.offSettings(); + this.generation++; + live.delete(this); + } + } + + return [ + field, + ViewPlugin.define((view) => new MarkerPlugin(view)), + // In the shared icon area, beside the inheritance icons and the other language markers. + iconAreaSource.of({ + order: options.order, + markers: (view) => (gutterIconsOn(view.state) ? placedSet(view.state.field(field)) : RangeSet.empty), + }), + ]; +} diff --git a/src/editor/navigation/springAopGutter.test.ts b/src/editor/navigation/springAopGutter.test.ts new file mode 100644 index 0000000000..7f0ee403f4 --- /dev/null +++ b/src/editor/navigation/springAopGutter.test.ts @@ -0,0 +1,348 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ lspSpringAopMarkers: vi.fn(), cancelRequest: vi.fn(async () => ({ status: "ok" })) })); +const nav = vi.hoisted(() => ({ + navigateTo: vi.fn(), + openPopup: vi.fn(), + pinToFind: vi.fn((symbol: string) => ({ label: "Open in Find Tool Window", run: () => symbol })), +})); +const library = vi.hoisted(() => ({ excluded: false })); +const refresh = vi.hoisted(() => ({ + listeners: [] as (() => void)[], + ide: [] as { event: string; fn: (e: { status?: string }) => void }[], +})); + +vi.mock("@/platform/ipc", async (importOriginal) => ({ + ...(await importOriginal()), + isTauri: () => true, + nextRequestId: () => 7, + onIdeEvent: (event: string, fn: (e: { status?: string }) => void) => { + refresh.ide.push({ event, fn }); + return () => {}; + }, + commands: ipc, +})); +vi.mock("@/editor/api", async (importOriginal) => ({ + ...(await importOriginal()), + whenAllSynced: () => Promise.resolve(), + isLibrarySource: () => library.excluded, +})); +vi.mock("@/editor/lsp/availability", async (importOriginal) => ({ + ...(await importOriginal()), + onLspRefresh: (_: string, fn: () => void) => refresh.listeners.push(fn), + onServerSettled: () => () => {}, +})); +vi.mock("@/editor/lsp/navigation", async (importOriginal) => ({ + ...(await importOriginal()), + navigateTo: nav.navigateTo, + pinToFind: nav.pinToFind, + locationItems: async (locs: { name?: string; path: string }[]) => + locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path })), +})); +vi.mock("@/editor/lsp/popupStore", async (importOriginal) => ({ + ...(await importOriginal()), + openPopup: nav.openPopup, +})); + +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { iconAreaExtension } from "@/editor/core/cm/iconArea"; +import type { SpringAopMarker, SpringAopTarget } from "@/platform/ipc"; +import { foregroundStarted } from "@/editor/lsp/foreground"; +import { useI18n } from "@/platform/i18n"; +import { useProject } from "@/platform/project"; +import { aopTooltip, springAopGutter } from "./springAopGutter"; + +// An aspect with one advice, a service whose `place` has two advices (the toAdvice chooser) and +// whose `cancel` has one (a direct jump). +const SOURCE = [ + "@Aspect", // 0 + "class AuditAspect {", // 1 + ' @Before("execution(* Service.place(..))")', // 2 + " void before() {}", // 3 advice, advises two methods + "}", // 4 + "class Service {", // 5 + " void place() {}", // 6 advised by two advices + " void cancel() {}", // 7 advised by one advice + "}", // 8 +].join("\n"); + +const range = (line: number, col: number, len: number) => ({ + start: { line, col }, + end: { line, col: col + len }, +}); +const target = ( + path: string, + line: number, + label: string, + adviceKind: SpringAopTarget["adviceKind"], + order: number | null, +): SpringAopTarget => ({ location: { path, range: range(line, 6, 4) }, label, adviceKind, order }); +const marker = ( + line: number, + col: number, + name: string, + direction: SpringAopMarker["direction"], + targets: SpringAopTarget[], +): SpringAopMarker => ({ range: range(line, col, name.length), name, direction, targets }); + +const BEFORE = target("/p/AuditAspect.java", 3, "before · AuditAspect.before()", "before", 1); +const AROUND = target("/p/TimingAspect.java", 4, "timed · TimingAspect.timed()", "around", null); +const AFTER = target("/p/NotificationAspect.java", 3, "sent · NotificationAspect.sent()", "after", 2); +const PLACE = target("/p/Service.java", 6, "place · Service.place()", null, null); +const CANCEL = target("/p/Service.java", 7, "cancel · Service.cancel()", null, null); + +const MARKERS: SpringAopMarker[] = [ + // Unsorted on purpose: the gutter orders icons by line. + marker(6, 7, "place", "toAdvice", [AROUND, BEFORE]), + marker(7, 7, "cancel", "toAdvice", [AFTER]), + marker(3, 7, "before", "toAdvised", [PLACE, CANCEL]), + // No target and a line past the end of the text: no icon. + marker(2, 20, "unmatched", "toAdvice", []), + marker(99, 0, "gone", "toAdvised", [PLACE]), +]; + +const answer = (markers: SpringAopMarker[] | null) => ({ status: "ok", data: markers }); + +describe("spring AOP gutter", () => { + let view: EditorView | null = null; + afterEach(() => { + view?.destroy(); + view = null; + vi.clearAllMocks(); + }); + + function open(language = "java", doc = 1) { + const ctx = { doc, path: "/p/AuditAspect.java", language, virtual: false } as Parameters[0]; + view = new EditorView({ + state: EditorState.create({ doc: SOURCE, extensions: [springAopGutter(ctx), iconAreaExtension] }), + parent: document.body, + }); + return view; + } + + const buttons = () => [...view!.dom.querySelectorAll("[data-spring-aop]")]; + const button = (row: string) => + buttons().find((b) => + b.title + .split("\n") + .slice(1) + .some((r) => r.startsWith(row)), + )!; + + it("puts an icon on each advised method and advice, in line order", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + expect(ipc.lspSpringAopMarkers).toHaveBeenCalledExactlyOnceWith(7, 1); + expect(buttons().map((b) => b.dataset.springAop)).toEqual(["toAdvised", "toAdvice", "toAdvice"]); + expect(buttons().map((b) => b.title.split("\n")[0])).toEqual([ + "Navigate to Advised Methods", + "Navigate to AOP Advices", + "Navigate to AOP Advices", + ]); + }); + + it("navigates to a single advice or advised method directly", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("sent · NotificationAspect.sent()")); + await vi.waitFor(() => + expect(nav.navigateTo).toHaveBeenCalledWith({ ...AFTER.location, name: "sent · NotificationAspect.sent()" }), + ); + // An advice with one advised method navigates there too. + ipc.lspSpringAopMarkers.mockResolvedValue( + answer([marker(3, 7, "cancel", "toAdvised", [CANCEL]), marker(7, 7, "cancel", "toAdvice", [AFTER])]), + ); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 }); + fireEvent.click(buttons()[0]!); + await vi.waitFor(() => expect(nav.navigateTo).toHaveBeenCalledTimes(2)); + expect(nav.navigateTo.mock.calls[1]![0].path).toBe("/p/Service.java"); + expect(nav.openPopup).not.toHaveBeenCalled(); + }); + + it("opens the chooser with the exact titles, advice rows saying kind and order", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("timed · TimingAspect.timed()")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + const chooser = nav.openPopup.mock.calls[0]![0]; + expect(chooser.title).toBe("Navigate to AOP Advices"); + expect(chooser.items).toEqual([ + { id: "0", label: "timed · TimingAspect.timed()", detail: "Around advice" }, + { id: "1", label: "before · AuditAspect.before()", detail: "Before advice · order 1" }, + ]); + expect(nav.pinToFind).toHaveBeenCalledWith("place", expect.any(Array), undefined); + expect(nav.navigateTo).not.toHaveBeenCalled(); + }); + + it("lists advised methods by their label only", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("place · Service.place()")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + const chooser = nav.openPopup.mock.calls[0]![0]; + expect(chooser.title).toBe("Navigate to Advised Methods"); + expect(chooser.items).toEqual([ + { id: "0", label: "place · Service.place()" }, + { id: "1", label: "cancel · Service.cancel()" }, + ]); + }); + + it("writes each tooltip row like the chooser, kind and order included", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + expect(button("timed · TimingAspect.timed()").title).toBe( + "Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — Before advice · order 1", + ); + expect(button("sent · NotificationAspect.sent()").title).toBe( + "Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2", + ); + expect(buttons()[0]!.title).toBe("Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()"); + // The accessible name is the tooltip, so the icon works from the keyboard. + expect(button("timed · TimingAspect.timed()").getAttribute("aria-label")).toBe( + button("timed · TimingAspect.timed()").title, + ); + }); + + it("names advice kinds and orders in the current locale", async () => { + const texts = { "Before advice": "前置通知", "order {n}": "顺序 {n}" }; + useI18n.setState({ locale: "zh", texts }); + try { + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[0]!])); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + expect(buttons()[0]!.title).toBe( + "Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — 前置通知 · 顺序 1", + ); + fireEvent.click(buttons()[0]!); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + expect(nav.openPopup.mock.calls[0]![0].items[1]).toEqual({ + id: "1", + label: "before · AuditAspect.before()", + detail: "前置通知 · 顺序 1", + }); + } finally { + useI18n.setState({ locale: "en", texts: {} }); + } + }); + + it("keeps a late answer for older text from replacing the current one", async () => { + let first!: (v: unknown) => void; + ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (first = r))); + open(); + await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledOnce(), { timeout: 2000 }); + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!])); + view!.dispatch({ changes: { from: 0, insert: " " } }); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + first(answer(MARKERS)); + await new Promise((r) => setTimeout(r, 50)); + expect(buttons()).toHaveLength(1); + expect(ipc.cancelRequest).toHaveBeenCalled(); + }); + + it("asks again when the server says the markers changed, clearing stale icons", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + // The advice's pointcut was narrowed in another file. + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS.filter((m) => m.name !== "place"))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 }); + // No source any more (another server took over): no icons. + ipc.lspSpringAopMarkers.mockResolvedValue(answer(null)); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + }); + + it("drops an answer already on its way when the markers changed", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + let late!: (v: unknown) => void; + ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (late = r))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledTimes(2), { timeout: 2000 }); + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!])); + refresh.listeners.forEach((l) => l()); + late(answer(MARKERS.slice(0, 2))); + await new Promise((r) => setTimeout(r, 50)); + expect(buttons()).toHaveLength(3); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + }); + + it("asks again when the source server stops, clearing its icons", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + ipc.lspSpringAopMarkers.mockResolvedValue(answer(null)); + for (const { event, fn } of refresh.ide) if (event === "languageServer") fn({ status: "stopped" }); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + }); + + it("asks nothing and shows nothing while Gutter Icons are off, then asks when turned on", async () => { + const settings = useProject.getState().settings; + const withIcons = (on: boolean) => + useProject.setState({ settings: { ...(settings as object), editor: { showGutterIcons: on } } as never }); + try { + withIcons(false); + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + expect(buttons()).toHaveLength(0); + withIcons(true); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + } finally { + useProject.setState({ settings }); + } + }); + + it("asks nothing for a document in an excluded folder", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + library.excluded = true; + try { + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + } finally { + library.excluded = false; + } + }); + + it("waits for a navigation the user started before asking", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + const done = foregroundStarted(); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + done(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + }); + + it("registers nothing for other languages or virtual documents", async () => { + open("kotlin"); + view!.destroy(); + open("java", -1); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + expect(buttons()).toHaveLength(0); + }); +}); + +describe("aopTooltip", () => { + it("names each advice's kind and order, and each advised method by its label", () => { + expect(aopTooltip(MARKERS[2]!)).toBe( + "Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()", + ); + expect(aopTooltip(MARKERS[1]!)).toBe( + "Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2", + ); + }); +}); diff --git a/src/editor/navigation/springAopGutter.ts b/src/editor/navigation/springAopGutter.ts new file mode 100644 index 0000000000..42b8ad546a --- /dev/null +++ b/src/editor/navigation/springAopGutter.ts @@ -0,0 +1,116 @@ +/** + * Spring AOP gutter icons on Java documents: an advised method navigates to the advices applied + * to it, an advice method to the methods it advises. One cancellable request per document answers + * both directions (`lspSpringAopMarkers`); a server without them means no icons. Advice rows say + * their kind and, when statically known, their order. + */ +import type { Extension, Text } from "@codemirror/state"; +import { GutterMarker } from "@codemirror/view"; +import type { EditorDocContext } from "@/editor/api"; +import { locationItems } from "@/editor/lsp/navigation"; +import { commands, type SpringAopAdviceKind, type SpringAopMarker, type SpringAopTarget } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { gutterIconMarkup } from "@/ui"; +import { openTargets } from "./implementationGutter"; +import { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter"; +import styles from "./LineMarkers.module.css"; + +/** The advice kinds as the tooltip and chooser name them. */ +const KIND_LABELS: Record = { + before: "Before advice", + after: "After advice", + afterReturning: "After returning advice", + afterThrowing: "After throwing advice", + around: "Around advice", +}; + +/** Markers on lines of `doc`, left to right within a line. */ +export function placeAopMarkers(doc: Text, markers: readonly SpringAopMarker[]): PlacedMarker[] { + return markers + .filter((m) => m.range.start.line < doc.lines && m.targets.length) + .sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col) + .map((marker) => ({ marker, pos: doc.line(marker.range.start.line + 1).from })); +} + +/** An advice row's detail: its kind and, when known, the Spring order. */ +export function adviceDetail(target: SpringAopTarget): string | null { + const parts: string[] = []; + if (target.adviceKind) parts.push(tx(KIND_LABELS[target.adviceKind])); + if (target.order !== null) parts.push(tx`order ${target.order}`); + return parts.length ? parts.join(" · ") : null; +} + +/** Tooltip and accessible name: what clicking does, then each target, an advice with its kind and order. */ +export function aopTooltip(marker: SpringAopMarker): string { + const head = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods"); + const rows = marker.targets.map((target) => { + if (marker.direction !== "toAdvice") return target.label; + const detail = adviceDetail(target); + return detail ? `${target.label} — ${detail}` : target.label; + }); + return [head, ...rows].join("\n"); +} + +/** One target navigates; several open the chooser, advice rows saying their kind and order. */ +export async function openAopTargets(marker: SpringAopMarker, anchor: { x: number; y: number }) { + const targets = marker.targets.map((t) => ({ ...t.location, name: t.label })); + const title = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods"); + await openTargets(targets, anchor, title, marker.name, async (locs) => { + const items = await locationItems(locs); + if (marker.direction !== "toAdvice") return items; + return items.map((item, i) => { + const detail = adviceDetail(marker.targets[i]!); + return detail ? { ...item, detail } : item; + }); + }); +} + +class AopMarker extends GutterMarker { + readonly tooltip: string; + readonly icon: string; + + constructor(readonly marker: SpringAopMarker) { + super(); + this.tooltip = aopTooltip(marker); + this.icon = marker.direction === "toAdvice" ? "gutter-spring-aop-to-advice" : "gutter-spring-aop-to-advised"; + } + + // The DOM holds the marker it navigates with: other targets need a new button. + override eq(other: GutterMarker): boolean { + return other instanceof AopMarker && other.marker === this.marker; + } + + override toDOM(): Node { + const button = document.createElement("button"); + button.type = "button"; + button.className = styles.stubMarker ?? ""; + button.dataset.springAop = this.marker.direction; + button.title = this.tooltip; + button.setAttribute("aria-label", this.tooltip); + button.innerHTML = gutterIconMarkup(this.icon) ?? ""; + // Keep the caret where it was; the click navigates, so the icon also works from the keyboard. + button.addEventListener("mousedown", (event) => { + event.preventDefault(); + event.stopPropagation(); + }); + button.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + const rect = button.getBoundingClientRect(); + void openAopTargets(this.marker, { x: rect.left, y: rect.bottom + 2 }); + }); + return button; + } +} + +/** Java source documents of the project; library classes and virtual documents have no aspects to find. */ +export function springAopGutter(ctx: EditorDocContext): Extension { + if (ctx.doc < 0 || ctx.language !== "java") return []; + return lspMarkerGutter(ctx, { + request: (request, doc) => commands.lspSpringAopMarkers(request, doc), + refreshKind: "springAopMarkers", + place: placeAopMarkers, + marker: (marker) => new AopMarker(marker), + order: 52, + }); +} diff --git a/src/editor/navigation/springBeanGutter.ts b/src/editor/navigation/springBeanGutter.ts index c18ced5abe..608413e8a8 100644 --- a/src/editor/navigation/springBeanGutter.ts +++ b/src/editor/navigation/springBeanGutter.ts @@ -5,51 +5,19 @@ * server provides them, and none means no icons. Asked again after edits, when the server says * the bean model changed (other files edited, a re-import) and when a server settles. */ -import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; -import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea"; -import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance"; -import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api"; -import { debounce, lspRequest } from "@/editor/lsp/lsp"; -import { onLspRefresh, onServerSettled } from "@/editor/lsp/availability"; -import { inForeground, onForeground } from "@/editor/lsp/foreground"; +import type { Extension, Text } from "@codemirror/state"; +import { GutterMarker } from "@codemirror/view"; +import type { EditorDocContext } from "@/editor/api"; import { locationItems } from "@/editor/lsp/navigation"; -import { - commands, - isCancelled, - nextRequestId, - onIdeEvent, - type RequestId, - type SpringBeanMarker, -} from "@/platform/ipc"; +import { commands, type SpringBeanMarker } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; -import { editorPrefs } from "@/platform/editorSettings"; -import { useProject } from "@/platform/project"; import { gutterIconMarkup } from "@/ui"; import { openTargets } from "./implementationGutter"; +import { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter"; import styles from "./LineMarkers.module.css"; -const DEBOUNCE_MS = 500; - -interface PlacedBean { - marker: SpringBeanMarker; - /** Start of the marker's line in the current state. */ - pos: number; -} - -const setBeans = StateEffect.define(); - -const beansField = StateField.define({ - create: () => [], - update(value, tr) { - for (const e of tr.effects) if (e.is(setBeans)) return e.value; - if (!tr.docChanged || !value.length) return value; - return value.map((b) => ({ ...b, pos: mapLineStart(tr, b.pos) })); - }, -}); - /** Markers on lines of `doc`, left to right within a line. */ -export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedBean[] { +export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedMarker[] { return markers .filter((m) => m.range.start.line < doc.lines && m.targets.length) .sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col) @@ -130,166 +98,14 @@ class BeanMarker extends GutterMarker { } } -/** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */ -const markerSets = new WeakMap>(); - -function beanSet(placed: readonly PlacedBean[]): RangeSet { - let set = markerSets.get(placed); - if (!set) { - set = RangeSet.of( - placed.map(({ marker, pos }) => new BeanMarker(marker).range(pos)), - true, - ); - markerSets.set(placed, set); - } - return set; -} - -const live = new Set(); -let watching = false; - -function watchChanges() { - if (watching) return; - watching = true; - const refreshAll = () => { - for (const plugin of live) plugin.refreshSoon(); - }; - // The server's own "markers changed" (another file edited, a re-import), or it (re)started. - onLspRefresh("springBeanMarkers", refreshAll); - // Answers given while a server was importing may be incomplete. - onServerSettled(refreshAll); - // A stopped or removed source must not leave icons that navigate to old targets. - onIdeEvent("languageServer", (e) => { - if (e.status === "stopped" || e.status === "crashed") refreshAll(); - }); - onIdeEvent("languageServerRemoved", refreshAll); - // Requests the user waits for go first (Go to Declaration, a refactoring), as for the inheritance icons. - onForeground((foreground) => { - for (const plugin of live) { - if (foreground) plugin.yieldToNavigation(); - else plugin.resumeAfterNavigation(); - } - }); -} - -class BeansPlugin { - private refresh = debounce(() => void this.run(), DEBOUNCE_MS); - private generation = 0; - private skipped = false; - private request: RequestId | null = null; - /** A pass was cancelled or held back by a navigation: run again once it is done. */ - private yielded = false; - private offSettings: () => void; - - constructor( - private view: EditorView, - private ctx: EditorDocContext, - ) { - live.add(this); - watchChanges(); - this.refresh(); - // Turning Gutter Icons back on asks again. - this.offSettings = useProject.subscribe((s, prev) => { - if (s.settings !== prev.settings) this.refresh(); - }); - } - - /** The markers on screen may be stale: an answer already on its way is dropped. */ - refreshSoon() { - this.generation++; - this.cancelRequest(); - this.refresh(); - } - - yieldToNavigation() { - if (this.request === null) return; - this.generation++; - this.cancelRequest(); - this.yielded = true; - } - - resumeAfterNavigation() { - if (!this.yielded) return; - this.yielded = false; - this.refresh(); - } - - update(u: ViewUpdate) { - if (u.docChanged) { - this.generation++; - this.cancelRequest(); - this.refresh(); - } else if (this.skipped && shownAgain(u)) this.refresh(); - // A local Gutter Icons override can turn the icons on. - else if (u.startState.field(localAppearanceField, false) !== u.state.field(localAppearanceField, false)) - this.refresh(); - } - - private cancelRequest() { - if (this.request === null) return; - void commands.cancelRequest(this.request).catch(() => {}); - this.request = null; - } - - private show(placed: PlacedBean[]) { - const current = this.view.state.field(beansField); - if (current.length || placed.length) this.view.dispatch({ effects: setBeans.of(placed) }); - } - - private async run() { - const view = this.view; - this.skipped = !view.dom.isConnected; - if (this.skipped) return; - if (inForeground()) { - this.yielded = true; - return; - } - const gen = ++this.generation; - this.cancelRequest(); - // Checked on every pass, as Code Vision does: excluding or including a folder changes it. - if (isLibrarySource(this.ctx) || !gutterIconsOn(view.state, undefined, editorPrefs())) { - this.show([]); - return; - } - const text = view.state.doc; - const stale = () => gen !== this.generation || view.state.doc !== text; - const request = (this.request = nextRequestId()); - try { - const markers = await lspRequest( - () => commands.lspSpringBeanMarkers(request, this.ctx.doc), - () => !stale(), - ); - if (stale()) return; - this.show(placeBeans(text, markers ?? [])); - } catch (e) { - if (stale()) return; - // A failed answer leaves no icon that could navigate to an old target. - this.show([]); - if (!isCancelled(e)) console.debug("[springBeans]", e); - } finally { - if (this.request === request) this.request = null; - } - } - - destroy() { - this.refresh.cancel(); - this.cancelRequest(); - this.offSettings(); - this.generation++; - live.delete(this); - } -} - /** Java source documents of the project; library classes and virtual documents have no beans to find. */ export function springBeanGutter(ctx: EditorDocContext): Extension { if (ctx.doc < 0 || ctx.language !== "java") return []; - return [ - beansField, - ViewPlugin.define((view) => new BeansPlugin(view, ctx)), - // After the inheritance icons (order 50), in the shared icon area. - iconAreaSource.of({ - order: 51, - markers: (view) => (gutterIconsOn(view.state) ? beanSet(view.state.field(beansField)) : RangeSet.empty), - }), - ]; + return lspMarkerGutter(ctx, { + request: (request, doc) => commands.lspSpringBeanMarkers(request, doc), + refreshKind: "springBeanMarkers", + place: placeBeans, + marker: (marker) => new BeanMarker(marker), + order: 51, + }); } diff --git a/src/editor/refactor/javaMove.test.ts b/src/editor/refactor/javaMove.test.ts index 8fcdb34057..eea3f73f92 100644 --- a/src/editor/refactor/javaMove.test.ts +++ b/src/editor/refactor/javaMove.test.ts @@ -1,5 +1,13 @@ import { describe, expect, it } from "vitest"; -import { packageRow, runJavaRefactoringCommand, targetTypes } from "./javaMove"; +import { + moveDestinationRows, + packageRow, + problemText, + runJavaRefactoringCommand, + stoppingProblem, + targetTypes, +} from "./javaMove"; +import type { MoveDestination, MoveInfo, RefactoringProblem } from "@/bindings"; describe("java move", () => { it("shows packages by name and marks the current one", () => { @@ -22,6 +30,65 @@ describe("java move", () => { expect(targetTypes(types, new Set(["com.example.orders.App"])).map((t) => t.name)).toEqual(["Order", "Strings"]); }); + it("labels java-analyzer destinations by kind", () => { + const dest = (d: Partial): MoveDestination => + ({ + kind: "class", + id: "", + name: "", + qualifiedName: "", + detail: "", + current: false, + targetType: "", + isField: false, + ...d, + }) as MoveDestination; + const info: MoveInfo = { + kind: "instanceMethod", + label: "Dog.bark()", + destinations: [ + dest({ kind: "field", id: "field:target", name: "target", targetType: "app.Target", isField: true }), + dest({ kind: "parameter", id: "parameter:other", name: "other", targetType: "app.Target" }), + dest({ kind: "class", id: "app.Target", name: "Target", qualifiedName: "app.Target" }), + dest({ kind: "package", id: "app.text", name: "app.text" }), + dest({ kind: "package", id: "app", name: "app", current: true }), + dest({ kind: "newFile", id: "newFile", name: "Inner" }), + ], + }; + const rows = moveDestinationRows(info); + expect(rows.map((r) => r.label)).toEqual([ + "app.Target target", + "app.Target other", + "Target", + "app.text", + "app", + "Move Inner to a new file", + ]); + expect(rows[0]!.detail).toBe("Field"); + expect(rows[1]!.detail).toBe("Parameter"); + expect(rows[4]!.disabled).toBeTruthy(); + }); + + it("stops only on a fatal problem and leaves errors and warnings to confirm", () => { + const problem = (severity: RefactoringProblem["severity"]) => ({ severity, message: severity, location: null }); + expect(stoppingProblem([problem("warning"), problem("error")])).toBeUndefined(); + expect(stoppingProblem([problem("error"), problem("fatal")])?.message).toBe("fatal"); + }); + + it("appends a problem's location to its message", () => { + expect( + problemText({ + severity: "warning", + message: "This call cannot be updated automatically", + location: { + path: "/p/Main.java", + range: { start: { line: 4, col: 9 }, end: { line: 4, col: 13 } }, + }, + } as never), + ).toBe("This call cannot be updated automatically (/p/Main.java:5:10)"); + expect(problemText({ severity: "warning", message: "Plain" } as never)).toBe("Plain"); + }); + it("leaves commands it doesn't know to the server", async () => { expect(await runJavaRefactoringCommand({} as never, ["extractInterface"])).toBe(false); }); diff --git a/src/editor/refactor/javaMove.ts b/src/editor/refactor/javaMove.ts index 3afef4bf1e..6be7369cd3 100644 --- a/src/editor/refactor/javaMove.ts +++ b/src/editor/refactor/javaMove.ts @@ -1,13 +1,15 @@ /** - * Java Move (F6) and Change Signature from jdtls' client-side refactoring command - * (`java.action.applyRefactoringCommand`): Move asks for the destination (a package, a class, - * or the field or parameter an instance method moves to), then jdtls checks the move and - * computes the edit, which is applied as one change after its problems are confirmed. + * Java Move (F6): java-analyzer's `moveInfo` / `move` when the server advertises them, else + * jdtls' client-side refactoring command (`java.action.applyRefactoringCommand`). Either way + * the UI picks the destination (a package, a class, or the field or parameter an instance + * method moves to), the server checks the move and computes the edit, and the edit is applied + * as one change after its problems are confirmed. */ import type { EditorView } from "@codemirror/view"; -import type { ServerRefactored } from "@/bindings"; +import type { MoveDestination, MoveInfo, RefactoringProblem, ServerRefactored } from "@/bindings"; import { whenSynced } from "@/editor/api"; import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp"; +import { offsetToPos } from "@/editor/lsp/positions"; import { showHint } from "@/editor/lsp/hint"; import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore"; import { tx } from "@/platform/i18n"; @@ -54,6 +56,21 @@ export function targetTypes(types: readonly unknown[], exclude: ReadonlySet text(a.name).localeCompare(text(b.name))); } +/** The problem that stops a move: a fatal one. Errors and warnings are conflicts the user may accept. */ +export function stoppingProblem(problems: readonly RefactoringProblem[]): RefactoringProblem | undefined { + return problems.find((p) => p.severity === "fatal"); +} + +/** A problem's message with its location appended, for the confirmation dialog. */ +export function problemText(problem: RefactoringProblem): string { + const location = problem.location; + if (!location) return problem.message; + const path = String(location.path || location.uri || ""); + const start = location.range?.start; + if (!path || !start) return problem.message; + return `${problem.message} (${path}:${start.line + 1}:${start.col + 1})`; +} + function errorText(e: unknown): string { if (isUnavailable(e)) return unavailableText(e, "No language server available"); return e instanceof Error ? e.message : String(e); @@ -78,14 +95,14 @@ async function move(view: EditorView, kind: string, request: MoveRequest) { moved = await lspRequest(() => commands.lspJavaMove(nextRequestId(), ctx.doc, kind, JSON.stringify(request), token), ); - const fatal = moved.problems.find((p) => p.severity === "fatal"); + const fatal = stoppingProblem(moved.problems); if (fatal || (!moved.edit && !moved.confirmation)) { - showHint(view, cannotPerform(fatal?.message ?? "Nothing to change")); + showHint(view, cannotPerform(fatal?.message ?? moved.problems[0]?.message ?? "Nothing to change")); return; } if (!moved.confirmation) break; // oxlint-disable-next-line no-await-in-loop -- the confirmation gates the next request - if (!(await confirmProblems(moved.problems.map((p) => p.message)))) return; + if (!(await confirmProblems(moved.problems.map(problemText)))) return; confirmation = moved.confirmation; } } catch (e) { @@ -234,6 +251,116 @@ async function moveType(view: EditorView, params: unknown, info: Json) { if (items.length) choose(view, tx("Move"), items); } +/** One chooser row for a java-analyzer Move destination. */ +export interface MoveDestinationRow { + destination: MoveDestination; + label: string; + detail?: string; + disabled?: string; +} + +export function moveDestinationRows(info: MoveInfo): MoveDestinationRow[] { + return info.destinations.map((destination) => { + if (destination.kind === "package") { + return { + destination, + label: destination.name, + detail: destination.current ? tx("Current package") : destination.detail || undefined, + disabled: destination.current ? tx("Current package") : undefined, + }; + } + if (destination.kind === "newFile") { + return { destination, label: tx`Move ${destination.name} to a new file` }; + } + if (destination.kind === "field" || destination.kind === "parameter") { + return { + destination, + label: `${destination.targetType} ${destination.name}`, + detail: destination.isField ? tx("Field") : tx("Parameter"), + }; + } + return { destination, label: destination.name, detail: destination.qualifiedName || undefined }; + }); +} + +async function runJavaMove( + view: EditorView, + doc: number, + pos: { line: number; col: number }, + destination: MoveDestination, +): Promise { + // The caret may have moved while the chooser was open; the position the + // destinations were computed for is the one that counts. + const now = offsetToPos(view.state.doc, view.state.selection.main.head); + if (now.line !== pos.line || now.col !== pos.col) return; + let moved: ServerRefactored; + try { + await whenSynced(view); + moved = await lspRequest(() => + commands.lspMoveEdit(nextRequestId(), doc, pos, { kind: destination.kind, id: destination.id }), + ); + } catch (e) { + if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e))); + return; + } + const blocking = stoppingProblem(moved.problems); + if (blocking || !moved.edit) { + showHint(view, cannotPerform(blocking?.message ?? moved.problems[0]?.message ?? "Nothing to change")); + return; + } + const conflicts = moved.problems.filter((p) => p.severity === "warning" || p.severity === "error"); + if (conflicts.length && !(await confirmProblems(conflicts.map(problemText)))) return; + await applyEdit(view, moved.edit); +} + +/** + * Move… through java-analyzer when it advertises the pair; false when the caller should fall + * back to the generic (jdtls code action) flow. + */ +let moveBusy = false; + +export async function startJavaMove(view: EditorView): Promise { + const ctx = docOf(view); + if (!ctx || ctx.language !== "java") return false; + if (moveBusy) return true; + moveBusy = true; + try { + await whenSynced(view); + const state = view.state; + const head = state.selection.main.head; + const pos = offsetToPos(state.doc, head); + let info: MoveInfo; + try { + info = await lspRequest(() => commands.lspMoveInfo(nextRequestId(), ctx.doc, pos)); + } catch (e) { + if (isCancelled(e)) return true; + if (isUnavailable(e)) return false; + showHint(view, cannotPerform(errorText(e))); + return true; + } + if (view.state.doc !== state.doc || view.state.selection.main.head !== head) return true; + const rows = moveDestinationRows(info); + if (!rows.length) { + showHint(view, cannotPerform(tx("Nothing to move here"))); + return true; + } + choose( + view, + tx`Move ${info.label}`, + rows.map((row) => ({ + id: `${row.destination.kind}:${row.destination.id}`, + label: row.label, + detail: row.detail, + disabled: row.disabled ?? null, + run: () => void runJavaMove(view, ctx.doc, pos, row.destination), + })), + ); + return true; + } finally { + moveBusy = false; + } +} + /** `java.action.applyRefactoringCommand`: the refactorings jdtls leaves to the client. */ export async function runJavaRefactoringCommand(view: EditorView, args: readonly unknown[]): Promise { const [command, params, info] = [text(args[0]), args[1], record(args[2])]; diff --git a/src/editor/refactor/refactorThis.ts b/src/editor/refactor/refactorThis.ts index cf6f994e51..c9bfb557e9 100644 --- a/src/editor/refactor/refactorThis.ts +++ b/src/editor/refactor/refactorThis.ts @@ -23,6 +23,7 @@ import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupSt import { applyCodeAction } from "@/editor/lsp/intentions"; import { planLocalRename } from "@/editor/lsp/syntaxFallback"; import { startPythonMove } from "./pythonMove"; +import { startJavaMove } from "./javaMove"; import { HIERARCHY_REFACTORINGS, REFACTORINGS, @@ -204,6 +205,9 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi await startPythonMove(view); return; } + if (id === "move" && ctx.language === "java" && (await startJavaMove(view))) { + return; + } if (id === "extractInterface" && EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) { await startExtractInterface(view); return; diff --git a/src/features/agents/AgentPluginsPage.test.tsx b/src/features/agents/AgentPluginsPage.test.tsx index b762c69575..6e7b17e6ca 100644 --- a/src/features/agents/AgentPluginsPage.test.tsx +++ b/src/features/agents/AgentPluginsPage.test.tsx @@ -101,6 +101,7 @@ const SAMPLE_CATALOG: AgentPluginCatalog = { commandCount: 0, hookFiles: ["hooks/hooks.json"], stdioCommands: ["azure: npx -y @azure/mcp server start"], + lspCommands: ["go: gopls serve"], capabilityHash: "abc123", requiresConsent: true, }, @@ -297,6 +298,8 @@ describe("AgentPluginsPage", () => { fireEvent.click(await screen.findByRole("button", { name: "Review & Enable…" })); const dialog = await screen.findByRole("dialog", { name: /Approve Plugin Capabilities/ }); expect(within(dialog).getByText("azure: npx -y @azure/mcp server start")).toBeInTheDocument(); + expect(within(dialog).getByText("Language Server Process")).toBeInTheDocument(); + expect(within(dialog).getByText("go: gopls serve")).toBeInTheDocument(); fireEvent.click(within(dialog).getByRole("button", { name: "Trust & Enable Plugin" })); await waitFor(() => @@ -347,7 +350,9 @@ describe("AgentPluginsPage", () => { const install = within(installDlg).getByRole("button", { name: "Trust & Install Plugin" }); expect(install).toBeDisabled(); - fireEvent.click(within(installDlg).getByLabelText("Approve bundled MCP server and lifecycle hook execution")); + fireEvent.click( + within(installDlg).getByLabelText("Approve bundled MCP server, language server and lifecycle hook execution"), + ); fireEvent.click(within(installDlg).getByLabelText("Confirm static security scan warnings")); expect(install).toBeDisabled(); fireEvent.click(within(installDlg).getByLabelText("Replace the existing plugin directory")); diff --git a/src/features/agents/AgentPluginsPage.tsx b/src/features/agents/AgentPluginsPage.tsx index a2b525bffc..bad14e4c60 100644 --- a/src/features/agents/AgentPluginsPage.tsx +++ b/src/features/agents/AgentPluginsPage.tsx @@ -1022,8 +1022,8 @@ function CapabilityConsentDialog({
- This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review - its capabilities before enabling: + This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands + when active. Review its capabilities before enabling: @@ -1038,6 +1038,16 @@ function CapabilityConsentDialog({
{cmd}
))} + {(cap.lspCommands ?? []).map((cmd) => ( +
+
+ + Language Server Process + +
+
{cmd}
+
+ ))} {(cap.hookFiles ?? []).map((hf) => (
@@ -1564,6 +1574,11 @@ function InstallPluginDialog({ MCP: {cmd}
))} + {(preview.capabilities.lspCommands ?? []).map((cmd) => ( +
+ LSP: {cmd} +
+ ))} {(preview.capabilities.hookFiles ?? []).map((hf) => (
Hook: {hf} @@ -1580,7 +1595,7 @@ function InstallPluginDialog({ )} {hasScanWarnings && ( diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index b46560ab06..f2224305de 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -261,6 +261,7 @@ min-width: 0; overflow-y: auto; overflow-x: hidden; + overscroll-behavior-y: none; overflow-anchor: none; padding: var(--space-3); display: flex; diff --git a/src/features/agents/composerSubmission.test.tsx b/src/features/agents/composerSubmission.test.tsx index 4533037562..bfd588138e 100644 --- a/src/features/agents/composerSubmission.test.tsx +++ b/src/features/agents/composerSubmission.test.tsx @@ -160,6 +160,16 @@ const paths = [ { name: "new task", key: HOME, send: () => startTask(), mock: backend.create }, ]; +describe("new task agent", () => { + it("starts with the agent the composer shows when the draft names a removed agent", async () => { + updateDraft({ provider: "removed-agent" }); + updateComposer(HOME, { ...emptyDraft(), text: "hello" }); + backend.create.mockResolvedValueOnce(ok(task("created"))); + await startTask(); + expect(backend.create).toHaveBeenCalledWith(expect.objectContaining({ provider: "codex" })); + }); +}); + describe.each(paths)("$name acknowledgement", (path) => { function begin() { const response = deferred(); diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 69ef0e6e9f..fa88a14afa 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -15,6 +15,7 @@ import { isVirtualUri } from "@/platform/virtualDocs"; import { call, commands } from "@/platform/ipc"; import { maybeEditorService, + provideAgentsService, registerAgentContextSource, registerEditorDropHandler, registerEditorKind, @@ -62,6 +63,7 @@ import { connect, disconnect, openHome, + openTaskWithPrompt, refreshModels, refreshProviders, refreshTaskModels, @@ -510,7 +512,9 @@ export function activate(): () => void { }, ]), ]; + provideAgentsService({ openTaskWithPrompt }); return () => { + provideAgentsService(undefined); disposers.reverse().forEach((d) => d()); disconnect(); }; diff --git a/src/features/agents/mcpServers.test.tsx b/src/features/agents/mcpServers.test.tsx index 517721c14d..847d2c9dfb 100644 --- a/src/features/agents/mcpServers.test.tsx +++ b/src/features/agents/mcpServers.test.tsx @@ -321,6 +321,11 @@ class FakeMcpBackend implements McpBackend { name: "dengliu_kubernetes__get_pod_logs", description: "Fetch pod logs (plugin: Kubernetes [dengliu.kubernetes])", }, + { name: "list_database_connections", description: "Lists the configured database data sources" }, + { name: "list_database_schemas", description: "Lists the schemas visible to a data source" }, + { name: "list_schema_objects", description: "Lists tables, views, routines and sequences" }, + { name: "get_database_object_description", description: "Describes a table's columns, keys and indexes" }, + { name: "execute_sql_query", description: "Runs one SELECT, WITH or EXPLAIN statement after confirmation" }, ], })); @@ -451,6 +456,24 @@ describe("McpServersPage & IdeMcpServerPage (Agents › MCP)", () => { expect(await screen.findByText("check_files")).toBeInTheDocument(); }); + it("lists the database tools under Exposed IDE Tools", async () => { + const backend = new FakeMcpBackend(); + render(); + + expect(await screen.findByTestId("mcp-ide-server-page")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Inspect Tools" })); + + expect(await screen.findByText("list_database_connections")).toBeInTheDocument(); + for (const name of [ + "list_database_schemas", + "list_schema_objects", + "get_database_object_description", + "execute_sql_query", + ]) { + expect(screen.getByText(name)).toBeInTheDocument(); + } + }); + it("labels MCP servers contributed by a plugin", async () => { const backend = new FakeMcpBackend(); backend.servers = [server({ id: "plugin:slack", name: "slack", scope: "user", pluginId: "slack" })]; diff --git a/src/features/agents/openTaskWithPrompt.test.ts b/src/features/agents/openTaskWithPrompt.test.ts new file mode 100644 index 0000000000..a51fd3d5f1 --- /dev/null +++ b/src/features/agents/openTaskWithPrompt.test.ts @@ -0,0 +1,85 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { AgentTask } from "@/bindings"; +import type { ComposerDraft } from "./composerModel"; +import { SESSION_KIND, TOOL_WINDOW, sessionKey } from "./model"; +import { composerDraft, openTaskWithPrompt, useAgents } from "./store"; +import { installTaskWindowRouting } from "./taskWindowRouting"; + +const mocks = vi.hoisted(() => ({ + call: vi.fn(), + openInput: vi.fn(), + closeInput: vi.fn(), + show: vi.fn(), +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + call: mocks.call, +})); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + editorService: () => ({ openInput: mocks.openInput, closeInput: mocks.closeInput, openTabs: () => [] }), + toolWindowService: () => ({ show: mocks.show }), +})); + +const task = { id: "t", title: "Review me", status: "ready" } as AgentTask; +const PROMPT = "Summarize the diff"; + +beforeEach(() => { + mocks.call.mockReset(); + mocks.openInput.mockReset(); + mocks.closeInput.mockReset(); + mocks.show.mockReset(); + useAgents.setState({ + tasks: new Map([["t", task]]), + composers: new Map(), + sessionLocation: "editor", + docked: null, + homeOpen: true, + lastTask: null, + focus: null, + }); +}); + +describe("openTaskWithPrompt (plugins' agents.start-task handoff)", () => { + it("opens the session, prefills its message field and focuses it, without sending", () => { + openTaskWithPrompt("t", PROMPT); + expect(mocks.openInput).toHaveBeenCalledWith( + { kind: SESSION_KIND, key: sessionKey("t"), data: { task: "t", title: "Review me" } }, + { focus: true }, + ); + expect(useAgents.getState().homeOpen).toBe(false); + expect(composerDraft("t").text).toBe(PROMPT); + expect(useAgents.getState().focus).toEqual({ key: "t", seq: 1 }); + expect(mocks.call).not.toHaveBeenCalled(); + }); + + it("prefills and focuses the docked conversation in the Agents tool window", () => { + useAgents.setState({ sessionLocation: "toolWindow" }); + openTaskWithPrompt("t", PROMPT); + expect(useAgents.getState().docked).toBe("t"); + expect(mocks.show).toHaveBeenCalledWith(TOOL_WINDOW, true); + expect(mocks.openInput).not.toHaveBeenCalled(); + expect(composerDraft("t").text).toBe(PROMPT); + expect(useAgents.getState().focus).toEqual({ key: "t", seq: 1 }); + expect(mocks.call).not.toHaveBeenCalled(); + }); + + it("writes the prompt into the window that shows the task instead of opening it here", () => { + let remote: ComposerDraft = { text: "", files: [], images: [] }; + const update = vi.fn((key: string, patch: Partial) => { + if (key !== "t") return false; + remote = { ...remote, ...patch }; + return true; + }); + const stop = installTaskWindowRouting(() => true, undefined, { read: () => remote, update }); + try { + openTaskWithPrompt("t", PROMPT); + expect(mocks.openInput).not.toHaveBeenCalled(); + expect(remote.text).toBe(PROMPT); + expect(useAgents.getState().composers.has("t")).toBe(false); + expect(mocks.call).not.toHaveBeenCalled(); + } finally { + stop(); + } + }); +}); diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index feac89e02c..fdced79900 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -535,6 +535,23 @@ export function Stream({ shownRow.current = null; holdShownRow(); }, [holdShownRow]); + const scrollTowardEnd = useCallback( + (target: EventTarget | null) => { + scrollingUp.current = false; + const el = ref.current; + if (!el || !slack.current || scrollOwner(target, el) !== el) return; + // The spacer holds the reader at the scroll limit after a fold or resize. A downward + // gesture there may never fire a scroll event, so release it on input. + shownRow.current = null; + setSlack(0); + if (el.scrollHeight - el.clientHeight - el.scrollTop < 1) { + position.current = { top: el.scrollTop, stick: true }; + positions.set(key, position.current); + } + updateJumpVisibility(el); + }, + [key, positions, setSlack, updateJumpVisibility], + ); /** A diagram that drew after the last streamed chunk grows the conversation: keep following. */ const onDiagramDrawn = useCallback(() => { const el = ref.current; @@ -680,15 +697,20 @@ export function Stream({ if (owner !== el) { const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop; if (room <= 1) e.preventDefault(); + else if (e.deltaMode === WheelEvent.DOM_DELTA_PIXEL && Math.abs(e.deltaY) > room) { + // A single trackpad delta can cross the edge before the next wheel event. + e.preventDefault(); + owner.scrollTop += Math.sign(e.deltaY) * room; + } return; } markUserScroll(); if (e.deltaY < 0) stopFollowing(e.target); - else if (e.deltaY > 0) scrollingUp.current = false; + else if (e.deltaY > 0) scrollTowardEnd(owner); }; el.addEventListener("wheel", onWheel, { passive: false }); return () => el.removeEventListener("wheel", onWheel); - }, [markUserScroll, stopFollowing]); + }, [markUserScroll, scrollTowardEnd, stopFollowing]); /** * The reader opened or closed a section: put its header back where it was, in the run or * output that scrolls it and then in the conversation. Following stops when that leaves any @@ -849,7 +871,7 @@ export function Stream({ markUserScroll(); const y = e.touches.length === 1 ? e.touches[0]!.clientY : null; if (y !== null && touchY.current !== null && y > touchY.current) stopFollowing(e.target); - else if (y !== null && touchY.current !== null && y < touchY.current) scrollingUp.current = false; + else if (y !== null && touchY.current !== null && y < touchY.current) scrollTowardEnd(e.target); touchY.current = y; }} onKeyDown={(e) => { @@ -861,9 +883,9 @@ export function Stream({ e.key === "ArrowDown" || e.key === "PageDown" || e.key === "End" || - (e.key === " " && !e.shiftKey) + (e.key === " " && !e.shiftKey && !isInteractiveTarget(e.target)) ) - scrollingUp.current = false; + scrollTowardEnd(e.target); }} onPointerDown={(e) => { if (isInteractiveTarget(e.target)) return; diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index 247bd34ea1..1982392e46 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -935,6 +935,36 @@ describe("scrolling", () => { expect(el.scrollTop).toBe(1000); }); + it.each(["wheel", "touch", "End"])("clears fold space when scrolling down again with %s", async (method) => { + backend.entries.set("A", [ + { type: "thought", text: "Weighing it" }, + { type: "agent", text: "Answer A" }, + ]); + useAgents.setState({ entries: new Map(backend.entries) }); + render(); + await screen.findByText("Answer A"); + const { el, summary, slack } = foldingStream(60); + summary.getBoundingClientRect = () => ({ top: 900 - el.scrollTop }) as DOMRect; + fireEvent.click(summary); + el.scrollTop = 660; + fireEvent.scroll(el); + fireEvent.click(summary); + expect(slack()).toBe(60); + // Space on the fold header activates it; only scroll input should release the spacer. + fireEvent.keyDown(summary, { key: " " }); + expect(slack()).toBe(60); + + if (method === "wheel") fireEvent.wheel(el, { deltaY: 12 }); + else if (method === "touch") { + fireEvent.touchStart(el, { touches: [{ clientY: 100 }] }); + fireEvent.touchMove(el, { touches: [{ clientY: 88 }] }); + } else fireEvent.keyDown(el, { key: "End" }); + + expect(slack()).toBe(0); + expect(el.scrollTop).toBe(el.scrollHeight - el.clientHeight); + expect(useAgents.getState().scrollPositions.get("A")?.stick).toBe(true); + }); + it("scrolls the innermost container under the wheel and never hands it to the conversation", () => { const transcript: AgentEntry[] = [tool("live", { status: "running", output: "Tool output" })]; useAgents.setState({ entries: new Map([["A", transcript]]) }); @@ -957,6 +987,11 @@ describe("scrolling", () => { output.scrollTop = 100; expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true); expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull(); + // A large pixel delta stops at the output boundary in either direction. + expect(fireEvent.wheel(output, { deltaY: 150 })).toBe(false); + expect(output.scrollTop).toBe(200); + expect(fireEvent.wheel(output, { deltaY: -250 })).toBe(false); + expect(output.scrollTop).toBe(0); // A gesture that started in the conversation stays there when the output slides under it. now = 2000; expect(fireEvent.wheel(el, { deltaY: -4 })).toBe(true); diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index ce3da26e51..be834f4f75 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -483,11 +483,8 @@ export function draftModelSettings( } export function setDraftOption(id: string, value: string) { - const { draft, providers } = useAgents.getState(); - const config = draftConfig( - providers.find((p) => p.id === draft.provider), - draft, - ); + const { draft } = useAgents.getState(); + const config = draftConfig(selectedProvider(), draft); const model = config.find((o) => o.category === "model")?.current; const target = config.find((o) => o.id === id); if (model && target && isPerModelOption(target)) { @@ -1601,15 +1598,15 @@ export async function startTask( projectRoot: string | null = null, worktreePath?: string | null, ): Promise { - const { draft, providers } = useAgents.getState(); + const { draft } = useAgents.getState(); const composer = composerDraft(HOME); if (!canSend(composer)) return; const started = generation; const command = shellCommand(composer); - const options = draftConfig( - providers.find((p) => p.id === draft.provider), - draft, - ); + // The agent the composer shows: a draft naming a removed agent falls back to the first one. + const provider = selectedProvider(); + const providerId = provider?.id ?? draft.provider; + const options = draftConfig(provider, draft); if ( options.some( (o) => @@ -1620,7 +1617,7 @@ export async function startTask( ) return; const model = options.find((o) => o.category === "model")?.current; - const defaults = providerDefaults(draft.provider); + const defaults = providerDefaults(providerId); const config = options.flatMap((o) => { // An untouched Codex tier inherits the runtime's default; explicit Off must still be sent. const value = @@ -1636,7 +1633,7 @@ export async function startTask( commands.agentCreate({ projectRoot, prompt: promptOf(HOME, composer), - provider: draft.provider, + provider: providerId, config, isolation, base: isolation === "worktree" && !reusedWorktree ? draft.base : null, @@ -2047,6 +2044,13 @@ export function focusComposer(key: string) { useAgents.setState((s) => ({ focus: { key, seq: (s.focus?.seq ?? 0) + 1 } })); } +/** Opens an existing task with `prompt` in its message field, focused, for review before sending. */ +export function openTaskWithPrompt(task: string, prompt: string) { + openTask(task); + updateComposer(task, { text: prompt }); + focusComposer(task); +} + /** Quotes `text` (a selection of the conversation) in the task's composer, to reply to it. */ export function quoteInComposer(task: string, text: string) { updateComposer(task, { text: withQuote(composerDraft(task).text, text) }); diff --git a/src/features/app/NewProject.tsx b/src/features/app/NewProject.tsx index 5c2e7f7ff4..10c152e1c4 100644 --- a/src/features/app/NewProject.tsx +++ b/src/features/app/NewProject.tsx @@ -351,7 +351,11 @@ export function NewProjectDialog({ const [edited, setEdited] = useState>({}); const [dynamic, setDynamic] = useState<{ id: string; key: string; fields: Field[] } | null>(null); const [dynamicError, setDynamicError] = useState(null); - const [requirements, setRequirements] = useState([]); + // Tagged with their generator, so another generator's warnings don't linger until its own check returns. + const [requirements, setRequirements] = useState<{ generator: string; list: Requirement[] }>({ + generator: "", + list: [], + }); /** Installed SDKs by kind, once detected. */ const [sdks, setSdks] = useState>>({}); const detecting = useRef(new Set()); @@ -427,8 +431,8 @@ export function NewProjectDialog({ let live = true; const timer = setTimeout(() => { call(commands.scaffoldRequirements(generator.id, JSON.parse(valuesKey) as Values)) - .then((r) => live && setRequirements(r)) - .catch(() => live && setRequirements([])); + .then((list) => live && setRequirements({ generator: generator.id, list })) + .catch(() => live && setRequirements({ generator: generator.id, list: [] })); }, 300); return () => { live = false; @@ -492,7 +496,7 @@ export function NewProjectDialog({ }, [path]); const visibleFields = fields.filter((f) => isVisible(f, values)); const invalidField = visibleFields.find((f) => fieldError(f, values[f.id] ?? "")); - const missing = requirements.filter((r) => !r.satisfied); + const missing = requirements.generator === generator?.id ? requirements.list.filter((r) => !r.satisfied) : []; const loadingDynamic = !!generator?.dynamic && !dynamicFields.length && !dynamicError; const invalid = !generator || !!nameError || !location.trim() || !!invalidField || missing.length > 0 || loadingDynamic; diff --git a/src/features/app/__tests__/jetbrainsSettings.test.ts b/src/features/app/__tests__/jetbrainsSettings.test.ts index f5731c471b..bf6d253528 100644 --- a/src/features/app/__tests__/jetbrainsSettings.test.ts +++ b/src/features/app/__tests__/jetbrainsSettings.test.ts @@ -374,4 +374,108 @@ describe("planJetBrainsImport", () => { expect(plan.liveTemplates?.skipped).toEqual(["templates/Python.xml › Python › brain (Brainfuck)"]); expect(plan.liveTemplates?.unsupported).toEqual(["templates/Python.xml › Python › iter › UNKNOWN: groovyScript"]); }); + + it("adds the JDKs and the default project's Maven settings", async () => { + const jdk = (name: string, type: string, home: string) => + ``; + const bundle = { + entries: ["options/jdk.table.xml", "options/project.default.xml"], + files: { + "options/jdk.table.xml": + '' + + jdk("corretto-17", "JavaSDK", "/home/me/.jdks/corretto-17") + + jdk("temurin-21", "JavaSDK", "/opt/jdk-21") + + jdk("Python 3.12", "Python SDK", "/usr/bin/python3") + + jdk("gone", "JavaSDK", "/old/jdk") + + "", + "options/project.default.xml": + '' + + '", + }, + }; + const homes: Record = { + "/home/me/.jdks/corretto-17": "/home/me/.jdks/corretto-17", + "/opt/jdk-21": "/opt/jdk-21", + }; + const plan = await planJetBrainsImport( + bundle, + { ...settings, languages: { java: { addedJdks: ["/opt/jdk-21"] } } }, + fontHeight, + [], + async (path) => homes[path] ?? null, + ); + expect(Object.fromEntries(plan.writes)).toEqual({ + "languages.java.addedJdks": ["/opt/jdk-21", "/home/me/.jdks/corretto-17"], + "languages.java.maven.home": "/opt/maven-3.9", + "languages.java.maven.userSettings": "/home/me/.m2/work.xml", + "languages.java.maven.localRepository": "/data/m2", + }); + expect(plan.rows).toContainEqual({ label: "JDKs", value: "corretto-17" }); + expect(plan.skipped).toEqual(["gone (JDK home not found)"]); + }); + + it("imports the Gradle settings for new projects", async () => { + const bundle = { + entries: ["options/jdk.table.xml", "options/gradle.default.xml", "options/gradle.settings.xml"], + files: { + "options/jdk.table.xml": + '' + + '', + "options/gradle.default.xml": component("GradleDefaultProjectSettings", { + delegatedBuild: "false", + distributionType: "LOCAL", + gradleHome: "/opt/gradle-8.10", + gradleJvm: "17", + }), + "options/gradle.settings.xml": component("GradleSystemSettings", { serviceDirectoryPath: "/data/gradle" }), + }, + }; + const plan = await planJetBrainsImport(bundle, settings, fontHeight, [], async (path) => path); + expect(Object.fromEntries(plan.writes)).toEqual({ + "languages.java.addedJdks": ["/opt/jdk-17"], + "languages.java.gradle.distribution": "local", + "languages.java.gradle.home": "/opt/gradle-8.10", + "languages.java.gradle.runUsing": "ide", + "languages.java.gradle.jvm": "/opt/jdk-17", + "languages.java.gradle.userHome": "/data/gradle", + }); + expect(plan.rows).toContainEqual({ label: "Build and run using", value: "OpenIDEA" }); + expect(plan.rows).toContainEqual({ label: "Gradle JVM", value: "17" }); + + const wrapper = { + entries: ["options/gradle.default.xml"], + files: { + "options/gradle.default.xml": component("GradleDefaultProjectSettings", { + distributionType: "WRAPPED", + gradleJvm: "#USE_PROJECT_JDK", + }), + }, + }; + expect((await planJetBrainsImport(wrapper, settings, fontHeight, [], async (path) => path)).writes).toEqual([]); + }); + + it("leaves the Maven home to the wrapper or bundled Maven when IDEA used them", async () => { + const settingsXml = (options: string) => ({ + entries: ["options/project.default.xml"], + files: { + "options/project.default.xml": + '' + + '", + }, + }); + const writes = async (options: string) => + Object.fromEntries((await planJetBrainsImport(settingsXml(options), settings, fontHeight, [])).writes); + expect(await writes('
{note && ( diff --git a/src/features/code-insight/usageAccessFilter.test.tsx b/src/features/code-insight/usageAccessFilter.test.tsx index fc6209ac74..c8c69d795f 100644 --- a/src/features/code-insight/usageAccessFilter.test.tsx +++ b/src/features/code-insight/usageAccessFilter.test.tsx @@ -1,5 +1,12 @@ import { afterEach, describe, expect, it } from "vitest"; -import { filterUsageAccess, loadAccessOptions, toggleUsageAccess, useUsageAccessOptions } from "./UsageAccessFilter"; +import { + filterUsageAccess, + hasImportStatements, + isImportStatement, + loadAccessOptions, + toggleUsageAccess, + useUsageAccessOptions, +} from "./UsageAccessFilter"; import type { Usage } from "./usages"; const rows: Usage[] = ["read", "write", "readWrite", "unknown", undefined].map((access, line) => ({ path: "/Bean.java", @@ -9,29 +16,73 @@ const rows: Usage[] = ["read", "write", "readWrite", "unknown", undefined].map(( text: "x", access: access as Usage["access"], })); +const statement = (text: string): Usage => ({ path: "/Bean.java", line: 9, col: 7, endCol: 11, text }); afterEach(() => { localStorage.clear(); - useUsageAccessOptions.setState({ read: true, write: true }); + useUsageAccessOptions.setState({ read: true, write: true, imports: true }); }); describe("read/write visibility", () => { it("matches all three reachable states and retains unknown/legacy rows", () => { - expect(filterUsageAccess(rows, { read: true, write: true })).toHaveLength(5); - expect(filterUsageAccess(rows, { read: true, write: false }).map((u) => u.line)).toEqual([0, 2, 3, 4]); - expect(filterUsageAccess(rows, { read: false, write: true }).map((u) => u.line)).toEqual([1, 2, 3, 4]); - expect(filterUsageAccess([{ ...rows[4]!, kind: "getter" }], { read: false, write: true })).toHaveLength(1); + expect(filterUsageAccess(rows, { read: true, write: true, imports: true })).toHaveLength(5); + expect(filterUsageAccess(rows, { read: true, write: false, imports: true }).map((u) => u.line)).toEqual([ + 0, 2, 3, 4, + ]); + expect(filterUsageAccess(rows, { read: false, write: true, imports: true }).map((u) => u.line)).toEqual([ + 1, 2, 3, 4, + ]); + expect( + filterUsageAccess([{ ...rows[4]!, kind: "getter" }], { read: false, write: true, imports: true }), + ).toHaveLength(1); }); it("turns the other button on when the last visible access is turned off", () => { toggleUsageAccess("write"); - expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false }); + expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false, imports: true }); toggleUsageAccess("read"); - expect(useUsageAccessOptions.getState()).toEqual({ read: false, write: true }); + expect(useUsageAccessOptions.getState()).toEqual({ read: false, write: true, imports: true }); toggleUsageAccess("write"); - expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false }); - expect(loadAccessOptions()).toEqual({ read: true, write: false }); + expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false, imports: true }); + expect(loadAccessOptions()).toEqual({ read: true, write: false, imports: true }); }); - it("starts with both on and repairs invalid persisted state", () => { - expect(loadAccessOptions()).toEqual({ read: true, write: true }); + it("starts with everything on and repairs invalid persisted state", () => { + expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: true }); localStorage.setItem("openidea.usages.accessFilter.v1", '{"read":false,"write":false}'); - expect(loadAccessOptions()).toEqual({ read: true, write: true }); + expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: true }); + // Settings saved before the import filter existed. + localStorage.setItem("openidea.usages.accessFilter.v1", '{"read":true,"write":false}'); + expect(loadAccessOptions()).toEqual({ read: true, write: false, imports: true }); + }); +}); +describe("import statements", () => { + it("recognises the lines that begin an import statement", () => { + for (const text of [ + "import com.baomidou.mybatisplus.core.mapper.BaseMapper;", + " import static java.util.Objects.requireNonNull;", + 'import { Bean } from "./bean";', + "from myapp.models import Bean", + "import lombok.Data", + ]) + expect(isImportStatement(statement(text))).toBe(true); + for (const text of ["Bean bean = new Bean();", 'const m = await import("./mod");', "important(1)", ""]) + expect(isImportStatement(statement(text))).toBe(false); + expect(hasImportStatements(rows)).toBe(false); + expect(hasImportStatements([...rows, statement("import a.B;")])).toBe(true); + }); + it("hides only import statements when turned off, whatever their access", () => { + const items = [ + statement("import a.Bean;"), + { ...statement("import a.Bean;"), kind: "field" as const, access: "read" as const }, + { ...statement("Bean b;"), kind: "field" as const, access: "read" as const }, + statement("Bean b;"), + ]; + expect(filterUsageAccess(items, { read: true, write: true, imports: false })).toEqual([items[2], items[3]]); + expect(filterUsageAccess(items, { read: false, write: true, imports: true })).toEqual([items[0], items[3]]); + expect(filterUsageAccess(items, { read: false, write: true, imports: false })).toEqual([items[3]]); + }); + it("toggles independently of the read/write buttons and persists", () => { + toggleUsageAccess("imports"); + expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: true, imports: false }); + expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: false }); + toggleUsageAccess("imports"); + expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: true, imports: true }); }); }); diff --git a/src/features/code-insight/usagePreview.test.tsx b/src/features/code-insight/usagePreview.test.tsx index 025c782d66..be2e77d400 100644 --- a/src/features/code-insight/usagePreview.test.tsx +++ b/src/features/code-insight/usagePreview.test.tsx @@ -35,7 +35,7 @@ it("shows a plain count for unclassified searches after a Java access mode was s const { useUsages } = await import("./usages"); const { useUsageAccessOptions } = await import("./UsageAccessFilter"); const rows = [0, 1].map((line) => ({ path: "/p/a.ts", line, col: 0, endCol: 3, text: "foo()" })); - useUsageAccessOptions.setState({ read: true, write: false }); + useUsageAccessOptions.setState({ read: true, write: false, imports: true }); useUsages.setState({ tabs: [ { @@ -55,6 +55,6 @@ it("shows a plain count for unclassified searches after a Java access mode was s expect(screen.getByText("2 results")).toBeInTheDocument(); expect(screen.queryByRole("group", { name: "Usage access filters" })).toBeNull(); view.unmount(); - useUsageAccessOptions.setState({ read: true, write: true }); + useUsageAccessOptions.setState({ read: true, write: true, imports: true }); useUsages.setState({ tabs: [], active: null }); }); diff --git a/src/features/code-insight/usagesExport.test.tsx b/src/features/code-insight/usagesExport.test.tsx index 57e7d20332..bafd5fa90b 100644 --- a/src/features/code-insight/usagesExport.test.tsx +++ b/src/features/code-insight/usagesExport.test.tsx @@ -26,7 +26,7 @@ const { useUsages } = await import("./usages"); const { useUsageAccessOptions } = await import("./UsageAccessFilter"); const { useProject } = await import("@/platform/project"); -const ALL = { read: true, write: true }; +const ALL = { read: true, write: true, imports: true }; const usage = (path: string, line: number, text: string, access?: Usage["access"]): Usage => ({ path, line, @@ -96,7 +96,7 @@ describe("usagesReportText", () => { }); it("applies the access filter and drops files it empties", () => { - const text = usagesReportText(search(), "/p", { read: false, write: true }, new Set()); + const text = usagesReportText(search(), "/p", { read: false, write: true, imports: true }, new Set()); expect(text).toBe( [ "Usages of 'total' in Project Files", @@ -181,7 +181,7 @@ describe("exportUsagesToTextFile", () => { show(search({ loading: true })); expect(canExportUsages()).toBe(false); show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] })); - useUsageAccessOptions.setState({ read: true, write: false }); + useUsageAccessOptions.setState({ read: true, write: false, imports: true }); expect(canExportUsages()).toBe(false); await exportUsagesToTextFile(); expect(save).not.toHaveBeenCalled(); @@ -215,7 +215,7 @@ describe("toolbar", () => { expect(button).toBeDisabled(); expect(canExportUsages()).toBe(false); act(() => show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] }))); - act(() => useUsageAccessOptions.setState({ read: true, write: false })); + act(() => useUsageAccessOptions.setState({ read: true, write: false, imports: true })); expect(screen.getByRole("button", { name: "Export to Text File…" })).toBeDisabled(); view.unmount(); }); diff --git a/src/features/code-insight/usagesPopup.test.tsx b/src/features/code-insight/usagesPopup.test.tsx index b1f83c9d7e..85db7ff6a8 100644 --- a/src/features/code-insight/usagesPopup.test.tsx +++ b/src/features/code-insight/usagesPopup.test.tsx @@ -67,7 +67,7 @@ const { useUsageAccessOptions } = await import("./UsageAccessFilter"); afterEach(() => act(() => { dismissUsagesPopup(); - useUsageAccessOptions.setState({ read: true, write: true }); + useUsageAccessOptions.setState({ read: true, write: true, imports: true }); localStorage.removeItem("openidea.usages.accessFilter.v1"); localStorage.removeItem("openidea.usages.popupSize.v1"); }), @@ -96,7 +96,7 @@ describe("Show Usages popup", () => { it("Open in Find Window moves the found usages instead of searching again", () => { open(); - fireEvent.click(screen.getByText(/Open in Find Window/)); + fireEvent.click(screen.getByRole("button", { name: "Open in Find Tool Window" })); expect(useUsagesPopup.getState().open).toBe(false); expect(showUsageResults).toHaveBeenCalledWith({ symbol: "foo", @@ -213,7 +213,7 @@ describe("semantic usage categories", () => { fireEvent.click(screen.getByRole("button", { name: "Show read accesses" })); expect(screen.getByRole("button", { name: "Show write accesses" })).toHaveAttribute("aria-pressed", "true"); expect(screen.getByText("3 of 4 found")).toBeInTheDocument(); - fireEvent.click(screen.getByText(/Open in Find Window/)); + fireEvent.click(screen.getByRole("button", { name: "Open in Find Tool Window" })); expect(showUsageResults).toHaveBeenLastCalledWith( expect.objectContaining({ classified: expect.arrayContaining([ @@ -242,6 +242,31 @@ it("keeps unknown results visible after classified results are replaced", () => expect(screen.getAllByRole("option")).toHaveLength(3); }); +it("filters import statements of a target without read/write classification", () => { + open(); + act(() => + useUsagesPopup.setState({ + groups: [ + { + path: "/p/Service.java", + usages: [ + usage("/p/Service.java", 0, "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"), + usage("/p/Service.java", 5, "public interface Service extends BaseMapper {}"), + ], + }, + ], + }), + ); + expect(screen.queryByRole("button", { name: "Show read accesses" })).toBeNull(); + expect(screen.getAllByRole("option")).toHaveLength(2); + fireEvent.click(screen.getByRole("button", { name: "Show import statements" })); + expect(screen.getByRole("button", { name: "Show import statements" })).toHaveAttribute("aria-pressed", "false"); + expect(screen.getByText("1 of 2 found")).toBeInTheDocument(); + expect(screen.getAllByRole("option")).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "Show import statements" })); + expect(screen.getAllByRole("option")).toHaveLength(2); +}); + it("preserves an exact multiline semantic range when transferring to Find", () => { const sourceLocation = { path: "/Bean.java", range: { start: { line: 1, col: 0 }, end: { line: 2, col: 10 } } }; expect( diff --git a/src/features/color-preview/ColorPreview.module.css b/src/features/color-preview/ColorPreview.module.css index 6f5e260942..3cbe045bee 100644 --- a/src/features/color-preview/ColorPreview.module.css +++ b/src/features/color-preview/ColorPreview.module.css @@ -23,6 +23,16 @@ width: 100%; height: 100%; } +/* A server color in the text (a Tailwind class): sized to the line, before the class. */ +.inline { + display: inline-block; + width: 0.8em; + height: 0.8em; + margin: 0 0.25em 0 0; + padding: 0; + vertical-align: -0.05em; + background: none; +} .editable { cursor: pointer; } diff --git a/src/features/color-preview/colors.test.ts b/src/features/color-preview/colors.test.ts index 1c1cc395f9..2abfbafa93 100644 --- a/src/features/color-preview/colors.test.ts +++ b/src/features/color-preview/colors.test.ts @@ -22,6 +22,11 @@ describe("findColors", () => { expect(texts("@media screen { }", "css")).toEqual([]); expect(texts(" color: $white; background: var(--off-white) off-white;", "scss")).toEqual([]); expect(texts(" color: #12345;", "css")).toEqual([]); + // A property name after an earlier declaration on the line (WebKit takes `background` as a system color). + expect(texts(".one { color: var(--brand); white: 0; }", "css")).toEqual([]); + expect(texts('

', "html")).toEqual([]); + expect(texts("a:hover { white: 0 }", "css")).toEqual([]); + expect(texts(".one { color: var(--brand); border: 1px solid white; }", "css")).toEqual(["white"]); }); it("takes only quoted hex values in code, and no names", () => { diff --git a/src/features/color-preview/colors.ts b/src/features/color-preview/colors.ts index 9b59ebc336..e8bf8a6db5 100644 --- a/src/features/color-preview/colors.ts +++ b/src/features/color-preview/colors.ts @@ -63,13 +63,17 @@ const JAVA_INT = /\bnew\s+(?:(?:java\.awt|javax\.swing\.plaf)\.)?(?:Color|ColorUIResource)\s*\(\s*(0[xX][0-9a-fA-F]{1,8})\s*\)/g; /** - * Whether `line` before `from` reads `property: value…` (`/:\s*(?:\S+\s+)*$/`). Only the text after - * the last colon is tested: a line of markup has many words, and testing the whole prefix for each - * was quadratic. + * Whether `line` before `from` reads `property: value…` (`/:\s*(?:\S+\s+)*$/`) within one + * declaration: a `;`, `{` or `}` after the colon starts the next one, whose property name is no value + * (`color: var(--a); background: …` must not read `background` as WebKit's system color). Only the + * text after the last colon is tested: a line of markup has many words, and testing the whole prefix + * for each was quadratic. */ function afterPropertyColon(line: string, from: number): boolean { const colon = line.lastIndexOf(":", from - 1); - return colon >= 0 && /^\s*(?:\S+\s+)*$/.test(line.slice(colon + 1, from)); + if (colon < 0) return false; + const value = line.slice(colon + 1, from); + return !/[;{}]/.test(value) && /^\s*(?:\S+\s+)*$/.test(value); } /** Global keywords and words that are valid colors but say nothing about one. */ diff --git a/src/features/color-preview/gutter.test.ts b/src/features/color-preview/gutter.test.ts index 2351cd17a7..d4d93afdf1 100644 --- a/src/features/color-preview/gutter.test.ts +++ b/src/features/color-preview/gutter.test.ts @@ -141,7 +141,7 @@ it("samples a screen color and offers it again as a recent color", async () => { expect(view.state.doc.toString()).toBe("color: #4c78ce;"); }); -it("ignores color-like Vue template text while previewing embedded styles", () => { +it("ignores color-like Vue template text while previewing embedded styles", async () => { view = new EditorView({ state: EditorState.create({ doc: '\n', @@ -152,8 +152,32 @@ it("ignores color-like Vue template text while previewing embedded styles", () = }), parent: document.body, }); - const swatches = [...view.dom.querySelectorAll(".cm-openidea-gutter-colors .cm-gutterElement span[title]")]; - expect(swatches.map((swatch) => swatch.getAttribute("title"))).toEqual(["#abc", "#ff0080"]); + // Shown once the background parse reaches the styles (it may finish after the editor opened). + await vi.waitFor(() => { + const swatches = [...view!.dom.querySelectorAll(".cm-openidea-gutter-colors .cm-gutterElement span[title]")]; + expect(swatches.map((swatch) => swatch.getAttribute("title"))).toEqual(["#abc", "#ff0080"]); + }); +}); + +it("shows a markup file's style colors once a parse that outlasted opening the editor finishes", async () => { + const styles = Array.from({ length: 4000 }, (_, i) => `.c${i} { margin: ${i}px; }`).join("\n"); + view = new EditorView({ + state: EditorState.create({ + doc: ``, + extensions: [ + vue(), + colorPreviewGutter({ doc: 1, path: "/p/a.vue", language: "vue", uiMode: null, readOnly: false }), + ], + }), + parent: document.body, + }); + view.scrollDOM.style.height = "100px"; + view.dispatch({ effects: EditorView.scrollIntoView(view.state.doc.length) }); + // The parse runs in idle time, which a busy machine gives out slowly. + await vi.waitFor( + () => expect(view!.dom.querySelector('.cm-openidea-gutter-colors span[title="#ff0080"]')).not.toBeNull(), + { timeout: 10_000 }, + ); }); it("ignores color-like HTML text while previewing inline styles", () => { diff --git a/src/features/color-preview/gutter.ts b/src/features/color-preview/gutter.ts index 11c992ace5..c78328f7c5 100644 --- a/src/features/color-preview/gutter.ts +++ b/src/features/color-preview/gutter.ts @@ -5,7 +5,7 @@ * its declaration, and modern function syntaxes show the resolved value without a picker. */ import { Facet, StateEffect, StateField, type EditorState, type Extension, type RangeSet } from "@codemirror/state"; -import { Decoration, EditorView, GutterMarker, WidgetType, gutter } from "@codemirror/view"; +import { Decoration, EditorView, GutterMarker, WidgetType, gutter, type ViewUpdate } from "@codemirror/view"; import { isolateHistory } from "@codemirror/commands"; import { syntaxTree } from "@codemirror/language"; import type { EditorDocContext } from "@/editor/api"; @@ -138,7 +138,7 @@ class Swatch extends GutterMarker { * usages resolving to a color, in source order and without overlaps (a `color-mix()` swatch covers * the `var()` references inside it). */ -export function lineSwatches(state: EditorState, pos: number, language: string): SwatchSpec[] { +export function lineSwatches(state: EditorState, pos: number, language: string, max = MAX_SWATCHES): SwatchSpec[] { const line = state.doc.lineAt(pos); if (line.length > MAX_LINE) return []; const matches = findColors(line.text, language, isColorName); @@ -174,7 +174,7 @@ export function lineSwatches(state: EditorState, pos: number, language: string): specs.sort((a, b) => a.from - b.from); const merged: SwatchSpec[] = []; for (const s of specs) if (!merged.length || merged[merged.length - 1]!.to <= s.from) merged.push(s); - return merged.slice(0, MAX_SWATCHES); + return merged.slice(0, max); } export function limitSwatches( @@ -320,6 +320,15 @@ function swatchCount(view: EditorView, held: number): number { return held; } +/** + * In markup (HTML, Vue…) a literal counts only inside a style, which the syntax tree tells: the + * background parse finishing after the editor opened changes the swatches of lines it reached. + */ +function parsedFurther(update: ViewUpdate): boolean { + const ctx = update.state.facet(colorContext); + return !!ctx && isMarkupLanguage(ctx.language) && syntaxTree(update.startState) !== syntaxTree(update.state); +} + export const colorGutter = gutter({ class: `${styles.gutter} cm-openidea-gutter-colors`, markers: (view) => view.state.facet(colorMarkers).map((markers) => markers(view)), @@ -330,7 +339,8 @@ export const colorGutter = gutter({ !update.viewportChanged && !update.geometryChanged && update.startState.facet(colorContext) === update.state.facet(colorContext) && - !update.transactions.some((tr) => tr.effects.length > 0) + !update.transactions.some((tr) => tr.effects.length > 0) && + !parsedFurther(update) ) return previous; const held = previous instanceof ColorSpacer ? previous.count : 0; @@ -345,6 +355,7 @@ export const colorGutter = gutter({ }, lineMarkerChange: (update) => update.docChanged || + parsedFurther(update) || update.startState.facet(colorContext) !== update.state.facet(colorContext) || update.startState.readOnly !== update.state.readOnly || update.transactions.some((tr) => tr.effects.some((e) => e.is(setVars))), diff --git a/src/features/color-preview/lspColors.test.ts b/src/features/color-preview/lspColors.test.ts index 2284b84b00..cd0b3f99ce 100644 --- a/src/features/color-preview/lspColors.test.ts +++ b/src/features/color-preview/lspColors.test.ts @@ -56,7 +56,7 @@ const swatches = (view: EditorView) => [ ...view.dom.querySelectorAll('button[data-color-source^="lsp:"]'), ]; -it("shares the four swatch slots across built-in, plugin and server colors on each line", async () => { +it("shares the four gutter slots with server colors on literals and shows the others in the text", async () => { vi.useFakeTimers(); ipc.pluginLanguageVisuals.mockResolvedValue({ status: "ok", @@ -86,8 +86,14 @@ it("shares the four swatch slots across built-in, plugin and server colors on ea const rows = [...view.dom.querySelectorAll(".cm-openidea-gutter-colors .cm-gutterElement")].filter((row) => row.querySelector("[title]"), ); - expect(rows.map((row) => row.querySelectorAll("[title]").length)).toEqual([4, 4, 4]); - const serverSwatch = swatches(view)[0]!; + // Line 1: its literals (built-in and server); line 2: a literal and the plugin color. The server + // colors on `p0`…`p4` aren't literals: they are swatches in the text, as WebStorm shows Tailwind + // classes' colors. + expect(rows.map((row) => row.querySelectorAll("[title]").length)).toEqual([4, 2]); + const inline = view.contentDOM.querySelectorAll('button[data-color-source^="lsp:"]'); + expect(inline).toHaveLength(10); + expect(view.contentDOM.querySelectorAll(".cm-line")[2]!.firstElementChild).toBe(inline[5]); + const serverSwatch = inline[0]! as HTMLButtonElement; await act(async () => fireEvent.mouseDown(serverSwatch, { button: 0 })); expect(screen.queryByRole("dialog", { name: "Color picker" })).not.toBeInTheDocument(); await act(async () => fireEvent.click(serverSwatch)); @@ -112,6 +118,20 @@ it("keeps the server's swatch for the second literal on a line", () => { expect(serverOnlyColors(state, "css", [literal, second])).toEqual([second]); }); +it("shows a Tailwind class's color in the text and a CSS value's in the gutter", async () => { + vi.useFakeTimers(); + const second = color(0, 0, 1, [0, 0, 1]); + ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [literal, tailwind, second] }); + const view = open(CSS, "css"); + await vi.advanceTimersByTimeAsync(300); + const inline = view.contentDOM.querySelectorAll('button[data-color-source^="lsp:"]'); + expect([...inline].map((b) => [view.posAtDOM(b), b.title])).toEqual([ + [0, "rgba(0, 0, 255, 1)"], + [view.state.doc.line(2).from + 12, "rgba(239, 68, 68, 1)"], + ]); + expect(view.dom.querySelectorAll('.cm-gutters button[data-color-source^="lsp:"]')).toHaveLength(0); +}); + it("keeps valid swatches when a server reports a range outside the document", async () => { vi.useFakeTimers(); ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [color(2, 0, 6, [0, 1, 0]), tailwind] }); diff --git a/src/features/color-preview/lspColors.ts b/src/features/color-preview/lspColors.ts index 32065e979c..570ee23fc9 100644 --- a/src/features/color-preview/lspColors.ts +++ b/src/features/color-preview/lspColors.ts @@ -2,9 +2,12 @@ * Colors the language servers report (`textDocument/documentColor`: Tailwind classes, CSS values…). * A color the built-in literal preview already shows at the same range gets no second swatch, and * picking a color writes it the way the server presents it (`textDocument/colorPresentation`). + * A color on a literal the built-in preview recognises (a CSS value) is a gutter icon, like the + * built-in ones; any other (a Tailwind class) is a swatch in the text before it, as WebStorm shows + * Tailwind CSS colors. */ import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state"; -import { ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { Decoration, EditorView, ViewPlugin, WidgetType, type ViewUpdate } from "@codemirror/view"; import { offsetsToRange, rangeToOffsets, @@ -22,6 +25,7 @@ import { useProject } from "@/platform/project"; import { colorGutter, colorMarkers, limitSwatches, lineSwatches } from "./gutter"; import { pluginSwatches } from "./pluginColors"; import { ProviderSwatch, mapColors } from "./providerSwatch"; +import styles from "./ColorPreview.module.css"; const setColors = StateEffect.define(); const colors = StateField.define({ @@ -62,8 +66,43 @@ export function serverOnlyColors(state: EditorState, language: string, list: Doc }); } +/** Whether `color` covers text the built-in preview shows as a color (a literal or a variable). */ +function onLiteral(state: EditorState, language: string, color: DocumentColor): boolean { + const { from, to } = rangeToOffsets(state.doc, color.range); + const line = state.doc.lineAt(from); + return lineSwatches(state, line.from, language, Infinity).some( + (s) => line.from + s.from < to && line.from + s.to > from, + ); +} + +/** A server color's swatch in the text, before the class or value it colors. */ +class InlineSwatch extends WidgetType { + constructor( + readonly color: DocumentColor, + readonly make: (view: EditorView, color: DocumentColor) => ProviderSwatch, + ) { + super(); + } + override eq(other: WidgetType) { + return other instanceof InlineSwatch && JSON.stringify(this.color) === JSON.stringify(other.color); + } + override toDOM(view: EditorView) { + const el = this.make(view, this.color).toDOM(); + el.classList.add(styles.inline!); + return el; + } + override ignoreEvent() { + return true; + } +} + export function lspColorPreview(ctx: EditorDocContext): Extension { if (ctx.doc < 0) return []; + const swatch = (view: EditorView, c: DocumentColor) => + new ProviderSwatch(`lsp:${c.server}`, c, view, async (chosen) => { + const list = await call(commands.lspColorPresentations(ctx.doc, chosen)); + return list.map((p) => ({ label: p.label, changes: textEditsToChanges(view.state.doc, p.edits) })); + }); return [ colors, colorGutter, @@ -73,19 +112,30 @@ export function lspColorPreview(ctx: EditorDocContext): Extension { limitSwatches( view.state, ctx.language, - view.state.field(colors), + view.state.field(colors).filter((c) => onLiteral(view.state, ctx.language, c)), (c) => c.range, pluginSwatches(view.state, ctx.language).map(([, c]) => c.range), - ).map((c) => - new ProviderSwatch(`lsp:${c.server}`, c, view, async (chosen) => { - const list = await call(commands.lspColorPresentations(ctx.doc, chosen)); - return list.map((p) => ({ label: p.label, changes: textEditsToChanges(view.state.doc, p.edits) })); - }).range(view.state.doc.line(c.range.start.line + 1).from), - ), - true, + ).map((c) => swatch(view, c).range(view.state.doc.line(c.range.start.line + 1).from)), ) : RangeSet.empty, ), + // Recomputed when the server answers or an edit moves the colors; hidden colors are cleared. + EditorView.decorations.compute([colors], (state) => + Decoration.set( + state + .field(colors) + .flatMap((c) => + onLiteral(state, ctx.language, c) + ? [] + : [ + Decoration.widget({ widget: new InlineSwatch(c, swatch), side: -1 }).range( + rangeToOffsets(state.doc, c.range).from, + ), + ], + ), + true, + ), + ), ViewPlugin.define( (view) => new (class { diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index b9a85710fd..b5466457b3 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -135,6 +135,8 @@ function isAttachableTarget(arg: unknown): arg is { show?: boolean; /** Merged into the attach request's arguments (Xcode's `sourceMap`). */ extra?: Record; + /** Re-runs the full launch + attach flow after installing a missing adapter. */ + retry?: () => void; } { const a = (arg && typeof arg === "object" ? arg : {}) as { attachable?: Partial }; return typeof a.attachable?.pid === "number" && typeof a.attachable.kind === "string"; @@ -790,13 +792,14 @@ export function registerDebugActions(): () => void { // Another JVM of the same run (a Gradle test worker, the one just detached) keeps it. const shared = process != null && - (justDetached(process) || + (justDetached(process, launch.adapter) || Object.values(useDebug.getState().sessions).some((s) => s.process === process && isLive(s))); const session = await startSession(launch, { process, runConfig: arg.runConfig, rerunnable: false, show: (arg as { show?: boolean }).show, + ...(isAttachableTarget(arg) && arg.retry ? { retry: arg.retry } : {}), }); // The process was started for this debugger and waits for it (`suspend=y`): without // the attach it would never go on, and Stop on the finished session can't reach it. diff --git a/src/features/debugger/launch.ts b/src/features/debugger/launch.ts index 7da89da4e8..354d142a5d 100644 --- a/src/features/debugger/launch.ts +++ b/src/features/debugger/launch.ts @@ -554,6 +554,7 @@ export function launchConfigFor( if (adapter === "delve") return delveLaunch(rc, cwd, root); if (adapter === "godot") return godotLaunch(rc, cwd); if (adapter === "php-debug") return phpDebugLaunch(rc, cwd, php); + if (adapter === "netcoredbg" && rc.kind === "dotnet-test") return null; if (adapter === "netcoredbg" && rc.kind === "dotnet") { if (!rc.params?.targetPath) return null; return { diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 3682099bf5..6f0a3fa09e 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -499,8 +499,11 @@ function replaceFinished(name: string, configId?: string, defer = false): Replac * An attach to `process` this soon after a session on it ended may be to such a JVM. */ const RELISTEN_MS = 3000; -export function justDetached(process: RunId | null | undefined): boolean { +/** The JVM debuggers, whose test workers reconnect to the same run (`DebugToolWindow`'s `JVM_ADAPTERS`). */ +const JDWP_ADAPTERS = new Set(["java-debug", "kotlin-debug-adapter", "kotlin-lsp"]); +export function justDetached(process: RunId | null | undefined, adapter?: string): boolean { if (process == null) return false; + if (adapter && !JDWP_ADAPTERS.has(adapter)) return false; const now = Date.now(); return Object.values(useDebug.getState().sessions).some( (s) => s.process === process && s.status === "terminated" && s.endedAt != null && now - s.endedAt < RELISTEN_MS, @@ -1005,7 +1008,7 @@ export async function startSession( return null; } // Attaching to a JVM that may be gone: the finished session stays until the attach succeeds. - const afterDetach = justDetached(options.process); + const afterDetach = justDetached(options.process, launch.adapter); const previousActive = useDebug.getState().active; // The finished tab stays in place until the new session appears there. let replaced = diff --git a/src/features/deployment/RemoteHostView.tsx b/src/features/deployment/RemoteHostView.tsx index 0da0ac4ace..db2da5a469 100644 --- a/src/features/deployment/RemoteHostView.tsx +++ b/src/features/deployment/RemoteHostView.tsx @@ -115,6 +115,18 @@ export function RemoteHostView() { disabled: !entries.length, run: () => void downloadTo(server, entries), }, + ...(server.kind === "sftp" && server.sshConfig + ? [ + { kind: "separator" as const }, + { + id: "sshSession", + label: "Start SSH Session in Directory", + icon: "terminal" as const, + disabled: !target, + run: () => target && void executeAction("ssh.startSession", { id: server.sshConfig, cwd: target }), + }, + ] + : []), { kind: "separator" }, { id: "newFolder", diff --git a/src/features/dotnet/index.ts b/src/features/dotnet/index.ts index 56df613aec..1d92773661 100644 --- a/src/features/dotnet/index.ts +++ b/src/features/dotnet/index.ts @@ -138,6 +138,7 @@ export function activate() { ...(["build", "restore", "clean"] as const).map((op) => ({ id: `dotnet.${op}`, title: op === "build" ? "Build .NET Project" : op === "restore" ? "Restore .NET Project" : "Clean .NET Project", + ...(op === "restore" ? { icon: "project-dotnet" } : {}), category: "Build", when: "projectOpen", run: ({ arg }: { arg?: unknown }) => buildDotnet(op, arg, runAudit), @@ -284,7 +285,7 @@ export function activate() { if (!path || !(isDotnetProjectPath(path) || isDotnetSolutionPath(path))) return []; return [ { kind: "action", action: "dotnet.build", arg: path }, - { kind: "action", action: "dotnet.restore", arg: path }, + // Restore is the project view's shared install item (`run.installDependencies`). { kind: "action", action: "dotnet.clean", arg: path }, ...(isDotnetFormatPath(path) ? (["dotnet.format", "dotnet.formatVerify"] as const).map((action): MenuItem => ({ diff --git a/src/features/dotnet/store.ts b/src/features/dotnet/store.ts index 94eb1d7155..2cb7c6cd9f 100644 --- a/src/features/dotnet/store.ts +++ b/src/features/dotnet/store.ts @@ -395,7 +395,7 @@ export async function runTests(test?: string) { env: {}, detected: true, isTest: true, - debugAdapter: null, + debugAdapter: "netcoredbg", params: { project: p.path, framework, diff --git a/src/features/dotnet/window.test.ts b/src/features/dotnet/window.test.ts index 94e6516abb..827f58225f 100644 --- a/src/features/dotnet/window.test.ts +++ b/src/features/dotnet/window.test.ts @@ -62,14 +62,13 @@ describe("standalone .NET tool window removal", () => { expect(list).toHaveBeenCalled(); }); - it("offers Build / Restore / Clean for a solution or project file in the Project view context menu", () => { + it("offers Build / Clean for a solution or project file in the Project view context menu (Restore is the shared install item)", () => { const actions = (path: string) => menuGroupItems("projectView", { paths: [path], dirs: [false] }).map((i) => i.kind === "action" ? `${i.action} ${String(i.arg)}` : i.kind, ); expect(actions("/repo/src/App/App.csproj")).toEqual([ "dotnet.build /repo/src/App/App.csproj", - "dotnet.restore /repo/src/App/App.csproj", "dotnet.clean /repo/src/App/App.csproj", "dotnet.format /repo/src/App/App.csproj", "dotnet.formatVerify /repo/src/App/App.csproj", @@ -81,7 +80,6 @@ describe("standalone .NET tool window removal", () => { ]); expect(actions("/repo/Demo.sln")).toEqual([ "dotnet.build /repo/Demo.sln", - "dotnet.restore /repo/Demo.sln", "dotnet.clean /repo/Demo.sln", "dotnet.format /repo/Demo.sln", "dotnet.formatVerify /repo/Demo.sln", diff --git a/src/features/github/details/Details.module.css b/src/features/github/details/Details.module.css index daab5a1d6c..9fcf8504bd 100644 --- a/src/features/github/details/Details.module.css +++ b/src/features/github/details/Details.module.css @@ -469,22 +469,26 @@ align-items: center; gap: var(--space-1); } +/* An editor (`src/editor/TextField.tsx`) filling the popup's free height. */ .submitEditor { flex: 1; min-height: 40px; - padding: var(--space-1) var(--space-2); + overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--bg-input); color: var(--fg); - font: inherit; line-height: var(--lh-code); - resize: none; - outline: none; } -.submitEditor:focus { +.submitEditor:focus-within { border-color: var(--focus-ring); } +.submitEditor :global(.cm-content) { + padding: var(--space-1) var(--space-2); +} +.submitEditor :global(.cm-editor.cm-focused) { + outline: none; +} .submitError { flex: 0 1 auto; min-height: 0; diff --git a/src/features/github/details/SubmitReviewPopup.tsx b/src/features/github/details/SubmitReviewPopup.tsx index 789116462a..1c3fc8ecc9 100644 --- a/src/features/github/details/SubmitReviewPopup.tsx +++ b/src/features/github/details/SubmitReviewPopup.tsx @@ -6,6 +6,7 @@ * it, or centred in the window. 500×200, resizable. */ import { useEffect, useState } from "react"; +import { TextField } from "@/editor/TextField"; import { Button, IconButton, Popup, Spinner, T } from "@/ui"; import { resolveMonoFont } from "@/platform/fonts"; import { useTx, tx } from "@/platform/i18n"; @@ -129,20 +130,23 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element

-