Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 25911a96fc fix(debugger): skip Windows Store Python aliases when starting debugpy
The built-in python.toml starts debugpy's adapter with a bare python3. On
Windows that name (and often python) resolves to an App Execution Alias in
%LOCALAPPDATA%\Microsoft\WindowsApps, which fails to start unless the
Store's Python is installed, so a Python Debug Server reported "failed to
start ...\WindowsApps\python3.exe" even with Python installed and on PATH.

The adapter now takes every match on PATH of the command, then python,
then the py launcher, and uses the first that is no alias or one that runs,
as the IDE already does when it installs Python tools.

Fixes #6818
2026-11-29 18:30:48 +08:00
1352 змінених файлів з 6378 додано та 111127 видалено

No files matched your search

-7
Переглянути файл
@@ -11,10 +11,3 @@ package(=ide-clipboard) & (
)
'''
test-group = "windows-clipboard"
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
# 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)))'
slow-timeout = { period = "60s", terminate-after = 5 }
-9
Переглянути файл
@@ -1,9 +0,0 @@
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
# the release each SHA comes from).
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
groups:
actions: { patterns: ["*"] }
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@v8
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+35 -53
Переглянути файл
@@ -106,8 +106,7 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
@@ -116,24 +115,22 @@ 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
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
@@ -145,23 +142,12 @@ 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
with: { tool: nextest }
- uses: taiki-e/install-action@nextest
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
# working copy's database); with CI set they fail instead of skipping when these are
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
- name: Subversion (macOS)
if: runner.os == 'macOS'
run: command -v svnadmin >/dev/null || brew install subversion
- name: Subversion version
if: runner.os != 'Windows'
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
shell: bash
@@ -173,10 +159,10 @@ jobs:
- 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@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
@@ -193,13 +179,10 @@ jobs:
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
clean resources:resources compiler:compile \
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -207,7 +190,7 @@ 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@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
@@ -252,10 +235,10 @@ 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: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
@@ -281,13 +264,13 @@ 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: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
key: plugins
@@ -317,9 +300,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@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
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
@@ -346,10 +329,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: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: cargo-deny }
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-deny
- run: cargo deny check
frontend:
@@ -359,13 +341,13 @@ 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@v5
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: dtolnay/rust-toolchain@stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -386,10 +368,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@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -408,10 +390,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@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -419,7 +401,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@v6
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+2 -3
Переглянути файл
@@ -21,7 +21,6 @@ concurrency:
jobs:
mirror:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 120
env:
@@ -36,10 +35,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@v5
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+3 -4
Переглянути файл
@@ -23,7 +23,6 @@ concurrency:
jobs:
cask:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 30
env:
@@ -42,16 +41,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@v5
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@v5
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@v5
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+16 -22
Переглянути файл
@@ -34,8 +34,6 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -108,9 +106,9 @@ jobs:
# 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)/'
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# 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|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
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)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
@@ -156,9 +154,9 @@ 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: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
@@ -185,7 +183,7 @@ 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@v6
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -204,20 +202,20 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@v5
# 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
- uses: dtolnay/rust-toolchain@stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
- uses: actions/download-artifact@v6
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@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -243,19 +241,19 @@ jobs:
fi
- if: matrix.language == 'python'
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
uses: actions/setup-python@v5
with: { python-version: "3.12" }
- if: matrix.language == 'python'
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: matrix.language == 'go'
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
uses: actions/setup-go@v5
with: { go-version: "1.27", cache: false }
- if: matrix.language == '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
uses: actions/setup-java@v4
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
@@ -267,7 +265,7 @@ jobs:
# 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
uses: gradle/actions/setup-gradle@v4
with: { gradle-version: "${{ env.GRADLE }}" }
- if: matrix.language == 'kotlin'
run: |
@@ -279,7 +277,7 @@ jobs:
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
- if: matrix.language == 'php'
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
uses: shivammathur/setup-php@v2
with: { php-version: "8.5", coverage: xdebug, tools: composer }
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
@@ -287,10 +285,6 @@ jobs:
# 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'
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
-104
Переглянути файл
@@ -1,104 +0,0 @@
name: Nightly
# Builds main every night, when it has moved since the last nightly, into a prerelease
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
on:
schedule:
- cron: "0 18 * * *" # 02:00 Beijing
workflow_dispatch:
inputs:
force:
description: "Build even when main has not changed since the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
jobs:
prepare:
if: github.repository == 'l0ng-ai/openidea'
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
FORCE: ${{ inputs.force == true }}
run: |
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
id: tag
if: steps.changed.outputs.skip != 'true'
env:
BUILD: ${{ github.run_number }}
run: |
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -q -m "chore: v$version"
git tag "v$version"
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
git push origin "refs/tags/v$version"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
release:
needs: prepare
if: needs.prepare.outputs.tag != ''
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
nightly: true
secrets: inherit
# Points the nightly channel at the new nightly and drops the old ones.
channel:
needs: [prepare, release]
permissions:
contents: write
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.prepare.outputs.tag }}
steps:
- name: Nightly manifest
run: |
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
exit 0
fi
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
if gh release view nightly >/dev/null 2>&1; then
gh release edit nightly --notes "$notes"
else
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
fi
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
- name: Drop old nightlies
run: |
gh release list --limit 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
while read -r old; do
gh release delete "$old" --cleanup-tag --yes
done
+1 -1
Переглянути файл
@@ -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@v8
with:
script: |
const pr = context.payload.pull_request;
+25 -87
Переглянути файл
@@ -19,7 +19,6 @@ env:
jobs:
plugin-keys:
permissions: {}
environment: release
runs-on: ubuntu-latest
outputs:
keys: ${{ steps.keys.outputs.keys }}
@@ -44,7 +43,6 @@ jobs:
contents: write
needs: plugin-keys
name: Build (${{ matrix.name }})
environment: release
env:
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
strategy:
@@ -71,15 +69,15 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@v5
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: dtolnay/rust-toolchain@stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
with: { key: "${{ matrix.target }}", cache-on-failure: true }
- name: Linux deps
if: runner.os == 'Linux'
@@ -87,57 +85,40 @@ jobs:
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
- run: pnpm install --frozen-lockfile
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
# key, so the unsigned build is a separate step without the secrets.
- name: Signing configured
id: signing
# Signing is optional: only secrets that are set get exported, so forks and
# unconfigured repos produce unsigned builds instead of failing.
- name: Signing env
shell: bash
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
run: |
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Build (signed)
if: steps.signing.outputs.updater == 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
- name: Build (unsigned)
if: steps.signing.outputs.updater != 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
done
true
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
if: runner.os == 'macOS' && env.APPLE_ID != ''
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
@@ -156,8 +137,6 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
$target = "${{ matrix.target }}"
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
@@ -197,11 +176,11 @@ 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@v5
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: dtolnay/rust-toolchain@stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
- name: musl toolchain
if: runner.os == 'Linux'
@@ -222,45 +201,6 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
# gets the key; without it the archives keep only their .sha256.
server-signatures:
permissions:
contents: write
needs: server
environment: release
runs-on: ubuntu-latest
steps:
- name: Signing configured
id: signing
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
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
run: pnpm install --frozen-lockfile
- name: Sign server archives
if: steps.signing.outputs.updater == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
for asset in "$RUNNER_TEMP"/server/*.gz; do
pnpm exec tauri signer sign "$asset"
done
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
@@ -269,7 +209,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@v8
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
@@ -284,8 +224,6 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
@@ -293,10 +231,10 @@ jobs:
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
+16 -38
Переглянути файл
@@ -7,27 +7,19 @@ on:
tag:
description: "Tag to release (e.g. v0.1.0); must already exist"
required: true
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
# official plugins, the CNB mirror or the Homebrew cask.
workflow_call:
inputs:
tag: { type: string, required: true }
nightly: { type: boolean, default: false }
permissions:
contents: read
concurrency:
group: release-${{ inputs.tag || github.ref_name }}
group: release-${{ github.event.inputs.tag || github.ref_name }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
TAG: ${{ inputs.tag || github.ref_name }}
TAG: ${{ github.event.inputs.tag || github.ref_name }}
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
# The jobs that read a signing key or token, here and in the workflows called below, run in
# the `release` environment, which holds those secrets.
jobs:
# Creates (or reuses) one draft release that every platform build uploads into.
create-release:
@@ -37,7 +29,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@v5
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -57,9 +49,7 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
uses: actions/github-script@v8
with:
script: |
const tag = process.env.TAG;
@@ -71,13 +61,8 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Prereleases are skipped: the notes span stable release to stable release. A
// nightly's span from the newest published release, nightly or stable (not the
// rolling `nightly` release, which only holds the channel's manifest).
const nightly = process.env.NIGHTLY === "true";
const previous = releases.find(
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
);
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
});
@@ -93,7 +78,7 @@ jobs:
needs: create-release
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ inputs.tag || github.ref_name }}
tag: ${{ github.event.inputs.tag || github.ref_name }}
release_id: ${{ needs.create-release.outputs.release_id }}
secrets: inherit
@@ -111,34 +96,29 @@ jobs:
contents: write
needs: create-release
name: Official plugins
environment: release
runs-on: ubuntu-22.04
env:
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
NIGHTLY: ${{ inputs.nightly == true }}
steps:
- id: key
run: |
if [ "$NIGHTLY" = true ]; then
echo "a nightly does not publish the official plugins"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$SIGNING_KEY" ]; then
if [ -z "$SIGNING_KEY" ]; then
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@v5
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: dtolnay/rust-toolchain@stable
if: steps.key.outputs.skip != 'true'
with: { targets: wasm32-wasip2 }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- uses: Swatinem/rust-cache@v2
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@v5
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@v5
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 +163,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@v8
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
@@ -195,15 +175,13 @@ jobs:
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
cnb-mirror:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ inputs.tag || github.ref_name }}" }
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ inputs.tag || github.ref_name }}" }
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
-1
Переглянути файл
@@ -15,7 +15,6 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+1 -4
Переглянути файл
@@ -152,10 +152,7 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
"no-await-in-loop": "error"
}
}
]
Створено
+54 -102
Переглянути файл
@@ -252,9 +252,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.1"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
dependencies = [
"async-task",
"concurrent-queue",
@@ -1552,9 +1552,9 @@ dependencies = [
[[package]]
name = "curve25519-dalek"
version = "5.1.0"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -2766,7 +2766,6 @@ dependencies = [
"gix-ignore",
"gix-index",
"gix-lock",
"gix-mailmap",
"gix-note",
"gix-object",
"gix-odb",
@@ -3133,18 +3132,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "gix-mailmap"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
dependencies = [
"bstr",
"gix-actor",
"gix-date",
"gix-error",
]
[[package]]
name = "gix-note"
version = "0.3.1"
@@ -4167,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4179,26 +4166,23 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"jiff",
"parking_lot 0.12.5",
"rustix",
"semver",
"serde",
"serde_json",
"sha1 0.10.7",
"specta",
"sqlx",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"which",
]
[[package]]
name = "ide-analysis"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4210,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"serde",
@@ -4222,7 +4206,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"chardetng",
@@ -4240,7 +4224,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4254,7 +4238,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4265,7 +4249,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4276,7 +4260,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4298,7 +4282,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-run",
@@ -4311,7 +4295,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4322,7 +4306,6 @@ dependencies = [
"ide-jvm-attach",
"ide-jvm-inspect",
"ide-language",
"ide-run",
"libc",
"memchr",
"parking_lot 0.12.5",
@@ -4341,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4380,7 +4363,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"serde",
@@ -4393,7 +4376,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4407,7 +4390,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4427,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-android",
"ide-core",
@@ -4438,7 +4421,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4450,7 +4433,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4462,7 +4445,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"criterion",
"ide-core",
@@ -4481,7 +4464,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4528,7 +4511,6 @@ dependencies = [
"ide-spell",
"ide-ssh",
"ide-streams",
"ide-svn",
"ide-syntax",
"ide-terminal",
"ide-text",
@@ -4565,7 +4547,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"http",
@@ -4588,7 +4570,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"criterion",
@@ -4611,7 +4593,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4623,7 +4605,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4639,7 +4621,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"libc",
"tempfile",
@@ -4648,7 +4630,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"futures",
"serde",
@@ -4659,7 +4641,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"criterion",
@@ -4700,7 +4682,6 @@ dependencies = [
"tree-sitter-make",
"tree-sitter-md",
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-php",
"tree-sitter-prisma-io",
@@ -4719,7 +4700,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"criterion",
"dunce",
@@ -4749,7 +4730,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"bytes",
"dunce",
@@ -4768,7 +4749,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"futures",
"ide-core",
@@ -4793,7 +4774,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"dunce",
@@ -4815,7 +4796,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4829,7 +4810,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"dunce",
"futures",
@@ -4849,7 +4830,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"dunce",
@@ -4875,7 +4856,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-tools",
@@ -4891,7 +4872,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4917,7 +4898,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"criterion",
"encoding_rs",
@@ -4938,7 +4919,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4951,7 +4932,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4976,7 +4957,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-language",
@@ -4987,24 +4968,9 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "ide-svn"
version = "0.1.56"
dependencies = [
"dunce",
"encoding_rs",
"ide-core",
"ide-vcs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"tempfile",
"which",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-syntax"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"ide-language",
@@ -5019,7 +4985,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"ide-core",
"libc",
@@ -5033,7 +4999,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"criterion",
"ide-core",
@@ -5046,19 +5012,16 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"blake3",
"flate2",
"hex",
"http",
"hyper-util",
"ide-core",
"ide-http",
"ide-language",
"libc",
"minisign-verify",
"parking_lot 0.12.5",
"serde",
"serde_json",
@@ -5073,7 +5036,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"dunce",
@@ -5095,7 +5058,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"chardetng",
"dunce",
@@ -5122,7 +5085,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5138,7 +5101,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"blake3",
"dunce",
@@ -5148,7 +5111,6 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
@@ -6787,7 +6749,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.56"
version = "0.1.55"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -9893,7 +9855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -10674,16 +10636,6 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-objc"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-ocaml"
version = "0.26.0"
+1 -3
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.56"
version = "0.1.55"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -24,7 +24,6 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-svn = { path = "crates/ide-svn" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
@@ -91,7 +90,6 @@ trash = "5"
blake3 = "1"
dunce = "1"
dirs = "6"
jiff = "0.2"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
-5
Переглянути файл
@@ -6,11 +6,6 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
Copyright 2000-2026 JetBrains s.r.o. and contributors.
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
their names and file contents from IntelliJ's svn4idea TreeConflictData
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
2000-2026 JetBrains s.r.o. and contributors.
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
Corporation, licensed under the MIT License.
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
## Community
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
## Topluluk
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
## 社区
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
+1 -4
Переглянути файл
@@ -18,18 +18,15 @@ ide-tools = { path = "../ide-tools" }
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
toml_edit.workspace = true
tracing.workspace = true
parking_lot.workspace = true
dunce.workspace = true
jiff.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
File diff suppressed because it is too large. Load diff
+1 -3
Переглянути файл
@@ -58,9 +58,7 @@ impl AgentManager {
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
+1 -338
Переглянути файл
@@ -131,263 +131,7 @@ fn is_bypass_mode(mode: &str) -> bool {
let lower = mode.to_lowercase();
let m: String =
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
}
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
existing.value = value.to_owned();
} else {
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
}
}
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
pub(crate) fn clamp_automation_permissions(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &mut [AgentConfigOption],
wanted: &mut Vec<crate::model::AgentConfigChoice>,
) {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return;
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass {
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
wanted.retain(|c| match c.id.as_str() {
"mode" => !is_bypass_mode(&c.value),
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
_ => true,
});
ask_for_approvals(config);
}
match provider {
"claude" | "claude-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "bypassPermissions".to_owned(),
}
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
match cur_wanted.as_deref() {
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "acceptEdits".to_owned(),
}
} else {
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
match cur_wanted.as_deref() {
Some("plan") => "plan".to_owned(),
_ => "default".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"codex" | "codex-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "full-access".to_owned(),
}
} else if mode == Some(AutomationPermissionMode::Default) {
"read-only".to_owned()
} else if mode.is_some() {
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
match cur_wanted.as_deref() {
Some("read-only") => "read-only".to_owned(),
_ => "ask".to_owned(),
}
} else {
// Scheduled /loop or Send Later under interactive Ask: never full-access.
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "ask".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"copilot" => {
if allow_bypass {
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
upsert_choice(wanted, "allow_all", "on");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("on".into());
}
}
} else {
upsert_choice(wanted, "allow_all", "off");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("off".into());
}
let non_auto = match wanted_val(wanted, "mode").as_deref() {
Some("plan") => "plan",
_ => "agent",
};
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
{
upsert_choice(wanted, "mode", non_auto);
}
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
&& opt.values.iter().any(|v| v.value == non_auto)
{
opt.current = Some(non_auto.into());
}
}
}
"cursor" => {
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
"bypass"
} else {
"ask"
};
upsert_choice(wanted, CURSOR_APPROVAL, target);
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
opt.current = Some(target.into());
}
}
_ => {
if allow_bypass {
let user_chose_non_bypass = config.iter().any(|o| {
is_approval_option(o)
&& wanted.iter().any(|c| {
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
})
});
if !user_chose_non_bypass {
apply_bypass_approvals(config);
}
}
}
}
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
// so `open_session` actively configures the live session even if the CLI's own config differs.
for opt in config.iter().filter(|o| is_approval_option(o)) {
if let Some(cur) = opt.current.as_deref() {
upsert_choice(wanted, &opt.id, cur);
}
}
}
/// Verifies that the session's reported `config` options do not exceed the required automation
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
/// in a more permissive mode than allowed.
pub(crate) fn verify_automation_ceiling(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &[AgentConfigOption],
) -> Result<(), String> {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return Ok(());
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass && bypass_approvals(config) {
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
}
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
let mode_cur = config
.iter()
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
.and_then(|o| o.current.as_deref());
if !allow_bypass {
match provider {
"claude" | "claude-acp" => {
if let Some(cur) = mode_cur {
let allowed = if interactive == NewTaskApprovals::Bypass
&& mode == Some(AutomationPermissionMode::Assisted)
{
matches!(cur, "default" | "plan" | "acceptEdits")
} else {
matches!(cur, "default" | "plan")
};
if !allowed {
return Err(format!(
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"codex" | "codex-acp" => {
if let Some(cur) = mode_cur {
let allowed = if mode == Some(AutomationPermissionMode::Default) {
cur == "read-only"
} else if mode.is_some() {
matches!(cur, "read-only" | "ask")
} else {
matches!(cur, "read-only" | "ask" | "auto")
};
if !allowed {
return Err(format!(
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"copilot" => {
if let Some(cur) = cur_of("allow_all")
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
{
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
}
if let Some(cur) = mode_cur
&& cur.eq_ignore_ascii_case("autopilot")
{
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
}
}
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
}
_ => {}
}
}
Ok(())
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
@@ -925,87 +669,6 @@ mod tests {
);
}
#[test]
fn automation_permissions_respect_interactive_approval_ceiling() {
use crate::automation::AutomationPermissionMode;
use crate::model::AgentConfigChoice;
use ide_core::settings::NewTaskApprovals;
let claude_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
"defaultValue": "default",
"options": [
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
]
}]}))
};
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
let mut c = claude_opts();
let mut wanted = Vec::new();
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::Assisted),
NewTaskApprovals::Bypass,
&mut c,
&mut wanted,
);
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
let mut c_ask = claude_opts();
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut c_ask,
&mut wanted_ask,
);
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
let mut copilot = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
"options": [{"value": "off"}, {"value": "on"}]}
]}));
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
clamp_automation_permissions(
"copilot",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut copilot,
&mut copilot_wanted,
);
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
assert!(!bypass_approvals(&copilot));
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
let codex_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"defaultValue": "ask",
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
}]}))
};
for (perm, interactive, expected) in [
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
] {
let mut opts = codex_opts();
let mut w = Vec::new();
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
}
}
#[test]
fn command_sources_in_updates_and_stored_tasks() {
let update = json!({"availableCommands": [
+3 -397
Переглянути файл
@@ -2,10 +2,9 @@
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
//! `<home>/.codex/session_index.jsonl`), and Copilot
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
//! `<home>/.codex/session_index.jsonl`).
use super::native::claude::history;
use serde::Serialize;
@@ -18,7 +17,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
@@ -27,9 +26,6 @@ pub struct ExternalSession {
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
/// apps write the same session, so forking a copy is the safe choice.
pub in_use: bool,
}
/// Modification time of `path` in ms, else 0.
@@ -127,7 +123,6 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -198,7 +193,6 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -252,289 +246,6 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
fn is_yaml_block_header(raw: &str) -> bool {
let mut chars = raw.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
}
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
fn parse_yaml_inline_value(raw: &str) -> String {
if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
}
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
let mut metadata = HashMap::new();
while let Some(line) = lines.next() {
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
continue;
}
let Some((key, raw)) = line.split_once(':') else { continue };
let key = key.trim();
let raw = raw.trim();
if key.is_empty() {
continue;
}
if is_yaml_block_header(raw) {
let folded = raw.starts_with('>');
let mut block = Vec::new();
while let Some(next) = lines.peek() {
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
block.push(lines.next().unwrap_or_default());
} else {
break;
}
}
while block.last().is_some_and(|l| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
.min()
.unwrap_or(0);
let sep = if folded { " " } else { "\n" };
let joined = block
.iter()
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
.collect::<Vec<_>>()
.join(sep);
if !joined.trim().is_empty() {
metadata.insert(key.to_owned(), joined);
}
} else if !raw.is_empty() {
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
}
}
(!metadata.is_empty()).then_some(metadata)
}
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
fn copilot_prompt(path: &Path) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
std::io::BufReader::new(file)
.lines()
.take(400)
.filter_map(|line| line.ok())
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
.find_map(|event| {
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
.flatten()
.filter(|text| !text.is_empty())
.map(short)
})
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
use sqlx::{Connection, Row};
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.create_if_missing(false)
.busy_timeout(std::time::Duration::from_millis(200));
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
Ok(rows) => rows,
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
};
let _ = conn.close().await;
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
let Some(home) = home else { return HashMap::new() };
let dbs = vscode_agent_host_dbs(home);
if dbs.is_empty() {
return HashMap::new();
}
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
// thread works from either without blocking a runtime worker.
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
scope
.spawn(|| {
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
return Vec::new();
};
rt.block_on(async {
let mut all = Vec::new();
for path in &dbs {
all.extend(read_vscode_chat_rows(path).await);
}
all
})
})
.join()
.unwrap_or_default()
});
let mut titles = HashMap::new();
for [pdata, scs_title, scs_source, metadata, payload] in rows {
let Some(pdata) = pdata else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
continue;
};
if let Some(title) =
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
{
titles.insert(sdk_id.to_owned(), title);
}
}
titles
}
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
/// so only a lock whose process still runs counts.
fn copilot_session_in_use(dir: &Path) -> bool {
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("inuse."))
.and_then(|n| n.strip_suffix(".lock"))
.and_then(|n| n.parse::<u32>().ok())
else {
return false;
};
ide_core::process::process_alive(pid)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let dir = entry.path();
let events = dir.join("events.jsonl");
if !events.is_file() {
return None;
}
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
if !in_project(cwd.as_deref(), root) {
return None;
}
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
let title = raw_name
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
let session = ExternalSession {
provider: "copilot".to_owned(),
session_id,
title,
cwd,
updated_ms: mtime(&events),
in_use: copilot_session_in_use(&dir),
};
Some((session, cli_user_named))
})
.collect();
if !pending.is_empty() {
let vscode_titles = vscode_copilot_titles(home);
for (session, cli_user_named) in &mut pending {
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
session.title = short(title);
}
}
}
pending.into_iter().map(|(s, _)| s).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -633,111 +344,6 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
rt.block_on(async {
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
conn.close().await.unwrap();
});
}
#[test]
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
json!({"type": "session.start", "data": {}}),
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
],
);
std::fs::write(
session.join("workspace.yaml"),
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
)
.unwrap();
let block_scalar = copilot_home.join("session-state/copilot-block");
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
block_scalar.join("workspace.yaml"),
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
)
.unwrap();
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
write(
&vscode_renamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
);
std::fs::write(
vscode_renamed.join("workspace.yaml"),
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
)
.unwrap();
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
vscode_placeholder.join("workspace.yaml"),
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
)
.unwrap();
let unnamed = copilot_home.join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
// A live holder marks the session in use; a lock left by a process that exited does not.
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
let empty = copilot_home.join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = copilot_home.join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
exec_sqlite(
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
);
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
assert_eq!(sessions.len(), 5);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert!(named.in_use);
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
let unnamed = by_id.remove("copilot-2").unwrap();
assert_eq!(unnamed.title, "add a regression test");
assert!(!unnamed.in_use);
}
#[test]
File diff suppressed because it is too large. Load diff
+16 -29
Переглянути файл
@@ -68,25 +68,9 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
/// Workspace servers so standalone settings entries always take precedence on name clashes.
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
let mut seen_projected: HashSet<String> = HashSet::new();
for srv in projected {
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
configured.push(srv);
}
}
configured
}
fn normalize_provider(id: &str) -> &str {
id.strip_suffix("-acp").unwrap_or(id)
}
@@ -415,8 +399,13 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
@@ -1062,14 +1051,6 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
out
}
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
read_external_file(path)
}
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
Ok(extract_servers_from_root(root, None))
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
@@ -1107,7 +1088,15 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
env.push((k.clone(), v.clone()));
}
}
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
@@ -1270,8 +1259,6 @@ mod tests {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
File diff suppressed because it is too large. Load diff
+3 -638
Переглянути файл
@@ -181,10 +181,6 @@ pub struct AgentTask {
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
@@ -199,10 +195,6 @@ pub struct AgentTask {
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -458,29 +450,11 @@ pub struct AgentPrompt {
pub images: Vec<AgentImage>,
}
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledTurnMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::automation::AutomationPermissionMode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_choices: Vec<AgentConfigChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_schedule_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
pub scheduled: Option<ScheduledTurnMeta>,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
@@ -860,10 +834,6 @@ pub struct NewAgentTask {
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes).
#[serde(default)]
#[specta(optional)]
pub memory_overrides: Option<AgentMemoryOverrides>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -942,7 +912,7 @@ pub struct AgentModelCatalog {
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
@@ -1005,7 +975,7 @@ pub enum AgentEvent {
pub use ide_core::settings::{AgentMcpServer, McpTransport};
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum McpScope {
User,
@@ -1040,14 +1010,6 @@ pub struct McpServer {
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -1080,231 +1042,7 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryKind {
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
#[default]
Instruction,
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
Rule,
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
AutoNote,
}
/// Which workspace, user, or CLI store a memory entry was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemorySource {
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
#[default]
Workspace,
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
ClaudeWorkspace,
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
ClaudeUser,
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
ClaudeAuto,
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
GithubWorkspace,
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
CopilotUser,
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
CodexUser,
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
CodexAuto,
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
CursorWorkspace,
/// `GEMINI.md`.
GeminiWorkspace,
/// `~/.gemini/GEMINI.md`.
GeminiUser,
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
HermesAuto,
}
impl AgentMemorySource {
/// True when the entry lives inside the current workspace and requires Workspace Trust.
pub fn is_workspace(self) -> bool {
matches!(
self,
Self::Workspace
| Self::ClaudeWorkspace
| Self::GithubWorkspace
| Self::CursorWorkspace
| Self::GeminiWorkspace
)
}
/// True when the entry is an agent's learned cross-session auto-memory store.
pub fn is_auto(self) -> bool {
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
}
}
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryOrigin {
#[default]
None,
Session,
Workspace,
User,
/// Locked `Off` because the workspace is untrusted.
Trust,
}
/// One discovered instruction file, rule file, or learned auto-memory note.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryEntry {
/// Stable identifier (`"<source>::<rel_key>"`).
pub id: String,
pub title: String,
pub description: String,
pub kind: AgentMemoryKind,
pub source: AgentMemorySource,
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentMemorySource>,
/// Canonical file path on disk.
pub path: IpcPath,
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub category: Option<String>,
/// Approximate prompt token cost (~4 chars/token).
pub approx_tokens: u32,
pub line_count: u32,
pub byte_len: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub modified_ms: Option<f64>,
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
pub writable: bool,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryState {
pub entry: AgentMemoryEntry,
pub mode: AgentMemoryMode,
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
pub origin: AgentMemoryOrigin,
}
/// Live auto-memory status and capability summary for one agent family.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentAutoMemoryStatus {
pub provider: String,
pub label: String,
pub mode: AutoMemoryMode,
pub origin: AgentMemoryOrigin,
pub note_count: u32,
pub rollout_count: u32,
pub approx_tokens: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub storage_path: Option<IpcPath>,
pub supports_auto_control: bool,
pub supports_file_exclusion: bool,
pub supports_reset: bool,
}
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryCatalog {
pub entries: Vec<AgentMemoryState>,
pub providers: Vec<AgentAutoMemoryStatus>,
pub auto_memory: AutoMemoryMode,
pub auto_memory_origin: AgentMemoryOrigin,
}
/// Per-session memory overrides stored on an [`AgentTask`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryOverrides {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub auto_memory: Option<AutoMemoryMode>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub entries: BTreeMap<String, AgentMemoryMode>,
}
impl AgentMemoryOverrides {
pub fn is_empty(&self) -> bool {
self.auto_memory.is_none() && self.entries.is_empty()
}
}
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryCreateTarget {
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
#[default]
AgentsMd,
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
ClaudeRule,
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
CopilotInstruction,
/// `<workspace>/.cursor/rules/<slug>.mdc`.
CursorRule,
}
/// Payload for creating a new instruction or rule file.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentMemoryInput {
pub scope: McpScope,
pub target: AgentMemoryCreateTarget,
#[serde(default)]
pub name: String,
#[serde(default)]
#[specta(optional)]
pub description: Option<String>,
#[serde(default)]
pub paths: Vec<String>,
pub content: String,
}
/// Payload for promoting an auto-memory note into `AGENTS.md`.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PromoteAgentMemoryInput {
pub source_id: String,
#[serde(default)]
#[specta(optional)]
pub heading: Option<String>,
#[serde(default)]
pub remove_source: bool,
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -1375,14 +1113,6 @@ pub struct AgentSkill {
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
@@ -1444,371 +1174,6 @@ pub struct McpDiscoveredServer {
pub header_keys: Vec<String>,
}
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginSource {
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
#[default]
CopilotUser,
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
ClaudeUser,
/// `~/.codex/plugins/cache/*`.
CodexUser,
/// `~/.gemini/extensions/*`.
GeminiUser,
}
/// Manifest format(s) recognized inside an agent plugin directory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginFormat {
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
#[default]
AgentPluginsV1,
/// `.openidea/plugin.json`.
OpenIdea,
/// `.claude-plugin/plugin.json`.
Claude,
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
Copilot,
/// `.codex-plugin/plugin.json`.
Codex,
/// `gemini-extension.json`.
GeminiExtension,
}
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginOrigin {
/// Native harness configuration owns the enabled state.
#[default]
None,
/// Locked `Off` because the workspace is untrusted.
Trust,
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
Consent,
}
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginConfigFieldKind {
#[default]
String,
Number,
Boolean,
Secret,
}
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginConfigField {
pub key: String,
pub title: String,
#[serde(default)]
pub description: String,
pub kind: AgentPluginConfigFieldKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub default_value: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub env_var: Option<String>,
/// Current non-sensitive value (always empty when `kind == Secret`).
#[serde(default)]
pub value: String,
/// True when a secret is stored in OS Keychain for this field.
#[serde(default)]
pub has_secret: bool,
}
/// Summary of components and executable capabilities bundled inside an agent plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCapabilities {
pub skill_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skill_names: Vec<String>,
pub mcp_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mcp_names: Vec<String>,
pub rule_count: u32,
pub subagent_count: u32,
pub command_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
pub has_canvas_or_app: bool,
/// 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<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
#[serde(default)]
pub requires_consent: bool,
}
/// One discovered agent plugin bundle on disk (or built-in).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlugin {
pub id: String,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub license: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
pub source: AgentPluginSource,
/// Scope this bundle is installed in. Native plugin folders and enablement config are
/// resolved relative to this scope.
pub scope: McpScope,
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub workspace_root: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentPluginSource>,
pub formats: Vec<AgentPluginFormat>,
pub root_path: IpcPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub manifest_path: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub readme_path: Option<IpcPath>,
pub default_enabled: bool,
pub approx_tokens: u32,
pub capabilities: AgentPluginCapabilities,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config_fields: Vec<AgentPluginConfigField>,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Resolved agent plugin state paired with its policy origin and consent status.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginState {
pub plugin: AgentPlugin,
pub enabled: bool,
pub origin: AgentPluginOrigin,
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
pub consent_required: bool,
}
/// Summary of a configured or repository-discovered plugin marketplace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceInfo {
pub id: String,
pub name: String,
pub source: String,
pub scope: McpScope,
/// True when discovered from a harness-native marketplace/configuration file.
pub discovered: bool,
}
/// Full catalog returned to Settings › Agents › Plugins.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCatalog {
pub plugins: Vec<AgentPluginState>,
pub marketplaces: Vec<AgentMarketplaceInfo>,
pub projected_skills: u32,
pub projected_mcp_servers: u32,
pub projected_rules: u32,
}
/// One installable plugin entry listed inside a marketplace or repository.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceCandidate {
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
pub source_spec: String,
pub subpath: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
pub already_installed_user: bool,
pub already_installed_workspace: bool,
}
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceBrowseResult {
pub source: String,
pub marketplace_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
pub candidates: Vec<AgentMarketplaceCandidate>,
}
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginInstallTarget {
pub harness: String,
pub supported: bool,
/// Why the harness cannot install this plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub reason: Option<String>,
/// Whether this harness can enable the plugin for just one workspace.
pub workspace_supported: bool,
/// This harness already records the plugin for the user / for the current workspace.
pub installed_user: bool,
pub installed_workspace: bool,
/// The harness store already holds this plugin version's folder, so installing replaces it.
pub overwrite_required: bool,
}
/// Security and capability preview of an agent plugin bundle before installation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginPreview {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
pub formats: Vec<AgentPluginFormat>,
pub capabilities: AgentPluginCapabilities,
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
pub targets: Vec<AgentPluginInstallTarget>,
}
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InstallAgentPluginRequest {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default)]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default)]
#[specta(optional)]
pub git_ref: Option<String>,
/// Pinned root tree SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default)]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub scope: McpScope,
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
pub harness: String,
#[serde(default)]
pub approve_capabilities: bool,
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
/// folder resolves to different executable capabilities.
#[serde(default)]
#[specta(optional)]
pub approved_capability_hash: Option<String>,
#[serde(default)]
pub confirm_warnings: bool,
#[serde(default)]
pub overwrite: bool,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+6 -62
Переглянути файл
@@ -174,14 +174,10 @@ struct Session {
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
memory_add_dir: Option<PathBuf>,
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
additional_dirs_claude_md: bool,
/// The workspace's other roots, each passed as `--add-dir`.
additional_dirs: Vec<String>,
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
cli_settings: Option<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
@@ -375,20 +371,13 @@ impl Shim {
}
});
let skills = params.pointer("/_meta/openidea/skills");
let memory = params.pointer("/_meta/openidea/memory");
let cli_settings = build_cli_settings(skills, memory);
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs_claude_md: memory
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
.and_then(Value::as_bool)
.unwrap_or(false),
additional_dirs: additional_dirs(params),
cli_settings,
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
@@ -739,28 +728,18 @@ impl Session {
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(dir) = &self.memory_add_dir
&& self.skills_add_dir.as_ref() != Some(dir)
{
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
for dir in &self.additional_dirs {
args.extend(["--add-dir".to_owned(), dir.clone()]);
}
if let Some(settings) = &self.cli_settings {
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let mut env = shim.config.env.clone();
if self.additional_dirs_claude_md
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
{
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
}
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
let io = shim
.cli
.launch(&launch, shim.on_stderr.clone())
@@ -1622,41 +1601,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
let mut root = skills
.and_then(|s| s.get("claudeSettings"))
.and_then(Value::as_str)
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
.unwrap_or_default();
if let Some(mem) = memory {
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
root.insert("autoMemoryEnabled".into(), json!(auto));
}
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
let clean: Vec<Value> =
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
if !clean.is_empty() {
root.insert("claudeMdExcludes".into(), Value::Array(clean));
}
}
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
root.insert(
"pluginConfigs".into(),
json!({
"cc-plugin-agents-md@builtin": {
"options": { "instructionFiles": inst }
}
}),
);
}
}
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
}
/// The session's `additionalDirectories`: the workspace's other roots.
fn additional_dirs(params: &Value) -> Vec<String> {
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
-73
Переглянути файл
@@ -1442,76 +1442,3 @@ async fn an_ephemeral_session_is_not_saved() {
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"skills": {
"claudeAddDir": "/tmp/farm-skills",
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
},
"memory": {
"autoMemory": "readOnly",
"claudeAutoMemory": false,
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
"claudeInstructionFiles": "claude-md-and-agents-md",
"claudeAddDir": "/tmp/farm-memory",
"claudeAdditionalDirsClaudeMd": true
}
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
assert_eq!(parsed["autoMemoryEnabled"], false);
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"memory": {
"claudeInstructionFiles": "claude-md-and-agents-md"
},
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
assert!(parsed["pluginConfigs"]["azure"].is_null());
}
-14
Переглянути файл
@@ -20,17 +20,6 @@ pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "memories",
description: "Show, enable, disable, or reset cross-session Codex memories.",
hint: Some("[show|on|off|reset]"),
choices: &[
("show", "Show consolidated memory summary for this thread."),
("on", "Enable memory generation for this thread."),
("off", "Disable memory generation for this thread."),
("reset", "Clear local Codex memory files and summaries."),
],
},
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
@@ -90,7 +79,6 @@ pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Memories,
Status,
Review,
ReviewBranch,
@@ -107,7 +95,6 @@ impl BuiltinCommand {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"memories" => Self::Memories,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
@@ -163,7 +150,6 @@ mod tests {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
-49
Переглянути файл
@@ -362,23 +362,6 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
{
map.insert("skills".into(), json!({ "config": off }));
}
if let Some(mem) = params.pointer("/_meta/openidea/memory")
&& let Some(map) = config.as_object_mut()
{
let mut mem_cfg = serde_json::Map::new();
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
mem_cfg.insert("use_memories".into(), json!(use_m));
}
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
mem_cfg.insert("generate_memories".into(), json!(gen_m));
}
if !mem_cfg.is_empty() {
map.insert("memories".into(), Value::Object(mem_cfg));
}
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
map.insert("developer_instructions".into(), json!(dev));
}
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
@@ -725,7 +708,6 @@ impl CodexShim {
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
@@ -765,36 +747,6 @@ impl CodexShim {
Ok(json!({ "stopReason": "end_turn" }))
}
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let arg = rest.trim().to_ascii_lowercase();
match arg.as_str() {
"" | "show" => {
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
let summary = res
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("No consolidated memories for this thread yet.");
self.say(session, summary);
}
"on" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
self.say(session, "Memory generation enabled for this thread.");
}
"off" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
self.say(session, "Memory generation disabled for this thread.");
}
"reset" => {
self.call("memory/reset", Value::Null).await?;
self.say(session, "Reset local Codex memories.");
}
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
}
Ok(())
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
@@ -1566,7 +1518,6 @@ fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
-75
Переглянути файл
@@ -1695,57 +1695,6 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn memories_commands_read_toggle_and_reset_through_app_server() {
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
(
"/memories",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": "Remembered: run targeted tests first." }),
"Remembered: run targeted tests first.",
),
(
"/memories show",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": null }),
"No consolidated memories for this thread yet.",
),
(
"/memories on",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "enabled" }),
json!({}),
"Memory generation enabled for this thread.",
),
(
"/memories off",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "disabled" }),
json!({}),
"Memory generation disabled for this thread.",
),
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
] {
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
let session = session_of(&results, "new");
let sent = sent(&frames, method);
assert_eq!(sent.len(), 1, "{prompt}");
let mut expected = expected_params;
if has_thread_id {
expected["threadId"] = json!(session);
assert_eq!(sent[0]["params"], expected, "{prompt}");
}
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
@@ -2138,8 +2087,6 @@ fn skills_become_commands_with_their_invocation_names() {
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
@@ -2155,28 +2102,6 @@ fn workspace_roots_join_the_thread_roots() {
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
let mut mem_req = json!({});
apply_thread_config(
&json!({
"cwd": "/w/api",
"mcpServers": [],
"_meta": {
"openidea": {
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
"memory": {
"codexUseMemories": true,
"codexGenerateMemories": false,
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
}
}
}
}),
&mut mem_req,
);
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
}
#[tokio::test(flavor = "multi_thread")]
+3 -88
Переглянути файл
@@ -37,15 +37,6 @@ 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 `<home>/.copilot`).
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
/// Pre-session discovery result for `Shared::fetch_settings`.
pub(crate) struct Discovered {
pub commands: Vec<Value>,
@@ -471,38 +462,6 @@ fn apply_skills(params: &Value, req: &mut Value) {
}
}
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
fn apply_memory(params: &Value, req: &mut Value) {
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
return;
};
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
let mut excluded: Vec<String> = req
.get("excludedTools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
if !excluded.iter().any(|t| t == "store_memory") {
excluded.push("store_memory".into());
}
req["excludedTools"] = json!(excluded);
}
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
req["customInstructions"] = json!(false);
}
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
req["systemMessage"] = json!({
"mode": "append",
"content": sys,
});
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -560,7 +519,6 @@ impl CopilotShim {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
@@ -579,7 +537,7 @@ impl CopilotShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
@@ -630,7 +588,6 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -659,25 +616,6 @@ impl CopilotShim {
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let loaded = self.resume_session(params, &session_id).await?;
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
self.replay_history(&actual_id).await;
Ok(loaded)
}
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
let target = forked
.get("sessionId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
.to_owned();
self.resume_session(params, &target).await
}
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
let cwd = str_param(params, "cwd")?;
let catalog = self.models().await?;
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
@@ -701,11 +639,9 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
let _ = settings.set(&catalog, MODEL, model_id);
}
@@ -716,6 +652,7 @@ impl CopilotShim {
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
}
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
@@ -726,28 +663,6 @@ impl CopilotShim {
}))
}
async fn replay_history(&self, session_id: &str) {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let updates = {
let mut state = self.state.lock();
let Some(entry) = state.sessions.get_mut(session_id) else { return };
events
.iter()
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
.collect::<Vec<_>>()
};
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
-170
Переглянути файл
@@ -115,18 +115,6 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
}
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
@@ -446,39 +434,6 @@ impl Handler for FakeCopilotServer {
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
"session.getMessages" => Ok(json!({
"events": [
{
"type": "user.message",
"data": { "content": "Fix the parser" }
},
{
"type": "assistant.message",
"data": {
"messageId": "history-message",
"reasoningText": "Inspect the grammar first.",
"content": "I fixed the parser."
}
},
{
"type": "tool.execution_start",
"data": {
"toolCallId": "history-tool",
"toolName": "view",
"arguments": { "path": "/tmp/parser.rs" }
}
},
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "history-tool",
"success": true,
"result": { "content": "fn parse() {}" }
}
}
]
})),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
@@ -719,81 +674,6 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_loads_and_replays_copilot_history() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let loaded: Value = client
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(loaded["sessionId"], "cop-sess-1");
assert!(
server
.calls
.lock()
.iter()
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
);
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
)
);
assert!(
seen.iter()
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
);
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let forked: Value = client
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(forked["sessionId"], "cop-sess-fork");
let calls = server.calls.lock();
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
@@ -953,56 +833,6 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let meta = json!({
"openidea": {
"memory": {
"autoMemory": "readOnly",
"copilotExcludeStoreMemory": true,
"copilotDisableCustomInstructions": true,
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
assert_eq!(
params["systemMessage"],
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
"{method}: {params}"
);
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
-49
Переглянути файл
@@ -370,55 +370,6 @@ impl EventTranslator {
}
out
}
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
/// event stream omits historical user messages and emits reasoning deltas, while the
/// persisted form has complete user and assistant messages.
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
if event_type == "user.message" {
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
return Translated { updates: Vec::new(), terminal: None };
};
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
return Translated {
updates: vec![(
target_session,
json!({
"sessionUpdate": "user_message_chunk",
"content": { "type": "text", "text": text },
}),
)],
terminal: None,
};
}
let mut translated = self.translate(main_session, event, fallback_limit);
if event_type == "assistant.message"
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
{
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
translated.updates.insert(
0,
(
target_session,
json!({
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": reasoning },
}),
),
);
}
translated
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
+5 -1
Переглянути файл
@@ -25,7 +25,11 @@ use std::sync::Arc;
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
pub(crate) fn newest_install(command: &str) -> String {
newest_install_in(command, &ide_core::tool_path::search_path())
let path = ide_core::process::host_var_os("PATH")
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
.unwrap_or_default();
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
newest_install_in(command, &ide_core::process::with_user_path(&path))
}
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
File diff suppressed because it is too large. Load diff
+11 -31
Переглянути файл
@@ -114,7 +114,7 @@ impl ProviderSpec {
if !program.is_absolute() {
return self.login_hint.clone();
}
let search = ide_core::tool_path::search_path();
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
let builtin = builtin_spec(&self.id);
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed_with_env(&spec.command, &spec.env),
installed: installed(&spec.command),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
@@ -1057,23 +1057,19 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
pub(crate) fn installed(command: &str) -> bool {
installed_with_env(command, &[])
}
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
let p = Path::new(command);
if p.components().count() > 1 || p.is_absolute() {
if p.components().count() > 1 {
return is_executable(p);
}
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
{
return true;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
}
fn is_executable(p: &Path) -> bool {
@@ -1330,22 +1326,6 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn installed_with_env_resolves_executables_on_provider_path() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
let exe = dir.path().join(name);
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(!installed("fake-agent"));
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
assert!(installed_with_env("fake-agent", &env));
}
#[test]
fn set_builtin_env_writes_and_clears_the_environment() {
let dir = tempfile::tempdir().unwrap();
+3 -5
Переглянути файл
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
}
fn on_path(command: &str) -> bool {
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
which::which(command).is_ok()
}
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
@@ -708,8 +708,7 @@ fn install_npm(
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
@@ -790,8 +789,7 @@ fn install_uv(
_ => format!("{name}=={}", entry.version),
};
check_spec(&spec)?;
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
let bin = dir.join("bin");
let mut cmd = Command::new(uv);
cmd.args(["tool", "install", "--force"])
+16 -1
Переглянути файл
@@ -185,7 +185,22 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
let file = Arc::new(Mutex::new(String::new()));
let connections = Arc::new(Mutex::new(0u32));
Arc::new(move |spec, cwd, client, on_stderr| {
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
let program = {
let path = Path::new(&spec.command);
if path.components().count() > 1 || path.is_absolute() {
path.to_path_buf()
} else {
let search = spec
.env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
}
};
let mut cmd = tokio::process::Command::new(&program);
ide_core::process::prepare(cmd.as_std_mut());
let mut child = cmd
File diff suppressed because it is too large. Load diff
+82 -34
Переглянути файл
@@ -275,27 +275,12 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
let states =
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
let projected = crate::plugins::projected_skill_roots(&states, None);
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
pub fn discover_skills_with_agent_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
@@ -353,19 +338,9 @@ pub fn discover_skills_with_agent_plugins(
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
for proj in agent_plugin_roots {
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
let Some(folder) = file_name(&proj.dir) else { continue };
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
} else {
for mut skill in skills_of(&proj.dir, proj.source) {
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
push_skill(skill);
}
}
@@ -413,6 +388,83 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
/// enablement) and flat 1-level `<plugin>` folders.
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
if !dir.is_dir() {
return;
}
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
return;
}
plugin_dirs.push(dir);
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
continue;
};
if raw_cache.is_empty() {
continue;
}
let dir =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
} else {
push_plugin(dir, &disabled_paths);
}
}
}
let plugins_root = copilot_dir.join("installed-plugins");
for entry in sorted(&plugins_root) {
if !entry.is_dir() {
continue;
}
if looks_like_plugin_dir(&entry) {
push_plugin(entry, &disabled_paths);
} else {
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
for sub in sorted(&entry) {
if sub.is_dir() {
push_plugin(sub, &disabled_paths);
}
}
}
}
let mut roots = Vec::new();
for plugin in plugin_dirs {
let skills_sub = plugin.join("skills");
if skills_sub.is_dir() {
roots.push((skills_sub, AgentSkillSource::CopilotUser));
} else {
roots.push((plugin, AgentSkillSource::CopilotUser));
}
}
roots
}
fn looks_like_plugin_dir(dir: &Path) -> bool {
dir.join("skills").is_dir()
|| dir.join("plugin.json").is_file()
|| dir.join(".plugin").is_dir()
|| dir.join(".claude-plugin").is_dir()
|| dir.join(".cursor-plugin").is_dir()
|| dir.join("SKILL.md").is_file()
}
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
/// category folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
@@ -492,8 +544,6 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
paths,
valid: warnings.is_empty(),
warnings,
plugin_id: None,
plugin_name: None,
}
}
@@ -1020,8 +1070,6 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
+4 -280
Переглянути файл
@@ -69,8 +69,6 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
impl FakeAgent {
@@ -181,7 +179,6 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
self.memory_calls.lock().push((method.to_owned(), params.pointer("/_meta/openidea/memory").cloned()));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
@@ -1289,7 +1286,6 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -1329,7 +1325,6 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -2191,41 +2186,6 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -3276,58 +3236,6 @@ fn plant_codex_session(root: &Path, session_id: &str) {
.unwrap();
}
/// Plants a recorded Copilot session below the test home.
fn plant_copilot_session(root: &Path, session_id: &str) {
let dir = root.join(".copilot").join("session-state").join(session_id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("workspace.yaml"),
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
)
.unwrap();
std::fs::write(
dir.join("events.jsonl"),
format!(
"{}\n",
json!({
"type": "user.message",
"data": {"content": "fix the Copilot parser"}
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn imports_copilot_sessions_and_loads_their_history() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let sessions = mgr.external_sessions();
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
assert_eq!(task.provider, "copilot");
for _ in 0..200 {
if agent.calls.lock().iter().any(|call| call == "session/load")
&& mgr.entries(&task.id, None).unwrap().len() >= 2
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
@@ -3348,28 +3256,6 @@ async fn fork_session_uses_the_id_codex_assigns() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_copilot_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
for _ in 0..200 {
if !agent.forks.lock().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "copilot names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
@@ -6056,8 +5942,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
McpServer {
id: "user::slack".into(),
@@ -6072,8 +5956,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
]
}));
@@ -6089,7 +5971,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6118,127 +5999,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(root, agent.clone());
mgr.set_memory_policy_hook(Box::new({
let root = root.to_path_buf();
move || memory::MemoryPolicy {
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
workspace: AgentMemorySettings::default(),
workspace_trusted: true,
workspace_roots: vec![root.clone()],
}
}));
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
let claude_task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new");
let mem = payload.unwrap();
assert_eq!(mem["autoMemory"], "readOnly");
assert_eq!(mem["claudeAutoMemory"], false);
assert!(
mem["claudeMdExcludes"]
.as_array()
.unwrap()
.iter()
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
);
}
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
let updated = mgr
.set_memory_overrides(
&claude_task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/load");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/fork");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
mgr.delete(&claude_task.id, false).await.unwrap();
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
for (provider, expected_field) in [
("codex", Some("codexUseMemories")),
("copilot", Some("copilotEnableMemory")),
("cursor", None),
("hermes", None),
] {
let t = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: provider.into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::new(),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new", "provider {provider}");
let mem = payload.expect("memory delivery present");
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
if let Some(field) = expected_field {
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
}
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
let tmp = tempfile::tempdir().unwrap();
@@ -6274,7 +6034,6 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6419,7 +6178,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6447,7 +6205,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6527,20 +6284,20 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp, None, None, &[]);
let params = session_params("/p", &mcp, None, &[]);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none, None, None, &[]).get("_meta").is_none());
assert!(session_params("/p", &none, None, &[]).get("_meta").is_none());
}
#[test]
fn session_params_offer_the_workspace_roots() {
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
let params = session_params("/w/api", &none, None, None, &["/w/web".to_owned()]);
let params = session_params("/w/api", &none, None, &["/w/web".to_owned()]);
assert_eq!(params["additionalDirectories"], json!(["/w/web"]));
assert!(session_params("/w/api", &none, None, None, &[]).get("additionalDirectories").is_none());
assert!(session_params("/w/api", &none, None, &[]).get("additionalDirectories").is_none());
}
#[tokio::test]
@@ -7041,36 +6798,3 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
mgr2.shutdown();
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn metadata_edits_do_not_bump_updated_ms() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let fixed_ms = 1_234.0;
handle.state.lock().task.updated_ms = fixed_ms;
mgr.rename(&task.id, "Custom Title").unwrap();
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
assert_eq!(after_mcp.updated_ms, fixed_ms);
let after_skill =
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
assert_eq!(after_skill.updated_ms, fixed_ms);
let after_memory = mgr
.set_memory_overrides(
&task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
+7 -377
Переглянути файл
@@ -9,34 +9,12 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
pub(crate) struct Created {
#[cfg_attr(not(test), allow(dead_code))]
pub path: PathBuf,
pub cwd: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
const OWNERSHIP_TAG: &str = "openidea-agent";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorktreeOwnership {
owner: String,
task_id: String,
worktree_root: PathBuf,
repo_root: PathBuf,
}
/// Returns the canonical root of the Git repository containing `project_root`, if any.
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
match Repo::discover(project_root)? {
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
None => Ok(None),
}
}
/// The repository of `path`, free to execute: the host runs every agent command that
/// reaches a repository only in a trusted project.
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
@@ -179,38 +157,9 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
}
}
#[cfg(test)]
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
create_for_task(project_root, worktrees_dir, "", title, base)
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
pub(crate) fn create_for_task(
project_root: &Path,
worktrees_dir: &Path,
task_id: &str,
title: &str,
base: Option<&str>,
) -> IdeResult<Created> {
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let canon_repo = dunce::canonicalize(repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
@@ -228,125 +177,7 @@ pub(crate) fn create_for_task(
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
let canon_wt = match dunce::canonicalize(&path) {
Ok(p) => p,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e.into());
}
};
let wt_repo = match repo_at(&canon_wt) {
Ok(r) => r,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
Ok(dirs) => dirs,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
}
let marker = WorktreeOwnership {
owner: OWNERSHIP_TAG.to_owned(),
task_id: task_id.to_owned(),
worktree_root: canon_wt.clone(),
repo_root: canon_repo,
};
if let Err(e) = serde_json::to_vec_pretty(&marker)
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
{
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
if !raw_cwd.is_dir() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::invalid(format!(
"project folder {} does not exist in base revision {}",
rel_subdir.display(),
base
)));
}
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
Ok(c) => c,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
if !canon_cwd.starts_with(canon_wt_root)
|| !real_cwd.starts_with(&real_wt)
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
{
return Err(IdeError::invalid(format!(
"worktree working directory {} resolves outside worktree {}",
target_cwd.display(),
canon_wt_root.display()
)));
}
Ok(canon_cwd)
}
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
/// symlink escapes on reused sessions/turns).
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
return Err(IdeError::invalid(format!(
"worktree working directory {} is outside managed worktrees directory {}",
cwd.display(),
worktrees_dir.display()
)));
}
let canon_wt_root = dunce::canonicalize(&wt_root)?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
}
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
Ok(Created { path, branch, base, base_commit })
}
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
@@ -355,94 +186,19 @@ fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBu
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(&target, true) {
let err = match repo.remove_worktree(path, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !target.exists() {
if !path.exists() {
return Ok(());
}
if !target.starts_with(&wt_base) || target == wt_base {
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
return Err(err);
}
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
}
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
///
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
/// files.
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
/// checkout intact.
pub(crate) fn remove_owned_automation_worktree(
project_root: &Path,
worktrees_dir: &Path,
cwd: &Path,
task_id: &str,
base_commit: Option<&str>,
require_clean: bool,
) -> IdeResult<bool> {
if !cwd.exists() || !worktrees_dir.exists() {
return Ok(false);
}
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
let canon_cwd = dunce::canonicalize(cwd)?;
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
}
let main_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_cwd)?;
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
if !canon_wt_root.starts_with(&canon_worktrees)
|| canon_wt_root == canon_worktrees
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
let [_, main_common] = main_repo.metadata_dirs()?;
let canon_git_dir = dunce::canonicalize(&git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_main_common = dunce::canonicalize(&main_common)?;
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
}
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
return Err(IdeError::invalid("worktree ownership marker does not match task"));
}
if require_clean {
let Some(base) = base_commit else {
return Ok(false);
};
if wt_repo.head()?.1.as_deref() != Some(base) {
return Ok(false);
}
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
if !wt_repo.status()?.is_empty() {
return Ok(false);
}
if !wt_repo.diff_with_worktree(base)?.is_empty() {
return Ok(false);
}
main_repo.remove_worktree(&canon_wt_root, false)?;
return Ok(true);
}
main_repo.remove_worktree(&canon_wt_root, true)?;
Ok(true)
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
}
/// On Windows a folder can't be deleted while a process still has a file in it open
@@ -2188,130 +1944,4 @@ mod tests {
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
#[test]
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("subapp");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
assert_eq!(
dunce::canonicalize(&created.cwd).unwrap(),
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
"project-relative cwd inside parent repo must be preserved inside worktree"
);
// Wrong task_id is refused and keeps the checkout untouched.
assert!(
remove_owned_automation_worktree(
&sub,
&wt_dir,
&created.cwd,
"wrong-task",
Some(&created.base_commit),
true,
)
.is_err()
);
assert!(created.path.exists());
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
git(&created.path, &["add", "packages/subapp/index.ts"]);
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
let removed_staged =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
assert!(created.path.exists());
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
let removed_clean =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(removed_clean);
assert!(!created.path.exists());
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
let manual_wt = wt_dir.join("foreign");
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
assert!(
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
.is_err()
);
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
}
#[cfg(unix)]
#[test]
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
let tmp = tempfile::tempdir().unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
let repo = tmp.path().join("repo");
let packages = repo.join("packages");
std::fs::create_dir_all(&packages).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
// 1a. Direct symlink pointing outside git is rejected immediately.
let escape_link = packages.join("escape");
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
let wt_dir = tmp.path().join("wt");
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
// must catch the escape and clean up the worktree!
let tricky = packages.join("tricky");
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
std::fs::remove_file(&tricky).unwrap();
std::fs::create_dir_all(&tricky).unwrap();
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
panic!("expected committed symlink escaping worktree root to be rejected");
};
assert!(
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
"unexpected error for committed symlink cwd: {err}"
);
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
// must be rejected by `verify_confined_worktree_cwd`!
let legit_sub = packages.join("legit");
std::fs::create_dir_all(&legit_sub).unwrap();
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "legit sub"]);
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
std::fs::remove_dir_all(&created.cwd).unwrap();
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
assert!(
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
}
-24
Переглянути файл
@@ -1,24 +0,0 @@
{
"version": 2,
"plugins": {
"evidence-plugin@evidence-mkt": [
{
"scope": "user",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
},
{
"scope": "project",
"projectPath": "$WORKSPACE",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
}
]
}
}
-6
Переглянути файл
@@ -1,6 +0,0 @@
[marketplaces.evidence-mkt]
source_type = "local"
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
[plugins."evidence-plugin@evidence-mkt"]
enabled = false
-19
Переглянути файл
@@ -1,19 +0,0 @@
// This file is managed automatically.
{
"installedPlugins": [
{
"name": "evidence-plugin",
"marketplace": "evidence-mkt",
"installed_at": "2026-11-30T21:50:25.665Z",
"enabled": true,
"version": "1.2.3",
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
"source": {
"source": "github",
"repo": "acme/plugins",
"sha": "1111111111111111111111111111111111111111",
"path": "plugins/evidence-plugin"
}
}
]
}
-8
Переглянути файл
@@ -1,8 +0,0 @@
{
"evidence-extension": {
"overrides": [
"$HOME/*",
"!$WORKSPACE/*"
]
}
}
+9 -53
Переглянути файл
@@ -85,26 +85,13 @@ gradle.projectsEvaluated {{
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
let invalid_output = "The resource build did not report an output directory";
if !output.is_absolute() {
return Err(IdeError::invalid(invalid_output));
if !output.is_absolute() || !output.is_dir() {
return Err(IdeError::invalid("The resource build did not report an output directory"));
}
let output = match fs::metadata(&output) {
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
_ => return Err(IdeError::invalid(invalid_output)),
};
let output = dunce::canonicalize(output)?;
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
return Ok(());
}
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
if output.is_none() && previous.is_empty() {
if paths.contains(&output) {
return Ok(());
}
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
@@ -112,10 +99,12 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
IdeError::invalid("Cannot find the running main class output directory; restart the application")
})?;
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let mut current = Vec::new();
if let Some(output) = output {
copy_resources(&output, &output, destination, &mut current)?;
}
copy_resources(&output, &output, destination, &mut current)?;
for rel in previous.iter().filter(|p| !current.contains(p)) {
let path = destination.join(rel);
if path.is_file() {
@@ -231,39 +220,6 @@ mod tests {
}
}
#[test]
fn missing_resource_output_publishes_an_empty_set() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let output = root.join("build/resources/main");
let cache = root.join("cache");
let runtime = root.join("bin/main");
let class_paths = [runtime.to_string_lossy().into_owned()];
let resource = "application.properties";
fs::create_dir(&cache).unwrap();
fs::create_dir_all(runtime.join("example")).unwrap();
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
let class = runtime.join("example/Application.class");
fs::write(&class, "running").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!output.exists());
fs::create_dir_all(&output).unwrap();
fs::write(output.join(resource), "server.port=8081").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(runtime.join(resource).is_file());
fs::remove_file(output.join(resource)).unwrap();
fs::remove_dir(&output).unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!runtime.join(resource).exists());
assert_eq!(fs::read_to_string(class).unwrap(), "running");
fs::write(output, "not a directory").unwrap();
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
}
#[test]
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
let tmp = tempfile::tempdir().unwrap();
+3 -138
Переглянути файл
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
@@ -815,74 +815,6 @@ pub fn run(
})
}
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
pub struct XcodebuildMessages {
parser: OutputParser,
cwd: PathBuf,
paths: PathMap,
lines: Lines,
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
done: bool,
}
impl XcodebuildMessages {
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
pub fn new(root: &Path, cwd: &Path) -> Self {
XcodebuildMessages {
parser: OutputParser::new(Format::Xcode),
cwd: cwd.to_path_buf(),
paths: PathMap::new(root),
lines: Lines::default(),
seen: HashSet::new(),
done: false,
}
}
/// Messages completed by `line` (without its line break).
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
if self.done {
return Vec::new();
}
let result = parse::strip_ansi(line);
let result = result.trim();
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
self.done = true;
return self.finish();
}
let raws = self.parser.feed(line).messages;
self.resolve(raws)
}
/// The message still waiting for detail lines.
pub fn finish(&mut self) -> Vec<BuildMessage> {
let raws = self.parser.finish();
self.resolve(raws)
}
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
raws.into_iter()
.map(|raw| {
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
if let Some(path) = m.path.clone().map(PathBuf::from)
&& !path.starts_with(&self.paths.root)
&& let Ok(real) = dunce::canonicalize(&path)
&& let Some(real) = real.to_str()
{
let mapped = self.paths.resolve(real, &self.cwd, None);
if mapped.starts_with(&self.paths.root) {
m.path = Some(mapped.into());
}
}
m
})
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
.collect()
}
}
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
@@ -986,7 +918,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
@@ -1404,73 +1336,6 @@ mod tests {
}
use super::*;
#[test]
fn xcodebuild_messages_once_per_build() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("Warn.swift");
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
let mut out = Vec::new();
// One copy per architecture, then the linker's per-architecture lists.
for line in [
warning.as_str(),
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
warning.as_str(),
"Undefined symbols for architecture x86_64:",
" \"_sym\", referenced from:",
"ld: symbol(s) not found for architecture x86_64",
"Undefined symbols for architecture arm64:",
" \"_sym\", referenced from:",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
// `count`, 0-based, underlined.
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
assert_eq!(
(out[1].path.is_none(), out[1].text.as_str()),
(true, "Undefined symbols\n\"_sym\", referenced from:")
);
}
#[test]
fn xcodebuild_messages_stop_at_the_build_result() {
let tmp = tempfile::tempdir().unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let mut out = Vec::new();
// An Xcode run configuration's output: the build, then the app's own console.
for line in [
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
"** BUILD SUCCEEDED **",
"error: request failed",
"warning: low memory",
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
}
#[cfg(unix)]
#[test]
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&root, &link).unwrap();
let mut x = XcodebuildMessages::new(&root, &root);
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
let out = x.finish();
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
}
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
-158
Переглянути файл
@@ -27,10 +27,6 @@ pub(crate) enum Format {
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
/// `Undefined symbols for architecture arm64:` with its indented details.
Xcode,
}
/// What a printed column counts.
@@ -335,59 +331,6 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
}
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
fn xcode_line(line: &str) -> Option<RawMessage> {
if let Some(m) = gcc_line(line) {
return Some(m);
}
if line.starts_with("Undefined symbols for architecture ") {
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
}
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
let rest = [".xcodeproj: ", ".xcworkspace: "]
.into_iter()
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
let (severity, msg) =
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
})?;
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
}
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
let t = line.trim_start();
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
if let Some((_, _, _, rest)) = path_line_col(line)
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
{
msg.text.push_str("\nnote: ");
msg.text.push_str(note.trim());
return true;
}
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
if excerpt {
if let Some(i) = t.find("- note: ") {
msg.text.push_str("\nnote: ");
msg.text.push_str(t[i + "- note: ".len()..].trim());
}
return true;
}
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
msg.text.push('\n');
msg.text.push_str(t);
return true;
}
false
}
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
if v.get("reason")?.as_str()? != "compiler-message" {
@@ -469,9 +412,6 @@ impl OutputParser {
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
_ => line,
};
if format == Format::Xcode {
return xcode_detail(&mut p.msg, line);
}
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
&& body.starts_with(" ")
&& !body.trim().is_empty()
@@ -507,7 +447,6 @@ impl OutputParser {
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Xcode => xcode_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -739,103 +678,6 @@ mod tests {
assert_eq!(out[2].text, "'missing.h' file not found");
}
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
#[test]
fn xcodebuild_swift_error_warning_and_note() {
let out = parse(
Format::Xcode,
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x201 | func warnMe() -> Int {\n\
\x202 | var count = 1\n\
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x203 | return count\n\
\x204 | }\n\
\n\
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
\x207 | \n\
\x208 | func name(_ s: Shade) -> String {\n\
\x209 | switch s {\n\
\x20 | |- error: switch must be exhaustive\n\
\x20 | `- note: add missing case: '.dark'\n\
10 | case .light: return \"light\"\n\
11 | }\n\
\n\
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
Failed frontend command:\n\
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].severity, Severity::Warning);
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
assert_eq!(out[1].severity, Severity::Error);
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
}
#[test]
fn xcodebuild_clang_errors_with_note() {
let out = parse(
Format::Xcode,
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
\x20 | ^~~~~~~~~~~~~~~~\n\
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
\x20 4 | void twice(void) {}\n\
\x20 | ^\n\
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
\x20 3 | void twice(void) {}\n\
\x20 | ^\n\
2 errors generated.\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
}
#[test]
fn xcodebuild_linker_errors_without_location() {
let out = parse(
Format::Xcode,
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
\x20 cd /p/Demo\n\
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
Undefined symbols for architecture arm64:\n\
\x20 \"_missing_symbol_xyz\", referenced from:\n\
\x20 Demo.callMissing() -> () in Missing.o\n\
ld: symbol(s) not found for architecture arm64\n\
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
\n\
** BUILD FAILED **\n\
\n\
The following build commands failed:\n\
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
);
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
assert_eq!(
found,
[
(
Severity::Warning,
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
true
),
(
Severity::Error,
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
true
),
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
]
);
}
#[test]
fn go_errors() {
let out = parse(
+4 -87
Переглянути файл
@@ -180,30 +180,6 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -257,7 +233,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -294,7 +270,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
continue;
}
@@ -322,7 +298,7 @@ pub fn module_classpaths(
}
}
}
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
Ok(classpaths.into_iter().next().unwrap())
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -370,8 +346,7 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -937,64 +912,6 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
+22 -100
Переглянути файл
@@ -4,8 +4,7 @@
//! same way into the test output, which also sees the production classes.
use super::*;
use ide_core::settings::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
split_jar_glob,
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
};
use std::fs;
@@ -105,17 +104,13 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
for entry in class_entries(root, class) {
add(entry);
}
add(class_entry(root, class));
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
for entry in class_entries(root, &dep.target) {
add(entry);
}
add(class_entry(root, &dep.target));
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
@@ -138,50 +133,29 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
root.join(dir)
}
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for jar in jar_files(dir, true) {
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
dirs.push(parent.to_path_buf());
}
}
dirs
}
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = split_jar_glob(value) {
return jar_files(&root.join(base), recursive);
}
let path = root.join(value.trim());
if path.is_dir() {
let jars = jar_files(&path, true);
if !jars.is_empty() {
return jars;
let entry = class_entry(root, value);
match entry.strip_suffix('*') {
Some(dir) => {
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
.unwrap_or_default();
jars.sort();
jars
}
None => vec![PathBuf::from(entry)],
}
vec![path]
}
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
fn class_entries(root: &Path, value: &str) -> Vec<String> {
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
if let Some((base, recursive)) = split_jar_glob(value) {
let dir = root.join(base);
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
}
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
fn class_entry(root: &Path, value: &str) -> String {
let path = root.join(value.trim());
if path.is_dir() {
let dirs = jar_dirs(&path);
if !dirs.is_empty() {
return dirs.iter().map(|d| wildcard(d)).collect();
}
let text = path.to_string_lossy().into_owned();
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
return text[..text.len() - 4].to_owned();
}
vec![path.to_string_lossy().into_owned()]
text
}
fn classpath(entries: &[String]) -> String {
@@ -466,10 +440,7 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
}
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
/// directory for `WarExploded`).
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
#[allow(clippy::too_many_arguments)]
pub fn structure_war_plan(
root: &Path,
@@ -478,7 +449,7 @@ pub fn structure_war_plan(
jdk: Option<&StructureJdk>,
language_level: &str,
artifact: &ArtifactConfig,
war: Option<&Path>,
war: &Path,
cache: &Path,
) -> IdeResult<BuildPlan> {
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
@@ -488,7 +459,7 @@ pub fn structure_war_plan(
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
plan.steps
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
plan.title = artifact.name.clone();
Ok(plan)
}
@@ -1173,53 +1144,4 @@ mod tests {
bad_result.messages
);
}
#[test]
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
let cache = tmp.path().join("cache");
write(&root.join("src/A.java"), "class A {}");
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
fs::create_dir_all(root.join("plain-classes")).unwrap();
write(&root.join("plain-classes/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary {
name: "web-libs".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
..Default::default()
},
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
],
artifacts: vec![ArtifactConfig {
name: "app:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/app_war_exploded".into(),
main_class: String::new(),
include_libraries: vec!["web-libs".into()],
}],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
let javac = &plan.steps[0];
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
let sep = std::path::MAIN_SEPARATOR;
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
let layout = plan.steps.iter().find_map(|s| match &s.action {
Some((Action::Layout { entries, .. }, _)) => Some(entries),
_ => None,
});
let entries = layout.expect("layout step");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
}
}
+4 -19
Переглянути файл
@@ -234,7 +234,9 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
Some(out)
}
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
@@ -281,28 +283,11 @@ fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
entries.push(entry);
i += 1;
if wide {
if i == count {
return None;
}
entries.push(Entry::Empty);
i += 1;
}
}
Some(Pool(entries))
}
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
pub fn class_file_name(data: &[u8]) -> Option<String> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
r.u2()?; // access_flags
Some(pool.class(r.u2()?)?.to_owned())
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ mod incremental;
mod javac;
mod model;
pub use classfile::{ClassFile, class_file_name};
pub use classfile::ClassFile;
pub use javac::{JavacPool, Reply, ServerKey};
use incremental::{ClassRecord, SetStamp, SetState};
+2 -83
Переглянути файл
@@ -69,9 +69,6 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -179,7 +176,6 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -252,7 +248,6 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1524,13 +1519,7 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let dependencies = ctx
.deps
.iter()
@@ -1540,26 +1529,11 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: scope(d),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
(!path.contains("${") && Path::new(&path).is_absolute())
.then(|| Path::new(&path).components().collect::<PathBuf>())
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1618,7 +1592,6 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
@@ -4488,58 +4461,4 @@ mod linkage_tests {
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
}
}
#[test]
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("child")).unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules><module>child</module></modules>
<build>
<plugins>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
<version>0.0.38</version>
</plugin>
</plugins>
</build>
</project>"#,
)
.unwrap();
std::fs::write(
root.join("child/pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>child</artifactId>
</project>"#,
)
.unwrap();
let model = load_with_repo(root, None);
for pom in ["pom.xml", "child/pom.xml"] {
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
let plugin = proj
.plugins
.iter()
.find(|p| p.prefix == "spring-javaformat")
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
assert_eq!(plugin.group_id, "io.spring.javaformat");
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
}
}
}
-25
Переглянути файл
@@ -314,30 +314,6 @@ pub struct SmartKeysSettings {
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -359,7 +335,6 @@ impl Default for SmartKeysSettings {
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
+1 -59
Переглянути файл
@@ -15,9 +15,7 @@ use std::sync::Arc;
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
/// breakpoints, which the editor owns, persists and mirrors to the backend.
/// Run would, answered the same way.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
@@ -27,10 +25,6 @@ pub enum McpUiRequest {
subject: String,
project: String,
detail: Option<String>,
/// The project is served without a window: the request shows in another project's window,
/// which names it and keeps the keyboard focus where it is.
#[serde(default)]
background: bool,
},
OpenFile {
path: crate::IpcPath,
@@ -47,36 +41,6 @@ pub enum McpUiRequest {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Start a run configuration in Debug mode as the IDE's Debug action would.
DebugConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
/// applies the edit to its current list, so a user's pending edit is not overwritten.
SetBreakpoint {
path: String,
breakpoint: McpBreakpoint,
},
/// Removes breakpoints from the window's own list. With no path, removes every line
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
RemoveBreakpoints {
path: Option<String>,
line: Option<u32>,
},
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
FlushBreakpoints,
}
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpBreakpoint {
pub line: u32,
pub enabled: bool,
pub condition: Option<String>,
pub hit_condition: Option<String>,
pub log_message: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -99,8 +63,6 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// Agent automations, run history, or session schedules changed on the host.
AutomationsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
@@ -161,8 +123,6 @@ pub enum IdeEvent {
DocDiskConflict {
doc: DocId,
path: String,
/// The file no longer exists: saving recreates it, and there is nothing to load.
deleted: bool,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
@@ -182,15 +142,6 @@ pub enum IdeEvent {
/// See `DocumentInfo::ui_mode`.
ui_mode: Option<String>,
},
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
/// was rewritten by another program), which the editor only learns when it opens.
DocEncoding {
doc: DocId,
encoding: String,
has_bom: bool,
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
line_ending: String,
},
/// Full replacement of diagnostics for one file from one producer.
Diagnostics {
path: crate::IpcPath,
@@ -253,15 +204,6 @@ pub enum IdeEvent {
message: String,
actions: Vec<String>,
},
/// A language server asked to show a document (`window/showDocument`), e.g. the
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
LspShowDocument {
uri: String,
path: Option<crate::IpcPath>,
selection: Option<crate::Range>,
take_focus: bool,
},
/// The request was answered or timed out; every window drops its dialog.
LspMessageRequestDone {
id: u32,
-72
Переглянути файл
@@ -1,35 +1,5 @@
//! Returning freed heap pages to the OS.
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
/// closing a project or a batch of tabs frees memory in bursts, released once.
pub fn release_free_pages_soon() {
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
debounce(&DUE, Duration::from_secs(2), release_free_pages);
}
/// Runs `run` on a background thread once `delay` passes after the last call.
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
if idle {
std::thread::spawn(move || {
loop {
let mut slot = due.lock().unwrap();
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
if left.is_zero() {
*slot = None;
drop(slot);
return run();
}
drop(slot);
std::thread::sleep(left);
}
});
}
}
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
@@ -48,45 +18,3 @@ pub fn release_free_pages() {
libc::malloc_trim(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
static RUNS: AtomicUsize = AtomicUsize::new(0);
fn count() {
RUNS.fetch_add(1, SeqCst);
}
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
-116
Переглянути файл
@@ -83,24 +83,6 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
cmd
}
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
/// stopped there as a background job when the app was started from a shell) falls back to
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
/// elsewhere.
pub fn own_session(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
unsafe {
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
}
}
cmd
}
/// Kills the child and everything it started, then reaps it.
///
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
@@ -640,30 +622,6 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
}
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
/// loaded into the process or re-read from the registry (#6806): the extra NUL
/// is treated as an entry separator and leaves a fragment with no `=`.
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
}
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
s.as_encoded_bytes().contains(&byte)
}
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
/// included when this process lacks the variable.
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
@@ -988,28 +946,6 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn own_session_leaves_the_controlling_terminal_behind() {
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
let mut cmd = Command::new("sh");
cmd.args(["-c", "ps -o tty= -p $$"]);
let out = own_session(&mut cmd).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
// Without a terminal (CI) the line above holds anyway: the child must lead a session
// of its own, which only `setsid` makes it.
let mut cmd = Command::new("sleep");
cmd.arg("5");
let mut child = own_session(&mut cmd).spawn().unwrap();
let pid = libc::pid_t::try_from(child.id()).unwrap();
// SAFETY: plain syscall on a child not reaped yet.
let session = unsafe { libc::getsid(pid) };
let _ = child.kill();
let _ = child.wait();
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
@@ -1240,29 +1176,6 @@ mod tests {
set_env_overlay(Vec::new());
}
#[test]
fn a_child_inside_a_project_gets_its_xcode() {
let root = std::path::Path::new("/openidea-test-process/xcode");
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
crate::project_env::set_developer_dir(root, Some(xcode.into()));
let developer_dir = |cmd: &Command| {
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
};
// xcodebuild, xcrun, a language server: a `Command` started in the project.
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root.join("App")));
assert_eq!(developer_dir(&tool), Some(xcode.into()));
// A terminal: a PTY applies the fixes itself.
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
let mut elsewhere = Command::new("xcodebuild");
prepare(elsewhere.current_dir("/openidea-test-process/other"));
assert_eq!(developer_dir(&elsewhere), None);
crate::project_env::set_developer_dir(root, None);
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root));
assert_eq!(developer_dir(&tool), None, "empty: the system default");
}
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
@@ -1304,35 +1217,6 @@ mod tests {
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
}
fn os_from_bytes(bytes: &[u8]) -> OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(bytes.to_vec())
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
}
}
#[test]
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
let ok_key = OsString::from("PATH");
let ok_val = OsString::from("/bin");
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
// A REG_MULTI_SZ value's interior NUL would split the environment block,
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
}
#[test]
fn changes_apply_in_order() {
let vars = apply_changes(
+2 -62
Переглянути файл
@@ -16,21 +16,13 @@ struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
developer_dir: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self {
root,
direnv: Vec::new(),
github_token: None,
developer_dir: None,
changes: Changes::default(),
loading: false,
}
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
}
fn rebuild(&mut self) {
@@ -41,16 +33,11 @@ impl Entry {
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
if let Some(dir) = &self.developer_dir {
combined.retain(|(k, _)| k != DEVELOPER_DIR);
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
}
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
}
}
@@ -157,31 +144,6 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
}
}
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
/// injected for children started in `root`. Returns whether it changed.
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
let dir = dir.filter(|d| !d.is_empty());
let mut entries = entries();
let idx = match entries.iter().position(|e| e.root == root) {
Some(idx) if entries[idx].developer_dir == dir => return false,
Some(idx) => idx,
None if dir.is_none() => return false,
None => {
entries.push(Entry::new(root.to_path_buf()));
entries.len() - 1
}
};
let entry = &mut entries[idx];
entry.developer_dir = dir;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
@@ -240,28 +202,6 @@ mod tests {
assert!(for_dir(inner).is_empty());
}
#[test]
fn the_projects_xcode_wins_over_envrc_and_clears() {
let root = Path::new("/openidea-test-env/xcode");
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert_eq!(
*for_dir(&root.join("App")),
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
);
assert!(set_developer_dir(root, None));
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
remove(root);
assert!(for_dir(root).is_empty());
let alone = Path::new("/openidea-test-env/xcode-alone");
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
assert!(set_developer_dir(alone, Some("/X".into())));
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
assert!(set_developer_dir(alone, None));
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
}
#[test]
fn waiting_ends_once_the_environment_is_read() {
let root = Path::new("/openidea-test-env/waiting");
+7 -24
Переглянути файл
@@ -5,29 +5,6 @@ use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
pub fn is_skipped_dir(name: &str) -> bool {
name.starts_with('.')
|| matches!(
name,
"node_modules"
| "target"
| "build"
| "dist"
| "vendor"
| "out"
| "bin"
| "obj"
| "venv"
| "SourcePackages"
| "Pods"
| "Carthage"
| "DerivedData"
)
}
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
@@ -36,7 +13,13 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
!is_skipped_dir(&entry.file_name().to_string_lossy())
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
})
.map(|entry| entry.path())
.collect();
+1 -7
Переглянути файл
@@ -203,9 +203,6 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -218,8 +215,7 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
/// Remote folder the project is synchronised to and run from (SSH).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -245,8 +241,6 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+1 -296
Переглянути файл
@@ -165,20 +165,6 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentPluginSettings)]
pub plugins: AgentPluginSettings,
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentAutomationSettings)]
pub automations: AgentAutomationSettings,
}
impl Default for AgentSettings {
@@ -210,9 +196,6 @@ impl Default for AgentSettings {
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -296,169 +279,6 @@ impl Default for AgentSkillPolicy {
}
}
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryMode {
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
#[default]
Auto,
/// Force-load into every session regardless of path scoping.
Always,
/// Exclude from sessions where the harness supports it.
Off,
}
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutoMemoryMode {
/// Leave the agent's own configuration untouched.
#[default]
Inherit,
/// Read past memories and record new ones.
ReadWrite,
/// Read past memories without recording new ones.
ReadOnly,
/// Neither read nor record cross-session auto-memories.
Off,
}
/// One memory or instruction entry's policy in Settings › Agents › Memory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryEntryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemoryMode)]
pub mode: AgentMemoryMode,
/// Agent provider ids this entry applies to; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
}
impl Default for AgentMemoryEntryPolicy {
fn default() -> Self {
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
}
}
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentProviderMemoryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
}
/// Agent memory settings (`[agents.memory]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemorySettings {
/// Default cross-session auto-memory policy across agents.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
/// Per-entry modes (`[agents.memory.entries.<id>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// One agent plugin bundle's policy in Settings › Agents › Plugins
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginEntryPolicy {
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub config: BTreeMap<String, String>,
}
/// Agent plugin bundle settings (`[agents.plugins]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginSettings {
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marketplaces: Vec<String>,
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
}
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationPreventSleep {
/// Prevent idle sleep while plugged into AC power.
#[default]
Ac,
/// Prevent idle sleep whenever an automated turn is running.
Always,
/// Never hold an idle-sleep assertion.
Never,
}
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationMisfirePolicy {
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
#[default]
RunOnce,
/// Skip missed occurrences and advance to the next future slot.
Skip,
}
/// Agent automation and headless scheduler settings (`[agents.automations]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentAutomationSettings {
/// Automatically register the headless login/boot scheduler service while at least one
/// automation is enabled, and unregister it when none remain enabled.
pub auto_start_service: bool,
/// Keep the local OpenIDEA host alive in the background when windows close while local
/// automations are enabled.
pub keep_alive_in_background: bool,
/// Prevent system idle sleep while an automated turn is running.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationPreventSleep)]
pub prevent_sleep: AutomationPreventSleep,
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationMisfirePolicy)]
pub misfire_policy: AutomationMisfirePolicy,
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
/// enabled scheduled automations.
pub keep_remote_daemon_alive: bool,
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
/// and zero commits.
pub auto_clean_worktrees: bool,
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
/// finished ones.
pub max_dirty_worktrees: u32,
}
impl Default for AgentAutomationSettings {
fn default() -> Self {
Self {
auto_start_service: false,
keep_alive_in_background: true,
prevent_sleep: AutomationPreventSleep::Ac,
misfire_policy: AutomationMisfirePolicy::RunOnce,
keep_remote_daemon_alive: true,
auto_clean_worktrees: true,
max_dirty_worktrees: 5,
}
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -1553,7 +1373,6 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1587,7 +1406,6 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1610,9 +1428,6 @@ pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
@@ -1625,22 +1440,12 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
#[default]
Ask,
Trusted,
Off,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
@@ -1885,26 +1690,6 @@ pub struct ZigSettings {
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SwiftSettings {
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
pub xcode: String,
}
impl SwiftSettings {
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
let xcode = self.xcode.trim();
if xcode.is_empty() {
return None;
}
let path = std::path::Path::new(xcode);
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
}
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -2111,10 +1896,6 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
#[serde(deserialize_with = "or_default")]
#[specta(type = TsServerLog)]
pub tsserver_log: TsServerLog,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
@@ -2122,27 +1903,10 @@ pub struct TypeScriptSettings {
impl Default for TypeScriptSettings {
fn default() -> Self {
Self {
version: "bundled".into(),
tsserver_max_memory: 0,
tsserver_log: TsServerLog::Off,
watch_problems: false,
}
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
}
}
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TsServerLog {
#[default]
Off,
Terse,
Normal,
RequestTime,
Verbose,
}
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -2168,37 +1932,6 @@ pub struct ProjectLibrary {
pub scope: DependencyScope,
}
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
let entry = entry.trim();
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
return Some((base, true));
}
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
}
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
match entry.file_type() {
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
out.push(path)
}
_ => {}
}
}
}
let mut out = Vec::new();
walk(dir, recursive, &mut out);
out
}
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -2346,20 +2079,6 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn the_xcode_setting_becomes_a_developer_dir() {
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
assert_eq!(dir(""), None);
assert_eq!(dir(" "), None);
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
assert_eq!(
dir("/Applications/Xcode.app/Contents/Developer"),
Some("/Applications/Xcode.app/Contents/Developer".into())
);
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
assert_eq!(s.languages.swift.xcode, "/X.app");
}
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
@@ -2370,20 +2089,6 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
let log = |v: &str| {
let s: Settings =
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
s.languages.typescript.tsserver_log
};
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
assert_eq!(log("3"), TsServerLog::Off);
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
-56
Переглянути файл
@@ -27,35 +27,6 @@ pub struct VcsSettings {
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
/// Settings › Version Control › Subversion.
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnSettings {
/// Path to the svn executable; empty = auto-detect.
pub executable: String,
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
pub interactive: bool,
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
}
impl Default for SvnSettings {
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
fn default() -> Self {
Self {
executable: String::new(),
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
}
}
}
/// Settings › Version Control › GitHub (`vcs.github`).
@@ -109,7 +80,6 @@ impl Default for VcsSettings {
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
svn: SvnSettings::default(),
}
}
}
@@ -560,7 +530,6 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -583,7 +552,6 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -602,14 +570,6 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -656,8 +616,6 @@ pub struct TerminalSettings {
pub close_on_exit: bool,
pub mouse_reporting: bool,
pub copy_on_selection: bool,
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
pub osc52_clipboard: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
@@ -698,7 +656,6 @@ impl Default for TerminalSettings {
close_on_exit: true,
mouse_reporting: true,
copy_on_selection: false,
osc52_clipboard: true,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
@@ -843,17 +800,4 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
-92
Переглянути файл
@@ -35,24 +35,6 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -104,57 +86,6 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,21 +103,6 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -211,14 +127,6 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
version.workspace = true
edition.workspace = true
license.workspace = true
+1 -1
Переглянути файл
@@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator
impl Accumulator {
/// Removes the branch data of lines whose branches are all taken or all missed.
pub(crate) fn drop_unanimous_branches(&mut self) {
fn drop_unanimous_branches(&mut self) {
for lines in self.files.values_mut() {
for acc in lines.values_mut() {
let taken = acc.branches.values().filter(|t| **t).count();
-26
Переглянути файл
@@ -13,7 +13,6 @@
//! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset |
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
//!
//! Lines in the model are 0-based, like every IPC coordinate.
@@ -25,7 +24,6 @@ mod jacoco;
mod lcov;
mod plan;
mod simplecov;
mod xccov;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
@@ -96,8 +94,6 @@ pub enum CoverageReportSpec {
Jacoco { dir: IpcPath },
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
Xccov { bundle: IpcPath, root: IpcPath },
}
/// A command line that installs a missing tool (run in the Run tool window).
@@ -238,31 +234,9 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
let text = read_report(lcov)?;
Ok(lcov::parse(&text, cwd).finish(runner))
}
CoverageReportSpec::Xccov { bundle, root } => {
if !bundle.exists() {
return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display())));
}
let report = xccov_json(&["--report", "--json"], bundle)?;
let archive = xccov_json(&["--archive", "--json"], bundle)?;
Ok(xccov::parse(&report, &archive, root)
.map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))?
.finish("xccov"))
}
}
}
/// `xcrun xccov view <args> <bundle>`'s output.
fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult<String> {
let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle))
.output()
.map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?;
if !out.status.success() {
let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned();
return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}")));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn read_report(path: &Path) -> IdeResult<String> {
std::fs::read_to_string(path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => {
-34
Переглянути файл
@@ -61,9 +61,6 @@ fn ready(
/// data; it must exist (the Gradle init script is written there). Probes tools,
/// so call it from a blocking thread.
pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
if config.kind == "xcode-test" {
return xcode(root, config, out);
}
let dir = wrap::run_dir(root, config);
let program = program_name(&config.command);
let first = config.args.first().map(String::as_str).unwrap_or_default();
@@ -339,20 +336,6 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
ready("coverage.py", &config, command, args, report)
}
/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test`
/// adds it at launch).
fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
let mut config = config.clone();
if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") {
config.args.drain(at..(at + 2).min(config.args.len()));
}
config.args.extend([s("-enableCodeCoverage"), s("YES")]);
let bundle = out.join("coverage.xcresult");
config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle));
let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() };
ready("xccov", &config, config.command.clone(), config.args.clone(), report)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -552,23 +535,6 @@ mod tests {
);
}
#[test]
fn xcode_tests_turn_coverage_on_into_their_own_bundle() {
let dir = tempfile::tempdir().unwrap();
let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]);
let p = prepare(dir.path(), &config, dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]);
let bundle = dir.path().join("coverage.xcresult");
assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy());
assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle));
// A trailing flag without a value is replaced too.
let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]);
let p = prepare(dir.path(), &config, dir.path());
assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]);
}
#[test]
fn unknown_commands_are_unsupported() {
let dir = tempfile::tempdir().unwrap();
-188
Переглянути файл
@@ -1,188 +0,0 @@
//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle:
//!
//! - `xcrun xccov view --report --json <bundle>`: the targets and their files. Files that only
//! test bundles (`*.xctest`) compile are left out.
//! - `xcrun xccov view --archive --json <bundle>`: `{ "<path>": [{ line, isExecutable,
//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its
//! own count; a covered line with a missed region is partial.
use crate::Accumulator;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Report {
#[serde(default)]
targets: Vec<Target>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Target {
#[serde(default)]
build_product_path: String,
#[serde(default)]
files: Vec<ReportFile>,
}
#[derive(Deserialize)]
struct ReportFile {
path: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Line {
line: u32,
is_executable: bool,
#[serde(default)]
execution_count: u64,
#[serde(default)]
subranges: Vec<Subrange>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subrange {
column: u32,
#[serde(default)]
length: u32,
#[serde(default)]
execution_count: u64,
}
/// `path` inside the project as the project names it: the project and xccov may name it through
/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData.
fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option<PathBuf> {
let real;
let rel = match path.strip_prefix(root) {
Ok(rel) => rel,
Err(_) => {
real = path.canonicalize().ok()?;
real.strip_prefix(real_root).ok()?
}
};
let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build"));
(!generated).then(|| root.join(rel))
}
pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result<Accumulator, serde_json::Error> {
let report: Report = serde_json::from_str(report)?;
let archive: BTreeMap<String, Vec<Line>> = serde_json::from_str(archive)?;
// App and framework sources: a file listed by an app or framework target counts even when a test
// bundle compiles it too (sources added to the test target's membership instead of `@testable`).
let is_test_bundle = |t: &Target| {
Path::new(&t.build_product_path)
.components()
.any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest")))
};
let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
// Both views go through `in_project`, so they match however each spells the path.
let sources: BTreeSet<PathBuf> = report
.targets
.iter()
.filter(|t| !is_test_bundle(t))
.flat_map(|t| &t.files)
.filter_map(|f| in_project(Path::new(&f.path), root, &real_root))
.collect();
let mut acc = Accumulator::default();
for (file, lines) in &archive {
let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else {
continue;
};
acc.file(&path);
for l in lines.iter().filter(|l| l.is_executable && l.line > 0) {
let n = l.line - 1;
acc.line(&path, n, l.execution_count);
if !l.subranges.is_empty() {
acc.branch(&path, n, "line".into(), l.execution_count > 0);
for r in &l.subranges {
acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0);
}
}
}
}
// Regions are not branches: keep only the partial marks of lines with mixed regions.
acc.drop_unanimous_branches();
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
// Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit
// test target; paths rewritten to /Users/me.
const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json");
const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json");
#[test]
fn reads_app_sources_and_leaves_out_test_bundles() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov");
assert!(!suite.has_branches);
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(
names,
[Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")]
);
// xccov's own totals for Calculator.swift: 14 of 17 lines.
let calc = &suite.files[1];
assert_eq!((calc.lines_total, calc.lines_covered), (17, 14));
let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap();
// `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region.
assert_eq!(at(7).hits, 0);
assert!(at(6).partial());
assert!(!at(1).partial());
}
#[test]
fn files_outside_the_project_are_dropped() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov");
assert!(suite.files.is_empty());
let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#;
let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 2);
}
#[test]
fn a_file_of_an_app_and_a_test_bundle_counts() {
let report = r#"{"targets":[
{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]},
{"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#;
let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(names, [Path::new("/p/A.swift")]);
}
#[cfg(unix)]
#[test]
fn paths_through_another_symlink_map_to_the_project() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().canonicalize().unwrap().join("real");
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("A.swift"), "").unwrap();
let link = dir.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let file = real.join("A.swift").to_string_lossy().into_owned();
let report =
format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#);
let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift"));
// The report names the file through the symlink, the archive by its real path.
let linked = link.join("A.swift").to_string_lossy().into_owned();
let report = report.replace(&file, &linked);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 1);
}
}
-226
Переглянути файл
@@ -1,226 +0,0 @@
{
"/Users/me/CovDemo/CovDemo/App.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
}
],
"/Users/me/CovDemo/CovDemo/Calculator.swift": [
{
"isExecutable": false,
"line": 1
},
{
"executionCount": 1,
"isExecutable": true,
"line": 2
},
{
"executionCount": 1,
"isExecutable": true,
"line": 3
},
{
"executionCount": 1,
"isExecutable": true,
"line": 4
},
{
"isExecutable": false,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7,
"subranges": [
{
"column": 19,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
},
{
"isExecutable": false,
"line": 12
},
{
"executionCount": 1,
"isExecutable": true,
"line": 13
},
{
"executionCount": 1,
"isExecutable": true,
"line": 14,
"subranges": [
{
"column": 18,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 15
},
{
"executionCount": 1,
"isExecutable": true,
"line": 16,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
},
{
"column": 26,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 17
},
{
"executionCount": 1,
"isExecutable": true,
"line": 18,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 19
},
{
"executionCount": 1,
"isExecutable": true,
"line": 20
}
],
"/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
},
{
"isExecutable": false,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
}
]
}
-140
Переглянути файл
@@ -1,140 +0,0 @@
{
"coveredLines": 28,
"executableLines": 31,
"lineCoverage": 0.9032258064516129,
"targets": [
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo",
"coveredLines": 18,
"executableLines": 21,
"files": [
{
"coveredLines": 14,
"executableLines": 17,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 2,
"name": "Calculator.add(_:_:)"
},
{
"coveredLines": 5,
"executableLines": 6,
"executionCount": 1,
"lineCoverage": 0.8333333333333334,
"lineNumber": 6,
"name": "Calculator.divide(_:_:)"
},
{
"coveredLines": 6,
"executableLines": 8,
"executionCount": 1,
"lineCoverage": 0.75,
"lineNumber": 13,
"name": "Calculator.describe(_:)"
}
],
"lineCoverage": 0.8235294117647058,
"name": "Calculator.swift",
"path": "/Users/me/CovDemo/CovDemo/Calculator.swift"
},
{
"coveredLines": 4,
"executableLines": 4,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CovDemoApp.body.getter"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "closure #1 in CovDemoApp.body.getter"
}
],
"lineCoverage": 1,
"name": "App.swift",
"path": "/Users/me/CovDemo/CovDemo/App.swift"
}
],
"lineCoverage": 0.8571428571428571,
"name": "CovDemo.app"
},
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests",
"coveredLines": 10,
"executableLines": 10,
"files": [
{
"coveredLines": 10,
"executableLines": 10,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #1 in CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #2 in CalculatorTests.testAdd()"
},
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 9,
"name": "CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #1 in CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #2 in CalculatorTests.testDivide()"
}
],
"lineCoverage": 1,
"name": "CalculatorTests.swift",
"path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift"
}
],
"lineCoverage": 1,
"name": "CovDemoTests.xctest"
}
]
}
-1
Переглянути файл
@@ -17,7 +17,6 @@ ide-jvm-attach.workspace = true
ide-jvm-inspect.workspace = true
ide-jdwp.workspace = true
ide-heap.workspace = true
ide-run.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+13 -101
Переглянути файл
@@ -360,63 +360,23 @@ fn find_binary_in(
}
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
(command == "lldb-dap" && !cfg!(windows))
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
.flatten()
})
find_binary(command, cwd).or_else(|| xcrun_tool(command))
}
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
/// The newest LLVM wins.
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
let version = |name: &str| -> Option<u32> {
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
v.parse().ok()
};
let mut found: Vec<(u32, PathBuf)> = Vec::new();
for dir in dirs {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
&& is_executable(&path, false)
{
found.push((v, path));
}
}
}
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
continue;
};
for name in ["lldb-dap", "lldb-vscode"] {
let path = entry.path().join("bin").join(name);
if is_executable(&path, false) {
found.push((v, path));
}
}
}
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
#[cfg(target_os = "macos")]
fn xcrun_tool(command: &str, cwd: &Path) -> Option<PathBuf> {
fn xcrun_tool(command: &str) -> Option<PathBuf> {
if command != "lldb-dap" {
return None;
}
let mut cmd = std::process::Command::new("/usr/bin/xcrun");
cmd.current_dir(cwd);
let out = ide_core::process::prepare(&mut cmd).args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
(out.status.success() && is_executable(&path, false)).then_some(path)
}
#[cfg(not(target_os = "macos"))]
fn xcrun_tool(_command: &str, _cwd: &Path) -> Option<PathBuf> {
fn xcrun_tool(_command: &str) -> Option<PathBuf> {
None
}
@@ -509,7 +469,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
const GDB_MIN_MAJOR: u32 = 14;
/// `(major, minor)` of the first version number in the output of `gdb --version`
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
@@ -550,29 +510,24 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
/// Probe the already resolved and verified executable with its launch environment.
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
}
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
let mut probe = Command::new(binary);
if let Some(path) = adapter_path(env, cwd) {
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
probe.env("PATH", path);
}
probe.current_dir(cwd);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
let probe = probe
.arg("--version")
.envs(env.iter().cloned())
.envs(spec.env.iter().cloned())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.output();
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
return None;
return Ok(None);
};
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
}
/// Refuse old GDB versions and report whether launch must follow configurationDone.
@@ -585,9 +540,8 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -1069,48 +1023,6 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
fn finds_versioned_lldb_dap() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let exe = |p: &Path| {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
exe(&bin.join("lldb-vscode-14"));
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
exe(&lib.join("llvm-18/bin/lldb-dap"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
exe(&bin.join("lldb-dap-19"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
}
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
#[test]
fn parses_gdb_versions() {
+3 -60
Переглянути файл
@@ -22,10 +22,8 @@ mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
pub mod native;
mod session;
mod stream_trace;
mod swiftpm;
pub mod unity;
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
@@ -508,11 +506,6 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
fn is_native(adapter: &str) -> bool {
matches!(adapter, "lldb-dap" | "codelldb")
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
@@ -620,16 +613,6 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
Ok(Some(DebugServer { host, port }))
}
/// A source served only through the `source` request whose `path` is no file, such as
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
pub(crate) fn frame_from(f: &Value) -> StackFrame {
let source = f.get("source");
@@ -642,11 +625,7 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
StackFrame {
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
path: source
.and_then(|s| s.get("path"))
.and_then(Value::as_str)
.filter(|p| !is_pseudo_path(source, p))
.map(Into::into),
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
presentation_hint: hint,
@@ -933,30 +912,6 @@ impl DebugManager {
.collect()
}
/// Whether `s` is live and currently suspended (a breakpoint, step or manual pause).
/// `None` when the session has ended.
pub fn session_suspended(&self, s: DebugSessionId) -> Option<bool> {
self.sessions.lock().get(&s).map(|session| session.suspended.get())
}
/// The thread of `s`'s most recent stop, when the adapter named one.
pub fn stopped_thread(&self, s: DebugSessionId) -> Option<i64> {
self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread())
}
/// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints
/// are keyed by file; function and data breakpoints have no file.
pub fn breakpoints(
&self,
owner: &str,
) -> (BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
let store = self.breakpoints.lock();
match store.get(owner) {
Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()),
None => Default::default(),
}
}
/// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`,
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
@@ -1101,9 +1056,6 @@ impl DebugManager {
.await?;
arguments["program"] = json!(program);
}
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
}
// Attach to a Node process started without `--inspect`: open its inspector first.
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
let pid = arguments.get("processId").and_then(|p| match p {
@@ -1422,9 +1374,6 @@ impl DebugManager {
.await?;
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
if s.adapter == adapter::JAVA_ANALYZER && s.request == "launch" {
session::shorten_java_analyzer_classpath(s, &mut arguments)?;
}
// The Kotlin adapters ignore the resolved classpath and project runtime on launch.
let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" {
session::start_kotlin_debuggee(s, &mut arguments).await?;
@@ -1643,16 +1592,11 @@ impl DebugManager {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && (!own_terminate || killed) {
// A native attach to a program a run started for the debugger (an Xcode app launched
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
// simulator then holds its launch (and the next one) forever.
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
let _ = s
.conn
.request_timeout(
"disconnect",
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
SHUTDOWN_TIMEOUT,
)
.await;
@@ -1796,8 +1740,7 @@ impl DebugManager {
let mut states = self.states.lock();
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
let next = session::state_from(bp, slot.line);
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
let next = BreakpointState { message: next.message.or(kept), ..next };
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
let changed = *slot != next;
*slot = next;
changed
-206
Переглянути файл
@@ -1,206 +0,0 @@
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
//! CodeLLDB is the debugger OpenIDEA can install itself.
use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
/// debugger command: a configured tool path, else the search path). Other launches pass through.
pub async fn choose(
mut config: LaunchConfig,
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
) -> IdeResult<LaunchConfig> {
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let found = tokio::task::spawn_blocking(move || {
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
if lookup("codelldb").is_some() {
return Found::CodeLldb;
}
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
match found {
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
Found::Nothing => return Err(missing(None)),
}
Ok(config)
}
enum Found {
LldbDap,
CodeLldb,
Gdb(PathBuf),
Nothing,
}
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
let found = match gdb {
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
IdeError::unavailable(format!(
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
))
}
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
None => Map::new(),
Some(Ok(Value::Object(extra))) => extra,
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
};
extra.remove("env");
let source_map = extra.remove("sourceMap");
if to == "codelldb" {
if let Some(Value::Array(pairs)) = source_map {
let map: Map<String, Value> = pairs
.iter()
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
_ => None,
})
.collect();
if !map.is_empty() {
extra.insert("sourceMap".into(), Value::Object(map));
}
}
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
}
config.adapter = to.to_owned();
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
name: "hello".into(),
adapter: "lldb-dap".into(),
request: "launch".into(),
program: Some("/home/dev/hello/build/hello".into()),
args: vec![],
cwd: Some(std::path::PathBuf::from("/").into()),
env: BTreeMap::from([("A".into(), "1".into())]),
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
}
}
fn extra(config: &LaunchConfig) -> Value {
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
}
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
}
#[tokio::test]
async fn keeps_lldb_dap_when_it_is_there() {
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "lldb-dap");
assert_eq!(config.extra_json, cmake_launch().extra_json);
}
#[tokio::test]
async fn falls_back_to_codelldb_with_its_launch_shape() {
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "codelldb");
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
assert_eq!(
extra(&config),
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
);
}
#[tokio::test]
async fn a_swift_package_evaluates_swift_under_codelldb() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
let config = choose(launch, only(&["codelldb"])).await.unwrap();
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
}
#[tokio::test]
async fn other_launches_pass_through() {
let mut attach = cmake_launch();
attach.request = "attach".into();
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
let mut rust = cmake_launch();
rust.adapter = "codelldb".into();
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
}
#[cfg(unix)]
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let gdb = dir.join("gdb");
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
gdb
}
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
#[cfg(unix)]
#[tokio::test]
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
#[tokio::test]
async fn falls_back_to_a_gdb_with_dap() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
}
}
+37 -177
Переглянути файл
@@ -136,16 +136,6 @@ pub(crate) struct Session {
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
/// Temporary pathing jars / argfiles created for this session; removed on stop/drop.
temp_files: Mutex<Vec<TempFile>>,
}
struct TempFile(PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// Which threads of the program are suspended: each from its `stopped` event until a
@@ -217,14 +207,6 @@ impl Suspension {
stops.all.is_some() || !stops.threads.is_empty()
}
/// The most recently stopped individual thread, when the stop named one. A stop of every
/// thread (`allThreadsStopped`) names none, so callers fall back to the adapter's first thread.
pub fn stopped_thread(&self) -> Option<i64> {
let stops = self.0.lock();
let latest = stops.latest()?;
stops.threads.iter().find(|&&(_, ticket)| ticket == latest).map(|&(id, _)| id)
}
/// A `stopped` event; `all`: its `allThreadsStopped`.
pub fn stopped(&self, thread: Option<i64>, all: bool) {
let mut stops = self.0.lock();
@@ -293,11 +275,6 @@ impl Suspension {
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
/// One literal: the UI looks it up in the text catalogs to translate it.
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -373,7 +350,6 @@ impl Session {
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
temp_files: Mutex::new(Vec::new()),
}
}
@@ -519,9 +495,6 @@ impl Session {
ids.insert(id, (path.to_path_buf(), i));
}
states[i] = state_from(r, breakpoints[i].line);
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
states[i].message = Some(UNBOUND_NATIVE.to_owned());
}
}
Ok(states)
}
@@ -608,7 +581,6 @@ impl Session {
if let Some(mut program) = self.program.lock().take() {
program.kill();
}
self.temp_files.lock().clear();
}
}
@@ -1142,27 +1114,21 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
// See #6806: do not inherit portable-pty's registry-built Windows env block.
cmd.env_clear();
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
cmd.env(k, v);
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
}
for (k, v) in ide_core::process::shell_env_in(cwd) {
if ide_core::process::is_spawnable_env_pair(&k, &v) {
cmd.env(k, v);
}
cmd.env(k, v);
}
cmd.env("TERM", "xterm-256color");
cmd.cwd(cwd);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
match v.as_str() {
Some(v)
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
{
cmd.env(k, v)
}
Some(_) => {}
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
};
}
@@ -1352,112 +1318,43 @@ fn kotlin_jvm_args(user: Vec<String>, windows: bool) -> Vec<String> {
args
}
fn json_string_list(args: &Value, key: &str) -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
}
fn json_args_len(args: &Value, key: &str) -> usize {
match args.get(key) {
Some(Value::String(s)) => s.len() + 3,
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(|s| s.len() + 3).sum(),
_ => 0,
}
}
/// Shortens `classPaths` for `java-analyzer dap` into a temporary manifest-only pathing jar when
/// the command line would exceed the OS limit (e.g. Windows `CreateProcessW` `os error 206` on
/// JDK 8 Spring Boot projects).
pub(crate) fn shorten_java_analyzer_classpath(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone());
if let Some(jar) =
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())?
{
s.temp_files.lock().push(TempFile(jar));
}
Ok(())
}
fn shorten_java_analyzer_classpath_with(
args: &mut Value,
cwd: &Path,
windows: bool,
temp_dir: &Path,
) -> ide_core::IdeResult<Option<PathBuf>> {
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let class_paths = json_string_list(args, "classPaths");
let module_paths = json_string_list(args, "modulePaths");
let extra_len = json_args_len(args, "vmArgs")
+ json_args_len(args, "args")
+ args.get("mainClass").and_then(Value::as_str).map_or(0, |s| s.len() + 3);
let Some(jar) = ide_run::java_cmdline::shorten_classpath_to_jar(
Path::new(java),
&class_paths,
&module_paths,
extra_len,
cwd,
windows,
temp_dir,
)?
else {
return Ok(None);
};
args["classPaths"] = json!([jar.to_string_lossy()]);
Ok(Some(jar))
}
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
use tokio::io::{AsyncBufReadExt, BufReader};
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let classpath = std::env::join_paths(json_string_list(args, "classPaths"))
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned();
let mut java_args = kotlin_jvm_args(json_string_list(args, "vmArguments"), cfg!(windows));
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
java_args.push("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0".to_owned());
java_args.push("-cp".to_owned());
java_args.push(classpath);
let modules = json_string_list(args, "modulePaths");
if !modules.is_empty() {
java_args.push("--module-path".to_owned());
java_args.push(
std::env::join_paths(modules)
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned(),
);
}
java_args.push(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?
.to_owned(),
);
java_args.extend(json_string_list(args, "programArgs"));
if let Some(shortened) = ide_run::java_cmdline::shorten(
Path::new(java),
&java_args,
&s.spec.cwd,
cfg!(windows),
&ide_run::java_cmdline::default_temp_dir(),
)? {
java_args = shortened.args;
s.temp_files.lock().push(TempFile(shortened.file));
}
let strings = |key: &str| -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
};
let classpath =
std::env::join_paths(strings("classPaths")).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
let mut cmd = tokio::process::Command::new(java);
cmd.current_dir(&s.spec.cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&java_args)
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(kotlin_jvm_args(strings("vmArguments"), cfg!(windows)))
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
.arg("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0")
.arg("-cp")
.arg(classpath);
let modules = strings("modulePaths");
if !modules.is_empty() {
cmd.arg("--module-path")
.arg(std::env::join_paths(modules).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?);
}
cmd.arg(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?,
)
.args(strings("programArgs"))
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
if let Some(v) = v.as_str() {
@@ -1776,41 +1673,4 @@ mod tests {
// SAFETY: signal 0 only checks whether the process exists.
assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
}
#[test]
fn java_analyzer_long_windows_classpath_is_shortened_to_pathing_jar() {
let dir = tempfile::tempdir().unwrap();
let short_cp = vec![r"C:\app\target\classes".to_owned()];
let mut short_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": short_cp,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
assert!(
super::shorten_java_analyzer_classpath_with(&mut short_args, dir.path(), true, dir.path())
.unwrap()
.is_none()
);
assert_eq!(short_args["classPaths"].as_array().unwrap().len(), 1);
let many: Vec<String> = (0..500)
.map(|i| format!(r"C:\Users\dev\.m2\repository\org\springframework\boot\dep-{i:04}\dep-{i:04}.jar"))
.collect();
let mut long_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": many,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
let jar = super::shorten_java_analyzer_classpath_with(&mut long_args, dir.path(), true, dir.path())
.unwrap()
.expect("long Windows classpath must be shortened into a pathing jar");
assert!(jar.is_file());
let replaced = long_args["classPaths"].as_array().unwrap();
assert_eq!(replaced.len(), 1);
assert_eq!(replaced[0].as_str().unwrap(), jar.to_string_lossy());
}
}
-68
Переглянути файл
@@ -1,68 +0,0 @@
//! SwiftPM launch integration: a launch request may carry
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
//! The run configuration's before launch task has built the product; this asks
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
use crate::adapter::find_binary;
use ide_core::{IdeError, IdeResult};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::process::Stdio;
/// `swift build` arguments that print the bin path for `buildArgs` without building.
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
let mut args = vec!["build".to_owned()];
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
}
args.push("--show-bin-path".into());
args
}
/// The built product of `swiftpm` (see the module docs).
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
let product = swiftpm
.get("product")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
let args = bin_path_args(swiftpm);
let mut cmd = tokio::process::Command::new(swift);
cmd.current_dir(cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let out = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
};
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
}
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
let stdout = String::from_utf8_lossy(&out.stdout);
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
if dir.is_empty() {
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
}
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
Ok(cwd.join(dir).join(exe))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
assert_eq!(
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
["build", "-c", "release", "--show-bin-path"]
);
}
}
+1 -63
Переглянути файл
@@ -138,8 +138,6 @@ struct Script {
output_after_terminate: bool,
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
supports_terminate: bool,
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
unbound_breakpoints: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
/// Send a `continued` event right after the first `stopped` one.
@@ -222,7 +220,6 @@ impl Default for Script {
fn default() -> Self {
Self {
run_in_terminal: None,
unbound_breakpoints: false,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
@@ -417,7 +414,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
.unwrap()
.iter()
.enumerate()
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
.collect();
ok!(msg, json!({"breakpoints": bps}));
}
@@ -2167,21 +2164,6 @@ fn frames_keep_their_instruction_pointer() {
assert!(json.get("instructionPointerReference").is_none());
}
#[test]
fn frames_drop_pseudo_paths_of_referenced_sources() {
let frame = |path: &str, reference: i64| {
frame_from(&json!({"id": 1, "name": "f", "line": 1,
"source": {"path": path, "sourceReference": reference}}))
.path
};
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
let here = env!("CARGO_MANIFEST_DIR");
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
@@ -4022,50 +4004,6 @@ async fn stop_detaches_from_an_attached_program() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
#[tokio::test]
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
let h = harness(Script::default());
let linked = |adapter: &str| LaunchConfig {
adapter: adapter.into(),
request: "attach".into(),
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
..config()
};
let id = h.start(linked("lldb-dap")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
let h = harness(Script::default());
let id = h.start(linked("debugpy")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
async fn an_unbound_native_breakpoint_says_why() {
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
assert!(!states[0].verified);
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
}
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
+62 -134
Переглянути файл
@@ -447,15 +447,6 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
// saves the separate query `table_comment` would make on the same `pg_class` row.
if let Some(comment) = next() {
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
if !comment.is_empty() {
details.comment = Some(comment);
}
}
}
fn flag(v: &Option<String>) -> bool {
@@ -1393,61 +1384,8 @@ impl DbManager {
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, ..Default::default() });
}
// Everything below describes the same table and none of it feeds the next, so it goes
// out together. Serialised, this is four round trips on the path that opens a table
// (`table_page_on` calls this for the primary key), which is what makes opening a table
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
// so one waits — still one round trip rather than five.
type Rows = Vec<Vec<Option<String>>>;
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let (index_q, fk_q, trigger_q) = (
sql::indexes(driver, schema, table),
sql::table_foreign_keys(driver, schema, table),
sql::triggers(driver, schema, table),
);
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
pool.rows(&index_q, MAX_META_ROWS),
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&fk_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("foreign keys: {}", e.message);
Ok(Vec::new())
}
}
},
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&trigger_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("triggers: {}", e.message);
Ok(Vec::new())
}
}
},
async {
// PostgreSQL reads it with the properties above; the engines without a
// `table_properties` query ask for it here.
match sql::table_comment(driver, schema, table) {
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
_ => Ok::<Rows, IdeError>(Vec::new()),
}
},
async {
match sql::table_properties(driver, schema, table) {
Some(q) => catalog_rows(pool, &q).await,
None => Ok::<Rows, IdeError>(Vec::new()),
}
},
);
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in index_rows? {
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
let mut it = r.into_iter();
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
else {
@@ -1463,7 +1401,11 @@ impl DbManager {
}),
}
}
let fk_rows = fk_rows?;
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
};
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
// SQLite keys that reference the primary key implicitly: look it up.
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
@@ -1476,7 +1418,15 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
let triggers = trigger_rows?
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
};
let triggers = trigger_rows
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
@@ -1489,21 +1439,26 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
let comment = comment_rows.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
);
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
match property_rows {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Ok(details)
}
@@ -1714,16 +1669,16 @@ impl DbManager {
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
}
DbDriver::Postgres => {
// Everything the script needs depends on the relation oid, so read that first and
// then the rest at once — five queries in flight against a pool of four, so one
// waits, but that is still two round trips instead of six.
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
rel.as_deref()
else {
return Err(missing());
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
_ => return Err(missing()),
};
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
if kind == "v" || kind == "m" {
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
let what = if kind == "m" { "materialized view" } else { "view" };
@@ -1731,70 +1686,43 @@ impl DbManager {
let target = sql::qualified(driver, schema, name);
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
}
let partition = match parent {
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
parent_schema: parent_schema.clone(),
parent_table: parent_table.clone(),
bound: bound.clone(),
}),
_ => None,
};
let is_partition = partition.is_some();
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
sql::postgres_ddl_columns(oid, is_partition),
sql::postgres_ddl_constraints(oid, is_partition),
sql::postgres_ddl_grants(oid),
sql::postgres_ddl_indexes(oid, is_partition),
sql::postgres_ddl_triggers(oid, is_partition),
);
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
catalog_rows(&pool, &cols_q),
pool.rows(&keys_q, MAX_META_ROWS),
pool.rows(&grants_q, MAX_META_ROWS),
pool.rows(&index_q, MAX_META_ROWS),
catalog_rows(&pool, &trigger_q),
);
let columns = col_rows?
let columns = pool
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let data_type = it.next().flatten()?;
let not_null = flag(&it.next().flatten());
let expression = it.next().flatten();
let comment = it.next().flatten().filter(|c| !c.is_empty());
let identity = it.next().flatten();
let generated = it.next().flatten();
let value =
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
Some(sql::DdlColumn {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
let constraints = key_rows?
let constraints = pool
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?))
})
.collect::<Vec<_>>();
let indexes =
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let grants = grant_rows?
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect::<Vec<_>>();
let triggers =
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let options = sql::DdlTableOptions {
unlogged: persistence.as_deref() == Some("u"),
partition_key: partition_key.clone(),
partition,
};
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
}
}
}
+24 -224
Переглянути файл
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
pg_get_partkeydef(c.oid), c.relpersistence \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
@@ -697,70 +697,40 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
/// On a partition, the not-null flag and expression describe overrides of the parent column.
///
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
/// that view reports `character varying` without the length, `numeric` without the precision,
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
/// recreate the table. It also lists only the columns the current role holds privileges on.
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
let pretty = "(a.attgenerated::text = 's') IS TRUE";
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
let (not_null, expression, identity, parent_join) = if partition {
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
(
"a.attnotnull AND NOT pa.attnotnull",
format!(
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
),
"NULL",
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
)
} else {
("a.attnotnull", expression, "a.attidentity::text", "")
};
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN {not_null} THEN 1 ELSE 0 END, \
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
}
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
pub fn postgres_ddl_constraints(oid: u32) -> String {
format!(
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
)
}
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
let local =
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
pub fn postgres_ddl_indexes(oid: u32) -> String {
format!(
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
ORDER BY 1"
)
}
@@ -779,10 +749,9 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
let local = if partition { " AND tgparentid = 0" } else { "" };
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
@@ -871,12 +840,6 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relispartition", "false")
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
// These flags entered the catalog in different releases. Keep whichever ones exist.
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -1036,42 +999,10 @@ pub struct DdlColumn {
pub name: String,
pub data_type: String,
pub not_null: bool,
pub value: Option<DdlColumnValue>,
pub default: Option<String>,
pub comment: Option<String>,
}
pub enum DdlColumnValue {
Default(String),
IdentityByDefault,
IdentityAlways,
GeneratedStored(String),
}
impl DdlColumnValue {
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
match (identity, generated) {
(Some("d"), _) => Some(Self::IdentityByDefault),
(Some("a"), _) => Some(Self::IdentityAlways),
(_, Some("s")) => expression.map(Self::GeneratedStored),
(_, None | Some("")) => expression.map(Self::Default),
_ => None,
}
}
}
#[derive(Default)]
pub struct DdlTableOptions {
pub unlogged: bool,
pub partition_key: Option<String>,
pub partition: Option<DdlPartition>,
}
pub struct DdlPartition {
pub parent_schema: String,
pub parent_table: String,
pub bound: String,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
@@ -1090,30 +1021,17 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
options: &DdlTableOptions,
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let partition = options.partition.as_ref();
let mut items: Vec<String> = columns
.iter()
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
.map(|c| {
let mut s = format!(" {}", quote_ident(d, &c.name));
if partition.is_none() {
s.push(' ');
s.push_str(&c.data_type);
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
if let Some(v) = &c.default {
s.push_str(&format!(" default {v}"));
}
match &c.value {
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
None => {}
}
if c.not_null
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
{
if c.not_null {
s.push_str(" not null");
}
s
@@ -1121,35 +1039,7 @@ pub fn postgres_table_ddl(
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let target = qualified(d, schema, table);
let persistence = if options.unlogged { "unlogged " } else { "" };
let mut out = format!("create {persistence}table {target}");
if let Some(partition) = partition {
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
out.push_str(&format!(" partition of {parent}"));
}
if partition.is_none() || !items.is_empty() {
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
}
if let Some(partition) = partition {
out.push_str("\n ");
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
// including doubled quotes, while matching the casing of the generated DDL.
for (i, part) in partition.bound.split('\'').enumerate() {
if i != 0 {
out.push('\'');
}
if i % 2 == 0 {
out.push_str(&part.to_ascii_lowercase());
} else {
out.push_str(part);
}
}
}
if let Some(key) = &options.partition_key {
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
}
out.push_str(";\n");
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
@@ -1526,31 +1416,15 @@ mod tests {
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
}
#[test]
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
// role holds privileges on. The DDL must therefore read `pg_attribute` with
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
// `text[]` and an enum name come out as written.
let q = postgres_ddl_columns(42, false);
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
assert!(q.contains("FROM pg_attribute a"), "{q}");
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
assert!(q.contains("attrelid = 42"), "{q}");
assert!(!q.contains("information_schema"), "{q}");
}
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
default: Some("'x'::character varying".into()),
comment: None,
},
];
@@ -1561,94 +1435,21 @@ mod tests {
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlTableOptions::default(),
&DdlExtras::default(),
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_renders_identity_and_stored_columns() {
let columns = [
("id_default", "bigint", true, "d", "", Some("ignored()")),
("id_always", "bigint", true, "a", "", None),
("total", "integer", true, "", "s", Some("qty * price")),
]
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
name: name.into(),
data_type: data_type.into(),
not_null,
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
comment: None,
});
let ddl =
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
assert_eq!(
ddl,
concat!(
"create table \"public\".\"t\"\n(\n",
" \"id_default\" bigint generated by default as identity,\n",
" \"id_always\" bigint generated always as identity,\n",
" \"total\" integer generated always as (qty * price) stored not null\n",
");\n",
)
);
}
#[test]
fn postgres_ddl_renders_unlogged_partitioned_parent() {
let columns =
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
let options =
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
assert_eq!(
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
);
}
#[test]
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
let columns = [DdlColumn {
name: "region".into(),
data_type: "text".into(),
not_null: false,
value: None,
comment: None,
}];
for (bound, rendered) in [
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
("DEFAULT", "default"),
] {
let options = DdlTableOptions {
partition: Some(DdlPartition {
parent_schema: "other".into(),
parent_table: "Parent\"Table".into(),
bound: bound.into(),
}),
..Default::default()
};
assert_eq!(
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
format!(
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\n"
)
);
}
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
value: None,
default: None,
comment: Some("what's this".into()),
},
];
@@ -1667,7 +1468,6 @@ mod tests {
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&DdlTableOptions::default(),
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
+2 -27
Переглянути файл
@@ -391,12 +391,9 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -525,17 +522,6 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -857,17 +843,6 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
-1
Переглянути файл
@@ -28,7 +28,6 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-svn.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
-18
Переглянути файл
@@ -111,24 +111,6 @@ impl AgentSecrets {
}
}
impl ide_agent::EnvSecrets for AgentSecrets {
fn get(&self, key: &str) -> Option<String> {
AgentSecrets::get(self, key)
}
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
AgentSecrets::set(self, key, value).map(|_| ())
}
fn delete(&self, key: &str) {
AgentSecrets::delete(self, key);
}
fn keys(&self, prefix: &str) -> Vec<String> {
AgentSecrets::keys(self, prefix)
}
}
#[cfg(test)]
mod tests {
use super::*;
-775
Переглянути файл
@@ -1,775 +0,0 @@
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
//! (or `<desktop-exe> --scheduler`).
//!
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
//! and at least one scheduled automation is active, registers the user login service; when
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
//! stops and unregisters the service.
use ide_core::{IdeError, IdeResult, IpcPath};
use parking_lot::{Mutex, RwLock};
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServicePlatform {
Macos,
Linux,
Windows,
Other,
}
impl ServicePlatform {
pub fn host() -> Self {
if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Other
}
}
}
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
#[derive(Default)]
pub struct BootServiceManager {
sync_lock: Mutex<()>,
override_dir: RwLock<Option<PathBuf>>,
executable_override: RwLock<Option<PathBuf>>,
platform_override: RwLock<Option<ServicePlatform>>,
command_runner: RwLock<Option<CommandRunner>>,
last_error: Mutex<Option<String>>,
}
#[derive(Clone, Debug)]
pub struct BootServiceState {
pub kind: String,
pub registered: bool,
pub path: Option<IpcPath>,
pub error: Option<String>,
pub linux_linger_enabled: Option<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OsServicePresence {
RegisteredAndActive,
RegisteredIdle,
ActiveUnregistered,
Absent,
}
impl OsServicePresence {
fn is_registered(self) -> bool {
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
}
fn is_loaded_or_active(self) -> bool {
!matches!(self, Self::Absent)
}
}
impl BootServiceManager {
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
Self {
sync_lock: Mutex::new(()),
override_dir: RwLock::new(dir),
executable_override: RwLock::new(None),
platform_override: RwLock::new(None),
command_runner: RwLock::new(None),
last_error: Mutex::new(None),
}
}
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
*self.override_dir.write() = dir;
}
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
*self.executable_override.write() = exe;
}
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
*self.platform_override.write() = runner.as_ref().map(|_| platform);
*self.command_runner.write() = runner;
}
fn effective_platform(&self) -> ServicePlatform {
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
}
fn effective_override_dir(&self) -> Option<PathBuf> {
self.override_dir
.read()
.clone()
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
}
fn uses_os_commands(&self) -> bool {
if self.command_runner.read().is_some() {
return true;
}
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
}
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
if let Some(runner) = self.command_runner.read().clone() {
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
}
let out = std::process::Command::new(program)
.args(args)
.output()
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
Ok((code, stdout, stderr))
}
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
let (code, stdout, stderr) = self.run_command(program, args)?;
if code == 0 {
return Ok(stdout);
}
let detail = stderr.trim();
let msg = if detail.is_empty() { stdout.trim() } else { detail };
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
}
fn scheduler_executable(&self) -> Option<PathBuf> {
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
}
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
if remote && platform == ServicePlatform::Linux {
"systemdUser"
} else {
match platform {
ServicePlatform::Macos => "launchAgent",
ServicePlatform::Linux => "systemdUser",
ServicePlatform::Windows => "windowsStartup",
ServicePlatform::Other => "backgroundHost",
}
}
}
pub fn service_kind(remote: bool) -> &'static str {
Self::service_kind_for(ServicePlatform::host(), remote)
}
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
let platform = self.effective_platform();
if let Some(dir) = self.effective_override_dir() {
let filename = match platform {
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
};
return Some(dir.join(filename));
}
let home = home_dir?;
match platform {
ServicePlatform::Macos => {
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
}
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
ServicePlatform::Windows => {
let appdata = std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
Some(
appdata
.join("Microsoft")
.join("Windows")
.join("Start Menu")
.join("Programs")
.join("Startup")
.join(WINDOWS_SCRIPT_NAME),
)
}
ServicePlatform::Other => None,
}
}
fn macos_domain() -> String {
#[cfg(target_os = "macos")]
{
format!("gui/{}", rustix::process::getuid().as_raw())
}
#[cfg(not(target_os = "macos"))]
{
"gui/501".to_owned()
}
}
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
/// file when status cannot be determined.
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
if !self.uses_os_commands() {
return Ok(OsServicePresence::Absent);
}
match platform {
ServicePlatform::Macos => {
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
if code == 0 {
return Ok(OsServicePresence::RegisteredAndActive);
}
let combined = format!("{stdout}\n{stderr}");
if code == 113 || combined.contains("Could not find service") {
return Ok(OsServicePresence::Absent);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
}
ServicePlatform::Linux => {
let (en_code, en_out, en_err) =
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
let en_state = en_out.trim();
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
true
} else if matches!(
en_state,
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
) {
false
} else {
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
)));
};
let (ac_code, ac_out, ac_err) =
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
let ac_state = ac_out.trim();
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
true
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
false
} else {
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
)));
};
Ok(match (enabled, active) {
(true, true) => OsServicePresence::RegisteredAndActive,
(true, false) => OsServicePresence::RegisteredIdle,
(false, true) => OsServicePresence::ActiveUnregistered,
(false, false) => OsServicePresence::Absent,
})
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
}
}
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
if !path.is_file() {
return false;
}
if !self.uses_os_commands() {
return true;
}
match platform {
ServicePlatform::Macos | ServicePlatform::Linux => {
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
}
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
ServicePlatform::Other => false,
}
}
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
let platform = self.effective_platform();
let path = self.service_file_path(home_dir);
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
BootServiceState {
kind: Self::service_kind_for(platform, remote).to_owned(),
registered,
path: path.map(IpcPath),
error: self.last_error.lock().clone(),
linux_linger_enabled,
}
}
/// Synchronizes the OS user service file and service manager state to match
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
let _guard = self.sync_lock.lock();
let result = self.sync_locked(home_dir, base_dir, should_register);
match &result {
Ok(_) => *self.last_error.lock() = None,
Err(err) => *self.last_error.lock() = Some(err.to_string()),
}
result
}
fn sync_locked(
&self,
home_dir: Option<&Path>,
base_dir: &Path,
should_register: bool,
) -> IdeResult<BootServiceState> {
let platform = self.effective_platform();
let Some(target) = self.service_file_path(home_dir) else {
return Ok(self.status(home_dir, false));
};
let use_os = self.uses_os_commands();
if should_register {
let exe = self
.scheduler_executable()
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
let content = render_service_file_for(platform, &exe, base_dir)?;
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
if file_changed {
ide_vfs::write_atomic(&target, content.as_bytes())?;
}
if use_os {
let already_registered = self.is_os_registered(platform, &target);
if file_changed || !already_registered {
self.activate_os_service(platform, &target)?;
}
}
} else {
if use_os {
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
let presence = self.query_os_presence(platform)?;
if presence.is_loaded_or_active() || target.exists() {
self.deactivate_os_service(platform, presence)?;
}
}
if target.exists() {
match std::fs::remove_file(&target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
}
Ok(BootServiceState {
kind: Self::service_kind_for(platform, false).to_owned(),
registered: self.is_os_registered(platform, &target),
path: Some(IpcPath(target)),
error: None,
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
})
}
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
let path_str = path
.to_str()
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
let _ = self.run_command("launchctl", &["bootout", &job]);
}
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
Ok(())
}
ServicePlatform::Linux => {
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if presence.is_loaded_or_active() {
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
let after = self.query_os_presence(platform)?;
if code != 0 && after.is_loaded_or_active() {
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
return Err(IdeError::internal(format!(
"launchctl bootout {job} exited with {code}: {detail}"
)));
}
}
Ok(())
}
ServicePlatform::Linux => {
match presence {
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::ActiveUnregistered => {
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::Absent => {}
}
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
}
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
render_service_file_for(ServicePlatform::host(), exe, base_dir)
}
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
match platform {
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
}
}
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
if s.is_empty() {
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
}
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
if !has_root {
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
}
if s.chars().any(char::is_control) {
return Err(IdeError::invalid(format!(
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
)));
}
Ok(s)
}
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
let log_path = base_dir.join("logs").join("scheduler.log");
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
let exe_esc = xml_escape(exe_str);
let home_esc = xml_escape(home_str);
let log_esc = xml_escape(log_str);
Ok(format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{SERVICE_LABEL}</string>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>ai.l0ng.openidea</string>
</array>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>ProgramArguments</key>
<array>
<string>{exe_esc}</string>
<string>--scheduler</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>OPENIDEA_SERVER_HOME</key>
<string>{home_esc}</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>{log_esc}</string>
</dict>
</plist>
"#
))
}
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
let exe_str = systemd_escape_literal_quoted(exe_raw);
let home_str = systemd_escape_literal_quoted(home_raw);
Ok(format!(
"[Unit]\n\
Description=OpenIDEA Headless Agent Automation Scheduler\n\
After=network-online.target\n\
\n\
[Service]\n\
Type=simple\n\
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
ExecStart=\"{exe_str}\" --scheduler\n\
Restart=on-failure\n\
RestartSec=10\n\
\n\
[Install]\n\
WantedBy=default.target\n"
))
}
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
if exe_raw.contains('"') || home_raw.contains('"') {
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
}
let home_esc = cmd_escape(home_raw);
let exe_esc = cmd_escape(exe_raw);
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
}
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
fn systemd_escape_literal_quoted(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
}
fn cmd_escape(s: &str) -> String {
s.replace('%', "%%")
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn check_linux_linger() -> bool {
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
&& !user.is_empty()
&& Path::new("/var/lib/systemd/linger").join(user).exists()
{
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
let after_specifiers = s.replace("%%", "%");
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
let mut out = String::new();
let mut chars = after_dollars.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
} else {
out.push(c);
}
}
out
}
#[test]
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
let plist = render_macos_plist(exe, home).unwrap();
assert!(plist.contains("dev&amp;co"));
let unit = render_systemd_unit(exe, home).unwrap();
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
assert!(env_line.contains("100%%data$dir"));
assert!(!env_line.contains("data$$dir"));
let env_inner =
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
assert!(exec_line.contains("openidea$bin"));
assert!(!exec_line.contains("openidea$$bin"));
assert!(exec_line.contains("open%%idea"));
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
assert!(render_windows_cmd(exe, home).is_err());
let win_ok = render_windows_cmd(
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
Path::new(r"C:\Users\dev&co\100%data$dir"),
)
.unwrap();
assert!(win_ok.contains("100%%data$dir"));
assert!(win_ok.contains("open%%idea$1.exe"));
// Line breaks, NULs, and relative paths are rejected across all platforms.
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
}
#[cfg(unix)]
#[test]
fn systemd_unit_rejects_non_utf8_paths() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
}
#[test]
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
let tmp = tempfile::tempdir().unwrap();
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
let enabled = Arc::new(AtomicBool::new(false));
let active = Arc::new(AtomicBool::new(false));
let fail_next_enable = Arc::new(AtomicBool::new(true));
let fail_next_disable = Arc::new(AtomicBool::new(true));
let disable_now_calls = Arc::new(AtomicUsize::new(0));
let enabled_c = enabled.clone();
let active_c = active.clone();
let fail_en_c = fail_next_enable.clone();
let fail_dis_c = fail_next_disable.clone();
let dis_calls_c = disable_now_calls.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Linux,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "systemctl");
match args {
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
if enabled_c.load(Ordering::Acquire) {
Ok((0, "enabled\n".into(), String::new()))
} else {
Ok((1, "disabled\n".into(), String::new()))
}
}
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
if active_c.load(Ordering::Acquire) {
Ok((0, "active\n".into(), String::new()))
} else {
Ok((3, "inactive\n".into(), String::new()))
}
}
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
if fail_en_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "dbus unavailable".into()))
} else {
enabled_c.store(true, Ordering::Release);
active_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
dis_calls_c.fetch_add(1, Ordering::AcqRel);
if fail_dis_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "unit busy".into()))
} else {
enabled_c.store(false, Ordering::Release);
active_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
other => panic!("unexpected systemctl args: {other:?}"),
}
})),
);
let home = tmp.path();
let data = tmp.path().join("data");
std::fs::create_dir_all(&data).unwrap();
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
// even though the unit file already exists on disk!
assert!(mgr.sync(Some(home), &data, true).is_err());
let st_failed = mgr.status(Some(home), true);
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
assert!(st_ok.registered);
assert!(st_ok.error.is_none());
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
assert!(mgr.status(Some(home), true).registered);
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
let st_off = mgr.sync(Some(home), &data, false).unwrap();
assert!(!st_off.registered);
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
let status_unknown = Arc::new(AtomicBool::new(false));
let status_unknown_c = status_unknown.clone();
let macos_loaded = Arc::new(AtomicBool::new(false));
let macos_loaded_c = macos_loaded.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Macos,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "launchctl");
match args {
["print", _] => {
if status_unknown_c.load(Ordering::Acquire) {
Ok((1, String::new(), "IPC transport error".into()))
} else if macos_loaded_c.load(Ordering::Acquire) {
Ok((0, "state = running\n".into(), String::new()))
} else {
Ok((113, String::new(), "Could not find service\n".into()))
}
}
["bootstrap", _, _] => {
macos_loaded_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
["bootout", _] => {
macos_loaded_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
other => panic!("unexpected launchctl args: {other:?}"),
}
})),
);
mgr.sync(Some(home), &data, true).unwrap();
let plist_path = mgr.service_file_path(Some(home)).unwrap();
assert!(plist_path.is_file());
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
status_unknown.store(true, Ordering::Release);
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
assert!(macos_loaded.load(Ordering::Acquire));
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
status_unknown.store(false, Ordering::Release);
mgr.sync(Some(home), &data, false).unwrap();
assert!(!macos_loaded.load(Ordering::Acquire));
assert!(!plist_path.exists());
}
}
File diff suppressed because it is too large. Load diff
-577
Переглянути файл
@@ -1,577 +0,0 @@
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::broadcast;
const OWNERS_DIR: &str = "owners";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerEndpoint {
pub instance_id: String,
pub pid: u32,
pub addr: String,
pub token: String,
}
#[derive(Clone, Debug)]
pub struct RoutedAgentEvent {
pub project_root: Option<PathBuf>,
pub event: AgentEvent,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerRequest {
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
Entries { token: String, task: String, subagent: Option<String> },
Respond { token: String, task: String, permission: u32, option: Option<String> },
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
Cancel { token: String, task: String, subagent: Option<String> },
StopBackground { token: String, task: String, background: String },
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
StopIdleWorker { token: String },
}
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerStreamItem {
Snapshot { tasks: Vec<AgentTask> },
Event { event: Box<AgentEvent> },
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
enum PeerReply<T> {
Ok { value: T },
Err { error: String },
}
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
automations_dir.join(OWNERS_DIR)
}
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
/// lock/endpoint files are cleaned up.
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
if owner_id.is_empty() {
return false;
}
if owner_id == self_instance_id {
return true;
}
let dir = owners_dir(automations_dir);
let lock_path = dir.join(format!("{owner_id}.lock"));
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
return false;
};
if file.try_lock().is_ok() {
let _ = file.unlock();
drop(file);
let _ = std::fs::remove_file(&lock_path);
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
false
} else {
true
}
}
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
return None;
}
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
let dir = owners_dir(automations_dir);
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if stem == self_instance_id {
continue;
}
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
out.push(ep);
}
}
out
}
pub struct OwnerNode {
pub instance_id: String,
lock_file: Mutex<Option<std::fs::File>>,
endpoint_path: Mutex<Option<PathBuf>>,
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
worker_stop_requested: std::sync::atomic::AtomicBool,
subscriptions: Mutex<HashMap<String, CancellationToken>>,
}
impl OwnerNode {
pub fn new(instance_id: String) -> Self {
let (events_tx, _) = broadcast::channel(512);
Self {
instance_id,
lock_file: Mutex::new(None),
endpoint_path: Mutex::new(None),
events_tx,
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
subscriptions: Mutex::new(HashMap::new()),
}
}
pub fn worker_stop_requested(&self) -> bool {
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
}
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
let mut guard = self.lock_file.lock();
if guard.is_some() {
return Ok(());
}
let dir = owners_dir(automations_dir);
std::fs::create_dir_all(&dir)?;
let lock_path = dir.join(format!("{}.lock", self.instance_id));
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
file.try_lock()
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
*guard = Some(file);
Ok(())
}
/// Starts the authenticated loopback RPC server for live run events and approvals.
pub fn start_server(
&self,
automations_dir: &Path,
runtime: &tokio::runtime::Handle,
shutdown: CancellationToken,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
node_ref: Arc<OwnerNode>,
) {
if self.ensure_lock(automations_dir).is_err() {
return;
}
if self.endpoint_path.lock().is_some() {
return;
}
let dir = owners_dir(automations_dir);
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
return;
};
if std_listener.set_nonblocking(true).is_err() {
return;
}
let Ok(local_addr) = std_listener.local_addr() else {
return;
};
let instance_id = self.instance_id.clone();
let json_path = dir.join(format!("{instance_id}.json"));
let ep = OwnerEndpoint {
instance_id: instance_id.clone(),
pid: std::process::id(),
addr: local_addr.to_string(),
token: token.clone(),
};
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
let _ = write_private_file(&json_path, &bytes);
}
*self.endpoint_path.lock() = Some(json_path.clone());
runtime.spawn(async move {
let Ok(listener) = TcpListener::from_std(std_listener) else {
let _ = std::fs::remove_file(&json_path);
return;
};
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
accepted = listener.accept() => {
let Ok((stream, _)) = accepted else { continue };
let token_c = token.clone();
let resolve_c = resolve_mgr.clone();
let list_c = list_live_tasks.clone();
let shutdown_c = shutdown.clone();
let node_c = node_ref.clone();
tokio::spawn(async move {
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
});
}
}
}
let _ = std::fs::remove_file(&json_path);
});
}
pub fn stop(&self, automations_dir: &Path) {
for (_, cancel) in self.subscriptions.lock().drain() {
cancel.cancel();
}
if let Some(ep_path) = self.endpoint_path.lock().take() {
let _ = std::fs::remove_file(ep_path);
}
if let Some(file) = self.lock_file.lock().take() {
let _ = file.unlock();
}
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
}
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
let token = CancellationToken::new();
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
prev.cancel();
}
token
}
pub fn unsubscribe(&self, subscriber: &str) {
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
prev.cancel();
}
}
}
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
f.write_all(bytes)?;
f.sync_all()
}
#[cfg(not(unix))]
{
std::fs::write(path, bytes)
}
}
async fn handle_peer_conn(
stream: TcpStream,
expected_token: String,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
shutdown: CancellationToken,
node: Arc<OwnerNode>,
) {
let (reader, mut writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
let Ok(Some(first_line)) = lines.next_line().await else {
return;
};
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
return;
};
let req_token = match &req {
PeerRequest::Subscribe { token, .. }
| PeerRequest::Entries { token, .. }
| PeerRequest::Respond { token, .. }
| PeerRequest::AnswerQuestion { token, .. }
| PeerRequest::Cancel { token, .. }
| PeerRequest::StopBackground { token, .. }
| PeerRequest::Prompt { token, .. }
| PeerRequest::StopIdleWorker { token } => token,
};
if req_token != &expected_token {
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
return;
}
match req {
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
let mut rx = node.events_tx.subscribe();
let canon_allowed: Vec<PathBuf> =
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
let initial = list_live_tasks(&canon_allowed, include_chat_only);
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
return;
}
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
recv = rx.recv() => {
match recv {
Ok(routed) => {
let matches = match &routed.project_root {
None => include_chat_only,
Some(actual) => {
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
canon_allowed.iter().any(|w| w == &cand)
}
};
if matches
&& write_json_line(
&mut writer,
&PeerStreamItem::Event { event: Box::new(routed.event) },
)
.await
.is_err()
{
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
}
PeerRequest::Entries { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
.await
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|r| r),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Respond { task, permission, option, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.respond(&task, permission, option),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Cancel { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.cancel(&task, subagent),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopBackground { task, background, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.stop_background(&task, &background).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Prompt { task, prompt, now, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.prompt(&task, prompt, now).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopIdleWorker { .. } => {
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
}
}
}
impl<T> PeerReply<T> {
fn from_res(res: IdeResult<T>) -> Self {
match res {
Ok(value) => Self::Ok { value },
Err(e) => Self::Err { error: e.to_string() },
}
}
fn err(msg: &str) -> Self {
Self::Err { error: msg.to_owned() }
}
}
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
line.push(b'\n');
writer.write_all(&line).await?;
writer.flush().await
}
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
let mut stream = TcpStream::connect(&ep.addr)
.await
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
write_json_line(&mut stream, req)
.await
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut lines = BufReader::new(stream).lines();
let raw = lines
.next_line()
.await
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
use std::io::{BufRead, Write};
let addr: std::net::SocketAddr = ep
.addr
.parse()
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
stream
.write_all(&line)
.and_then(|()| stream.flush())
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut reader = std::io::BufReader::new(stream);
let mut raw = String::new();
reader
.read_line(&mut raw)
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
if raw.trim().is_empty() {
return Err(IdeError::unavailable("automation worker closed connection without replying"));
}
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
}
pub fn peer_respond(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
}
pub async fn peer_answer_question(
ep: &OwnerEndpoint,
task: String,
question: String,
answer: Option<String>,
) -> IdeResult<()> {
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
}
pub fn peer_cancel(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
subagent: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
}
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
}
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
}
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
for ep in endpoints {
runtime.spawn(async move {
let token = ep.token.clone();
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
});
}
}
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
pub fn attach_peer_stream(
runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
allowed_roots: Vec<PathBuf>,
include_chat_only: bool,
cancel: CancellationToken,
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
) -> Vec<AgentTask> {
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
runtime.spawn(async move {
let connect_fut = TcpStream::connect(&ep.addr);
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
let _ = snap_tx.send(Vec::new());
return;
};
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
if write_json_line(&mut stream, &req).await.is_err() {
let _ = snap_tx.send(Vec::new());
return;
}
let mut lines = BufReader::new(stream).lines();
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
Ok(PeerStreamItem::Snapshot { tasks }) => {
let _ = snap_tx.send(tasks);
}
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
},
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
}
loop {
tokio::select! {
_ = cancel.cancelled() => break,
next = lines.next_line() => {
match next {
Ok(Some(line)) => {
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
on_event(*event);
}
}
_ => break,
}
}
}
}
});
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
}
+17 -86
Переглянути файл
@@ -18,7 +18,6 @@ use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
Scheduler,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
@@ -30,7 +29,6 @@ usage:
openidea-server --web [options] [<project>]
openidea-server --stdio
openidea-server --attach <project-path>
openidea-server --scheduler
openidea-server --mcp-stdio [--project <path>]
openidea-server --connect <host> <port>
openidea-server --version
@@ -235,7 +233,6 @@ fn main() {
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
print_usage();
@@ -295,21 +292,17 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
@@ -319,85 +312,23 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
shutdown_all(&host, plugins.as_ref()).await;
0
}
Mode::Scheduler => {
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
inherit_trust(&host);
host.automations.set_headless_worker_mode(true);
host.automations.start(&host);
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
let mut idle_ticks = 0u32;
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
#[cfg(unix)]
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
loop {
#[cfg(unix)]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = terminate.recv() => break,
_ = check.tick() => {}
}
#[cfg(not(unix))]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = check.tick() => {}
}
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
.effective()
.agents
.automations
.auto_start_service;
let running = host.automations.has_running_runs();
if host.automations.worker_stop_requested() || !service_enabled {
if !running {
tracing::info!("headless scheduler login service disabled; exiting");
break;
}
} else if host.automations.has_enabled_schedules() || running {
idle_ticks = 0;
} else {
idle_ticks += 1;
if idle_ticks >= 3 {
tracing::info!("no enabled automations remain; headless scheduler exiting");
break;
}
}
}
shutdown_all(&host, None).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
-2
Переглянути файл
@@ -398,7 +398,6 @@ pub async fn serve(
};
let shutdown = CancellationToken::new();
host.automations.start(&host);
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
@@ -542,7 +541,6 @@ fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host.automations.keeps_remote_daemon_alive(host)
|| host
.projects()
.iter()
-76
Переглянути файл
@@ -14,65 +14,6 @@ pub const DATA_ENV: &str = "OPENIDEA_DATA_DIR";
/// Moves the logs.
pub const LOG_ENV: &str = "OPENIDEA_LOG_DIR";
/// A portable install's settings file, next to the executable: `NAME=value` lines setting the
/// variables above (and only those), so the install needs no environment. A variable already set
/// in the environment wins; a relative value is taken from the file's folder.
pub const PROPERTIES_FILE: &str = "openidea.properties";
/// The folder `openidea.properties` is read from: the executable's, the AppImage file's when run
/// from one, the folder holding the `.app` bundle on macOS.
fn install_dir() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
// `APPIMAGE` is inherited by everything started from inside one; only trust it for the
// executable it mounted.
let appdir = std::env::var_os("APPDIR").filter(|v| !v.is_empty());
if let (Some(image), Some(appdir)) = (std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()), appdir)
&& exe.starts_with(appdir)
{
return PathBuf::from(image).parent().map(Path::to_path_buf);
}
let dir = exe.parent()?;
if cfg!(target_os = "macos")
&& let Some(bundle) = dir.ancestors().nth(2).filter(|b| b.extension().is_some_and(|e| e == "app"))
{
return bundle.parent().map(Path::to_path_buf);
}
Some(dir.to_path_buf())
}
/// The variables an `openidea.properties` in `dir` sets, made absolute, leaving out those
/// `is_set` reports the environment already has. Unknown keys and comments (`#`, `!`) are ignored.
fn properties_in(dir: &Path, text: &str, is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, PathBuf)> {
let mut out: Vec<(&'static str, PathBuf)> = Vec::new();
for line in text.lines().map(str::trim) {
if line.starts_with(['#', '!']) {
continue;
}
let Some((key, value)) = line.split_once('=') else { continue };
let (key, value) = (key.trim(), value.trim());
let Some(name) = [CONFIG_ENV, DATA_ENV, LOCAL_DATA_ENV, LOG_ENV].into_iter().find(|n| *n == key) else {
continue;
};
if value.is_empty() || is_set(name) || out.iter().any(|(n, _)| *n == name) {
continue;
}
// An absolute value replaces `dir`.
out.push((name, dir.join(value)));
}
out
}
/// Applies the install's `openidea.properties` to the environment, so the directories below and
/// every process the IDE starts see the same locations. Call first thing in `main`.
pub fn load_properties_file() {
let Some(dir) = install_dir() else { return };
let Ok(text) = fs::read_to_string(dir.join(PROPERTIES_FILE)) else { return };
for (name, value) in properties_in(&dir, &text, |n| std::env::var_os(n).is_some_and(|v| !v.is_empty())) {
// SAFETY: called at the start of `main`, before any other thread exists.
unsafe { std::env::set_var(name, value) };
}
}
/// `$OPENIDEA_CONFIG_DIR/<identifier>` when set, else the OS configuration directory
/// (Tauri's `app_config_dir`). Like the local data, the identifier keeps release and
/// per-worktree debug builds apart under one root; a relative path is an error.
@@ -723,23 +664,6 @@ mod tests {
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn a_properties_file_sets_the_directory_variables_relative_to_its_folder() {
let dir = std::env::temp_dir().join("portable");
let abs = std::env::temp_dir().join("elsewhere");
let text = format!(
"# portable install\n! also a comment\nOPENIDEA_CONFIG_DIR = data\nOPENIDEA_DATA_DIR=data\n\
OPENIDEA_LOCAL_DATA_DIR={}\nOPENIDEA_LOG_DIR=\nOPENIDEA_CONFIG_DIR=ignored\nPATH=/bin\nnot a pair\n",
abs.display()
);
let set = properties_in(&dir, &text, |_| false);
assert_eq!(set, [(CONFIG_ENV, dir.join("data")), (DATA_ENV, dir.join("data")), (LOCAL_DATA_ENV, abs.clone())]);
// The environment wins over the file.
let set = properties_in(&dir, &text, |n| n == CONFIG_ENV);
assert_eq!(set.iter().map(|(n, _)| *n).collect::<Vec<_>>(), [DATA_ENV, LOCAL_DATA_ENV]);
assert!(set.iter().all(|(_, v)| v.is_absolute()));
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+16 -57
Переглянути файл
@@ -448,39 +448,18 @@ pub async fn format(
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
// A notebook cell is a document of the language servers only: `documents` holds what the
// editor opened, so ⌥⌘L in a cell used to answer "document DocId#N is not open".
let source = match project.documents.snapshot(doc) {
Ok(snap) => FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
},
Err(e) => match project.lsp.cell_text(doc) {
Some(cell) => FormatSource {
path: cell_script_path(&cell.path).into(),
language: cell.language,
text: cell.text,
doc: Some(doc),
version: cell.version,
read_only: false,
},
None => return Err(e),
},
let snap = project.documents.snapshot(doc)?;
let source = FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
};
format_source(host, window, &project, source, range, options).await
}
/// The file name a formatter is given for a cell's text. It only picks the language and the
/// settings: the text arrives on stdin. The notebook's own `.ipynb` would make Ruff parse the
/// cell as notebook JSON instead of Python.
fn cell_script_path(notebook: &Path) -> PathBuf {
notebook.with_extension("py")
}
/// Format a separate snapshot using the file's language, settings and formatter.
pub async fn format_text(
host: &Host,
@@ -1406,14 +1385,6 @@ mod tests {
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
}
#[test]
fn a_cell_is_formatted_as_python_rather_than_as_notebook_json() {
// Ruff reads the extension of `--stdin-filename` to decide what the text is; `.ipynb`
// made it expect notebook JSON and fail on the cell's source.
assert_eq!(cell_script_path(Path::new("/p/notebooks/a.ipynb")), Path::new("/p/notebooks/a.py"));
assert_eq!(cell_script_path(Path::new("/p/a.b.ipynb")), Path::new("/p/a.b.py"));
}
#[test]
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
let dir = tempfile::tempdir().unwrap();
@@ -1601,21 +1572,15 @@ mod tests {
let text = "a\n b\nc\nd\n e\n";
let formatted = "a\nb\nc\nd\ne\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let started = std::time::Instant::now();
let edits = minimal_edits(text, whole);
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
}
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
assert_eq!(after(text, &edits), formatted);
// Merged or not, the edits stay between the first and the last changed line.
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
// Single-line edits are already minimal and pass through.
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
assert_eq!(minimal_edits(text, small.clone()), small);
@@ -1666,17 +1631,11 @@ mod tests {
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let started = std::time::Instant::now();
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
}
// Merged or not, the edits leave the unchanged first and last lines alone.
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
+1 -56
Переглянути файл
@@ -4,7 +4,6 @@
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
pub mod agent_secrets;
pub mod automations;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
@@ -28,13 +27,10 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
pub mod svn;
mod swiftlint;
pub mod trust;
mod ts_code_style;
mod tsc_watch;
pub mod web_server;
mod xcode_env;
pub use project::{Project, history_retention};
@@ -92,10 +88,6 @@ impl HostConfig {
pub struct Host {
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
pub(crate) subversion: Option<bool>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -108,18 +100,14 @@ pub struct Host {
pub mcp_agent_runs: mcp::AgentRuns,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
pub automations: Arc<automations::AutomationService>,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
pub data_dir: PathBuf,
/// Machine-local tools and rebuildable caches.
pub local_data_dir: PathBuf,
home_dir: Option<PathBuf>,
pub languages: Arc<LanguageRegistry>,
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
@@ -218,26 +206,6 @@ impl Host {
self
}
/// Adds a version control system besides Git: projects opened afterwards look for its
/// working copies (when trusted) and route the Changes view, status and log to them.
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
self.vcs_providers.push(provider);
self
}
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
pub fn with_subversion(mut self, prompts: bool) -> Self {
self.subversion = Some(prompts);
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -258,13 +226,9 @@ impl Host {
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
@@ -272,11 +236,9 @@ impl Host {
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
proxy_session_password: Mutex::default(),
@@ -306,7 +268,6 @@ impl Host {
config_dir,
data_dir,
local_data_dir,
home_dir: dirs::home_dir(),
sink_for,
owner,
runtime,
@@ -495,9 +456,6 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
@@ -512,20 +470,13 @@ impl Host {
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let shutdown_agents = if !project.light
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
{
Vec::new()
} else {
vec![project.agents.clone()]
};
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: shutdown_agents,
agents: vec![project.agents.clone()],
agent_reason,
terminals: Some(terminals),
processes: Some(processes),
@@ -588,8 +539,6 @@ impl Host {
if let Some(retired) = retired {
let _ = retired.join();
}
// The project's buffers, index and caches are dropped: hand their pages back.
ide_core::memory::release_free_pages_soon();
})
}
@@ -654,7 +603,6 @@ impl Host {
}
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
self.automations.stop();
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
@@ -748,9 +696,6 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
+8 -8
Переглянути файл
@@ -172,15 +172,15 @@ impl Policy {
})
}
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path, within)
fn resolve(&self, path: &Path) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
}
}
/// The root of the project that serves `path` in the background under the current
/// settings and trust decisions; with `within`, only a root strictly inside it. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
Policy::current(host)?.resolve(path, within)
/// settings and trust decisions. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
Policy::current(host)?.resolve(path)
}
/// How long a project may stay idle; `None` when `minutes` is 0 (never unloaded).
@@ -283,7 +283,7 @@ impl BackgroundProjects {
state.opening = Some(root.to_path_buf());
Opening(self)
};
if serving_root(host, root, None).as_deref() != Some(root) {
if serving_root(host, root).as_deref() != Some(root) {
return Err(IdeError::unavailable(format!("{} is not served in the background", root.display())));
}
let limit = project_limit(host.global_settings.effective().mcp_server.background_project_limit);
@@ -444,7 +444,7 @@ impl BackgroundProjects {
impl Host {
/// The window, and its project, that has `root` open as a project (not in LightEdit).
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
let projects = self.projects.read();
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
@@ -463,7 +463,7 @@ impl Host {
}
let policy = Policy::current(self);
for root in roots {
if policy.as_ref().and_then(|policy| policy.resolve(&root, None)).as_deref() != Some(&root) {
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
self.mcp_background.detach(self, &root, None);
}
}
+13 -59
Переглянути файл
@@ -10,9 +10,7 @@ use std::path::{Path, PathBuf};
/// folders containing it and, in `Trusted` mode, of the trusted projects, the trusted recent
/// projects and the nearest trusted folder with a project marker. `None` when the mode is
/// `Off`, when `path` is relative or missing, and when no folder qualifies. Listed and
/// recent folders that are gone or not absolute paths are skipped. With `within` (the root
/// of the open project containing `path`) only folders strictly inside it count, and the
/// others aren't looked up on disk.
/// recent folders that are gone or not absolute paths are skipped.
pub(crate) fn resolve(
mode: McpBackgroundProjects,
listed: &[PathBuf],
@@ -20,7 +18,6 @@ pub(crate) fn resolve(
recents: &[PathBuf],
home: Option<&Path>,
path: &Path,
within: Option<&Path>,
) -> Option<PathBuf> {
let by_trust = match mode {
McpBackgroundProjects::Off => return None,
@@ -31,37 +28,23 @@ pub(crate) fn resolve(
return None;
}
let path = dunce::canonicalize(path).ok()?;
let within = within.map(|root| (root, dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())));
let open = within.as_ref().map(|(_, root)| root.as_path());
// Only folders strictly inside `within` count. An entry is checked by its text before it
// is canonicalized, so folders elsewhere (a network mount among them) aren't touched; one
// that reaches inside through a link from elsewhere is left out.
let inside = |entry: &Path, canonical: bool| {
within.as_ref().is_none_or(|(raw, root)| {
(entry.starts_with(root) && entry != root) || (!canonical && entry.starts_with(raw) && entry != *raw)
})
};
// A relative entry would be read against the working directory, which says nothing
// about the user's folders (`/` for an app started from the Finder).
let existing = |entry: &PathBuf| {
(entry.is_absolute() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
};
let existing = |entry: &PathBuf| entry.is_absolute().then(|| dunce::canonicalize(entry).ok()).flatten();
// A listed folder serves its subtree whether or not it is trusted: it opens restricted then.
let mut candidates: Vec<PathBuf> = listed.iter().filter_map(existing).collect();
if by_trust {
let projects = decisions.projects.iter().filter(|p| inside(p, true));
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
candidates.extend(decisions.projects.iter().filter(|p| trusted_here(decisions, p)).cloned());
// Remote projects are recorded as locations (`ssh://…`), not as folders of this machine.
let local = recents.iter().filter(|p| !p.to_string_lossy().contains("://"));
candidates.extend(local.filter_map(existing).filter(|p| trusted_here(decisions, p)));
let home = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
// A trusted location and the home folder hold projects; neither is one.
candidates
.extend(marker_root(&path, open).filter(|a| {
.extend(marker_root(&path).filter(|a| {
trusted_here(decisions, a) && !decisions.locations.contains(a) && home.as_ref() != Some(a)
}));
}
candidates.retain(|candidate| inside(candidate, true));
innermost(&candidates, &path).cloned()
}
@@ -81,10 +64,9 @@ fn trusted_here(decisions: &TrustDecisions, root: &Path) -> bool {
/// The first ancestor of `path`, itself included, that looks like a project: it holds an
/// `.openidea` folder, or a `.git` or `.jj` entry (a linked worktree's `.git` is a file).
/// The search stops short of `within`.
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
fn marker_root(path: &Path) -> Option<PathBuf> {
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
path.ancestors().find(marked).map(Path::to_path_buf)
}
#[cfg(test)]
@@ -177,35 +159,7 @@ mod tests {
restricted: paths(restricted),
};
let home = base.join("home");
let found =
resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path), None);
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
#[test]
fn inside_an_open_project_only_a_folder_below_its_root_serves_a_path() {
let (_tmp, base) = tree();
let at = |folders: &[&str]| folders.iter().map(|folder| base.join(folder)).collect::<Vec<_>>();
let trusted = |projects: &[&str], locations: &[&str]| TrustDecisions {
projects: at(projects),
locations: at(locations),
..Default::default()
};
let within = base.join("code/app");
let (none, root, location) = (trusted(&[], &[]), trusted(&["code/app"], &[]), trusted(&[], &["code"]));
let (src, nested) = ("code/app/src", "code/app/.wt/feature");
let below = trusted(&[nested], &[]);
let nested_src = "code/app/.wt/feature/src";
for (what, mode, listed, decisions, path, expected) in [
("a listed folder below the root", Listed, &[src][..], &none, src, Some(src)),
("the listed root and a listed folder around it", Listed, &["code", "code/app"], &none, src, None),
("the trusted root", Trusted, &[], &root, src, None),
("the root's own marker", Trusted, &[], &location, src, None),
("a repository below the root", Trusted, &[], &location, nested_src, Some(nested)),
("a trusted project below the root", Trusted, &[], &below, nested_src, Some(nested)),
] {
let found = resolve(mode, &at(listed), decisions, &[], None, &base.join(path), Some(&within));
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
@@ -216,7 +170,7 @@ mod tests {
let listed = [base.join("code/app"), PathBuf::from("code/app"), PathBuf::from(".")];
let none = TrustDecisions::default();
for path in ["code/app/src", ".", "src"] {
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path), None), None, "{path}");
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
}
}
@@ -234,7 +188,7 @@ mod tests {
("the same folder listed by its full path", Listed, absolute, &none, &[][..], Some(&here)),
("the same folder recent by its full path", Trusted, &[][..], &around, absolute, Some(&here)),
] {
assert_eq!(resolve(mode, listed, decisions, recents, None, &here, None).as_ref(), expected, "{what}");
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
}
}
@@ -246,13 +200,13 @@ mod tests {
let none = TrustDecisions::default();
// Listed by the link, asked for by the real path, and the other way round (`/tmp` and `/private/tmp`).
for (listed, path) in [("link/app", "code/app/src"), ("code/app", "link/app/src"), ("link/app", "link/app")] {
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path), None);
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
assert_eq!(found, Some(base.join("code/app")), "{listed} for {path}");
}
let trusted = TrustDecisions { locations: vec![base.join("code")], ..Default::default() };
let recent = [base.join("link/plain")];
assert_eq!(
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src"), None),
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
Some(base.join("code/plain"))
);
}
@@ -265,10 +219,10 @@ mod tests {
std::fs::create_dir_all(base.join("ssh:/box/app/src")).unwrap();
let recent = [PathBuf::from(format!("{}/ssh://box/app", base.display()))];
let trusted = TrustDecisions { locations: vec![base.clone()], ..Default::default() };
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src"), None), None);
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
let local = [base.join("ssh:/box/app")];
assert_eq!(
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
Some(base.join("ssh:/box/app"))
);
}
+3 -3
Переглянути файл
@@ -708,7 +708,7 @@ async fn a_host_that_serves_none_refuses_every_folder_whatever_the_settings_say(
let root = f.root("inventory");
f.host.mcp_background.serve_none();
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts"), None), None);
assert_eq!(registry.resolve(&root.join("parts")), None);
assert_eq!(f.refused("inventory"), format!("{} is not served in the background", root.display()));
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
@@ -726,11 +726,11 @@ async fn a_call_that_arrives_after_the_server_was_turned_off_opens_nothing() {
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts"), None), None, "no folder is served with the server off");
assert_eq!(registry.resolve(&root.join("parts")), None, "no folder is served with the server off");
assert!(registry.tools(&root).is_err());
f.set("enabled", json!(true));
assert_eq!(registry.resolve(&root.join("parts"), None), Some(root));
assert_eq!(registry.resolve(&root.join("parts")), Some(root));
f.open("inventory");
assert_eq!(f.loaded(), ["inventory"]);
}
File diff suppressed because it is too large. Load diff
-1
Переглянути файл
@@ -429,7 +429,6 @@ Requires a filePath parameter containing the path to the file to open.
The file path can be absolute or relative to the project root.
Optionally puts the caret at a 1-based line and column.",
|call| async move {
call.needs_window()?;
let raw = call.str("filePath")?;
// Opening shows the file to the user: outside the project the user agrees first.
let path = call.resolve_readable(&raw).await?;
+17 -5
Переглянути файл
@@ -1,7 +1,7 @@
use super::page::{OFFSET, Page};
use super::search::{PathScope, paths_param};
use super::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{Diagnostic, IdeResult, Severity};
use ide_core::{Diagnostic, IdeError, IdeResult, Severity};
use serde_json::{Map, Value, json};
/// Problems `get_project_problems` lists by default.
@@ -51,16 +51,28 @@ Lines and UTF-16 columns are 1-based.",
]
}
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
/// Editors and the Problems view are reported by a window: a project served in the
/// background has none, and says so instead of answering as if nothing were open.
fn reported_by_a_window(call: &Call) -> IdeResult<()> {
if !super::BackgroundProjects::is_key(call.window()) {
return Ok(());
}
let (tool, root) = (&call.tool, call.root().display());
Err(IdeError::unavailable(format!(
"{tool} needs the project open in a window: {root} is served in the background."
)))
}
/// [`reported_by_a_window`] for the Problems view, which `check_files` stands in for.
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
call.needs_window().map_err(|mut error| {
reported_by_a_window(call).map_err(|mut error| {
error.message.push_str(" Use check_files for diagnostics.");
error
})
}
async fn open_editors(call: Call) -> IdeResult<Output> {
call.needs_window()?;
reported_by_a_window(&call)?;
let paths = PathScope::of(&call)?;
let windows = call.host.mcp_windows(call.root());
let open = call.host.mcp_reports.editors(&windows);
@@ -72,7 +84,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
}
async fn current_file(call: Call) -> IdeResult<Output> {
call.needs_window()?;
reported_by_a_window(&call)?;
let editor = call.host.mcp_reports.focused(call.window());
Output::json(match editor {
None => json!({}),
Loaded 100 of 1352 files, more files were not shown because too many files have changed in this diff. Show more