дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
211
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
251f3953fa | ||
|
|
aa124276b2 | ||
|
|
fb91ace8aa | ||
|
|
c931cbecc0 | ||
|
|
cfaf05c84b | ||
|
|
59f3994b6c | ||
|
|
908b753daf | ||
|
|
3790f578be | ||
|
|
68ffce6340 | ||
|
|
3f74972f11 | ||
|
|
eefe6cc9c8 | ||
|
|
e9480d690c | ||
|
|
13b8024588 | ||
|
|
452d897032 | ||
|
|
a69ff2499d | ||
|
|
0df4bc2289 | ||
|
|
83a3b1208a | ||
|
|
94cfde8025 | ||
|
|
b228d31ff9 | ||
|
|
f160d60a7a | ||
|
|
46031d162b | ||
|
|
4c44beba35 | ||
|
|
65545d3563 | ||
|
|
b4148e2f39 | ||
|
|
6e642b4d4b | ||
|
|
4bd6f8e720 | ||
|
|
7145b81ac1 | ||
|
|
8f080ee99e | ||
|
|
feb5262a16 | ||
|
|
7911a74c05 | ||
|
|
bb7cacb357 | ||
|
|
b5f7f0f472 | ||
|
|
8a26dff72b | ||
|
|
529cd33ddc | ||
|
|
838cf14845 | ||
|
|
4baa407e25 | ||
|
|
b01ba2da03 | ||
|
|
e4f7709f53 | ||
|
|
bcee799269 | ||
|
|
ec4da5efa5 | ||
|
|
94a28cbd1d | ||
|
|
63830dcbaf | ||
|
|
4ab9f02dc2 | ||
|
|
1102822981 | ||
|
|
006777dae1 | ||
|
|
df77c18117 | ||
|
|
360c6f1ae1 | ||
|
|
258639c372 | ||
|
|
9a10fde46f | ||
|
|
eecd78aee5 | ||
|
|
32fa8b60f8 | ||
|
|
7f81ec7f63 | ||
|
|
1f4ac3afbb | ||
|
|
7a20b20b2d | ||
|
|
cd0fe6c8f5 | ||
|
|
b8d0d12142 | ||
|
|
7ba1acc0cf | ||
|
|
9aab39de87 | ||
|
|
c77545460d | ||
|
|
6d22097e9a | ||
|
|
cd92df2007 | ||
|
|
8a301dad86 | ||
|
|
66b90e3ee8 | ||
|
|
ee6f9f81a5 | ||
|
|
c13cb2bf27 | ||
|
|
7d30d23a56 | ||
|
|
749c34df7a | ||
|
|
acf5e53953 | ||
|
|
9d5c294218 | ||
|
|
588d1d17aa | ||
|
|
6b94744df3 | ||
|
|
30c80107e3 | ||
|
|
05a88394fb | ||
|
|
455e32ab76 | ||
|
|
c55ee61b71 | ||
|
|
0b7485f69f | ||
|
|
5a44ccb615 | ||
|
|
587d964e42 | ||
|
|
63f20ce5cc | ||
|
|
2389f55bae | ||
|
|
af416b0572 | ||
|
|
a19864d5b1 | ||
|
|
1548f5cfe5 | ||
|
|
bca532e4e3 | ||
|
|
c04fe9a72b | ||
|
|
04d5eae0d1 | ||
|
|
32242eaf53 | ||
|
|
ef986fbeca | ||
|
|
7f40257632 | ||
|
|
630e56a263 | ||
|
|
6d576e8ff5 | ||
|
|
6600a06ee8 | ||
|
|
ca4644cbde | ||
|
|
d1c07306e9 | ||
|
|
9f63ea75fe | ||
|
|
cff33ee70d | ||
|
|
ccb73f4efd | ||
|
|
d69ebb9f1e | ||
|
|
579ce3f731 | ||
|
|
71ded3e4c0 | ||
|
|
59397c4842 | ||
|
|
76cb012b92 | ||
|
|
853a0304e1 | ||
|
|
5c2b52075d | ||
|
|
2389c0e07e | ||
|
|
df5df76c92 | ||
|
|
4fe11aacbd | ||
|
|
11db5c34d9 | ||
|
|
7d4d0cb921 | ||
|
|
d84cae9525 | ||
|
|
61a4118921 | ||
|
|
63ce54dc1e | ||
|
|
2d3f81cf54 | ||
|
|
cd989aace8 | ||
|
|
bb628998cc | ||
|
|
72aa411d2b | ||
|
|
d1925ada22 | ||
|
|
1eb91d4cef | ||
|
|
3b00295036 | ||
|
|
86a39c6573 | ||
|
|
979d19d066 | ||
|
|
ea32779559 | ||
|
|
42ba15665b | ||
|
|
65e243f5fc | ||
|
|
3a956c72b8 | ||
|
|
84ae5bb179 | ||
|
|
f49302d365 | ||
|
|
35f525dbde | ||
|
|
24b00c3db1 | ||
|
|
6a1cd830f5 | ||
|
|
9e605ee761 | ||
|
|
cf5493959b | ||
|
|
8f1d2afb0c | ||
|
|
d48146f52d | ||
|
|
5cfd5157d0 | ||
|
|
0ba39f732e | ||
|
|
194b01d74f | ||
|
|
6ea187f0d0 | ||
|
|
0fe7fa9b48 | ||
|
|
f75b1c0a04 | ||
|
|
e5642b0631 | ||
|
|
632ee77580 | ||
|
|
51227d5898 | ||
|
|
f5180392f2 | ||
|
|
3278eab0c8 | ||
|
|
71bfc70996 | ||
|
|
1e6ab2ecff | ||
|
|
0f0e3e73e7 | ||
|
|
a2498f096a | ||
|
|
494d1a9bf5 | ||
|
|
417ecfed50 | ||
|
|
94653b487d | ||
|
|
a5473e896a | ||
|
|
8483c355c8 | ||
|
|
8d2d2d27e6 | ||
|
|
72db7ecb97 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 | ||
|
|
a5f958d544 | ||
|
|
4aeeb4d883 | ||
|
|
15f3eadcf1 | ||
|
|
ae9804bc8b | ||
|
|
644a380616 | ||
|
|
4a41b14992 | ||
|
|
551328c901 | ||
|
|
54ce7ac6f8 | ||
|
|
a33c46465b | ||
|
|
b747e81cb6 | ||
|
|
24fdbb54db | ||
|
|
535f7584ee | ||
|
|
49e26d1de1 | ||
|
|
40fb4923e6 | ||
|
|
8fefbc1c82 | ||
|
|
059dca5b34 | ||
|
|
277464e93b | ||
|
|
a6e9c79c96 | ||
|
|
1a6c0dff36 | ||
|
|
73708c8e7d | ||
|
|
d2cc2093b1 | ||
|
|
ff9a48eb0e | ||
|
|
24e42bb302 | ||
|
|
67c00a986a | ||
|
|
896ec3b924 | ||
|
|
2f18cacbaf | ||
|
|
2cad48b401 | ||
|
|
1f8cf7e3a8 | ||
|
|
978bcd6dd4 | ||
|
|
a1d406beb3 | ||
|
|
b46c467fc3 | ||
|
|
091dd85ef0 | ||
|
|
4eab243ef2 | ||
|
|
56c6e8090a | ||
|
|
bd3f0cb651 | ||
|
|
fe1838aca6 | ||
|
|
9737adb66c | ||
|
|
1c4aa9f1b2 | ||
|
|
4335cf46af | ||
|
|
f2b602a48e | ||
|
|
b4c8a6708c | ||
|
|
8e36365bc4 | ||
|
|
b5a8a77cfa | ||
|
|
70a4fbec3a | ||
|
|
b640078b11 | ||
|
|
e186f74782 | ||
|
|
25d0294947 | ||
|
|
5d26e44c0e | ||
|
|
6e327e6ffc | ||
|
|
81d1285e38 |
No files matched your search
@@ -16,5 +16,5 @@ test-group = "windows-clipboard"
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & binary(=integration) & (test(/^svn::/) | test(/^ij_svn_roots::/)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
@@ -6,4 +6,6 @@ updates:
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
actions: { patterns: ["*"] }
|
||||
# tauri-action builds and uploads the release, so its updates come as their own PR and are
|
||||
# merged after a draft release has gone through with them.
|
||||
actions: { patterns: ["*"], exclude-patterns: ["tauri-apps/tauri-action"] }
|
||||
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
|
||||
RUFF=0.17.3
|
||||
GOPLS=v0.24.0
|
||||
JDTLS=1.63.0-202610191322
|
||||
KOTLIN_LSP=271.2085.0
|
||||
KOTLIN_LSP=271.3588.0
|
||||
GRADLE=8.14.3
|
||||
INTELEPHENSE=1.18.5
|
||||
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
|
||||
|
||||
@@ -118,13 +118,6 @@ jobs:
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
@@ -148,6 +141,11 @@ jobs:
|
||||
fi
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: nextest }
|
||||
# ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet`
|
||||
# CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
@@ -164,11 +162,14 @@ jobs:
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
- run: mkdir -p dist
|
||||
shell: bash
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo fmt --all --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# On PRs, run clippy on Linux only; macOS/Windows still compile and test all targets
|
||||
# via nextest, and run clippy on main/merge_group so platform-only lints are still caught.
|
||||
- if: runner.os == 'Linux' || github.event_name != 'pull_request'
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
@@ -212,14 +213,47 @@ jobs:
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
|
||||
# YAPPI_PYTHON those tests return early.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.environment == 'github-hosted'
|
||||
id: yappi-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install yappi for the Python profiler tests
|
||||
if: steps.yappi-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.yappi-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv"
|
||||
venv_py="$RUNNER_TEMP/yappi-venv/bin/python"
|
||||
[ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe"
|
||||
"$venv_py" -m pip install yappi==1.7.6
|
||||
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
|
||||
# python_memray.rs profiles real runs. memray has no Windows build.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
|
||||
id: memray-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install memray for the Python profiler tests
|
||||
# Self-hosted runners have no setup-python; without MEMRAY_PYTHON those tests return early.
|
||||
if: steps.memray-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.memray-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/memray-venv"
|
||||
"$RUNNER_TEMP/memray-venv/bin/python" -m pip install memray==1.21.0
|
||||
echo "MEMRAY_PYTHON=$RUNNER_TEMP/memray-venv/bin/python" >> "$GITHUB_ENV"
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# --workspace, not -p ide-host: -p would rebuild instead of reusing the test build above.
|
||||
cargo nextest run --workspace --run-ignored only \
|
||||
-E 'package(=ide-host) & binary(=integration) & test(=remote_daemon::compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
@@ -258,7 +292,9 @@ jobs:
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
with:
|
||||
key: server-musl
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
|
||||
@@ -26,6 +26,9 @@ on:
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "!src/platform/locales/text/**"
|
||||
- "!src/platform/locales/*.json"
|
||||
- "src/platform/locales/en.json"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
@@ -89,6 +92,7 @@ jobs:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
languages: ${{ steps.classify.outputs.languages }}
|
||||
groups: ${{ steps.classify.outputs.groups }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
@@ -98,8 +102,18 @@ jobs:
|
||||
set -euo pipefail
|
||||
all="typescript python rust go java kotlin php c cpp"
|
||||
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
|
||||
emit_groups() {
|
||||
jq -nc --argjson langs "$1" '
|
||||
[
|
||||
{ name: "jvm", languages: ($langs | map(select(. == "java" or . == "kotlin"))) },
|
||||
{ name: "systems", languages: ($langs | map(select(. == "rust" or . == "go" or . == "c" or . == "cpp"))) },
|
||||
{ name: "scripting", languages: ($langs | map(select(. == "typescript" or . == "python" or . == "php"))) }
|
||||
] | map(select(.languages | length > 0))'
|
||||
}
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$all")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
@@ -108,8 +122,9 @@ jobs:
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# ide-lsp/dap/run/sdk/tools. Also skip non-English lazy locale catalogs (smoke always
|
||||
# runs in the default English locale).
|
||||
unused='^(crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/|src/platform/locales/text/)'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
@@ -117,6 +132,8 @@ jobs:
|
||||
case "$f" in
|
||||
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
|
||||
crates/*/tests/* | crates/*/benches/*) ;;
|
||||
src/platform/locales/en.json) langs="$all"; break ;;
|
||||
src/platform/locales/*.json) ;;
|
||||
fixtures/ts-app/*) langs+=" typescript" ;;
|
||||
fixtures/python-app/*) langs+=" python" ;;
|
||||
fixtures/rust-app/*) langs+=" rust" ;;
|
||||
@@ -141,7 +158,9 @@ jobs:
|
||||
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
|
||||
esac
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$langs")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
@@ -190,12 +209,12 @@ jobs:
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
name: Language smoke (${{ matrix.group.name }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
group: ${{ fromJSON(needs.changes.outputs.groups) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
@@ -208,7 +227,8 @@ jobs:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- if: contains(matrix.group.languages, 'rust')
|
||||
uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
|
||||
with: { name: smoke-bin }
|
||||
@@ -223,11 +243,11 @@ jobs:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- if: matrix.language == 'typescript'
|
||||
- if: contains(matrix.group.languages, 'typescript')
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
- if: contains(matrix.group.languages, 'c') || contains(matrix.group.languages, 'cpp')
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
@@ -243,22 +263,22 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
with: { python-version: "3.12" }
|
||||
- if: matrix.language == 'python'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
|
||||
|
||||
- if: matrix.language == 'go'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
|
||||
with: { go-version: "1.27", cache: false }
|
||||
- if: matrix.language == 'go'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
run: go install "golang.org/x/tools/gopls@$GOPLS"
|
||||
|
||||
- if: matrix.language == 'java' || matrix.language == 'kotlin'
|
||||
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
- if: contains(matrix.group.languages, 'java')
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
@@ -267,10 +287,12 @@ jobs:
|
||||
echo "$RUNNER_TEMP/jdtls/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
|
||||
- if: matrix.language == 'kotlin'
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
with:
|
||||
gradle-version: "${{ env.GRADLE }}"
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/kotlin-lsp" "$RUNNER_TEMP/bin"
|
||||
curl -fsSL "https://download.jetbrains.com/language-server/kotlin-server/$KOTLIN_LSP/kotlin-server-$KOTLIN_LSP.tar.gz" \
|
||||
@@ -279,31 +301,48 @@ jobs:
|
||||
echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
|
||||
with: { php-version: "8.5", coverage: xdebug, tools: composer }
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
- if: matrix.language == 'typescript'
|
||||
- name: Code intelligence and project smoke
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
status=0
|
||||
for lang in ${{ join(matrix.group.languages, ' ') }}; do
|
||||
echo "::group::language_smoke ($lang)"
|
||||
../../smoke-bin/language_smoke --ignored --exact "$lang" || status=1
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
if [ "$lang" = typescript ]; then
|
||||
../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style || status=1
|
||||
fi
|
||||
if [ "$lang" = java ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier || status=1
|
||||
fi
|
||||
if [ "$lang" = kotlin ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact gradle_sync || status=1
|
||||
fi
|
||||
if [ "$lang" = python ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact python_venv || status=1
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
exit "$status"
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
- name: Run and debug smoke
|
||||
shell: bash
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
env: { GITHUB_TOKEN: "${{ github.token }}" }
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pattern="^($(echo "${{ join(matrix.group.languages, '|') }}"))$"
|
||||
status=0
|
||||
pnpm smoke smoke/run.test.ts -t "$pattern" || status=1
|
||||
pnpm smoke smoke/debug.test.ts -t "$pattern" || status=1
|
||||
exit "$status"
|
||||
@@ -47,6 +47,7 @@ jobs:
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
OPENIDEA_BUILD: ${{ github.sha }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -27,6 +27,7 @@ dist-ssr
|
||||
|
||||
# Rust
|
||||
target/
|
||||
!/crates/ide-ssh/src/target/
|
||||
# Tauri generated schemas
|
||||
/src-tauri/gen/schemas
|
||||
*.tsbuildinfo
|
||||
|
||||
+3
-1
@@ -122,7 +122,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `pnpm dogfood:servers [all | x86_64 | aarch64]` (or `mise run dogfood:servers ...`) — cross-build and locally stage Linux `openidea-server` binaries with Zig.
|
||||
- `pnpm dogfood:all [all | x86_64 | aarch64] [--build-only]` (or `mise run dogfood:all ...`) — run `dogfood:local` and `dogfood:servers` in parallel, without requiring an SSH host;
|
||||
`dogfood:all <remote_name> [--restart | --no-restart]` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel instead.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
|
||||
Створено
+121
-159
@@ -104,12 +104,6 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ambient-authority"
|
||||
version = "0.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
@@ -775,24 +769,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-primitives"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
|
||||
dependencies = [
|
||||
"ambient-authority",
|
||||
"fs-set-times",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.1",
|
||||
"ipnet",
|
||||
"maybe-owned",
|
||||
"rustix",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cargo-platform"
|
||||
version = "0.3.3"
|
||||
@@ -1202,27 +1178,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
|
||||
checksum = "1e3f0670397b48cb1ac491069afd5229a7bac64eb6102c285f1185d56a2d1982"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64-meta"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
|
||||
checksum = "fb3c47010315916ed3cb3ad200a2f6762e653c9efb295e756732890ee5c3a772"
|
||||
dependencies = [
|
||||
"cranelift-srcgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bforest"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
|
||||
checksum = "31966de669d154078a789193b7be55db68e767f302119aa6d5f6c9eb307351ea"
|
||||
dependencies = [
|
||||
"cranelift-entity",
|
||||
"wasmtime-internal-core",
|
||||
@@ -1230,9 +1206,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bitset"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
|
||||
checksum = "f7fb2cb0d1e8551fa2cc98dd1b4c34c33f0a9c62170fcf2321a81d4b3ce1122f"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -1241,9 +1217,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
|
||||
checksum = "380a92c92c3532dccdc76d6aaede0d1e44bfd7e564b57ba7c594769138d4a7cd"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"cranelift-assembler-x64",
|
||||
@@ -1272,9 +1248,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-meta"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
|
||||
checksum = "2f516745d087302bc038d41ee3e6a440270ec499b99aff997de08c980077c3be"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
"cranelift-codegen-shared",
|
||||
@@ -1285,24 +1261,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-shared"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
|
||||
checksum = "3cc33acbe213c870f12a8533f063e00bce075155492506f342ac0105603acbee"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-control"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
|
||||
checksum = "c1c425eefbef5e5c94464f827cbe44db138f372b25d8613df829002226a1f540"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-entity"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
|
||||
checksum = "3329ddee61c0af3e8c040b68e336a85d1c48eafb05461318359823366a231a9c"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"serde",
|
||||
@@ -1312,9 +1288,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-frontend"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
|
||||
checksum = "2b5c35b9f2ca742b49837ff9eaaccbd0889ce98bdfdc94655e09308040bd2378"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -1325,26 +1301,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-isle"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
|
||||
checksum = "def117e190cbbfcdc21b6f6bf16a9e72e1c4161d3e24bf0325162e005342e6ef"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-native"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
|
||||
checksum = "3f141d6357c868a4baa8764a7965a614f044818d6a36d5aeea2b9df572bce4d9"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"libc",
|
||||
"mach2",
|
||||
"target-lexicon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-srcgen"
|
||||
version = "0.136.7"
|
||||
version = "0.138.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
|
||||
checksum = "edc821d1689091a9277e0638a6463d8a013cb1f5cae5d5e68b8582feef7b2e3a"
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
@@ -2387,17 +2364,6 @@ dependencies = [
|
||||
"num",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-set-times"
|
||||
version = "0.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -4287,6 +4253,7 @@ dependencies = [
|
||||
name = "ide-coverage"
|
||||
version = "0.1.57"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
"quick-xml 0.42.0",
|
||||
@@ -4555,6 +4522,7 @@ name = "ide-http"
|
||||
version = "0.1.57"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"encoding_rs",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4690,6 +4658,7 @@ dependencies = [
|
||||
"tree-sitter-nix",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-ocaml",
|
||||
"tree-sitter-odin",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-prisma-io",
|
||||
"tree-sitter-proto",
|
||||
@@ -4721,6 +4690,7 @@ dependencies = [
|
||||
"ide-sdk",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -5284,28 +5254,6 @@ dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "3.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -5903,12 +5851,6 @@ dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maybe-owned"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.11.0"
|
||||
@@ -7176,9 +7118,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
@@ -7465,9 +7407,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-interpreter"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
|
||||
checksum = "8345a00a393704a3195710f11800eb86a35ddee962cc2051eb20a0bb40da594d"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"log",
|
||||
@@ -7477,13 +7419,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-macros"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
|
||||
checksum = "7856bc0bfba6621c0419f482e87be915201b8d14cedd5d5ec8c793c266c43251"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10573,6 +10515,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-odin"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24db210fe9ba2237c71c5030d7b146c7025420ba72dd8013d13cd822c3a8d77a"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-php"
|
||||
version = "0.25.1"
|
||||
@@ -11065,19 +11017,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f64765e43c000fae008a48db8b288e175e237fc9ce20a26586836878c1bee89f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
"wasmparser 0.258.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e10808eb27efde692f1b1706089fe19296728bf872291f5b4e0d50fba88f2f"
|
||||
checksum = "8997a297f42413bee775d73a750def062ee1ec4a6d904703cb08046c0296774d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap 2.14.2",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11098,6 +11060,17 @@ name = "wasmparser"
|
||||
version = "0.258.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe9269dd817e0e7021bf534ccd9761bc2d64778b6708e41228b8439d75eaa0b1"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap 2.14.2",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -11108,20 +11081,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmprinter"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "14a457ba8670a3db3d357c1aeac3ed4fe378a76054a221789f0df0ea507e292b"
|
||||
checksum = "b40c3aedc383a68866a7bae302578765c3f05c9e11ea6d242e5cc450f8300a26"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"termcolor",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
|
||||
checksum = "4fe4d7f7bae504c067d5eaf3c990f706f416d9aba0c86fbd17f69aa1625514c9"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"async-trait",
|
||||
@@ -11130,6 +11103,7 @@ dependencies = [
|
||||
"cc",
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
"indexmap 2.14.2",
|
||||
"libc",
|
||||
"log",
|
||||
"mach2",
|
||||
@@ -11145,7 +11119,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmtime-environ",
|
||||
"wasmtime-internal-component-macro",
|
||||
"wasmtime-internal-component-util",
|
||||
@@ -11161,9 +11135,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-environ"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
|
||||
checksum = "e121151e0fd47b956f9b6bc7959a0a48e10e4947ef133515073a7c3a952845f8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cpp_demangle",
|
||||
@@ -11180,11 +11154,10 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmprinter",
|
||||
"wasmtime-internal-component-util",
|
||||
"wasmtime-internal-core",
|
||||
@@ -11192,14 +11165,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-macro"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
|
||||
checksum = "ef79e1caafa01f06dc80d2c2125b80ee0a80ce4e429c2a5060d9c7efa0929c59"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
"wasmtime-internal-component-util",
|
||||
"wasmtime-internal-wit-bindgen",
|
||||
"wit-parser",
|
||||
@@ -11207,15 +11180,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-util"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
|
||||
checksum = "56db007f81976ef523c554928318e1ec5cb1e65247f9c964a9f223cab063d99e"
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-core"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
|
||||
checksum = "07cb09d8608a4343c2f039f4ed8ef734c08733887e5e50a19711668c324a1efd"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"libm",
|
||||
@@ -11224,9 +11197,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-cranelift"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
|
||||
checksum = "158d190d15edb4baec25ea293c79b905b389c2354fccc6a59ae31974a30f024c"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"cranelift-control",
|
||||
@@ -11241,7 +11214,7 @@ dependencies = [
|
||||
"smallvec",
|
||||
"target-lexicon",
|
||||
"thiserror 2.0.21",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wasmtime-environ",
|
||||
"wasmtime-internal-core",
|
||||
"wasmtime-internal-unwinder",
|
||||
@@ -11250,9 +11223,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-fiber"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
|
||||
checksum = "a9ac783ac0c8a20cf1bf1a33599345ed62dc8e7bddfa2929cedb68aa0722ec2f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -11264,9 +11237,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-debug"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
|
||||
checksum = "2153e59eefff0626431d2c8eea389db01b3e10fcaeaf17a1c034772213902d73"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"wasmtime-internal-versioned-export-macros",
|
||||
@@ -11274,9 +11247,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-icache-coherence"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
|
||||
checksum = "25b5537454e038b22b38404f9efacb376fa65957064e5b39dff6b044ed46e007"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasmtime-internal-core",
|
||||
@@ -11285,9 +11258,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-unwinder"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
|
||||
checksum = "2f4f72e4d5be23320ee4dd70c8020e6ce861a0fb2851e91be91cbc842debddf8"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"log",
|
||||
@@ -11297,20 +11270,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-versioned-export-macros"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
|
||||
checksum = "1af2217d501904ce9f9e1771bde6633ddb3c717d5dbef57c994f96acadb7a030"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-wit-bindgen"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
|
||||
checksum = "b9d9a611c2a63d553eee62a0555114ab221c54ae30d08d50b92f2ac2e449baa7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -11322,15 +11295,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
|
||||
checksum = "a5099e3b95d50c5c7998da4ca0c9c25402dd865e45386690a9a40add3f575011"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
"cap-primitives",
|
||||
"futures",
|
||||
"libc",
|
||||
"rand 0.10.3",
|
||||
"rustix",
|
||||
"rustix-linux-procfs",
|
||||
@@ -11341,14 +11314,13 @@ dependencies = [
|
||||
"wasmtime",
|
||||
"wasmtime-wasi-io",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi-io"
|
||||
version = "49.0.7"
|
||||
version = "51.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
|
||||
checksum = "ad8ac873113e37bf22bbd58523ea82d45591eeb4f71e06809534d3950345718c"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -11367,7 +11339,7 @@ dependencies = [
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
"wasm-encoder 0.258.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12046,16 +12018,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
@@ -12064,9 +12026,9 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0fca88950af0c1f42bc77e17315e48798b8d68340171b6d204f62bc19a878a6"
|
||||
checksum = "4189bd180353b942b788715519dff886517b540e648c6f6e5129f57429945bf7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -12075,17 +12037,17 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-encoder 0.263.0",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.258.3"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72a2127663dcf3ee16614fb0e3c33d5c6c66fec9dad317a8b0fdd3869487a533"
|
||||
checksum = "874d6ce9db4261cb66980ab14f3da066b24292497b6f46f988c0d1b9b27913f3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -12097,7 +12059,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
|
||||
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Знакомая вам IDE, переписанная на Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Документация</a>
|
||||
·
|
||||
<a href="#сравнение-производительности">Производительность</a>
|
||||
·
|
||||
<a href="#плагины">Плагины</a>
|
||||
·
|
||||
<a href="#сообщество">Сообщество</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA переносит привычные для пользователей IntelliJ IDEA сочетания клавиш, окна инструментов
|
||||
и глобальный поиск в нативное приложение с ядром на Rust.
|
||||
|
||||
Редактор, средства анализа кода, отладчик, Git, терминал, клиенты для работы с базами данных и HTTP.
|
||||
Поддержка более 60 языков. Сборки для macOS, Windows и Linux.
|
||||
|
||||
На macOS IDE также можно установить через Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Сравнение производительности
|
||||
|
||||
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
|
||||
с прогретыми кешами, медиана пяти запусков:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------------------- | ------------------- | ---------------------- |
|
||||
| Появление окна с проектом | **0,9 с** | 3,1 с |
|
||||
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
|
||||
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
|
||||
| Процессорное время до готовности | **2,4 с** | 47,9 с |
|
||||
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
|
||||
| Завершение работы | **0,3 с** | 5,9 с |
|
||||
|
||||
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
|
||||
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
|
||||
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
|
||||
Измерения обеих IDE проводились извне по одной методике: с помощью
|
||||
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
|
||||
|
||||
## Плагины
|
||||
|
||||
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
|
||||
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
|
||||
для тем оформления, тем значков и языков писать код не нужно.
|
||||
|
||||
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
|
||||
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
|
||||
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
|
||||
|
||||
## Сообщество
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
|
||||
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
|
||||
|
||||
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · 简体中文
|
||||
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::is_copilot_provider(spec.base_id())
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
@@ -53,7 +53,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
@@ -69,7 +69,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(&launch.id, &mut options);
|
||||
config::add_client_options(launch.base_id(), &mut options);
|
||||
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
|
||||
let mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
@@ -119,7 +119,7 @@ async fn run_once(
|
||||
.commands
|
||||
.lock()
|
||||
.clone()
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
|
||||
Ok::<_, String>(Discovered { config: options, commands, levels })
|
||||
};
|
||||
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
|
||||
|
||||
@@ -80,6 +80,8 @@ fn client_capabilities() -> Value {
|
||||
"subagents": {},
|
||||
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
|
||||
"elicitation": { "form": {} },
|
||||
// Ghost-text next-prompt suggestions (`prompt_suggestions_update`).
|
||||
"session": { "promptSuggestions": {} },
|
||||
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
|
||||
// only when the client advertises this flag (undocumented Cursor ACP extension).
|
||||
"_meta": { "parameterizedModelPicker": true },
|
||||
@@ -94,7 +96,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value {
|
||||
json!({
|
||||
"protocolVersion": 2,
|
||||
"info": client_info,
|
||||
"capabilities": {},
|
||||
"capabilities": { "session": { "promptSuggestions": {} } },
|
||||
"clientCapabilities": client_capabilities(),
|
||||
"clientInfo": client_info,
|
||||
})
|
||||
@@ -359,7 +361,7 @@ impl Handler for Dialect {
|
||||
|
||||
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
|
||||
if self.v2() && method == "session/request_permission" {
|
||||
return self.on_request_with_data(method, params);
|
||||
return self.inner.on_request_raw(method, v1_permission_request(params), raw);
|
||||
}
|
||||
self.inner.on_request_raw(method, params, raw)
|
||||
}
|
||||
|
||||
@@ -133,11 +133,14 @@ fn the_negotiating_request_carries_both_versions() {
|
||||
);
|
||||
// Forms only: URL mode would open pages the agent names.
|
||||
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
|
||||
assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
|
||||
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
|
||||
let mut expected = sent;
|
||||
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
|
||||
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
|
||||
expected["session"] = p["clientCapabilities"]["session"].clone();
|
||||
assert_eq!(expected, p["clientCapabilities"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String);
|
||||
#[derive(Default)]
|
||||
pub struct AgentCatalogs {
|
||||
state: Mutex<State>,
|
||||
/// Orders model requests by when they were made, not when they reach `state`.
|
||||
tickets: std::sync::atomic::AtomicU64,
|
||||
#[cfg(test)]
|
||||
clock_ms: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
@@ -49,6 +51,8 @@ struct Entry {
|
||||
abort: Option<tokio::task::AbortHandle>,
|
||||
flight_model: Option<String>,
|
||||
requested_model: Option<String>,
|
||||
/// Ticket of the newest model request applied: an older one arriving late can't supersede it.
|
||||
model_ticket: u64,
|
||||
model_failures: HashMap<String, ModelFailure>,
|
||||
catalog: Option<CatalogData>,
|
||||
}
|
||||
@@ -254,7 +258,16 @@ impl AgentCatalogs {
|
||||
}
|
||||
let unavailable = || "The agent did not report settings for the selected model".to_owned();
|
||||
let spec = shared.spec(provider).ok_or_else(unavailable)?;
|
||||
let (_, flight) = self.request(shared, spec, false, Some(model));
|
||||
// Taken now: the blocking task may run after a newer selection's request.
|
||||
let ticket = self.ticket();
|
||||
let flight = {
|
||||
let catalogs = self.clone();
|
||||
let shared = shared.clone();
|
||||
let model = model.to_owned();
|
||||
tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
if let Some(mut ready) = flight {
|
||||
while !*ready.borrow_and_update() {
|
||||
if ready.changed().await.is_err() {
|
||||
@@ -324,12 +337,49 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
|
||||
/// The model the running discovery of `provider` looks up, if one is running.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option<Option<String>> {
|
||||
let state = self.state.lock();
|
||||
let entry = state.entries.get(&Self::key(shared, provider))?;
|
||||
entry.flight.as_ref().map(|_| entry.flight_model.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn request_as_of(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
model: &str,
|
||||
ticket: u64,
|
||||
) -> Option<watch::Receiver<bool>> {
|
||||
self.request_with(shared, spec, false, Some(model), ticket).1
|
||||
}
|
||||
|
||||
pub(crate) fn ticket(&self) -> u64 {
|
||||
self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
pub(crate) fn request(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
force: bool,
|
||||
model: Option<&str>,
|
||||
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
|
||||
let ticket = self.ticket();
|
||||
self.request_with(shared, spec, force, model, ticket)
|
||||
}
|
||||
|
||||
/// [`Self::request`] for a request made when `ticket` was taken. A model request older than
|
||||
/// the newest one applied neither changes the requested model nor supersedes its flight.
|
||||
fn request_with(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
force: bool,
|
||||
model: Option<&str>,
|
||||
ticket: u64,
|
||||
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
|
||||
let key = Self::key(shared, &spec.id);
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
@@ -381,6 +431,7 @@ impl AgentCatalogs {
|
||||
abort: None,
|
||||
flight_model: None,
|
||||
requested_model: None,
|
||||
model_ticket: 0,
|
||||
model_failures: HashMap::new(),
|
||||
},
|
||||
);
|
||||
@@ -397,10 +448,15 @@ impl AgentCatalogs {
|
||||
|| (!fresh && catalog.model_option().is_none())
|
||||
})
|
||||
.map(str::to_owned);
|
||||
if model.is_some() && entry.requested_model.as_deref() != model {
|
||||
entry.requested_model = model.map(str::to_owned);
|
||||
let stale = model.is_some() && ticket < entry.model_ticket;
|
||||
if model.is_some() && !stale {
|
||||
entry.model_ticket = ticket;
|
||||
if entry.requested_model.as_deref() != model {
|
||||
entry.requested_model = model.map(str::to_owned);
|
||||
}
|
||||
}
|
||||
let superseded = model.is_some()
|
||||
let superseded = !stale
|
||||
&& model.is_some()
|
||||
&& entry.flight.is_some()
|
||||
&& (entry.flight_model.is_some() || target.is_some())
|
||||
&& entry.flight_model.as_deref() != target.as_deref();
|
||||
@@ -444,7 +500,22 @@ impl AgentCatalogs {
|
||||
let flight_key = key.clone();
|
||||
let task = shared.runtime.clone().spawn(async move {
|
||||
let result = discover(&shared, spec, model.as_deref()).await;
|
||||
coordinator.complete(&shared, flight_key, generation, model, result);
|
||||
let current = {
|
||||
let shared = shared.clone();
|
||||
let provider_id = flight_key.2.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == provider_id)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root))
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
coordinator.complete(&shared, flight_key, generation, model, current, result);
|
||||
let _ = done.send(true);
|
||||
});
|
||||
// A subscriber can re-enter and change configuration during the start event.
|
||||
@@ -466,14 +537,9 @@ impl AgentCatalogs {
|
||||
key: Key,
|
||||
generation: u64,
|
||||
model: Option<String>,
|
||||
current: Option<LaunchContext>,
|
||||
result: Result<Discovered, String>,
|
||||
) {
|
||||
let current = shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == key.2)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
|
||||
// Configuration may have changed without another refresh request arriving.
|
||||
@@ -680,7 +746,7 @@ async fn discover(
|
||||
Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
@@ -704,7 +770,7 @@ async fn discover(
|
||||
Ok(found) => Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::model::AgentEntry;
|
||||
use crate::timeline::{Timeline, blocks_text, content_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
|
||||
pub(crate) type Session = Option<String>;
|
||||
@@ -107,7 +108,7 @@ impl Conversation {
|
||||
out.push((parent, index));
|
||||
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
|
||||
let id = Some(id.to_owned());
|
||||
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
|
||||
out.extend(child.end_turn(None, &HashSet::new()).into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
}
|
||||
"session_message" | "session_message_chunk" => {
|
||||
@@ -169,18 +170,20 @@ impl Conversation {
|
||||
self.subagents.retain(|_| keep.next().unwrap_or(true));
|
||||
}
|
||||
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background),
|
||||
/// and the requests in `open`, which they asked, stay open.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done, open).into_iter().map(|i| (None, i)).collect()
|
||||
}
|
||||
|
||||
/// Settles everything left open once the agent is gone, subagents included.
|
||||
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
|
||||
let none = HashSet::new();
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None, &none).into_iter().map(|i| (None, i)).collect();
|
||||
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
|
||||
for s in &mut self.subagents {
|
||||
let id = Some(s.id.clone());
|
||||
let mut changed = s.timeline.end_turn(None);
|
||||
let mut changed = s.timeline.end_turn(None, &none);
|
||||
changed.extend(s.timeline.stop_subagents(now));
|
||||
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
|
||||
+520
-165
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,14 @@
|
||||
//! Unified Agent Memory hub (#6810): discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across every coding agent (`claude`,
|
||||
//! `codex`, `copilot`, `cursor`, `gemini`, `hermes`, `opencode`, and custom ACP agents),
|
||||
//! deduplicates symlinks and `@AGENTS.md` imports, resolves `[agents.memory]` policies
|
||||
//! under Workspace Trust without mutating tracked repository files, stages per-session
|
||||
//! `_meta.openidea.memory` delivery for each driver.
|
||||
//! Unified Agent Rules & Memory hub: discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across coding agents (`claude`, `codex`,
|
||||
//! `copilot`, `cursor`, `gemini`, `hermes`, and custom ACP agents), deduplicates symlinks
|
||||
//! and `@AGENTS.md` wrapper imports, resolves per-provider auto-memory policies under
|
||||
//! Workspace Trust, and builds native per-session `_meta.openidea.memory` payloads only
|
||||
//! for drivers that enforce them (`claude`, `codex`).
|
||||
|
||||
use crate::{
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
|
||||
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
|
||||
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryKind,
|
||||
AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource, AutoMemoryMode,
|
||||
CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,7 +21,11 @@ const CLAUDE_MEMORY_INDEX_WARN_LINES: u32 = 180;
|
||||
const CLAUDE_MEMORY_INDEX_BYTE_CAP: u64 = 25 * 1024;
|
||||
const CLAUDE_MEMORY_INDEX_WARN_BYTES: u64 = 22 * 1024;
|
||||
const INSTRUCTION_WARN_LINES: u32 = 200;
|
||||
const MAX_STAGED_SYSTEM_BYTES: usize = 32 * 1024;
|
||||
|
||||
const CLAUDE_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const CODEX_AUTO_MODES: &[AutoMemoryMode] =
|
||||
&[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::ReadOnly, AutoMemoryMode::Off];
|
||||
const HERMES_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
@@ -46,56 +50,43 @@ impl Default for MemoryPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory`.
|
||||
/// Per-session auto-memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory` for native drivers that enforce it (`claude`, `codex`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Delivery {
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_auto_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub claude_md_excludes: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_instruction_files: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_add_dir: Option<PathBuf>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub claude_additional_dirs_claude_md: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_use_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_generate_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_developer_instructions: Option<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_exclude_store_memory: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_enable_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_disable_custom_instructions: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_system_message: Option<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
/// Normalizes a provider id to its auto-memory policy key.
|
||||
/// Native `claude` and `codex` keep their exact ids (distinct from `claude-acp` / `codex-acp`,
|
||||
/// whose external ACP adapters do not consume `_meta.openidea.memory`); Hermes profiles collapse
|
||||
/// onto `"hermes"`.
|
||||
pub fn provider_key(provider: &str) -> &str {
|
||||
let trimmed = provider.trim();
|
||||
if trimmed == "hermes" || trimmed.starts_with("hermes-") { "hermes" } else { trimmed }
|
||||
}
|
||||
|
||||
pub fn normalize_provider_id(provider: &str) -> &str {
|
||||
let base = provider.strip_suffix("-acp").unwrap_or(provider);
|
||||
if base == "hermes" || base.starts_with("hermes-") { "hermes" } else { base }
|
||||
}
|
||||
|
||||
pub fn matches_agent_filter(agents: &[String], provider: &str) -> bool {
|
||||
if agents.is_empty() {
|
||||
return true;
|
||||
/// Auto-memory modes enforced by `provider`. Empty means the agent manages auto-memory itself.
|
||||
pub fn supported_auto_memory_modes(provider: &str) -> &'static [AutoMemoryMode] {
|
||||
match provider_key(provider) {
|
||||
"claude" => CLAUDE_AUTO_MODES,
|
||||
"codex" => CODEX_AUTO_MODES,
|
||||
"hermes" => HERMES_AUTO_MODES,
|
||||
_ => &[],
|
||||
}
|
||||
let target = normalize_provider_id(provider);
|
||||
agents.iter().any(|raw| {
|
||||
let trimmed = raw.trim();
|
||||
trimmed.eq_ignore_ascii_case(provider) || normalize_provider_id(trimmed).eq_ignore_ascii_case(target)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `provider`'s auto-memory mode is persisted directly in its own native config file
|
||||
/// (e.g. `~/.hermes/config.yaml`) rather than per-project settings or per-session overrides.
|
||||
pub fn is_native_config_auto_memory(provider: &str) -> bool {
|
||||
provider_key(provider) == "hermes"
|
||||
}
|
||||
|
||||
fn source_key(source: AgentMemorySource) -> &'static str {
|
||||
@@ -473,7 +464,7 @@ pub fn discover_memories_with_plugins(
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (discovered entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
@@ -481,105 +472,45 @@ pub fn resolve_catalog(
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
) -> AgentMemoryCatalog {
|
||||
let resolved_entries = resolve_entries(entries, session_overrides, policy);
|
||||
let (auto_memory, auto_memory_origin) = resolve_global_auto_memory(session_overrides, policy);
|
||||
let providers = build_provider_statuses(&resolved_entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries: resolved_entries, providers, auto_memory, auto_memory_origin }
|
||||
let providers = build_provider_statuses(&entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries, providers, workspace_trusted: policy.workspace_trusted }
|
||||
}
|
||||
|
||||
/// Resolves every discovered memory entry's effective [`AgentMemoryMode`] with precedence:
|
||||
/// `Workspace Trust > Session Override > Workspace Settings > User Settings > Default (Auto)`.
|
||||
pub fn resolve_entries(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> Vec<AgentMemoryState> {
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
if entry.source.is_workspace() && !policy.workspace_trusted {
|
||||
out.push(AgentMemoryState {
|
||||
entry,
|
||||
mode: AgentMemoryMode::Off,
|
||||
agents: Vec::new(),
|
||||
origin: AgentMemoryOrigin::Trust,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &entry.id)
|
||||
.filter(|p| policy.workspace_trusted || p.mode == AgentMemoryMode::Off);
|
||||
let user_pol = lookup_entry_policy(&policy.user.entries, &entry.id);
|
||||
let agents = ws_pol
|
||||
.filter(|p| !p.agents.is_empty())
|
||||
.or_else(|| user_pol.filter(|p| !p.agents.is_empty()))
|
||||
.map(|p| p.agents.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let (mode, origin) =
|
||||
if let Some(chosen) = session_overrides.and_then(|s| lookup_session_entry(&s.entries, &entry.id)) {
|
||||
(chosen, AgentMemoryOrigin::Session)
|
||||
} else if let Some(ws) = ws_pol {
|
||||
(ws.mode, AgentMemoryOrigin::Workspace)
|
||||
} else if let Some(us) = user_pol {
|
||||
(us.mode, AgentMemoryOrigin::User)
|
||||
} else {
|
||||
(AgentMemoryMode::Auto, AgentMemoryOrigin::None)
|
||||
};
|
||||
out.push(AgentMemoryState { entry, mode, agents, origin });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn resolve_global_auto_memory(
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let ws_mode = policy.workspace.auto_memory;
|
||||
if ws_mode != AutoMemoryMode::Inherit && (policy.workspace_trusted || ws_mode == AutoMemoryMode::Off) {
|
||||
return (ws_mode, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` (`claude`, `codex`, `copilot`, `hermes`, etc.).
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` that supports OpenIDEA-managed
|
||||
/// settings/session overrides (`claude`, `codex`).
|
||||
/// Precedence: `Session Override > Workspace Settings (when trusted or Off) > User Settings > Inherit`.
|
||||
pub fn resolve_provider_auto_memory(
|
||||
provider: &str,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
let supported = supported_auto_memory_modes(provider);
|
||||
if supported.is_empty() || is_native_config_auto_memory(provider) {
|
||||
return (AutoMemoryMode::Inherit, AgentMemoryOrigin::None);
|
||||
}
|
||||
let accepts = |mode: AutoMemoryMode| mode != AutoMemoryMode::Inherit && supported.contains(&mode);
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory)
|
||||
&& accepts(mode)
|
||||
{
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let key = normalize_provider_id(provider);
|
||||
let key = provider_key(provider);
|
||||
if let Some(ws_prov) = policy.workspace.providers.get(key)
|
||||
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(ws_prov.auto_memory)
|
||||
&& (policy.workspace_trusted || ws_prov.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (ws_prov.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.workspace.auto_memory != AutoMemoryMode::Inherit
|
||||
&& (policy.workspace_trusted || policy.workspace.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (policy.workspace.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if let Some(user_prov) = policy.user.providers.get(key)
|
||||
&& user_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(user_prov.auto_memory)
|
||||
{
|
||||
return (user_prov.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
fn build_provider_statuses(
|
||||
states: &[AgentMemoryState],
|
||||
entries: &[AgentMemoryEntry],
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
@@ -587,11 +518,9 @@ fn build_provider_statuses(
|
||||
let stats_for = |src: AgentMemorySource| -> (u32, u32) {
|
||||
let mut count = 0u32;
|
||||
let mut tokens = 0u32;
|
||||
for s in states.iter().filter(|s| s.entry.source == src) {
|
||||
for e in entries.iter().filter(|e| e.source == src) {
|
||||
count += 1;
|
||||
if s.mode != AgentMemoryMode::Off {
|
||||
tokens = tokens.saturating_add(s.entry.approx_tokens);
|
||||
}
|
||||
tokens = tokens.saturating_add(e.approx_tokens);
|
||||
}
|
||||
(count, tokens)
|
||||
};
|
||||
@@ -614,19 +543,12 @@ fn build_provider_statuses(
|
||||
codex_dir.as_ref().map(|d| markdown_files(&d.join("rollout_summaries"), 1).len() as u32).unwrap_or(0);
|
||||
let (codex_mode, codex_origin) = resolve_provider_auto_memory("codex", session_overrides, policy);
|
||||
|
||||
let (copilot_mode, copilot_origin) = resolve_provider_auto_memory("copilot", session_overrides, policy);
|
||||
|
||||
let (hermes_notes, hermes_tokens) = stats_for(AgentMemorySource::HermesAuto);
|
||||
let hermes_dir = hermes_root(home).map(|r| r.join("memories"));
|
||||
let (mut hermes_mode, hermes_origin) = resolve_provider_auto_memory("hermes", session_overrides, policy);
|
||||
if hermes_mode == AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(cfg_mode) = read_hermes_config_memory_mode(&root)
|
||||
{
|
||||
hermes_mode = cfg_mode;
|
||||
}
|
||||
|
||||
let (acp_mode, acp_origin) = resolve_provider_auto_memory("acp", session_overrides, policy);
|
||||
let (hermes_mode, hermes_origin) = match hermes_root(home).and_then(|root| read_hermes_config_memory_mode(&root)) {
|
||||
Some(cfg_mode) => (cfg_mode, AgentMemoryOrigin::Native),
|
||||
None => (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native),
|
||||
};
|
||||
|
||||
vec![
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -634,12 +556,12 @@ fn build_provider_statuses(
|
||||
label: "Claude Code".into(),
|
||||
mode: claude_mode,
|
||||
origin: claude_origin,
|
||||
supported_modes: CLAUDE_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: claude_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: claude_tokens,
|
||||
storage_path: claude_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: true,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -647,295 +569,81 @@ fn build_provider_statuses(
|
||||
label: "Codex".into(),
|
||||
mode: codex_mode,
|
||||
origin: codex_origin,
|
||||
supported_modes: CODEX_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: codex_notes,
|
||||
rollout_count: codex_rollouts,
|
||||
approx_tokens: codex_tokens,
|
||||
storage_path: codex_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "copilot".into(),
|
||||
label: "GitHub Copilot".into(),
|
||||
mode: copilot_mode,
|
||||
origin: copilot_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: home.map(|h| h.join(".copilot").into()),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "hermes".into(),
|
||||
label: "Hermes Agent".into(),
|
||||
mode: hermes_mode,
|
||||
origin: hermes_origin,
|
||||
supported_modes: HERMES_AUTO_MODES.to_vec(),
|
||||
native_config_only: true,
|
||||
note_count: hermes_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: hermes_tokens,
|
||||
storage_path: hermes_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "acp".into(),
|
||||
label: "Cursor / Gemini / ACP".into(),
|
||||
mode: acp_mode,
|
||||
origin: acp_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: None,
|
||||
supports_auto_control: false,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Directory under `<store_dir>/session-memory/<task_id>` holding per-session staged rules.
|
||||
pub fn farm_dir(store_dir: &Path, task_id: &str) -> PathBuf {
|
||||
store_dir.join("session-memory").join(task_id)
|
||||
/// Builds the per-session [`Delivery`] payload (`_meta.openidea.memory`) for a native driver
|
||||
/// (`"claude"` or `"codex"`). Returns `None` when `auto_memory` is `Inherit` or the driver
|
||||
/// does not consume `_meta.openidea.memory`.
|
||||
pub fn build_delivery(driver_key: &str, auto_memory: AutoMemoryMode) -> Option<Delivery> {
|
||||
if auto_memory == AutoMemoryMode::Inherit {
|
||||
return None;
|
||||
}
|
||||
match driver_key {
|
||||
"claude" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(true), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(false), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Inherit | AutoMemoryMode::ReadOnly => None,
|
||||
},
|
||||
"codex" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(true),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::ReadOnly => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Off => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(false),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Inherit => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a deleted task's staged memory folder, if any.
|
||||
pub fn remove_farm(store_dir: &Path, task_id: &str) {
|
||||
let _ = std::fs::remove_dir_all(farm_dir(store_dir, task_id));
|
||||
}
|
||||
|
||||
/// Computes the per-session [`Delivery`] payload (`_meta.openidea.memory`) for `provider`,
|
||||
/// staging non-native rules into `farm` where needed (e.g. Claude `.claude/rules/`).
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
states: &[AgentMemoryState],
|
||||
auto_memory: AutoMemoryMode,
|
||||
cwd: &Path,
|
||||
home: Option<&Path>,
|
||||
) -> std::io::Result<Delivery> {
|
||||
let norm = normalize_provider_id(provider);
|
||||
let mut out = Delivery { auto_memory, ..Delivery::default() };
|
||||
|
||||
let claude_rules_dir = farm.join(".claude/rules");
|
||||
match std::fs::remove_dir_all(&claude_rules_dir) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
/// Explicitly updates Hermes's native `config.yaml` (`memory_enabled` and `user_profile_enabled`).
|
||||
/// Never called during session startup — only when the user changes Hermes's setting directly.
|
||||
pub fn set_hermes_auto_memory(provider: &str, mode: AutoMemoryMode, home: Option<&Path>) -> Result<(), String> {
|
||||
if !matches!(mode, AutoMemoryMode::ReadWrite | AutoMemoryMode::Off) {
|
||||
return Err("Hermes auto-memory supports only On (readWrite) or Off".into());
|
||||
}
|
||||
|
||||
match norm {
|
||||
"claude" => {
|
||||
out.claude_auto_memory = match auto_memory {
|
||||
AutoMemoryMode::Inherit => None,
|
||||
AutoMemoryMode::ReadWrite => Some(true),
|
||||
// Claude Code has one boolean (`autoMemoryEnabled`): ReadOnly and Off both stop background writes;
|
||||
// existing `MEMORY.md` entries that remain `Auto`/`Always` can still be staged as read-only rules.
|
||||
AutoMemoryMode::ReadOnly | AutoMemoryMode::Off => Some(false),
|
||||
};
|
||||
|
||||
let mut agents_md_active = false;
|
||||
let mut agents_md_off = false;
|
||||
let mut claude_md_active = false;
|
||||
|
||||
for state in states {
|
||||
let effective_on = state.mode != AgentMemoryMode::Off && matches_agent_filter(&state.agents, provider);
|
||||
let p = state.entry.path.0.as_path();
|
||||
let fname = file_name(p).unwrap_or_default();
|
||||
|
||||
if matches!(state.entry.source, AgentMemorySource::Workspace) && fname == "AGENTS.md" {
|
||||
if effective_on {
|
||||
agents_md_active = true;
|
||||
} else {
|
||||
agents_md_off = true;
|
||||
}
|
||||
}
|
||||
if matches!(state.entry.source, AgentMemorySource::ClaudeWorkspace)
|
||||
&& matches!(fname.as_str(), "CLAUDE.md" | "CLAUDE.local.md")
|
||||
&& effective_on
|
||||
{
|
||||
claude_md_active = true;
|
||||
}
|
||||
|
||||
if !effective_on {
|
||||
if !state.entry.source.is_auto() {
|
||||
out.claude_md_excludes.push(p.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stage `Always` rules from other agents, or a `ReadOnly` `ClaudeAuto` `MEMORY.md`,
|
||||
// into `<farm>/.claude/rules/`.
|
||||
let stage_into_claude = (auto_memory == AutoMemoryMode::ReadOnly
|
||||
&& state.entry.source == AgentMemorySource::ClaudeAuto
|
||||
&& fname == "MEMORY.md")
|
||||
|| (state.mode == AgentMemoryMode::Always
|
||||
&& !matches!(
|
||||
state.entry.source,
|
||||
AgentMemorySource::ClaudeWorkspace | AgentMemorySource::ClaudeUser
|
||||
));
|
||||
|
||||
if stage_into_claude {
|
||||
stage_claude_rule(&claude_rules_dir, state)?;
|
||||
}
|
||||
}
|
||||
|
||||
if agents_md_active && claude_md_active {
|
||||
out.claude_instruction_files = Some("claude-md-and-agents-md".into());
|
||||
} else if agents_md_off {
|
||||
out.claude_instruction_files = Some("claude-md".into());
|
||||
}
|
||||
|
||||
if claude_rules_dir.exists() {
|
||||
out.claude_add_dir = Some(farm.to_path_buf());
|
||||
out.claude_additional_dirs_claude_md = true;
|
||||
}
|
||||
}
|
||||
"codex" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.codex_use_memories = Some(false);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::CodexUser | AgentMemorySource::CodexAuto)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.codex_developer_instructions = Some(extra);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.copilot_enable_memory = Some(false);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
}
|
||||
let native_instructions: Vec<&AgentMemoryState> = states
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
matches!(
|
||||
s.entry.source,
|
||||
AgentMemorySource::Workspace
|
||||
| AgentMemorySource::ClaudeWorkspace
|
||||
| AgentMemorySource::GithubWorkspace
|
||||
| AgentMemorySource::CopilotUser
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if !native_instructions.is_empty()
|
||||
&& native_instructions
|
||||
.iter()
|
||||
.all(|s| s.mode == AgentMemoryMode::Off || !matches_agent_filter(&s.agents, provider))
|
||||
{
|
||||
out.copilot_disable_custom_instructions = true;
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::GithubWorkspace | AgentMemorySource::CopilotUser)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.copilot_system_message = Some(extra);
|
||||
}
|
||||
}
|
||||
"hermes" => {
|
||||
if auto_memory != AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(prof_home) = hermes::profile_home(&root, provider)
|
||||
{
|
||||
let _ = write_hermes_config_memory_mode(&prof_home, auto_memory);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn stage_claude_rule(rules_dir: &Path, state: &AgentMemoryState) -> std::io::Result<()> {
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
std::fs::create_dir_all(rules_dir)?;
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let slug = sanitize_slug(&state.entry.id);
|
||||
let out_text = if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
let mut header = String::from("---\npaths:\n");
|
||||
for p in &state.entry.paths {
|
||||
header.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
|
||||
}
|
||||
header.push_str("---\n\n");
|
||||
header.push_str(body);
|
||||
header.push('\n');
|
||||
header
|
||||
} else {
|
||||
format!("{body}\n")
|
||||
};
|
||||
std::fs::write(rules_dir.join(format!("{slug}.md")), out_text)
|
||||
}
|
||||
|
||||
fn collect_staged_text<F>(
|
||||
states: &[AgentMemoryState],
|
||||
provider: &str,
|
||||
_cwd: &Path,
|
||||
_home: Option<&Path>,
|
||||
include: F,
|
||||
) -> String
|
||||
where
|
||||
F: Fn(&AgentMemoryState) -> bool,
|
||||
{
|
||||
let mut buf = String::new();
|
||||
for state in states {
|
||||
if state.mode == AgentMemoryMode::Off || !matches_agent_filter(&state.agents, provider) {
|
||||
continue;
|
||||
}
|
||||
if !include(state) {
|
||||
continue;
|
||||
}
|
||||
// Path-scoped rules only enter un-scoped system prompts when explicitly set to `Always`.
|
||||
if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
continue;
|
||||
};
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let chunk = format!("## Memory ({})\n{}\n\n", state.entry.title, body);
|
||||
if buf.len() + chunk.len() > MAX_STAGED_SYSTEM_BYTES {
|
||||
break;
|
||||
}
|
||||
buf.push_str(&chunk);
|
||||
}
|
||||
buf.trim().to_owned()
|
||||
let root = hermes_root(home).ok_or("Home directory is unavailable")?;
|
||||
let prof_home = hermes::profile_home(&root, provider).unwrap_or(root);
|
||||
write_hermes_config_memory_mode(&prof_home, mode).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
|
||||
@@ -1064,9 +772,7 @@ pub fn promote_memory(
|
||||
pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), String> {
|
||||
let entry = entries.iter().find(|e| e.id == id).ok_or_else(|| format!("Memory entry `{id}` was not found"))?;
|
||||
if !entry.writable {
|
||||
return Err(
|
||||
"Curated instruction and rule files cannot be deleted here; open the file or set its mode to Off.".into()
|
||||
);
|
||||
return Err("Curated instruction and rule files cannot be deleted here; open the file in the editor.".into());
|
||||
}
|
||||
match std::fs::remove_file(&entry.path.0) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -1079,7 +785,7 @@ pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), Strin
|
||||
pub fn reset_provider_memory(provider: &str, workspaces: &[PathBuf], home: Option<&Path>) -> Result<u32, String> {
|
||||
let home = home.ok_or("Home directory is unavailable")?;
|
||||
let mut removed = 0u32;
|
||||
match normalize_provider_id(provider) {
|
||||
match provider_key(provider) {
|
||||
"claude" => {
|
||||
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
|
||||
for f in markdown_files(&dir, 2) {
|
||||
@@ -1134,19 +840,6 @@ fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn sanitize_slug(raw: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in raw.chars() {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
} else if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
}
|
||||
let trimmed = out.trim_matches('-');
|
||||
if trimmed.is_empty() { "memory".into() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn format_markdown_with_frontmatter(
|
||||
description: Option<&str>,
|
||||
paths_key: &str,
|
||||
@@ -1201,17 +894,6 @@ fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply:
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup_entry_policy<'a>(
|
||||
map: &'a BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
id: &str,
|
||||
) -> Option<&'a AgentMemoryEntryPolicy> {
|
||||
map.get(id).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
fn lookup_session_entry(map: &BTreeMap<String, AgentMemoryMode>, id: &str) -> Option<AgentMemoryMode> {
|
||||
map.get(id).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn claude_auto_memory_dirs(claude_home: &Path, home: &Path, workspaces: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -1899,111 +1581,112 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_resolution_enforces_workspace_trust_and_precedence() {
|
||||
fn policy_resolution_enforces_workspace_trust_and_provider_capabilities() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
write(&ws.join("AGENTS.md"), "Workspace instructions\n");
|
||||
write(&home.join(".claude/CLAUDE.md"), "User memory\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
|
||||
let mut ws_settings = AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() };
|
||||
// Untrusted workspace tries to turn user memory `Always` on (ignored!) and another `Off` (honored).
|
||||
ws_settings.entries.insert(
|
||||
"claudeUser::CLAUDE.md".into(),
|
||||
AgentMemoryEntryPolicy { mode: AgentMemoryMode::Always, agents: Vec::new() },
|
||||
);
|
||||
let mut ws_settings = AgentMemorySettings::default();
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("claude".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite });
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("codex".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::Off });
|
||||
|
||||
let untrusted = MemoryPolicy {
|
||||
user: AgentMemorySettings::default(),
|
||||
workspace: ws_settings.clone(),
|
||||
workspace: ws_settings,
|
||||
workspace_trusted: false,
|
||||
workspace_roots: vec![ws.clone()],
|
||||
};
|
||||
let cat = resolve_catalog(entries.clone(), None, &untrusted, Some(&home));
|
||||
// Workspace entry locked `Off` by Trust
|
||||
let ws_state = cat.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state.mode, ws_state.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Trust));
|
||||
// Untrusted workspace could NOT escalate `claudeUser::CLAUDE.md` or `autoMemory`
|
||||
let user_state = cat.entries.iter().find(|s| s.entry.id == "claudeUser::CLAUDE.md").unwrap();
|
||||
assert_eq!((user_state.mode, user_state.origin), (AgentMemoryMode::Auto, AgentMemoryOrigin::None));
|
||||
assert_eq!(cat.auto_memory, AutoMemoryMode::Inherit);
|
||||
assert!(!cat.workspace_trusted);
|
||||
// Untrusted workspace cannot enable Claude auto-memory, but can turn Codex auto-memory off.
|
||||
let claude = cat.providers.iter().find(|p| p.provider == "claude").unwrap();
|
||||
assert_eq!((claude.mode, claude.origin), (AutoMemoryMode::Inherit, AgentMemoryOrigin::None));
|
||||
assert_eq!(claude.supported_modes, [AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off]);
|
||||
let codex = cat.providers.iter().find(|p| p.provider == "codex").unwrap();
|
||||
assert_eq!((codex.mode, codex.origin), (AutoMemoryMode::Off, AgentMemoryOrigin::Workspace));
|
||||
let hermes = cat.providers.iter().find(|p| p.provider == "hermes").unwrap();
|
||||
assert!(hermes.native_config_only);
|
||||
assert_eq!((hermes.mode, hermes.origin), (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native));
|
||||
|
||||
// Session override wins in a trusted workspace
|
||||
// Session override wins in a trusted workspace, and unsupported modes are ignored.
|
||||
let trusted = MemoryPolicy { workspace_trusted: true, ..untrusted };
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("workspace::AGENTS.md".into(), AgentMemoryMode::Off)]),
|
||||
};
|
||||
let cat2 = resolve_catalog(entries, Some(&session), &trusted, Some(&home));
|
||||
assert_eq!((cat2.auto_memory, cat2.auto_memory_origin), (AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session));
|
||||
let ws_state2 = cat2.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state2.mode, ws_state2.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Session));
|
||||
let session_ro = AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) };
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("claude", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Workspace)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("codex", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session)
|
||||
);
|
||||
// External ACP adapters and unsupported providers never report OpenIDEA auto-memory control.
|
||||
assert!(supported_auto_memory_modes("claude-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("codex-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("copilot").is_empty());
|
||||
assert!(supported_auto_memory_modes("cursor").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
|
||||
fn builds_delivery_only_for_native_claude_and_codex_and_keeps_hermes_explicit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
let farm = tmp.path().join("farm");
|
||||
|
||||
write(&ws.join("AGENTS.md"), "Shared workspace rule\n");
|
||||
write(&ws.join("CLAUDE.md"), "Claude-specific rule\n");
|
||||
write(&ws.join("CLAUDE.local.md"), "Noisy local note\n");
|
||||
write(
|
||||
&ws.join(".github/instructions/ipc.instructions.md"),
|
||||
"---\napplyTo: \"crates/**/*.rs\"\n---\nUse async IPC for disk ops.\n",
|
||||
);
|
||||
write(&home.join(".gemini/GEMINI.md"), "Keep PRs focused.\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([
|
||||
("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off),
|
||||
// `Always` delivers another agent's files to every agent, path scope dropped.
|
||||
("githubWorkspace::.github/instructions/ipc.instructions.md".into(), AgentMemoryMode::Always),
|
||||
("geminiUser::GEMINI.md".into(), AgentMemoryMode::Always),
|
||||
]),
|
||||
};
|
||||
let policy = MemoryPolicy { workspace_roots: vec![ws.clone()], workspace_trusted: true, ..Default::default() };
|
||||
let cat = resolve_catalog(entries, Some(&session), &policy, Some(&home));
|
||||
// Claude: Inherit -> None, ReadWrite -> true, Off -> false, ReadOnly -> None
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Inherit), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadOnly), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadWrite).unwrap().claude_auto_memory, Some(true));
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Off).unwrap().claude_auto_memory, Some(false));
|
||||
|
||||
// 1. Claude delivery
|
||||
let claude = stage(&farm, "claude", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(claude.claude_auto_memory, Some(false));
|
||||
assert_eq!(claude.claude_instruction_files.as_deref(), Some("claude-md-and-agents-md"));
|
||||
assert!(claude.claude_md_excludes.iter().any(|p| p.ends_with("CLAUDE.local.md")));
|
||||
assert!(claude.claude_add_dir.is_some());
|
||||
assert!(claude.claude_additional_dirs_claude_md);
|
||||
let staged_rule = std::fs::read_to_string(
|
||||
farm.join(".claude/rules/githubworkspace-github-instructions-ipc-instructions-md.md"),
|
||||
// Codex: ReadWrite / ReadOnly / Off
|
||||
assert_eq!(build_delivery("codex", AutoMemoryMode::Inherit), None);
|
||||
let codex_ro = build_delivery("codex", AutoMemoryMode::ReadOnly).unwrap();
|
||||
assert_eq!(codex_ro.codex_use_memories, Some(true));
|
||||
assert_eq!(codex_ro.codex_generate_memories, Some(false));
|
||||
let codex_off = build_delivery("codex", AutoMemoryMode::Off).unwrap();
|
||||
assert_eq!(codex_off.codex_use_memories, Some(false));
|
||||
assert_eq!(codex_off.codex_generate_memories, Some(false));
|
||||
|
||||
// Copilot, ACP, Hermes produce no session delivery and never touch Hermes config.yaml
|
||||
assert_eq!(build_delivery("copilot", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("acp", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("hermes", AutoMemoryMode::Off), None);
|
||||
assert!(!home.join(".hermes/config.yaml").exists());
|
||||
|
||||
// Explicit Hermes toggle updates config.yaml directly and rejects unsupported modes
|
||||
assert!(set_hermes_auto_memory("hermes", AutoMemoryMode::ReadOnly, Some(&home)).is_err());
|
||||
set_hermes_auto_memory("hermes", AutoMemoryMode::Off, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_and_overrides_deserialize_cleanly() {
|
||||
let legacy_settings: AgentMemorySettings = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "readOnly",
|
||||
"providers": { "codex": { "autoMemory": "off" } },
|
||||
"entries": { "workspace::AGENTS.md": { "mode": "off" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
|
||||
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
|
||||
assert_eq!(legacy_settings.providers["codex"].auto_memory, AutoMemoryMode::Off);
|
||||
|
||||
// 2. Codex delivery
|
||||
let codex = stage(&farm, "codex", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(codex.codex_use_memories, Some(true));
|
||||
assert_eq!(codex.codex_generate_memories, Some(false));
|
||||
assert!(codex.codex_developer_instructions.as_deref().unwrap().contains("Keep PRs focused."));
|
||||
|
||||
// 3. Copilot delivery
|
||||
let copilot = stage(&farm, "copilot", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(copilot.copilot_enable_memory, Some(true));
|
||||
assert!(copilot.copilot_exclude_store_memory);
|
||||
let copilot_message = copilot.copilot_system_message.as_deref().unwrap();
|
||||
assert!(copilot_message.contains("Keep PRs focused."));
|
||||
// Copilot reads `.github/instructions` natively: not repeated in the system message.
|
||||
assert!(!copilot_message.contains("Use async IPC"));
|
||||
|
||||
// 4. Hermes delivery updates config.yaml
|
||||
let _ = stage(&farm, "hermes", &cat.entries, AutoMemoryMode::Off, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
let legacy_overrides: AgentMemoryOverrides = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "off",
|
||||
"entries": { "workspace::AGENTS.md": "off" }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_overrides.auto_memory, Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -204,6 +204,10 @@ pub struct AgentTask {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
/// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub prompt_suggestions: Box<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -769,6 +773,12 @@ pub struct AgentProvider {
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// The built-in agent this one is an instance of.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
/// A built-in agent, of which another instance can be added.
|
||||
#[serde(default)]
|
||||
pub can_duplicate: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -864,6 +874,10 @@ pub struct NewAgentTask {
|
||||
pub isolation: Isolation,
|
||||
/// Branch to start the worktree from; the current branch when `None`.
|
||||
pub base: Option<String>,
|
||||
/// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub worktree_path: Option<IpcPath>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
@@ -1107,8 +1121,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1174,7 +1188,7 @@ impl AgentMemorySource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
/// Which layer decided a provider's effective [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
@@ -1183,8 +1197,8 @@ pub enum AgentMemoryOrigin {
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`).
|
||||
Native,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
@@ -1231,18 +1245,6 @@ pub struct AgentMemoryEntry {
|
||||
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")]
|
||||
@@ -1251,41 +1253,43 @@ pub struct AgentAutoMemoryStatus {
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
/// Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_modes: Vec<AutoMemoryMode>,
|
||||
/// True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
/// rather than a project or per-session override.
|
||||
#[serde(default)]
|
||||
pub native_config_only: bool,
|
||||
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`.
|
||||
/// Full catalog returned to Settings › Agents › Rules & 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 entries: Vec<AgentMemoryEntry>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
pub workspace_trusted: bool,
|
||||
}
|
||||
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
/// Per-session auto-memory override stored on an [`AgentTask`] or automation.
|
||||
#[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()
|
||||
self.auto_memory.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1876,13 +1880,16 @@ pub struct McpProbeResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
|
||||
/// launches as its base does when `command` is empty); the id becomes the
|
||||
/// `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CustomAgentInput {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub base: Option<String>,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
|
||||
@@ -174,13 +174,9 @@ 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`).
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
@@ -400,11 +396,6 @@ impl Shim {
|
||||
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,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
@@ -774,11 +765,6 @@ 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()]);
|
||||
}
|
||||
@@ -789,12 +775,7 @@ impl Session {
|
||||
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 env = shim.config.env.clone();
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
@@ -1657,8 +1638,8 @@ 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.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with
|
||||
/// `autoMemoryEnabled` from `_meta.openidea.memory` 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"))
|
||||
@@ -1666,27 +1647,8 @@ fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<
|
||||
.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 }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(auto) = memory.and_then(|m| m.get("claudeAutoMemory")).and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
|
||||
@@ -1553,7 +1553,7 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
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();
|
||||
@@ -1569,45 +1569,8 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"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"
|
||||
"autoMemory": "off",
|
||||
"claudeAutoMemory": false
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
@@ -1615,12 +1578,12 @@ async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_inje
|
||||
});
|
||||
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.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());
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert!(parsed.get("claudeMdExcludes").is_none());
|
||||
assert!(parsed.get("pluginConfigs").is_none());
|
||||
}
|
||||
@@ -385,18 +385,25 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let use_m = mem.get("codexUseMemories").and_then(Value::as_bool);
|
||||
let gen_m = mem.get("codexGenerateMemories").and_then(Value::as_bool);
|
||||
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(v) = use_m {
|
||||
mem_cfg.insert("use_memories".into(), json!(v));
|
||||
}
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
if let Some(v) = gen_m {
|
||||
mem_cfg.insert("generate_memories".into(), json!(v));
|
||||
}
|
||||
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));
|
||||
// Codex's `memories` feature flag defaults to `false`; turn it on whenever the user
|
||||
// explicitly asks to read or generate memories.
|
||||
if use_m == Some(true) || gen_m == Some(true) {
|
||||
let features = map.entry("features".to_owned()).or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if let Some(f) = features.as_object_mut() {
|
||||
f.insert("memories".into(), json!(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
|
||||
@@ -131,6 +131,7 @@ for line in sys.stdin:
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
base: None,
|
||||
};
|
||||
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
|
||||
let models: Vec<_> = found
|
||||
@@ -2226,8 +2227,7 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2235,8 +2235,27 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
&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"]["features"]["memories"], true);
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
|
||||
let mut off_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"codexUseMemories": false,
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut off_req,
|
||||
);
|
||||
assert_eq!(off_req["config"]["memories"], json!({ "use_memories": false, "generate_memories": false }));
|
||||
assert!(off_req["config"].get("features").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -471,38 +471,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)
|
||||
}
|
||||
@@ -630,7 +598,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
|
||||
@@ -701,7 +668,6 @@ 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();
|
||||
|
||||
@@ -953,56 +953,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!({
|
||||
|
||||
@@ -18,8 +18,49 @@ pub(crate) mod codex;
|
||||
pub(crate) mod copilot;
|
||||
|
||||
use ide_jsonrpc::{Framing, Handler, Peer};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
const VERSION_CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct VersionCacheKey {
|
||||
path: PathBuf,
|
||||
modified: Option<SystemTime>,
|
||||
len: Option<u64>,
|
||||
#[cfg(unix)]
|
||||
ino: Option<u64>,
|
||||
}
|
||||
|
||||
impl VersionCacheKey {
|
||||
fn of(real: &Path) -> Self {
|
||||
let meta = std::fs::metadata(real).ok();
|
||||
#[cfg(unix)]
|
||||
let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino);
|
||||
Self {
|
||||
path: real.to_path_buf(),
|
||||
modified: meta.as_ref().and_then(|m| m.modified().ok()),
|
||||
len: meta.as_ref().map(std::fs::Metadata::len),
|
||||
#[cfg(unix)]
|
||||
ino,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedVersion {
|
||||
version: Vec<u64>,
|
||||
checked_at: Instant,
|
||||
}
|
||||
|
||||
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
|
||||
|
||||
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = OnceLock::new();
|
||||
CACHE.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
|
||||
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
|
||||
@@ -38,27 +79,69 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
let names =
|
||||
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
|
||||
let mut seen = Vec::new();
|
||||
let candidates: Vec<PathBuf> = std::env::split_paths(search)
|
||||
let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
|
||||
.filter(|p| p.is_file())
|
||||
.filter(|p| {
|
||||
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
|
||||
let new = !seen.contains(&real);
|
||||
seen.push(real);
|
||||
new
|
||||
.filter_map(|p| {
|
||||
let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
|
||||
if seen.contains(&real) {
|
||||
return None;
|
||||
}
|
||||
seen.push(real.clone());
|
||||
Some((p, real))
|
||||
})
|
||||
.collect();
|
||||
if candidates.len() < 2 {
|
||||
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
return candidates
|
||||
.into_iter()
|
||||
.next()
|
||||
.map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned());
|
||||
}
|
||||
// Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning
|
||||
// `--version` on concurrent or repeated lookups while still noticing upgraded binaries.
|
||||
let versions: Vec<Option<Vec<u64>>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect();
|
||||
handles.into_iter().map(|h| h.join().ok().flatten()).collect()
|
||||
});
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter_map(|p| version_of(&p).map(|v| (v, p)))
|
||||
.zip(versions)
|
||||
.filter_map(|((p, _), v)| v.map(|v| (v, p)))
|
||||
.max_by(|a, b| a.0.cmp(&b.0))
|
||||
.map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn cached_version_of(program: &Path, real: &Path) -> Option<Vec<u64>> {
|
||||
let key = VersionCacheKey::of(real);
|
||||
let slot = {
|
||||
let mut cache = version_cache().lock();
|
||||
if cache.len() > 64 {
|
||||
cache.retain(|_, slot| {
|
||||
slot.try_lock()
|
||||
.is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL))
|
||||
});
|
||||
}
|
||||
cache.entry(key).or_default().clone()
|
||||
};
|
||||
let mut guard = slot.lock();
|
||||
if let Some(cached) = guard.as_ref()
|
||||
&& cached.checked_at.elapsed() < VERSION_CACHE_TTL
|
||||
{
|
||||
return Some(cached.version.clone());
|
||||
}
|
||||
match version_of(program) {
|
||||
Some(version) => {
|
||||
*guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() });
|
||||
Some(version)
|
||||
}
|
||||
None => {
|
||||
*guard = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `x.y.z` from `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
|
||||
fn version_of(program: &Path) -> Option<Vec<u64>> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
@@ -144,4 +227,77 @@ mod tests {
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_caches_versions_and_invalidates_on_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
|
||||
// Replacing the older binary with a newer version invalidates only its cache entry.
|
||||
let upgraded = old.join("agent");
|
||||
std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_deduplicates_concurrent_probes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
let expected = new.join("agent").to_string_lossy().into_owned();
|
||||
let barrier = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
newest_install_in("agent", &search)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
assert_eq!(handle.join().unwrap(), expected);
|
||||
}
|
||||
});
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ pub(crate) struct ProviderSpec {
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
pub source: AgentSource,
|
||||
/// The built-in agent an instance copies (its identity); `None` for every other agent.
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
|
||||
@@ -108,11 +110,17 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
base: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
/// The built-in id this agent is an instance of, or else its own id.
|
||||
pub(crate) fn base_id(&self) -> &str {
|
||||
self.base.as_deref().unwrap_or(&self.id)
|
||||
}
|
||||
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
@@ -122,7 +130,7 @@ impl ProviderSpec {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let builtin = builtin_spec(self.base_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))
|
||||
}
|
||||
@@ -161,7 +169,7 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let is_copilot = is_copilot_provider(self.base_id());
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
@@ -191,7 +199,7 @@ impl ProviderSpec {
|
||||
} else if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
@@ -217,7 +225,7 @@ impl ProviderSpec {
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
if let Some((separate_cmd, separate_args)) = match self.base_id() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
@@ -231,7 +239,7 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id)
|
||||
if let Some(builtin) = builtin_spec(self.base_id())
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
@@ -241,7 +249,7 @@ impl ProviderSpec {
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
@@ -532,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with(
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
|
||||
let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() };
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
@@ -620,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if spec.base.is_some() {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
} else if let Some(default) = &builtin {
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
@@ -649,6 +659,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
cli_install_command: None,
|
||||
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(),
|
||||
base: spec.base.clone(),
|
||||
can_duplicate: builtin.is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -687,13 +699,17 @@ pub(crate) fn set_builtin_additional_args(
|
||||
})
|
||||
}
|
||||
|
||||
/// The environment built-in `id` starts with, through its agent file (empty clears it).
|
||||
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
|
||||
/// (empty clears it).
|
||||
pub(crate) fn set_builtin_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if builtin_spec(id).is_none() {
|
||||
return set_instance_env(custom_dir, secrets, id, env);
|
||||
}
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
@@ -725,6 +741,26 @@ pub(crate) fn set_builtin_env(
|
||||
})
|
||||
}
|
||||
|
||||
/// An instance's environment is all its own: never merged with its base's.
|
||||
fn set_instance_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
let id = validated_custom_id(id)?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
|
||||
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
|
||||
agent
|
||||
}
|
||||
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
|
||||
};
|
||||
agent.env = env;
|
||||
agent.write_with(&file, &id, secrets)
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
@@ -741,6 +777,7 @@ fn update_builtin(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(builtin.name.clone()),
|
||||
base: None,
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
@@ -786,7 +823,8 @@ fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem.
|
||||
/// a safe file stem. An instance of a built-in (`base`) may leave the command
|
||||
/// empty to launch as its base does.
|
||||
pub(crate) fn save_custom(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
@@ -796,9 +834,19 @@ pub(crate) fn save_custom(
|
||||
if builtin_spec(&id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
|
||||
}
|
||||
if input.command.trim().is_empty() {
|
||||
let base = match input.base.as_deref() {
|
||||
Some(base) => {
|
||||
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let inherits = input.command.trim().is_empty();
|
||||
if inherits && base.is_none() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
if inherits && !input.args.is_empty() {
|
||||
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
@@ -811,8 +859,9 @@ pub(crate) fn save_custom(
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some(input.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
|
||||
command: if inherits { String::new() } else { input.command.clone() },
|
||||
base: base.map(|b| b.id),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
@@ -884,6 +933,7 @@ pub(crate) fn import_acp(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(outcome.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
@@ -926,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String {
|
||||
pub(crate) struct CustomAgent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Driver::is_acp")]
|
||||
pub driver: Driver,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
@@ -956,9 +1010,13 @@ impl Driver {
|
||||
|
||||
impl CustomAgent {
|
||||
pub(crate) fn read(path: &Path) -> Result<Self, String> {
|
||||
std::fs::read_to_string(path)
|
||||
let agent = std::fs::read_to_string(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
|
||||
if agent.command.is_empty() && agent.base.is_none() {
|
||||
return Err("missing field `command`".into());
|
||||
}
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Writes the file atomically (a reader never sees half of it).
|
||||
@@ -1030,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
|
||||
}
|
||||
|
||||
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
|
||||
/// built-in id replaces it.
|
||||
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
|
||||
/// the built-in as its own file left it, so file order does not matter.
|
||||
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
|
||||
let mut specs = builtins();
|
||||
let mut files: Vec<PathBuf> = custom_dir
|
||||
@@ -1042,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
|
||||
.collect();
|
||||
files.sort();
|
||||
let mut instances = Vec::new();
|
||||
for path in files {
|
||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
|
||||
let explicit_driver = std::fs::read_to_string(&path)
|
||||
@@ -1055,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(base) = agent.base.clone() {
|
||||
if builtin_spec(&id).is_some() {
|
||||
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
|
||||
} else if agent.registry.is_some() {
|
||||
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
|
||||
} else if builtin_spec(&base).is_none() {
|
||||
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
|
||||
} else {
|
||||
instances.push((id, agent));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let env: Vec<(String, String)> = agent.env.into_iter().collect();
|
||||
let source = match agent.registry {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
@@ -1070,6 +1142,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
base: None,
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
@@ -1097,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
for (id, agent) in instances {
|
||||
let base = agent.base.expect("instances have a base");
|
||||
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
|
||||
let (driver, command, args) = if agent.command.is_empty() {
|
||||
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
|
||||
} else {
|
||||
(agent.driver, agent.command, agent.args)
|
||||
};
|
||||
let login_hint = base_spec.login_hint.clone();
|
||||
// Copies of one agent follow it, in the order of their file names.
|
||||
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
|
||||
specs.insert(
|
||||
at,
|
||||
ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver,
|
||||
command,
|
||||
managed_cli: None,
|
||||
args,
|
||||
additional_args_len: 0,
|
||||
env: agent.env.into_iter().collect(),
|
||||
login_hint,
|
||||
source: AgentSource::Custom,
|
||||
base: Some(base),
|
||||
id,
|
||||
},
|
||||
);
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
@@ -1169,6 +1270,7 @@ mod tests {
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
@@ -1509,6 +1611,7 @@ mod tests {
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
@@ -1566,6 +1669,7 @@ mod tests {
|
||||
let path = dir.path().join("codex.toml");
|
||||
CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
@@ -1592,6 +1696,7 @@ mod tests {
|
||||
for field in ["name", "driver", "args", "env", "unnamed"] {
|
||||
let mut agent = CustomAgent {
|
||||
name: Some("Claude Code".into()),
|
||||
base: None,
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
@@ -1646,6 +1751,7 @@ mod tests {
|
||||
let path = dir.path().join("agents").join("amp-acp.toml");
|
||||
let agent = CustomAgent {
|
||||
name: Some("Amp".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
@@ -1666,6 +1772,7 @@ mod tests {
|
||||
CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec!["acp".into()],
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
@@ -1887,4 +1994,188 @@ github.com
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
|
||||
fn write_agent(dir: &Path, id: &str, text: &str) {
|
||||
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
|
||||
}
|
||||
|
||||
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
|
||||
load(Some(dir), None).into_iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inherit_the_base_launch_whatever_the_file_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance =
|
||||
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
|
||||
// `a-claude` sorts before the base's own file, `z-claude` after it.
|
||||
write_agent(dir.path(), "a-claude", instance);
|
||||
write_agent(dir.path(), "z-claude", instance);
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"claude",
|
||||
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
|
||||
);
|
||||
let builtin = builtin_spec("claude").unwrap();
|
||||
for id in ["a-claude", "z-claude"] {
|
||||
let spec = spec_of(dir.path(), id).unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
|
||||
assert_eq!(spec.args, builtin.args);
|
||||
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
|
||||
assert_eq!(spec.login_hint, builtin.login_hint);
|
||||
assert_eq!(
|
||||
(&spec.source, spec.base.as_deref(), spec.base_id()),
|
||||
(&AgentSource::Custom, Some("claude"), "claude")
|
||||
);
|
||||
assert_eq!(spec.name, "Claude Work");
|
||||
}
|
||||
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
|
||||
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_follow_their_base_in_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
|
||||
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
|
||||
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
|
||||
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
|
||||
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
|
||||
assert_eq!(at("codex-2"), at("codex") + 1);
|
||||
assert_eq!(at("mine"), ids.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_with_its_own_command_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"codex-2",
|
||||
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
|
||||
);
|
||||
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
|
||||
let spec = spec_of(dir.path(), "codex-2").unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
|
||||
assert_eq!(spec.args, ["app-server", "-v"]);
|
||||
assert_eq!(spec.base.as_deref(), Some("codex"));
|
||||
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_instances_are_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
|
||||
write_agent(dir.path(), "first", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "chained", "base = \"first\"\n");
|
||||
write_agent(dir.path(), "codex", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
|
||||
let specs = load(Some(dir.path()), None);
|
||||
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["first"]);
|
||||
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_custom_writes_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = |id: &str, base: &str| CustomAgentInput {
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
..custom_input(id)
|
||||
};
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert_eq!(
|
||||
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
|
||||
(Driver::Claude, "claude", Some("claude"))
|
||||
);
|
||||
|
||||
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
|
||||
.unwrap();
|
||||
let own = spec_of(dir.path(), "own").unwrap();
|
||||
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
|
||||
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
|
||||
.unwrap_err();
|
||||
assert!(!dir.path().join("other.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_describe_their_base() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n");
|
||||
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
|
||||
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
|
||||
let work = info("work");
|
||||
assert_eq!(work.base.as_deref(), Some("claude"));
|
||||
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
|
||||
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
|
||||
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
|
||||
let claude = info("claude");
|
||||
assert!(claude.can_duplicate && claude.base.is_none());
|
||||
let mine = info("mine");
|
||||
assert!(!mine.can_duplicate && mine.base.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn instances_sign_in_with_their_own_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("claude");
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert!(spec.can_sign_in(dir.path(), None));
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert!(launch.args.is_empty());
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secrets = MemorySecrets::default();
|
||||
let s = Some(&secrets as &dyn EnvSecrets);
|
||||
let instance = CustomAgentInput {
|
||||
base: Some("copilot".into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
..custom_input("copilot-work")
|
||||
};
|
||||
save_custom(dir.path(), s, &instance).unwrap();
|
||||
let env = BTreeMap::from([
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
|
||||
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
|
||||
]);
|
||||
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
|
||||
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
|
||||
assert_eq!(describe(&spec).env, env);
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
|
||||
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
|
||||
|
||||
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
|
||||
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
|
||||
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
|
||||
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
|
||||
assert!(secrets.keys("agent/bad-base/").is_empty());
|
||||
remove_custom(dir.path(), s, "copilot-work").unwrap();
|
||||
assert!(!dir.path().join("copilot-work.toml").exists());
|
||||
assert!(secrets.keys("agent/copilot-work/").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -587,6 +587,7 @@ fn install_entry_with(
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
@@ -985,6 +986,7 @@ mod tests {
|
||||
let entries = parse(INDEX).unwrap();
|
||||
let installed = |id: &str, version: &str| CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
@@ -1222,6 +1224,7 @@ esac
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
|
||||
@@ -49,6 +49,8 @@ struct FakeAgent {
|
||||
/// Hold the late mode reply until the prompt's permission request is already waiting.
|
||||
hold_late_mode: bool,
|
||||
empty_config: AtomicBool,
|
||||
/// Text sent as an agent message when a session opens, before any prompt (pi-acp's startup info).
|
||||
startup_notice: Mutex<Option<String>>,
|
||||
/// Blocks `session/new` until discovery times out (see `acp::discover` test timeout).
|
||||
hold_session_new: AtomicBool,
|
||||
/// Sleeps this long at the start of `session/set_config_option`, after noting the time.
|
||||
@@ -77,6 +79,10 @@ struct FakeAgent {
|
||||
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
|
||||
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
|
||||
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
|
||||
/// What the client answered to the requests sent with [`FakeAgent::ask_aside`], by label.
|
||||
aside: Arc<Mutex<Vec<(String, Value)>>>,
|
||||
/// How far a test let a scenario that waits for it go on.
|
||||
go: AtomicU32,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -144,6 +150,117 @@ impl FakeAgent {
|
||||
);
|
||||
self.say(root, "Found it");
|
||||
}
|
||||
|
||||
/// Sends a request without waiting for its answer, as a subagent working beside its
|
||||
/// parent does; the answer is noted in `aside` under `label`.
|
||||
fn ask_aside(&self, label: &str, method: &str, params: Value) {
|
||||
let (peer, aside, label, method) = (self.latest(), self.aside.clone(), label.to_owned(), method.to_owned());
|
||||
tokio::runtime::Handle::current().spawn(async move {
|
||||
let answer = peer.request::<_, Value>(&method, params, None).await;
|
||||
aside.lock().push((label, answer.unwrap_or_else(|e| json!(e.to_string()))));
|
||||
});
|
||||
}
|
||||
|
||||
/// Waits up to 5 s for `done`.
|
||||
fn wait_until(&self, done: impl Fn(&Self) -> bool) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !done(self) && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until the test lets the scenario past `step` (see `go`), for at most 10 s.
|
||||
async fn step(&self, step: u32) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
|
||||
while self.go.load(Ordering::Acquire) < step && tokio::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subagent `c1` of `root` asks for permission while it works, and the turn goes on as
|
||||
/// `then` says.
|
||||
fn subagent_asks(&self, root: &str, then: &str) -> Value {
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "subagent_update", "sessionId": "c1", "title": "Explore",
|
||||
"capabilities": {"cancel": {}}, "state": {"state": "running"}}),
|
||||
);
|
||||
self.ask_aside(
|
||||
"permission",
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t1", "title": "Run ls"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
);
|
||||
let stopped = || {
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "subagent_update", "sessionId": "c1",
|
||||
"state": {"state": "idle", "stopReason": "cancelled"}}),
|
||||
)
|
||||
};
|
||||
let cancelled = |agent: &Self| agent.calls.lock().iter().any(|c| c == "session/cancel");
|
||||
match then {
|
||||
// Stop Subagent: the agent reports the subagent stopped once its requests are answered.
|
||||
"the user stops it" => {
|
||||
self.ask_aside(
|
||||
"form",
|
||||
"elicitation/create",
|
||||
json!({"sessionId": "c1", "mode": "form", "message": "Which layout?",
|
||||
"requestedSchema": {"type": "object", "properties": {"layout": {"type": "string", "title": "Layout"}}}}),
|
||||
);
|
||||
self.wait_until(cancelled);
|
||||
self.wait_until(|agent| agent.aside.lock().len() == 2);
|
||||
stopped();
|
||||
}
|
||||
"it stops" => {
|
||||
self.wait_until(|agent| agent.go.load(Ordering::Acquire) >= 1);
|
||||
stopped();
|
||||
self.wait_until(|agent| !agent.aside.lock().is_empty());
|
||||
}
|
||||
// The subagent works on after the turn it started in.
|
||||
"the user stops the task" => {
|
||||
self.wait_until(cancelled);
|
||||
return json!({"stopReason": "cancelled"});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
json!({"stopReason": "end_turn"})
|
||||
}
|
||||
|
||||
/// Asks twice and takes both requests back at step 1: the first with ACP's
|
||||
/// `$/cancel_request`, the second as a `Peer` does when its request is cancelled
|
||||
/// (`$/cancelRequest`). The turn ends at step 2.
|
||||
fn asks_then_withdraws(&self, session: &str) {
|
||||
let peer = self.latest();
|
||||
let token = ide_core::CancellationToken::new();
|
||||
let ask = |title: &str, cancel| {
|
||||
peer.request::<_, Value>(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session, "toolCall": {"toolCallId": title, "title": title},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
cancel,
|
||||
)
|
||||
};
|
||||
let first = async {
|
||||
tokio::select! {
|
||||
biased;
|
||||
answer = ask("Run make", None) => {
|
||||
self.aside.lock().push(("first".to_owned(), answer.unwrap_or_else(|e| json!(e.to_string()))));
|
||||
}
|
||||
() = self.step(2) => {}
|
||||
}
|
||||
};
|
||||
let take_back = async {
|
||||
self.step(1).await;
|
||||
// The first request is this connection's first, which `Peer` numbers 1.
|
||||
peer.notify("$/cancel_request", json!({"requestId": 1})).unwrap();
|
||||
token.cancel();
|
||||
self.step(2).await;
|
||||
};
|
||||
let second = ask("Run make test", Some(token.clone()));
|
||||
// Polled in order, so the first request is sent first.
|
||||
let _ = tokio::runtime::Handle::current().block_on(async { tokio::join!(biased; first, second, take_back) });
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for FakeAgent {
|
||||
@@ -221,6 +338,9 @@ impl Handler for FakeAgent {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
if let Some(notice) = self.startup_notice.lock().clone() {
|
||||
self.say("s1", ¬ice);
|
||||
}
|
||||
if self.empty_config.load(Ordering::Acquire) {
|
||||
return Ok(json!({"sessionId": "s1"}));
|
||||
}
|
||||
@@ -367,6 +487,17 @@ impl Handler for FakeAgent {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if let Some(then) = text.strip_prefix("subagent asks, then ") {
|
||||
return Ok(self.subagent_asks(&session, then));
|
||||
}
|
||||
if text == "ask, then withdraw" {
|
||||
self.asks_then_withdraws(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if let Some(reason) = text.strip_prefix("stop with ") {
|
||||
self.say(&session, "Here is the fix:\n```rust\nfn parse(input: &str) -> Result<");
|
||||
return Ok(json!({"stopReason": reason}));
|
||||
}
|
||||
if text == "late option" {
|
||||
// An option the session offers only once it runs.
|
||||
self.update(
|
||||
@@ -919,6 +1050,37 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn text_the_agent_sends_before_the_prompt_is_not_part_of_the_reply() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.startup_notice.lock() = Some("pi v1.5.2\n---\n## Context\n- AGENTS.md\n".into());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
ephemeral: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let replies: Vec<String> = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
AgentEntry::Agent { text } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(replies.last().map(String::as_str), Some("second turn"));
|
||||
assert!(replies.iter().any(|t| t.starts_with("pi v1.5.2")));
|
||||
shut_down(&mgr, &agent).await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_commands_share_catalog_discovery_and_persist_results() {
|
||||
@@ -1395,6 +1557,31 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
|
||||
}
|
||||
|
||||
fn instance_of(id: &str, base: &str) -> crate::CustomAgentInput {
|
||||
crate::CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_offer_the_commands_of_their_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
mgr.save_custom_agent(instance_of("codex-work", "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
assert_eq!((mgr.base_provider_id("codex-work"), mgr.base_provider_id("custom")), ("codex".into(), "custom".into()));
|
||||
let names = |commands: Vec<AgentCommand>| commands.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let instance = names(mgr.commands("codex-work", None).await.unwrap());
|
||||
assert!(instance.iter().any(|name| name == "review"), "{instance:?}");
|
||||
assert_eq!(instance, names(mgr.commands("codex", None).await.unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2272,14 +2459,25 @@ 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.
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks,
|
||||
/// also when the task runs an instance of Codex.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
for provider in ["codex", "codex-work"] {
|
||||
codex_writer_conflict_forks_on_a_new_connection(provider).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn codex_writer_conflict_forks_on_a_new_connection(provider: &str) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
if provider != "codex" {
|
||||
mgr.save_custom_agent(instance_of(provider, "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
}
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.create(NewAgentTask { prompt: text("again"), provider: provider.into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
@@ -2854,6 +3052,184 @@ async fn subagents_get_their_own_conversation() {
|
||||
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
|
||||
}
|
||||
|
||||
/// A task started with `prompt` against a fake agent of its own.
|
||||
async fn started(dir: &Path, prompt: &str) -> (Arc<FakeAgent>, AgentManager, String) {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(dir, agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text(prompt), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
(agent, mgr, task.id)
|
||||
}
|
||||
|
||||
/// The ids of the requests task `id` shows unanswered, once there are `n`.
|
||||
async fn open_requests(mgr: &AgentManager, id: &str, n: usize) -> Vec<u32> {
|
||||
for _ in 0..500 {
|
||||
let open: Vec<u32> = mgr
|
||||
.entries(id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
AgentEntry::Permission { id, chosen: None, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if open.len() == n {
|
||||
return open;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("task never showed {n} open requests");
|
||||
}
|
||||
|
||||
/// What the card of request `request` records as chosen.
|
||||
fn chosen(mgr: &AgentManager, id: &str, request: u32) -> Option<String> {
|
||||
mgr.entries(id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, chosen, .. } if id == request => Some(chosen),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Waits up to 5 s for `done`.
|
||||
async fn until(done: impl Fn() -> bool) {
|
||||
for _ in 0..500 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent's answers to the requests it sent aside, by label.
|
||||
fn aside_answers(agent: &FakeAgent) -> Vec<(String, Value)> {
|
||||
let mut answers = agent.aside.lock().clone();
|
||||
answers.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
answers
|
||||
}
|
||||
|
||||
fn cancelled() -> Value {
|
||||
json!({"outcome": {"outcome": "cancelled"}})
|
||||
}
|
||||
|
||||
/// Stopping a subagent answers what it asked as cancelled, before the agent reports it stopped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stopping_a_subagent_cancels_its_open_requests() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then the user stops it").await;
|
||||
let requests = open_requests(&mgr, &task, 2).await;
|
||||
mgr.cancel(&task, Some("c1".into())).unwrap();
|
||||
until(|| agent.aside.lock().len() == 2).await;
|
||||
let answers = aside_answers(&agent);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let cards: Vec<_> = requests.iter().map(|&r| chosen(&mgr, &task, r)).collect();
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(answers, [("form".to_owned(), json!({"action": "cancel"})), ("permission".to_owned(), cancelled())]);
|
||||
assert_eq!(cards, [Some("Cancelled".to_owned()), Some("Cancelled".to_owned())]);
|
||||
}
|
||||
|
||||
/// A subagent that works on keeps its request when the task's turn is stopped and ends: the
|
||||
/// user can still answer it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_subagent_keeps_its_open_request_past_the_stopped_turn() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then the user stops the task").await;
|
||||
let request = open_requests(&mgr, &task, 1).await[0];
|
||||
mgr.cancel(&task, None).unwrap();
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let after_the_turn = (chosen(&mgr, &task, request), aside_answers(&agent));
|
||||
let answered = mgr.respond(&task, request, Some("yes".into()));
|
||||
until(|| !agent.aside.lock().is_empty()).await;
|
||||
let answers = aside_answers(&agent);
|
||||
let card = chosen(&mgr, &task, request);
|
||||
|
||||
// It asks again with no turn running; answered, the task is Ready again.
|
||||
let peer = agent.latest();
|
||||
let again = tokio::spawn(async move {
|
||||
peer.request::<_, Value>(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t2", "title": "Run pwd"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
});
|
||||
wait_for(&mgr, &task, AgentStatus::NeedsInput).await;
|
||||
let second = open_requests(&mgr, &task, 1).await[0];
|
||||
mgr.respond(&task, second, Some("yes".into())).unwrap();
|
||||
let _ = again.await;
|
||||
let status = mgr.task(&task).unwrap().state.lock().task.status;
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(after_the_turn, (None, Vec::new()));
|
||||
assert!(answered.is_ok(), "{answered:?}");
|
||||
assert_eq!(answers, [("permission".to_owned(), json!({"outcome": {"outcome": "selected", "optionId": "yes"}}))]);
|
||||
assert_eq!(card.as_deref(), Some("Allow"));
|
||||
assert_eq!(status, AgentStatus::Ready);
|
||||
}
|
||||
|
||||
/// A subagent that stops has no use for what it still waits for: its requests are cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_subagent_that_stops_has_its_open_request_cancelled() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "subagent asks, then it stops").await;
|
||||
let request = open_requests(&mgr, &task, 1).await[0];
|
||||
agent.go.store(1, Ordering::Release);
|
||||
until(|| !agent.aside.lock().is_empty()).await;
|
||||
let answers = aside_answers(&agent);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
let card = chosen(&mgr, &task, request);
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(answers, [("permission".to_owned(), cancelled())]);
|
||||
assert_eq!(card.as_deref(), Some("Cancelled"));
|
||||
}
|
||||
|
||||
/// A request the agent takes back closes while the turn goes on, answered as cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_agent_can_withdraw_its_requests() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (agent, mgr, task) = started(tmp.path(), "ask, then withdraw").await;
|
||||
let requests = open_requests(&mgr, &task, 2).await;
|
||||
agent.go.store(1, Ordering::Release);
|
||||
let closed = || requests.iter().all(|&r| chosen(&mgr, &task, r).is_some());
|
||||
until(|| closed() && !agent.aside.lock().is_empty()).await;
|
||||
let cards: Vec<_> = requests.iter().map(|&r| chosen(&mgr, &task, r)).collect();
|
||||
let answers = aside_answers(&agent);
|
||||
agent.go.store(2, Ordering::Release);
|
||||
wait_for(&mgr, &task, AgentStatus::Ready).await;
|
||||
shut_down(&mgr, &agent).await;
|
||||
assert_eq!(cards, [Some("Cancelled".to_owned()), Some("Cancelled".to_owned())]);
|
||||
assert_eq!(answers, [("first".to_owned(), cancelled())]);
|
||||
}
|
||||
|
||||
/// A turn that ends at one of the agent's limits says so, as a refusal does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_turn_stopped_by_a_limit_says_so() {
|
||||
for (reason, message) in [
|
||||
("max_tokens", "The reply was cut off: the agent reached its output token limit."),
|
||||
("max_turn_requests", "The turn stopped: the agent reached its limit of model requests per turn."),
|
||||
("refusal", "The agent declined to continue."),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text(&format!("stop with {reason}")),
|
||||
provider: "claude".into(),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Error { message: message.into() }), "{reason}: {entries:?}");
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_blocks_declare_the_type_of_their_bytes() {
|
||||
let image = |mime: &str, data: &str| AgentImage {
|
||||
@@ -3394,7 +3770,7 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
let epoch = handle.shared.shutdown_epoch();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, epoch))
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms, None, epoch))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
@@ -4079,6 +4455,56 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
/// A model request reaches the catalogs from a blocking task, so it may arrive after a newer
|
||||
/// selection's; arriving late, it must not supersede (and abort) the newer discovery.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_late_model_request_never_supersedes_a_newer_discovery() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.model_options.lock() = HashMap::from([
|
||||
("big".into(), effort_options(&["low", "high"], "high")),
|
||||
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
|
||||
("plain".into(), vec![]),
|
||||
]);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude-acp".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
let restored = Arc::new(manager(tmp.path(), agent.clone()));
|
||||
let (catalogs, shared) = (restored.shared.paths.catalogs.clone(), restored.shared.clone());
|
||||
let spec = || shared.spec("claude-acp").unwrap();
|
||||
|
||||
let late = catalogs.ticket();
|
||||
let (release, gate) = std::sync::mpsc::channel();
|
||||
*agent.model_config_gate.lock() = Some(gate);
|
||||
let newer = {
|
||||
let (catalogs, shared) = (catalogs.clone(), shared.clone());
|
||||
tokio::spawn(async move { catalogs.load_levels(&shared, "claude-acp", "plain").await })
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while agent.model_config_gate.lock().is_some() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())));
|
||||
|
||||
catalogs.request_as_of(&shared, spec(), "small", late);
|
||||
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())), "not superseded");
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(newer.await.unwrap().unwrap(), Vec::<AgentConfigOption>::new());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
|
||||
for value in [None, Some("false"), Some("true")] {
|
||||
@@ -4229,6 +4655,59 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Saving or dropping a Cursor instance on disk is reflected on the very first `providers()` call.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn new_cursor_instance_has_approval_option_on_first_providers_call() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
// Saved through the API: base_provider_id and providers() see it immediately without reload_providers().
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
assert_eq!(mgr.base_provider_id("cursor-work"), "cursor");
|
||||
// Hand-written on disk: providers() updates its cache before mapping per-provider options.
|
||||
std::fs::write(tmp.path().join("agents/cursor-disk.toml"), "base = \"cursor\"\nname = \"Cursor Disk\"\n").unwrap();
|
||||
let list = mgr.providers();
|
||||
for id in ["cursor-work", "cursor-disk"] {
|
||||
let info = list.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(info.config.iter().any(|o| o.id == config::CURSOR_APPROVAL), "{id}: {:?}", info.config);
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance of Cursor offers Cursor's client-side approval option, and a scheduled turn
|
||||
/// clamps it as it clamps Cursor's own.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_take_the_approval_options_and_automation_clamp_of_their_base() {
|
||||
for provider in ["cursor", "cursor-work"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
mgr.reload_providers();
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: provider.into(),
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let approval = || {
|
||||
let snapshot = mgr.task_snapshot(&task.id).unwrap();
|
||||
snapshot.config.iter().find(|o| o.id == config::CURSOR_APPROVAL).and_then(|o| o.current.clone())
|
||||
};
|
||||
assert_eq!(approval().as_deref(), Some("bypass"), "{provider}");
|
||||
let meta = ScheduledTurnMeta {
|
||||
permissions: Some(automation::AutomationPermissionMode::Default),
|
||||
..Default::default()
|
||||
};
|
||||
mgr.prompt_scheduled(&task.id, text("again"), meta).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(approval().as_deref(), Some("ask"), "{provider}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() {
|
||||
for prompt in ["ask", "qwen ask"] {
|
||||
@@ -6559,6 +7038,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -6592,25 +7072,28 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
|
||||
async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() {
|
||||
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() },
|
||||
user: AgentMemorySettings {
|
||||
providers: BTreeMap::from([
|
||||
("claude".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
("codex".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
]),
|
||||
},
|
||||
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.
|
||||
// 1. Native Claude task with initial `Off`, then updated while idle, then forked.
|
||||
let claude_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6619,12 +7102,10 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: 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)]),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6635,51 +7116,64 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
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["autoMemory"], "off");
|
||||
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`.
|
||||
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `ReadWrite`.
|
||||
let updated = mgr
|
||||
.set_memory_overrides(
|
||||
&claude_task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.set_memory_overrides(&claude_task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadWrite) })
|
||||
.unwrap();
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
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");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readWrite");
|
||||
assert_eq!(mem["claudeAutoMemory"], true);
|
||||
}
|
||||
|
||||
// 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));
|
||||
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/fork");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "off");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "readWrite");
|
||||
}
|
||||
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),
|
||||
] {
|
||||
// 2. Native Codex delivers `codexUseMemories` / `codexGenerateMemories`.
|
||||
let codex_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &codex_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["codexUseMemories"], true);
|
||||
assert_eq!(mem["codexGenerateMemories"], false);
|
||||
}
|
||||
|
||||
// 3. ACP and non-native providers (copilot, cursor, hermes, claude-acp) receive NO `_meta.openidea.memory`.
|
||||
for provider in ["copilot", "cursor", "hermes", "claude-acp"] {
|
||||
let t = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6688,12 +7182,10 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::new(),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6702,11 +7194,7 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
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}");
|
||||
}
|
||||
assert!(payload.is_none(), "provider {provider} should not receive memory delivery: {payload:?}");
|
||||
}
|
||||
|
||||
mgr.shutdown();
|
||||
@@ -6741,6 +7229,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::from([
|
||||
@@ -6890,6 +7379,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -6918,6 +7408,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
worktree_path: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
@@ -7620,12 +8111,8 @@ async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
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();
|
||||
let after_memory =
|
||||
mgr.set_memory_overrides(&task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }).unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
|
||||
@@ -7647,3 +8134,162 @@ async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shared_worktree_delete_preserves_checkout_across_subdirs() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
std::fs::create_dir_all(repo.dir.join("packages").join("app")).unwrap();
|
||||
repo.write("packages/app/a.txt", "hello\n");
|
||||
repo.commit("init");
|
||||
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
|
||||
let root_task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Reuse the same worktree for a task rooted in a subdirectory of the repository.
|
||||
let sub_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(repo.dir.join("packages").join("app"))),
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
worktree_path: Some(root_task.cwd.clone()),
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(root_task.cwd.0, sub_task.cwd.0);
|
||||
assert!(sub_task.cwd.0.starts_with(&root_task.cwd.0));
|
||||
|
||||
// Deleting the root task with `remove_worktree = true` MUST keep the shared worktree intact.
|
||||
mgr.delete(&root_task.id, true).await.unwrap();
|
||||
assert!(sub_task.cwd.0.exists(), "shared worktree was deleted while subdir sibling still exists");
|
||||
|
||||
// Deleting the final surviving task removes the worktree.
|
||||
mgr.delete(&sub_task.id, true).await.unwrap();
|
||||
assert!(!root_task.cwd.0.exists(), "worktree should be removed once no tasks share it");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn checkout_branch_guards_archived_untrusted_busy_siblings_and_updates_base_commit() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
// Create a diverged branch with its own commit.
|
||||
repo.git(&["checkout", "-q", "-b", "feat/diverged"]);
|
||||
repo.write("diverged.txt", "from diverged\n");
|
||||
repo.commit("diverged commit");
|
||||
let diverged_head = worktree::head_of(&repo.dir).unwrap().1;
|
||||
repo.git(&["checkout", "-q", "main"]);
|
||||
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
|
||||
let wt_a = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let wt_b = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Worktree,
|
||||
worktree_path: Some(wt_a.cwd.clone()),
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let original_base_commit = wt_a.base_commit.clone();
|
||||
|
||||
// 1. Busy sibling blocks checkout on the shared worktree.
|
||||
mgr.task(&wt_b.id).unwrap().state.lock().busy = true;
|
||||
let err = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("running"), "unexpected error: {err}");
|
||||
mgr.task(&wt_b.id).unwrap().state.lock().busy = false;
|
||||
|
||||
// 2. Creating a new branch (`create == true`) updates `branch` on both siblings while preserving `base_commit`.
|
||||
let out = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", true).await.unwrap();
|
||||
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
|
||||
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
|
||||
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
|
||||
assert_eq!(snap_a.branch.as_deref(), Some("feat/new-from-wt"));
|
||||
assert_eq!(snap_b.branch.as_deref(), Some("feat/new-from-wt"));
|
||||
assert_eq!(snap_a.base_commit, original_base_commit);
|
||||
assert_eq!(snap_b.base_commit, original_base_commit);
|
||||
|
||||
// 3. Switching to an existing diverged branch (`create == false`) updates `branch`, `base`,
|
||||
// and `base_commit` on both siblings so unrelated commits don't pollute Changes.
|
||||
let out = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap();
|
||||
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
|
||||
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
|
||||
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
|
||||
assert_eq!(snap_a.branch.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_b.branch.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_a.base.as_deref(), Some("feat/diverged"));
|
||||
assert_eq!(snap_a.base_commit.as_deref(), Some(diverged_head.as_str()));
|
||||
assert_eq!(snap_b.base_commit.as_deref(), Some(diverged_head.as_str()));
|
||||
let grouped = mgr.grouped_changes(&wt_a.id).await.unwrap();
|
||||
assert!(grouped.commits.is_empty(), "unrelated commits on switched branch leaked into Changes");
|
||||
assert!(grouped.uncommitted.is_empty());
|
||||
|
||||
// 4. Archived task rejects branch checkout.
|
||||
mgr.archive(&wt_a.id).unwrap();
|
||||
let err = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("archived"), "unexpected error: {err}");
|
||||
|
||||
// 5. Untrusted local repo rejects `checkout_branch`.
|
||||
let local_task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "claude".into(),
|
||||
prompt: text("again"),
|
||||
isolation: Isolation::Local,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
mgr.set_repo_trust_hook(Arc::new(|_| false));
|
||||
let err = mgr.checkout_branch(&local_task.id, "feat/diverged", false).await.unwrap_err();
|
||||
assert!(err.to_string().contains("not trusted"), "unexpected error: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rollback_clears_prompt_suggestions() {
|
||||
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();
|
||||
*handle.state.lock().task.prompt_suggestions = vec!["Follow up".into()];
|
||||
}
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.as_slice(), ["Follow up"]);
|
||||
|
||||
mgr.rollback(&task.id, 0, false).await.unwrap();
|
||||
assert!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.is_empty());
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
@@ -20,6 +20,8 @@ pub(crate) struct Timeline {
|
||||
cards: HashMap<String, usize>,
|
||||
/// Session messages, by message id.
|
||||
messages: HashMap<String, usize>,
|
||||
/// The next agent text starts an entry of its own (see [`Timeline::seal`]).
|
||||
sealed: bool,
|
||||
}
|
||||
|
||||
/// What a `session/update` changed in the timeline.
|
||||
@@ -138,10 +140,17 @@ impl Timeline {
|
||||
out
|
||||
}
|
||||
|
||||
/// A prompt is being sent: text the agent sent before it (a startup notice) is not the
|
||||
/// start of the reply, so the reply's text gets an entry of its own.
|
||||
pub fn seal(&mut self) {
|
||||
self.sealed = true;
|
||||
}
|
||||
|
||||
fn append_text(&mut self, thought: bool, text: &str) -> usize {
|
||||
let sealed = std::mem::take(&mut self.sealed);
|
||||
match self.entries.last_mut() {
|
||||
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
|
||||
Some(AgentEntry::Agent { text: t }) if !thought && !sealed => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought && !sealed => t.push_str(text),
|
||||
_ => {
|
||||
let text = text.to_owned();
|
||||
return self.push(if thought {
|
||||
@@ -307,9 +316,9 @@ impl Timeline {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Settles what an ended turn left open: running tools and pending permissions,
|
||||
/// and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
|
||||
/// Settles what an ended turn left open: running tools and pending permissions (but the
|
||||
/// requests in `open`), and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
// A steered message rides along in a running turn; the one that started it owns its end.
|
||||
let started = self.entries.iter().rposition(|e| matches!(e, AgentEntry::User { steered: false, .. }));
|
||||
@@ -325,7 +334,7 @@ impl Timeline {
|
||||
*status = AgentToolStatus::Failed;
|
||||
changed.push(i);
|
||||
}
|
||||
AgentEntry::Permission { chosen, .. } if chosen.is_none() => {
|
||||
AgentEntry::Permission { id, chosen, .. } if chosen.is_none() && !open.contains(id) => {
|
||||
*chosen = Some("Cancelled".into());
|
||||
changed.push(i);
|
||||
}
|
||||
@@ -357,7 +366,8 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
/// Replaces a tool's output, diffs and images with `content`: an update's `content` replaces the
|
||||
/// whole array, so what it leaves out is gone.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
@@ -389,20 +399,14 @@ fn merge_content(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = if text.is_empty() { command.to_owned() } else { format!("{command}\n{text}") };
|
||||
}
|
||||
*output = (!text.is_empty()).then(|| tail(text));
|
||||
*diffs = new_diffs;
|
||||
*images = new_images;
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
@@ -464,7 +468,7 @@ mod tests {
|
||||
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
|
||||
assert_eq!(t.apply(&update).changed, vec![0]);
|
||||
assert!(t.end_turn(None).is_empty());
|
||||
assert!(t.end_turn(None, &HashSet::new()).is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
|
||||
let saved = serde_json::to_string(&t.entries).unwrap();
|
||||
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
|
||||
@@ -612,6 +616,42 @@ mod tests {
|
||||
assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_with_content_replaces_all_of_the_calls_content() {
|
||||
let text = |t: &str| json!({"type": "content", "content": {"type": "text", "text": t}});
|
||||
let update = |id: &str, content: Value| json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "content": content});
|
||||
let mut t = Timeline::default();
|
||||
// An edit announced with its diff that fails: the error replaces the diff.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "e1", "title": "Edit a.txt", "kind": "edit",
|
||||
"status": "pending",
|
||||
"content": [{"type": "diff", "path": "/p/a.txt", "oldText": "one\n", "newText": "two\nthree\n"}]}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "e1", "status": "failed",
|
||||
"content": [text("old_string not found in a.txt")]}));
|
||||
let AgentEntry::Tool { diffs, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(diffs.is_empty(), "{diffs:?}");
|
||||
assert_eq!(output.as_deref(), Some("old_string not found in a.txt"));
|
||||
// Text replaces images, and no content clears the output.
|
||||
let image =
|
||||
json!({"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "iVBORw0KGgo="}});
|
||||
t.apply(&update("e1", json!([image])));
|
||||
t.apply(&update("e1", json!([text("done")])));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(images.is_empty());
|
||||
assert_eq!(output.as_deref(), Some("done"));
|
||||
t.apply(&update("e1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(*output, None);
|
||||
// The command a call announced (`$ cmd`) stays above what replaces its output.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r1", "title": "Run make", "kind": "execute",
|
||||
"content": [text("$ make")]}));
|
||||
t.apply(&update("r1", json!([text("building")])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make\nbuilding"));
|
||||
t.apply(&update("r1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_is_one_entry_and_end_turn_settles_open_items() {
|
||||
let mut t = Timeline::default();
|
||||
@@ -621,16 +661,20 @@ mod tests {
|
||||
t.push(AgentEntry::Agent { text: "between".into() });
|
||||
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
|
||||
t.push(AgentEntry::Permission {
|
||||
id: 1,
|
||||
let permission = |id| AgentEntry::Permission {
|
||||
id,
|
||||
title: "Run?".into(),
|
||||
command: None,
|
||||
options: vec![],
|
||||
questions: vec![],
|
||||
form: None,
|
||||
chosen: None,
|
||||
});
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
};
|
||||
t.push(permission(1));
|
||||
// A request that stays open (a subagent's that works on) keeps its card.
|
||||
t.push(permission(2));
|
||||
assert_eq!(t.end_turn(None, &HashSet::from([2])), vec![2, 3]);
|
||||
assert!(matches!(t.entries[4], AgentEntry::Permission { chosen: None, .. }));
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
assert_eq!(again.tools.get("c"), Some(&2));
|
||||
@@ -652,11 +696,11 @@ mod tests {
|
||||
t.push(user(1.0));
|
||||
t.push(AgentEntry::Agent { text: "a".into() });
|
||||
t.push(user(2.0));
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![2]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![2]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: None, .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
// Settled once: a later end (a restart) doesn't move it.
|
||||
assert_eq!(t.end_turn(Some(9.0)), Vec::<usize>::new());
|
||||
assert_eq!(t.end_turn(Some(9.0), &HashSet::new()), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -677,7 +721,7 @@ mod tests {
|
||||
t.push(user(2.0, true));
|
||||
// The steered message rides along in the turn: the reply's time belongs to the
|
||||
// message that started it.
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![0]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![0]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
|
||||
}
|
||||
|
||||
@@ -287,6 +287,88 @@ pub(crate) fn create_for_task(
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can
|
||||
/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories,
|
||||
/// or worktrees belonging to a different Git repository than `project_root`. Preserves any
|
||||
/// project-relative subdirectory inside `project_root` just like [`create_for_task`].
|
||||
pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult<Created> {
|
||||
let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?;
|
||||
if !canon_input.is_dir() {
|
||||
return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display())));
|
||||
}
|
||||
let project_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_input)?;
|
||||
let [_, project_common] = project_repo.metadata_dirs()?;
|
||||
let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_project_common = dunce::canonicalize(&project_common)?;
|
||||
if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree {} is not a linked worktree of this repository",
|
||||
worktree_path.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.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 root does not match managed worktrees directory"));
|
||||
}
|
||||
let canon_repo = dunce::canonicalize(project_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 raw_cwd =
|
||||
if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in worktree {}",
|
||||
rel_subdir.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?;
|
||||
let (branch, base_commit) = head_of(&canon_cwd)?;
|
||||
Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit })
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted
|
||||
/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD
|
||||
/// commit (when available), and checkout outcome.
|
||||
pub(crate) fn checkout_branch(
|
||||
cwd: &Path,
|
||||
branch: &str,
|
||||
create: bool,
|
||||
) -> IdeResult<(String, Option<String>, ide_vcs::CheckoutOutcome)> {
|
||||
let name = branch.trim();
|
||||
if name.is_empty() {
|
||||
return Err(IdeError::invalid("branch name cannot be empty"));
|
||||
}
|
||||
let repo = repo_at(cwd)?;
|
||||
let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with(name, create, &options)?;
|
||||
let (current, head_commit) = match head_of(cwd) {
|
||||
Ok((b, commit)) => (b, Some(commit)),
|
||||
Err(_) => (name.to_owned(), None),
|
||||
};
|
||||
Ok((current, head_commit, outcome))
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -327,23 +409,60 @@ pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) ->
|
||||
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)
|
||||
/// Returns a canonical comparison key for the managed worktree checkout root containing `path`,
|
||||
/// so two tasks pointing to different subdirs or path casings of the same worktree match.
|
||||
pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf {
|
||||
let (root, _) = worktree_checkout_root(worktrees_dir, path);
|
||||
let resolved = dunce::canonicalize(&root).unwrap_or(root);
|
||||
normalize_path_key(resolved)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn first_child_under(base: &Path, path: &Path) -> Option<PathBuf> {
|
||||
if let Ok(rel) = path.strip_prefix(base)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
return Some(base.join(first));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let base_comps: Vec<String> =
|
||||
base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
|
||||
let path_comps: Vec<std::path::Component<'_>> = path.components().collect();
|
||||
if path_comps.len() > base_comps.len()
|
||||
&& base_comps
|
||||
.iter()
|
||||
.zip(path_comps.iter())
|
||||
.all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase())
|
||||
{
|
||||
return Some(base.join(path_comps[base_comps.len()]));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Some(child) = first_child_under(worktrees_dir, path) {
|
||||
return (child, 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 Some(child) = first_child_under(&canon_wt_dir, path) {
|
||||
return (child, 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()
|
||||
&& let Some(child) = first_child_under(&canon_wt_dir, &canon_path)
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
@@ -2314,4 +2433,109 @@ mod tests {
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_validates_confinement_and_repo_membership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let other = tmp.path().join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
git(&other, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(other.join("b.txt"), "world\n").unwrap();
|
||||
git(&other, &["add", "."]);
|
||||
git(&other, &["commit", "-q", "-m", "init other"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
// Reusing a managed worktree of the same repository succeeds and reports its live branch.
|
||||
let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused.cwd, created.cwd);
|
||||
assert_eq!(reused.branch, created.branch);
|
||||
assert_eq!(reused.base_commit, created.base_commit);
|
||||
|
||||
// Paths outside `worktrees_dir` are rejected.
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err());
|
||||
|
||||
// Worktrees belonging to a different repository are rejected.
|
||||
let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap();
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_branch_creates_and_switches_branches_in_worktree() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(branch, "feat/follow-up");
|
||||
assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
|
||||
let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(back, created.branch);
|
||||
assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("app");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(sub.join("a.txt"), "hello\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-sub", "Subdir work", None).unwrap();
|
||||
assert!(created.cwd.ends_with(Path::new("packages").join("app")));
|
||||
|
||||
// Passing either the worktree root or the subdir cwd resolves to the same subdir cwd.
|
||||
let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap();
|
||||
assert_eq!(reused_from_root.cwd, created.cwd);
|
||||
assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap());
|
||||
|
||||
let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused_from_sub.cwd, created.cwd);
|
||||
|
||||
// `shared_worktree_root` matches root and subdir (and mixed casing on Windows).
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &created.cwd)
|
||||
);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase());
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &upper)
|
||||
);
|
||||
}
|
||||
|
||||
// A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected.
|
||||
let standalone = wt_dir.join("standalone");
|
||||
std::fs::create_dir_all(&standalone).unwrap();
|
||||
git(&standalone, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(standalone.join("x.txt"), "x\n").unwrap();
|
||||
git(&standalone, &["add", "."]);
|
||||
git(&standalone, &["commit", "-q", "-m", "standalone"]);
|
||||
assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err());
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref(), crate::maven::maven_version(&p.command)),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -294,7 +294,7 @@ pub fn plan(
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind, file)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
@@ -553,10 +553,24 @@ fn dotnet_target(dir: &Path) -> Option<PathBuf> {
|
||||
solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned()
|
||||
}
|
||||
|
||||
/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// `dotnet build` of `file` when it is a solution or project in `dir` (a run configuration's
|
||||
/// project), else of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// Build Artifacts publishes. The summary that repeats every message is left out.
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind, file: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
let given = file.filter(|f| {
|
||||
f.parent() == Some(dir)
|
||||
&& f.is_file()
|
||||
&& f.extension().is_some_and(|e| {
|
||||
matches!(
|
||||
e.to_string_lossy().to_ascii_lowercase().as_str(),
|
||||
"sln" | "slnx" | "csproj" | "fsproj" | "vbproj"
|
||||
)
|
||||
})
|
||||
});
|
||||
let target = given
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| dotnet_target(dir))
|
||||
.ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
|
||||
let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" };
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
@@ -1734,6 +1748,36 @@ mod tests {
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[0], "publish");
|
||||
// A run configuration's project is built even when its folder holds other projects or a
|
||||
// solution that sort first (#8179).
|
||||
write(&net, "src/Host/Legacy.csproj", "<Project/>");
|
||||
write(&net, "src/Host/Main.csproj", "<Project/>");
|
||||
write(&net, "src/Host/All.sln", "");
|
||||
for name in ["Main.csproj", "All.sln", "Legacy.csproj"] {
|
||||
let file = net.join("src/Host").join(name);
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&file),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], name);
|
||||
}
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&net.join("src/Host/Program.cs")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], "All.sln");
|
||||
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
|
||||
@@ -64,6 +64,7 @@ pub(super) fn build_javac_step(
|
||||
cwd: &Path,
|
||||
out_dir: &Path,
|
||||
classpath: &str,
|
||||
encoding: &str,
|
||||
sources: &[PathBuf],
|
||||
release: Vec<String>,
|
||||
file: &Path,
|
||||
@@ -73,7 +74,7 @@ pub(super) fn build_javac_step(
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
|
||||
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
|
||||
step.args.extend(["-encoding".into(), encoding.to_owned(), "-g".into()]);
|
||||
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
|
||||
if !classpath.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath.to_owned()]);
|
||||
@@ -118,6 +119,8 @@ pub struct SingleFileTarget {
|
||||
pub pl: String,
|
||||
/// `maven.compiler.release` (or equivalent) of the module's project.
|
||||
pub java_version: Option<u32>,
|
||||
/// `project.build.sourceEncoding` of the module's project, as the POM spells it.
|
||||
pub source_encoding: Option<String>,
|
||||
}
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
@@ -147,7 +150,15 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The Maven reactor target for a launch module whose source file is not known yet.
|
||||
@@ -165,7 +176,15 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `javac` for the module: its `JAVA_HOME`, else `PATH`.
|
||||
@@ -405,8 +424,11 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
let build_classpath = maven::plugin_goal(
|
||||
"dependency:build-classpath",
|
||||
maven::local_repository_for(&top.options).as_deref(),
|
||||
maven::maven_version(&top.command),
|
||||
);
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
@@ -468,7 +490,17 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
build_javac_step(
|
||||
javac,
|
||||
&target.module,
|
||||
&target.out_dir,
|
||||
classpath,
|
||||
target.source_encoding.as_deref().unwrap_or("UTF-8"),
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
target.top.env.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -644,8 +676,17 @@ pub fn gradle_compile_file_plan(
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
let step = build_javac_step(
|
||||
&javac,
|
||||
&module_dir,
|
||||
&out_dir,
|
||||
&classpath,
|
||||
"UTF-8",
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
gradle.env.clone(),
|
||||
)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
@@ -706,6 +747,28 @@ mod tests {
|
||||
assert_eq!(test.out_dir, root.join("app/target/test-classes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_reads_sources_in_the_encoding_of_the_module_pom() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><project.build.sourceEncoding>ISO-8859-15</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
let at = step.args.iter().position(|a| a == "-encoding").expect("an -encoding");
|
||||
assert_eq!(step.args[at + 1], "ISO-8859-15");
|
||||
assert_eq!(target.source_encoding.as_deref(), Some("ISO-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -373,7 +373,7 @@ pub fn structure_compile_file_plan(
|
||||
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let release = single::release_args(level, jdk.map(|j| j.major));
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, "UTF-8", &src_roots, release, file, env)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,15 @@ def describe = { Project p ->
|
||||
try { p.extensions.findByName('testing')?.suites?.each { suites << it.sources.name } } catch (ignored) {}
|
||||
def ideaTests = [] as Set
|
||||
try { p.extensions.findByName('idea')?.module?.testSources?.files?.each { ideaTests << canon(it) } } catch (ignored) {}
|
||||
// The `Test` tasks running each classes folder, as IDEA maps tests to tasks: a JVM test
|
||||
// suite's tests run with its own task (`integrationTest`), not with `test`.
|
||||
def testTasks = [:]
|
||||
try {
|
||||
p.tasks.withType(Test).each { t ->
|
||||
def dirs = t.hasProperty('testClassesDirs') ? t.testClassesDirs.files : [t.testClassesDir]
|
||||
dirs.findAll { it != null }.each { testTasks.get(canon(it), []) << t.name }
|
||||
}
|
||||
} catch (ignored) {}
|
||||
m.sourceSets = sets.collect { s ->
|
||||
def res = s.resources.srcDirs.collect(canon)
|
||||
def src = s.allSource.srcDirs.collect(canon) - res
|
||||
@@ -49,6 +58,11 @@ def describe = { Project p ->
|
||||
def set = [name: s.name, test: test, src: src, res: res]
|
||||
def processed = processedResources(p, s)
|
||||
if (processed != null) set.processed = processed
|
||||
try {
|
||||
def classes = s.output.hasProperty('classesDirs') ? s.output.classesDirs.files : [s.output.classesDir]
|
||||
def tasks = classes.findAll { it != null }.collectMany { testTasks[canon(it)] ?: [] }.unique()
|
||||
if (!tasks.isEmpty()) set.testTasks = tasks
|
||||
} catch (ignored) {}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,20 @@ pub struct GradleProject {
|
||||
/// `:buildSrc`); null for the opened build.
|
||||
#[serde(default)]
|
||||
pub build: Option<String>,
|
||||
/// The project's `Test` tasks, or null before Gradle reports the project.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub test_tasks: Option<Vec<GradleTestTask>>,
|
||||
}
|
||||
|
||||
/// A `Test` task and the source folders of the source sets whose test classes it runs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GradleTestTask {
|
||||
/// Name in its project (`test`, `integrationTest`).
|
||||
pub name: String,
|
||||
/// Project-relative.
|
||||
pub source_folders: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -341,6 +355,7 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro
|
||||
tasks,
|
||||
resolvable_configurations: None,
|
||||
build: None,
|
||||
test_tasks: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,6 +395,9 @@ pub struct ReportedSourceSet {
|
||||
/// includes / excludes, extra sources), which the Java language server's copy does not.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub processed: Option<ProcessedResources>,
|
||||
/// The `Test` tasks whose `testClassesDirs` hold the set's classes.
|
||||
#[serde(default, rename = "testTasks", skip_serializing_if = "Vec::is_empty")]
|
||||
pub test_tasks: Vec<String>,
|
||||
}
|
||||
|
||||
/// The task that copies a source set's resources, and where it writes them.
|
||||
@@ -455,6 +473,7 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
project.resolvable_configurations = p.resolvable_configurations.clone();
|
||||
project.build = p.build.clone();
|
||||
project.test_tasks = Some(test_tasks(root, p));
|
||||
project
|
||||
})
|
||||
.collect();
|
||||
@@ -466,6 +485,20 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
}
|
||||
|
||||
fn test_tasks(root: &Path, p: &ReportedProject) -> Vec<GradleTestTask> {
|
||||
let mut out: Vec<GradleTestTask> = Vec::new();
|
||||
for set in &p.source_sets {
|
||||
for name in &set.test_tasks {
|
||||
let folders = set.src.iter().map(|dir| rel(root, Path::new(dir)));
|
||||
match out.iter_mut().find(|t| t.name == *name) {
|
||||
Some(task) => task.source_folders.extend(folders),
|
||||
None => out.push(GradleTestTask { name: name.clone(), source_folders: folders.collect() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Project directories outside `root`, outermost only (`../svc`, not also `../svc/sources/app`):
|
||||
/// the folders IDEA shows as extra top-level module roots.
|
||||
pub fn external_roots<'a>(root: &Path, dirs: impl IntoIterator<Item = &'a str>) -> Vec<PathBuf> {
|
||||
@@ -1748,4 +1781,48 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
|
||||
assert!(!model.projects[4].tasks.is_empty());
|
||||
assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_test_tasks_carry_the_source_folders_they_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let src = |dir: &str| root.join(dir).to_string_lossy().into_owned();
|
||||
let set = |name: &str, dirs: &[&str], tasks: &[&str]| ReportedSourceSet {
|
||||
name: name.into(),
|
||||
test: !tasks.is_empty(),
|
||||
src: dirs.iter().map(|d| src(d)).collect(),
|
||||
test_tasks: tasks.iter().map(|t| (*t).into()).collect(),
|
||||
..ReportedSourceSet::default()
|
||||
};
|
||||
// As `gradle-model.gradle` prints a project with a JVM test suite.
|
||||
let reported = ReportedProject {
|
||||
path: ":app".into(),
|
||||
dir: src("app"),
|
||||
source_sets: vec![
|
||||
set("main", &["app/src/main/java"], &[]),
|
||||
set("test", &["app/src/test/java"], &["test"]),
|
||||
set(
|
||||
"integrationTest",
|
||||
&["app/src/integrationTest/java", "app/src/integrationTest/kotlin"],
|
||||
&["integrationTest"],
|
||||
),
|
||||
],
|
||||
..ReportedProject::default()
|
||||
};
|
||||
let line = format!("{MODEL_LINE}{}\n", serde_json::to_string(&reported).unwrap());
|
||||
assert!(line.contains(r#""testTasks":["integrationTest"]"#), "{line}");
|
||||
let mut model = GradleModel::default();
|
||||
merge_reported_projects(&root, &mut model, &parse_reported_projects(&line));
|
||||
let task = |name: &str, folders: &[&str]| GradleTestTask {
|
||||
name: name.into(),
|
||||
source_folders: folders.iter().map(|f| (*f).into()).collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
model.projects[0].test_tasks,
|
||||
Some(vec![
|
||||
task("test", &["app/src/test/java"]),
|
||||
task("integrationTest", &["app/src/integrationTest/java", "app/src/integrationTest/kotlin"]),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -113,12 +113,15 @@ impl JavaBuildService {
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let force_canonical: HashSet<PathBuf> = set.force.iter().filter_map(|p| dunce::canonicalize(p).ok()).collect();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
|| (!force_canonical.is_empty()
|
||||
&& dunce::canonicalize(path).ok().is_some_and(|c| force_canonical.contains(&c)))
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
@@ -507,42 +510,111 @@ fn ant_match(pattern: &str, path: &str) -> bool {
|
||||
segments(&p, &s)
|
||||
}
|
||||
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes.
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes. A file
|
||||
/// reached through several links is listed once: javac 8 fails on a class named twice, and newer
|
||||
/// ones record a single source for it, whose removal would leave the other spelling uncompiled.
|
||||
/// Deduplication runs after includes/excludes so an excluded alias cannot hide a valid path, and
|
||||
/// prefers a path that passes through no symlink over a linked one.
|
||||
fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<PathBuf>> {
|
||||
let config = set.compiler.as_ref();
|
||||
let includes = config.map(|c| c.includes.as_slice()).unwrap_or_default();
|
||||
let excludes = config.map(|c| c.excludes.as_slice()).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut kept: HashMap<PathBuf, (PathBuf, bool)> = HashMap::new();
|
||||
for root in &set.source_roots {
|
||||
if model::is_processor_output(set, root) || !root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let mut pending = vec![root.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(root, cancel, &mut |path, canonical, via_link| {
|
||||
if path.extension().is_none_or(|e| e != "java") {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if kind.is_dir() {
|
||||
pending.push(path);
|
||||
} else if path.extension().is_some_and(|e| e == "java") {
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if included && !excludes.iter().any(|p| ant_match(p, &rel)) && seen.insert(path.clone()) {
|
||||
out.push(path);
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
match kept.entry(canonical) {
|
||||
std::collections::hash_map::Entry::Vacant(slot) => {
|
||||
slot.insert((path, via_link));
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut slot) => {
|
||||
if slot.get().1 && !via_link {
|
||||
slot.insert((path, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let mut out: Vec<PathBuf> = kept.into_values().map(|(path, _)| path).collect();
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reports the files under `root` with their canonical paths and whether the path passed through
|
||||
/// any symlink, following links to folders: a module can link a shared source folder into its own,
|
||||
/// and Maven's resources plugin copies through such links too. Files keep the spelling under
|
||||
/// `root`, so javac's messages and the debugger name the path the user opened. Only links back to
|
||||
/// an ancestor on the current descent path (cycles) are skipped. Each folder is read in full
|
||||
/// before its subfolders, so a deep tree holds one open directory at a time; real entries come
|
||||
/// before links, by name, so the walk order does not depend on the file system's order.
|
||||
fn walk_files(root: &Path, cancel: &CancellationToken, found: &mut dyn FnMut(PathBuf, PathBuf, bool)) -> IdeResult<()> {
|
||||
type DirEntry = (bool, std::ffi::OsString, PathBuf, bool);
|
||||
struct Frame {
|
||||
canonical: std::rc::Rc<PathBuf>,
|
||||
via_link: bool,
|
||||
entries: std::vec::IntoIter<DirEntry>,
|
||||
}
|
||||
|
||||
fn read_sorted_entries(dir: &Path, cancel: &CancellationToken) -> IdeResult<Option<std::vec::IntoIter<DirEntry>>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return Ok(None) };
|
||||
let mut entries: Vec<DirEntry> = read
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let kind = e.file_type().ok()?;
|
||||
Some((kind.is_symlink(), e.file_name(), e.path(), kind.is_dir()))
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
Ok(Some(entries.into_iter()))
|
||||
}
|
||||
|
||||
let Ok(canonical) = dunce::canonicalize(root) else { return Ok(()) };
|
||||
let via_link = std::fs::symlink_metadata(root).is_ok_and(|m| m.file_type().is_symlink());
|
||||
let Some(entries) = read_sorted_entries(root, cancel)? else { return Ok(()) };
|
||||
|
||||
let root_canonical = std::rc::Rc::new(canonical);
|
||||
let mut ancestors: HashSet<std::rc::Rc<PathBuf>> = HashSet::from([std::rc::Rc::clone(&root_canonical)]);
|
||||
let mut stack = vec![Frame { canonical: root_canonical, via_link, entries }];
|
||||
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
let Some((linked, name, path, is_dir)) = frame.entries.next() else {
|
||||
let done = stack.pop().expect("top frame");
|
||||
ancestors.remove(&done.canonical);
|
||||
continue;
|
||||
};
|
||||
let (is_dir, real) = if linked {
|
||||
let (Ok(meta), Ok(target)) = (std::fs::metadata(&path), dunce::canonicalize(&path)) else { continue };
|
||||
(meta.is_dir(), target)
|
||||
} else {
|
||||
(is_dir, frame.canonical.join(&name))
|
||||
};
|
||||
let entry_via_link = frame.via_link || linked;
|
||||
if !is_dir {
|
||||
found(path, real, entry_via_link);
|
||||
} else if !ancestors.contains(&real)
|
||||
&& let Some(children) = read_sorted_entries(&path, cancel)?
|
||||
{
|
||||
let real = std::rc::Rc::new(real);
|
||||
ancestors.insert(std::rc::Rc::clone(&real));
|
||||
stack.push(Frame { canonical: real, via_link: entry_via_link, entries: children });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
@@ -1241,21 +1313,11 @@ fn remove_classes(dir: &Path) {
|
||||
fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeMap<PathBuf, FileStamp>> {
|
||||
let mut out = BTreeMap::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
} else if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -1265,27 +1327,15 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
continue;
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
}
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -819,3 +819,314 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.java` files `java_sources` lists for one source root.
|
||||
#[cfg(unix)]
|
||||
fn sources_of(root: &Path) -> Vec<PathBuf> {
|
||||
let set = SourceSet { source_roots: vec![root.to_path_buf()], ..Default::default() };
|
||||
java_sources(&set, &CancellationToken::new()).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_directory_links_and_keep_the_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app/src/main/java");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
write(&base, "shared/b/c/C.java", "package b.c;\npublic class C {}\n");
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
// A link to a file was already listed; it stays listed.
|
||||
write(&base, "shared/D.java", "package d;\npublic class D {}\n");
|
||||
fs::create_dir_all(root.join("d")).unwrap();
|
||||
symlink(base.join("shared/D.java"), root.join("d/D.java")).unwrap();
|
||||
// A broken link is skipped.
|
||||
symlink(base.join("missing"), root.join("gone")).unwrap();
|
||||
// javac and the debugger get the path the user opened, not the link's target.
|
||||
assert_eq!(
|
||||
sources_of(&root),
|
||||
[root.join("a/A.java"), root.join("b/B.java"), root.join("b/c/C.java"), root.join("d/D.java")]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_stop_at_link_cycles() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
symlink(&root, root.join("a/up")).unwrap();
|
||||
symlink(".", root.join("a/here")).unwrap();
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
symlink(base.join("shared"), base.join("shared/b/back")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("a/A.java"), root.join("b/B.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_links_that_share_a_folder() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&base, "shared/s/S.java", "package s;\npublic class S {}\n");
|
||||
let shared = base.join("shared/s");
|
||||
// Each module links the same folder into its own sources: every one of them compiles it.
|
||||
let (one, two) = (base.join("one/src"), base.join("two/src"));
|
||||
for root in [&one, &two] {
|
||||
fs::create_dir_all(root).unwrap();
|
||||
symlink(&shared, root.join("s")).unwrap();
|
||||
}
|
||||
assert_eq!(sources_of(&one), [one.join("s/S.java")]);
|
||||
assert_eq!(sources_of(&two), [two.join("s/S.java")]);
|
||||
// Within one source set a file reached through two links is listed once, real entries before links, then by name.
|
||||
let three = base.join("three/src");
|
||||
fs::create_dir_all(three.join("x")).unwrap();
|
||||
symlink(&shared, three.join("s")).unwrap();
|
||||
symlink(&shared, three.join("x/s")).unwrap();
|
||||
assert_eq!(sources_of(&three), [three.join("x/s/S.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_list_a_file_reached_through_two_paths_once() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
symlink(root.join("p"), root.join("alias")).unwrap();
|
||||
symlink(root.join("p/C.java"), root.join("C.java")).unwrap();
|
||||
// The real folder comes before the links to it.
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_match_each_nested_root_against_its_own_paths() {
|
||||
// Without links the listing is what it was before links were followed: a file the outer
|
||||
// root's relative path excludes is still listed through the inner root.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outer = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let inner = outer.join("inner");
|
||||
write(&outer, "inner/X.java", "class X {}\n");
|
||||
write(&outer, "Y.java", "class Y {}\n");
|
||||
let set = SourceSet {
|
||||
source_roots: vec![outer.clone(), inner.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["inner/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [outer.join("Y.java"), inner.join("X.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_find_a_file_deep_in_plain_folders() {
|
||||
// Iterative walk with one folder open at a time: avoids exhausting file descriptors under
|
||||
// macOS's default limit of 256 and avoids overflowing Windows' 1-2 MB thread stack in deep
|
||||
// trees. Target 3000 levels on Windows (long paths up to 32,767 chars); on Unix, cap to the
|
||||
// deepest path that fits under PATH_MAX (1024 bytes on macOS, 4096 bytes on Linux).
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let max_path_bytes: Option<usize> = if cfg!(target_os = "macos") {
|
||||
Some(1020)
|
||||
} else if cfg!(unix) {
|
||||
Some(4090)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let target_depth = 3000;
|
||||
let depth = match max_path_bytes {
|
||||
Some(limit) => target_depth.min(limit.saturating_sub(root.as_os_str().len() + "/C.java".len()) / 2),
|
||||
None => target_depth,
|
||||
};
|
||||
assert!(depth >= 300, "temp root too long for deep folder test: {}", root.display());
|
||||
|
||||
let mut dir = root.clone();
|
||||
for _ in 0..depth {
|
||||
dir.push("d");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
}
|
||||
let file = dir.join("C.java");
|
||||
fs::write(&file, "class C {}\n").unwrap();
|
||||
|
||||
let set = SourceSet { source_roots: vec![root], ..Default::default() };
|
||||
let found = java_sources(&set, &CancellationToken::new()).unwrap();
|
||||
|
||||
// Remove iteratively so deep trees don't rely on recursive directory removal.
|
||||
fs::remove_file(&file).unwrap();
|
||||
for _ in 0..depth {
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
dir.pop();
|
||||
}
|
||||
assert_eq!(found, [file]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn compiles_the_other_spelling_when_the_kept_link_goes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { p.C c; }\n"),
|
||||
("shared/p/C.java", "package p;\npublic class C {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
symlink(f.root.join("shared/p"), java.join("p")).unwrap();
|
||||
symlink(f.root.join("shared/p"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// The class keeps its source through the link that is left.
|
||||
fs::remove_file(java.join("p")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn builds_and_recompiles_sources_under_a_linked_folder() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new b.B().b(); } }\n"),
|
||||
("shared/b/B.java", "package b;\npublic class B { public int b() { return 1; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
std::os::unix::fs::symlink(f.root.join("shared/b"), f.root.join("app/src/main/java/b")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.contains(&"javac app (main, 2 files)".to_owned()), "{steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// An edit behind the link is seen through it.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// Errors name the file as it sits under the source root.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return \"\"; } }\n");
|
||||
let failed = f.launch(false);
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(
|
||||
error.path.as_deref(),
|
||||
Some(f.root.join("app/src/main/java/b/B.java").as_path()),
|
||||
"{:?}",
|
||||
failed.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resources_under_a_linked_folder_are_copied_refreshed_and_pruned() {
|
||||
let Some(f) =
|
||||
Fixture::new(&[("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), ("shared/r/x.txt", "one\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
fs::create_dir_all(f.root.join("app/src/main/resources")).unwrap();
|
||||
std::os::unix::fs::symlink(f.root.join("shared/r"), f.root.join("app/src/main/resources/r")).unwrap();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "one\n");
|
||||
|
||||
// An edit behind the link reaches the copy the launch reads.
|
||||
f.write("shared/r/x.txt", "two\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "two\n");
|
||||
|
||||
// So does a file deleted behind it.
|
||||
fs::remove_file(f.root.join("shared/r/x.txt")).unwrap();
|
||||
f.steps_of_launch();
|
||||
assert!(!f.out("t.app/classes/r/x.txt").exists(), "the removed resource stays on the classpath");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_keep_a_valid_link_when_an_earlier_alias_is_excluded() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src/main/java");
|
||||
write(&base, "shared/one/p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("a")).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("z")).unwrap();
|
||||
let set = SourceSet {
|
||||
source_roots: vec![root.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["a/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [root.join("z/p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn excluded_link_alias_does_not_drop_compiled_classes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><artifactId>maven-compiler-plugin</artifactId>",
|
||||
"<configuration><excludes><exclude>a/**</exclude></excludes></configuration>",
|
||||
"</plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[("app/pom.xml", &pom), ("shared/one/p/C.java", "package p;\npublic class C {}\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
fs::create_dir_all(&java).unwrap();
|
||||
symlink(f.root.join("shared/one"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// Adding an excluded link to the same folder must not hide the surviving link or delete its class.
|
||||
symlink(f.root.join("shared/one"), java.join("a")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(steps.is_empty(), "{steps:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_prefer_a_plain_path_over_an_earlier_linked_alias() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src/main/java");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(root.join("a")).unwrap();
|
||||
symlink(root.join("p"), root.join("a/link")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recompiles_a_single_file_through_either_the_plain_or_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[("app/src/main/java/p/C.java", "package p;\npublic class C {}\n")]) else {
|
||||
return;
|
||||
};
|
||||
f.steps_of_launch();
|
||||
let java = f.root.join("app/src/main/java");
|
||||
assert!(f.out("t.app/classes/p/C.class").is_file());
|
||||
|
||||
// Adding a link under an earlier directory keeps the plain spelling and still lets Recompile
|
||||
// hit through either spelling.
|
||||
fs::create_dir_all(java.join("a")).unwrap();
|
||||
symlink(java.join("p"), java.join("a/link")).unwrap();
|
||||
let second = f.steps_of_launch();
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("p/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("a/link/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
assert!(second.is_empty(), "{second:?}");
|
||||
}
|
||||
@@ -98,14 +98,19 @@ pub fn load_linked_with_jdk(
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), maven_jdk_version);
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_activation(root, repo, &activation, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
if !m.profiles.iter().any(|x| x.id == p.id) {
|
||||
m.profiles.push(p);
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
for p in maven::settings_profiles(&settings_file) {
|
||||
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
|
||||
existing.active_by_default |= p.active_by_default;
|
||||
} else {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
@@ -157,8 +162,8 @@ pub fn maven_external_roots(
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs = maven::external_pom_dirs(root, &settings.linked_projects);
|
||||
if trusted {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
dirs.extend(maven::reactor_external_dirs(root, &profiles, &settings.unlinked_projects));
|
||||
let activation = maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), None);
|
||||
dirs.extend(maven::reactor_external_dirs(root, &activation, &settings.unlinked_projects));
|
||||
}
|
||||
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect();
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
@@ -334,6 +339,47 @@ mod tests {
|
||||
assert_eq!(roots(&settings, true), [a, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_maven_turns_on_by_itself_is_shown_on_and_unticking_it_turns_it_off() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for module in ["extras", "it"] {
|
||||
std::fs::create_dir(root.join(module)).unwrap();
|
||||
std::fs::write(root.join(module).join("pom.xml"), "<project><artifactId>m</artifactId></project>").unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><artifactId>root</artifactId><packaging>pom</packaging><profiles>
|
||||
<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>
|
||||
<profile><id>full</id><activation><property><name>!quick</name></property></activation><modules><module>extras</module></modules></profile>
|
||||
<profile><id>ci</id><modules><module>it</module></modules></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir(root.join(".mvn")).unwrap();
|
||||
std::fs::write(root.join(".mvn/maven.config"), "-Pci\n").unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: root.join("settings.xml").to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let load = || load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags =
|
||||
|m: &maven::MavenModel| m.profiles.iter().map(|p| (p.id.clone(), p.active_by_default)).collect::<Vec<_>>();
|
||||
let pair = |id: &str, on: bool| (id.to_owned(), on);
|
||||
|
||||
// On by default (the tool window's grey check), so `dev` steps aside as it does in Maven.
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", false), pair("full", true), pair("ci", true)]);
|
||||
assert_eq!(model.projects[0].modules, ["extras/pom.xml", "it/pom.xml"]);
|
||||
|
||||
// Unticked: off in the model, still on by default so the tool window keeps passing `-P !id`.
|
||||
save_maven_profiles(&cache, &["!full".into(), "!ci".into()]).unwrap();
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", true), pair("full", true), pair("ci", true)]);
|
||||
assert!(model.projects[0].modules.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_profiles_and_checkbox_choices_control_modules_before_sync() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -358,6 +404,50 @@ mod tests {
|
||||
assert!(modules(&settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>test3</id></profile>
|
||||
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
std::fs::write(
|
||||
&settings_xml,
|
||||
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: settings_xml.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert!(
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
// As in Maven, `dev` steps aside: settings.xml turns on test3 of the same POM.
|
||||
assert!(flags.contains(&("dev", false)), "activeByDefault beside an active profile: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "case-insensitive activeByDefault of a module: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_build_systems_and_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,463 @@
|
||||
//! Which profiles of a POM Maven turns on for a project, decided as Maven 3.9 does
|
||||
//! (`DefaultProfileSelector` and its activators): from the `-P` entries, the `-D` properties of
|
||||
//! `.mvn/maven.config`, the JDK Maven runs on, the OS and the files of the project.
|
||||
|
||||
use super::{RawProfile, interpolate, jdk_matches};
|
||||
use crate::xml::Element;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What decides profile activation besides the POMs and the machine. The `.mvn/maven.config`
|
||||
/// of each build is read with its POMs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct ProfileActivation {
|
||||
/// `-P` entries of every Maven run (`!id` or `-id` turns a profile off): Settings › Maven's
|
||||
/// active profiles and the `<activeProfiles>` of the user `settings.xml`.
|
||||
pub profiles: Vec<String>,
|
||||
/// `-P` entries chosen in the Maven tool window.
|
||||
pub choices: Vec<String>,
|
||||
/// Feature version of the JDK Maven runs on.
|
||||
pub jdk: Option<u32>,
|
||||
}
|
||||
|
||||
impl ProfileActivation {
|
||||
/// For the builds under `root`, with the Maven tool window's `choices`.
|
||||
pub fn new(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
choices: &[String],
|
||||
jdk: Option<u32>,
|
||||
) -> Self {
|
||||
let mut profiles = settings.profiles(&[]);
|
||||
if let Some(file) = super::user_settings_file(root, settings) {
|
||||
profiles.extend(super::settings_active_profiles(&file));
|
||||
}
|
||||
Self { profiles, choices: choices.to_vec(), jdk }
|
||||
}
|
||||
|
||||
/// `Some(false)` when a `-P` entry turns profile `id` off (that wins in Maven, whatever the
|
||||
/// order), `Some(true)` when one turns it on. The tool window's entries for `except` are
|
||||
/// left out.
|
||||
fn explicit(&self, config: &MavenConfig, id: &str, except: Option<&str>) -> Option<bool> {
|
||||
let choices = self.choices.iter().filter(|c| except.is_none_or(|except| entry(c).1 != except));
|
||||
let mut on = None;
|
||||
for (turns_on, entry) in self.profiles.iter().chain(&config.profiles).chain(choices).map(|e| entry(e)) {
|
||||
if entry == id {
|
||||
if !turns_on {
|
||||
return Some(false);
|
||||
}
|
||||
on = Some(true);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
}
|
||||
|
||||
/// A `-P` entry as (turns the profile on, its id): `!id` and `-id` turn it off, `+id` and
|
||||
/// Maven 3.9's optional `?id` turn it on.
|
||||
fn entry(entry: &str) -> (bool, &str) {
|
||||
let entry = entry.trim();
|
||||
let (on, id) = match entry.strip_prefix(['!', '-']) {
|
||||
Some(id) => (false, id),
|
||||
None => (true, entry.strip_prefix('+').unwrap_or(entry)),
|
||||
};
|
||||
(on, id.strip_prefix('?').unwrap_or(id).trim())
|
||||
}
|
||||
|
||||
/// The `-P` and `-D` options of the `.mvn/maven.config` Maven reads before every run.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct MavenConfig {
|
||||
profiles: Vec<String>,
|
||||
properties: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl MavenConfig {
|
||||
/// The `maven.config` of a Maven run in `dir`: in the `.mvn` folder of the nearest folder
|
||||
/// from `dir` up that has one, as the `mvn` script finds the build's base directory; else
|
||||
/// where it would be created in `dir`.
|
||||
pub(crate) fn file(dir: &Path) -> PathBuf {
|
||||
let base = dir.ancestors().find(|d| !d.as_os_str().is_empty() && d.join(".mvn").is_dir());
|
||||
base.unwrap_or(dir).join(".mvn").join("maven.config")
|
||||
}
|
||||
|
||||
pub(crate) fn read(file: &Path) -> Self {
|
||||
std::fs::read_to_string(file).map(|text| Self::parse(&text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Since Maven 3.9 each line is one argument (`-P a` and `-P` followed by `a` both work);
|
||||
/// lines starting with `#` are comments.
|
||||
fn parse(text: &str) -> Self {
|
||||
let mut config = Self::default();
|
||||
let mut args = text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#'));
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(value) = option_value(arg, "-P", "--activate-profiles", &mut args) {
|
||||
config.profiles.extend(value.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned));
|
||||
} else if let Some(value) = option_value(arg, "-D", "--define", &mut args) {
|
||||
// `-Dname` alone sets it to `true`, as on the command line.
|
||||
let (name, value) = value.split_once('=').unwrap_or((value, "true"));
|
||||
config.properties.insert(name.trim().to_owned(), value.to_owned());
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the option `short` / `long` given in `arg` (`-Pa`, `-P a`, `--activate-profiles=a`)
|
||||
/// or as the next argument.
|
||||
fn option_value<'a>(
|
||||
arg: &'a str,
|
||||
short: &str,
|
||||
long: &str,
|
||||
args: &mut impl Iterator<Item = &'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let value = match arg.strip_prefix(long) {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with(['=', ' ', '\t']) => rest.trim_start_matches('='),
|
||||
Some(_) => return None,
|
||||
None => arg.strip_prefix(short)?,
|
||||
};
|
||||
match value.trim() {
|
||||
"" => args.next(),
|
||||
value => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// A profile's `<activation>`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Activation {
|
||||
pub(crate) by_default: bool,
|
||||
/// `<jdk>`: `21`, `1.8`, `[17,)`, `!21`.
|
||||
pub(crate) jdk: Option<String>,
|
||||
os: Option<OsCondition>,
|
||||
property: Option<PropertyCondition>,
|
||||
file: Option<FileCondition>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct OsCondition {
|
||||
family: Option<String>,
|
||||
name: Option<String>,
|
||||
arch: Option<String>,
|
||||
version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PropertyCondition {
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FileCondition {
|
||||
exists: Option<String>,
|
||||
missing: Option<String>,
|
||||
}
|
||||
|
||||
impl Activation {
|
||||
pub(crate) fn read(profile: &Element) -> Self {
|
||||
let Some(a) = profile.child("activation") else { return Self::default() };
|
||||
Self {
|
||||
by_default: a.text_of("activeByDefault").is_some_and(|v| v.eq_ignore_ascii_case("true")),
|
||||
// Present but empty, Maven's prefix match takes any JDK.
|
||||
jdk: a.child("jdk").map(|jdk| jdk.text.trim().to_owned()),
|
||||
os: a.child("os").map(|os| OsCondition {
|
||||
family: os.text_of("family"),
|
||||
name: os.text_of("name"),
|
||||
arch: os.text_of("arch"),
|
||||
version: os.text_of("version"),
|
||||
}),
|
||||
property: a
|
||||
.child("property")
|
||||
.map(|p| PropertyCondition { name: p.text_of("name").unwrap_or_default(), value: p.text_of("value") }),
|
||||
file: a.child("file").map(|f| FileCondition { exists: f.text_of("exists"), missing: f.text_of("missing") }),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn checks_files(&self) -> bool {
|
||||
self.file.is_some()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.jdk.is_none() && self.os.is_none() && self.property.is_none() && self.file.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the profiles of one project are activated with.
|
||||
pub(crate) struct Env<'a> {
|
||||
pub(crate) activation: &'a ProfileActivation,
|
||||
pub(crate) config: &'a MavenConfig,
|
||||
/// The folder of the project being built, also for the profiles its parents declare.
|
||||
pub(crate) basedir: &'a Path,
|
||||
}
|
||||
|
||||
impl Env<'_> {
|
||||
/// Whether the `<activation>` conditions of each profile hold; the files they look at are
|
||||
/// added to `files`. `properties` are the own `<properties>` of the POM declaring them.
|
||||
pub(crate) fn conditions(
|
||||
&self,
|
||||
profiles: &[RawProfile],
|
||||
properties: &[(String, String)],
|
||||
files: &mut Vec<PathBuf>,
|
||||
) -> Vec<bool> {
|
||||
if profiles.iter().all(|p| p.activation.is_empty()) {
|
||||
return vec![false; profiles.len()];
|
||||
}
|
||||
let props = self.interpolation(properties);
|
||||
profiles.iter().map(|p| self.holds(&p.activation, &props, files)).collect()
|
||||
}
|
||||
|
||||
/// Which profiles are on: those a `-P` entry turns on or whose `conditions` hold, unless one
|
||||
/// turns them off; the `activeByDefault` ones only when no other profile of the POM is on.
|
||||
/// The tool window's choice for profile `except` is left out.
|
||||
pub(crate) fn select(&self, profiles: &[RawProfile], conditions: &[bool], except: Option<&str>) -> Vec<bool> {
|
||||
let explicit: Vec<Option<bool>> =
|
||||
profiles.iter().map(|p| self.activation.explicit(self.config, &p.id, except)).collect();
|
||||
let mut on: Vec<bool> = explicit.iter().zip(conditions).map(|(e, &holds)| e.unwrap_or(holds)).collect();
|
||||
if !on.contains(&true) {
|
||||
for ((on, p), e) in on.iter_mut().zip(profiles).zip(&explicit) {
|
||||
*on = p.activation.by_default && *e != Some(false);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
|
||||
/// Whether each profile is on unless the Maven tool window turns it off: what the tool
|
||||
/// window shows as on by default, so that unticking it passes `-P!id`.
|
||||
pub(crate) fn implicit(&self, profiles: &[RawProfile], conditions: &[bool]) -> Vec<bool> {
|
||||
profiles.iter().enumerate().map(|(i, p)| self.select(profiles, conditions, Some(&p.id))[i]).collect()
|
||||
}
|
||||
|
||||
/// Values for `${…}` in activation conditions: the declaring POM's own properties, then the
|
||||
/// `-D` ones, then the JVM's; `${basedir}` is the project's.
|
||||
fn interpolation(&self, properties: &[(String, String)]) -> HashMap<String, String> {
|
||||
let mut props: HashMap<String, String> = ["os.name", "os.arch", "user.home"]
|
||||
.into_iter()
|
||||
.filter_map(|k| Some((k.to_owned(), system_property(k)?)))
|
||||
.collect();
|
||||
props.extend(self.config.properties.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
props.extend(properties.iter().cloned());
|
||||
let basedir = self.basedir.to_string_lossy().into_owned();
|
||||
props.insert("project.basedir".into(), basedir.clone());
|
||||
props.insert("basedir".into(), basedir);
|
||||
props
|
||||
}
|
||||
|
||||
/// Since Maven 3.2.2 every condition present has to hold, and one at least has to be present.
|
||||
fn holds(&self, a: &Activation, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let jdk = self.activation.jdk;
|
||||
let results = [
|
||||
a.jdk.as_ref().map(|spec| jdk.is_some() && (spec.is_empty() || jdk_matches(spec, jdk))),
|
||||
a.os.as_ref().map(|os| os_matches(os, props)),
|
||||
a.property.as_ref().map(|p| self.property_matches(p, props)),
|
||||
a.file.as_ref().map(|f| self.file_matches(f, props, files)),
|
||||
];
|
||||
let mut present = results.into_iter().flatten().peekable();
|
||||
present.peek().is_some() && present.all(|holds| holds)
|
||||
}
|
||||
|
||||
fn property_matches(&self, p: &PropertyCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = interpolate(&p.name, props);
|
||||
let (negated, name) = negation(&name);
|
||||
if name.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let actual = self.config.properties.get(name).cloned().or_else(|| system_property(name));
|
||||
match p.value.as_deref().map(|v| interpolate(v, props)) {
|
||||
Some(value) => {
|
||||
let (negated, value) = negation(&value);
|
||||
negated != (actual.as_deref() == Some(value))
|
||||
}
|
||||
None => negated != actual.is_some_and(|v| !v.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
fn file_matches(&self, f: &FileCondition, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let (path, missing) = match (&f.exists, &f.missing) {
|
||||
(Some(path), _) => (path, false),
|
||||
(None, Some(path)) => (path, true),
|
||||
(None, None) => return false,
|
||||
};
|
||||
let path = crate::gradle::normalize(&self.basedir.join(interpolate(path, props)));
|
||||
let exists = path.exists();
|
||||
files.push(path);
|
||||
exists != missing
|
||||
}
|
||||
}
|
||||
|
||||
fn negation(value: &str) -> (bool, &str) {
|
||||
match value.strip_prefix('!') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, value),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<os>` as Maven 3.9 matches it (`org.apache.maven.utils.Os`) against what Java reports for
|
||||
/// this machine.
|
||||
fn os_matches(os: &OsCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = os_name().to_lowercase();
|
||||
let test = |value: &Option<String>, matches: &dyn Fn(&str) -> bool| {
|
||||
value.as_deref().is_none_or(|v| {
|
||||
let v = interpolate(v, props).to_lowercase();
|
||||
let (negated, v) = negation(&v);
|
||||
negated != matches(v)
|
||||
})
|
||||
};
|
||||
(os.family.is_some() || os.name.is_some() || os.arch.is_some())
|
||||
// The OS version Java reports is not known here.
|
||||
&& os.version.is_none()
|
||||
&& test(&os.family, &|family| family_matches(family, &name))
|
||||
&& test(&os.name, &|n| n == name)
|
||||
&& test(&os.arch, &|arch| arch == os_arch())
|
||||
}
|
||||
|
||||
fn family_matches(family: &str, os_name: &str) -> bool {
|
||||
let windows = os_name.contains("windows");
|
||||
let win9x = windows && ["95", "98", "me", "ce"].iter().any(|v| os_name.contains(v));
|
||||
let mac = os_name.contains("mac") || os_name.contains("darwin");
|
||||
match family {
|
||||
"windows" => windows,
|
||||
"win9x" => win9x,
|
||||
"winnt" => windows && !win9x,
|
||||
"dos" => cfg!(windows) && !os_name.contains("netware"),
|
||||
"mac" => mac,
|
||||
"unix" => !cfg!(windows) && !os_name.contains("openvms") && (!mac || os_name.ends_with('x')),
|
||||
"tandem" => os_name.contains("nonstop_kernel"),
|
||||
"z/os" => os_name.contains("z/os") || os_name.contains("os/390"),
|
||||
family => os_name.contains(family),
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.name` as Java reports it; on Windows it also names the version, which is not known here.
|
||||
fn os_name() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
"macos" => "Mac OS X",
|
||||
"windows" => "Windows",
|
||||
"linux" => "Linux",
|
||||
"freebsd" => "FreeBSD",
|
||||
"openbsd" => "OpenBSD",
|
||||
"netbsd" => "NetBSD",
|
||||
"solaris" | "illumos" => "SunOS",
|
||||
"aix" => "AIX",
|
||||
os => os,
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.arch` as Java reports it.
|
||||
fn os_arch() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"x86_64" if cfg!(target_os = "macos") => "x86_64",
|
||||
"x86_64" => "amd64",
|
||||
"x86" if cfg!(windows) => "x86",
|
||||
"x86" => "i386",
|
||||
"powerpc64" if cfg!(target_endian = "little") => "ppc64le",
|
||||
"powerpc64" => "ppc64",
|
||||
arch => arch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The system properties of Maven's JVM that conditions use: the environment as `env.*`, and
|
||||
/// those of the JVM's own that are known here.
|
||||
fn system_property(name: &str) -> Option<String> {
|
||||
if let Some(var) = name.strip_prefix("env.") {
|
||||
return std::env::var(var).ok();
|
||||
}
|
||||
match name {
|
||||
"os.name" => Some(os_name().to_owned()),
|
||||
"os.arch" => Some(os_arch().to_owned()),
|
||||
"user.home" => dirs::home_dir().map(|home| home.to_string_lossy().into_owned()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn profiles(xml: &str) -> Vec<RawProfile> {
|
||||
super::super::parse_pom(&format!("<project><profiles>{xml}</profiles></project>")).unwrap().profiles
|
||||
}
|
||||
|
||||
fn holds(env: &Env, activation: &str) -> bool {
|
||||
let profiles = profiles(&format!("<profile><id>p</id><activation>{activation}</activation></profile>"));
|
||||
env.conditions(&profiles, &[], &mut Vec::new())[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_config_takes_one_option_per_line() {
|
||||
let config = MavenConfig::parse(
|
||||
"# shared options\n-Pci,!slow\n-P\nnative\n--activate-profiles=docs\n-Dflavor=x\n-Dquick\n-D\nmode=a=b\n-T4\n",
|
||||
);
|
||||
assert_eq!(config.profiles, ["ci", "!slow", "native", "docs"]);
|
||||
let properties = HashMap::from(
|
||||
[("flavor", "x"), ("quick", "true"), ("mode", "a=b")].map(|(k, v)| (k.to_owned(), v.to_owned())),
|
||||
);
|
||||
assert_eq!(config.properties, properties);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditions_hold_as_mavens_activators_decide() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("present")).unwrap();
|
||||
let activation = ProfileActivation { jdk: Some(21), ..Default::default() };
|
||||
let config = MavenConfig::parse("-Dflavor=x\n-Dempty=\n");
|
||||
let env = Env { activation: &activation, config: &config, basedir: dir.path() };
|
||||
let family = if cfg!(windows) {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"mac"
|
||||
} else {
|
||||
"unix"
|
||||
};
|
||||
let cases = [
|
||||
("<property><name>flavor</name></property>".to_owned(), true),
|
||||
("<property><name>!flavor</name></property>".into(), false),
|
||||
("<property><name>flavor</name><value>x</value></property>".into(), true),
|
||||
("<property><name>flavor</name><value>!x</value></property>".into(), false),
|
||||
("<property><name>empty</name></property>".into(), false),
|
||||
("<property><name>!unset</name></property>".into(), true),
|
||||
(format!("<os><family>{family}</family></os>"), true),
|
||||
(format!("<os><family>!{family}</family></os>"), false),
|
||||
("<os><family>os/400</family></os>".into(), false),
|
||||
(format!("<os><arch>{}</arch></os>", os_arch()), true),
|
||||
// Maven compares what Java reports (`Mac OS X`, `aarch64`), not other spellings.
|
||||
(format!("<os><name>{}</name></os>", os_name()), true),
|
||||
("<os><name>macos</name></os>".into(), false),
|
||||
("<os><arch>arm64</arch></os>".into(), false),
|
||||
("<os/>".into(), false),
|
||||
("<file><exists>present</exists></file>".into(), true),
|
||||
("<file><missing>${basedir}/absent</missing></file>".into(), true),
|
||||
("<file/>".into(), false),
|
||||
("<jdk>[17,)</jdk>".into(), true),
|
||||
("<jdk></jdk>".into(), true),
|
||||
(format!("<os><family>{family}</family></os><jdk>[30,)</jdk>"), false),
|
||||
];
|
||||
for (activation, expected) in cases {
|
||||
assert_eq!(holds(&env, &activation), expected, "{activation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_turned_off_stays_off_and_active_by_default_ones_step_aside() {
|
||||
let ps = profiles(
|
||||
"<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>\
|
||||
<profile><id>ci</id></profile>",
|
||||
);
|
||||
let config = MavenConfig::default();
|
||||
let none = [false, false];
|
||||
let select = |profiles: &[&str], choices: &[&str], implicit: bool| {
|
||||
let activation = ProfileActivation {
|
||||
profiles: profiles.iter().map(|p| p.to_string()).collect(),
|
||||
choices: choices.iter().map(|p| p.to_string()).collect(),
|
||||
jdk: None,
|
||||
};
|
||||
let env = Env { activation: &activation, config: &config, basedir: Path::new("/") };
|
||||
if implicit { env.implicit(&ps, &none) } else { env.select(&ps, &none, None) }
|
||||
};
|
||||
assert_eq!(select(&[], &[], false), [true, false]);
|
||||
assert_eq!(select(&[], &["ci"], false), [false, true]);
|
||||
assert_eq!(select(&[], &["ci", "dev"], false), [true, true]);
|
||||
// Turned off by the tool window while Settings turn it on: off, whatever the order.
|
||||
assert_eq!(select(&["ci"], &["!ci"], false), [true, false]);
|
||||
// Still on unless the tool window turns it off, so it keeps passing `-P!ci`.
|
||||
assert_eq!(select(&["ci"], &["!ci"], true), [true, true]);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -44,7 +43,15 @@ impl Artifact {
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
let relative = jar.strip_prefix(repository).ok()?;
|
||||
let (jar, relative) = match jar.strip_prefix(repository) {
|
||||
Ok(rel) => (jar.to_path_buf(), rel.to_path_buf()),
|
||||
Err(_) => {
|
||||
let canon_repo = dunce::canonicalize(repository).ok()?;
|
||||
let canon_jar = dunce::canonicalize(jar).unwrap_or_else(|_| jar.to_path_buf());
|
||||
let rel = canon_jar.strip_prefix(&canon_repo).ok()?.to_path_buf();
|
||||
(canon_jar, rel)
|
||||
}
|
||||
};
|
||||
let parts: Vec<&str> = relative
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
@@ -64,8 +71,8 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
binary: jar,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,6 +106,11 @@ fn resolve(
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
// The newest `maven-dependency-plugin` the project's Maven can load (#8114).
|
||||
let plugin = format!(
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:{}",
|
||||
super::pinned_plugin("maven-dependency-plugin", super::maven_version(&project.command))
|
||||
);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
@@ -107,14 +119,14 @@ fn resolve(
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
format!("{plugin}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
args.extend([format!("{plugin}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
@@ -290,6 +302,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_canonicalized_jar_against_non_canonical_repository() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let real_repo = dir.path().join("real-repo");
|
||||
let sibling = dir.path().join("other");
|
||||
let jar = real_repo.join("org/example/demo/1.2.3/demo-1.2.3.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(&sibling).unwrap();
|
||||
fs::write(&jar, b"").unwrap();
|
||||
let canon_jar = dunce::canonicalize(&jar).unwrap();
|
||||
let non_canon_repo = sibling.join("..").join("real-repo");
|
||||
|
||||
let found = artifact(&canon_jar, &non_canon_repo).expect("should match via canonicalized repo fallback");
|
||||
assert_eq!(found.group, "org.example");
|
||||
assert_eq!(found.name, "demo");
|
||||
assert_eq!(found.version, "1.2.3");
|
||||
assert_eq!(found.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link_repo = dir.path().join("m2-link");
|
||||
std::os::unix::fs::symlink(&real_repo, &link_repo).unwrap();
|
||||
let linked = artifact(&canon_jar, &link_repo).expect("should match through symlinked Maven repo");
|
||||
assert_eq!(linked.group, "org.example");
|
||||
assert_eq!(linked.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
@@ -81,6 +81,9 @@ struct GradleCache {
|
||||
/// The projects report how their resources are processed; older caches are stale.
|
||||
#[serde(default)]
|
||||
resources: bool,
|
||||
/// The source sets report the `Test` tasks running them; older caches are stale.
|
||||
#[serde(default)]
|
||||
test_tasks: bool,
|
||||
}
|
||||
|
||||
/// Init script printing every project, its source sets and Java version once configured.
|
||||
@@ -89,34 +92,39 @@ const MODEL_INIT_SCRIPT: &str = include_str!("gradle-model.gradle");
|
||||
const MAVEN_CACHE: &str = "maven.json";
|
||||
const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
/// `repo` is the local repository the build resolves from and `maven` the version of the Maven
|
||||
/// that runs them, when known. Both goals name their plugin by coordinates: offline, a prefix
|
||||
/// resolves only from group metadata the repository may lack. The tree uses a pinned
|
||||
/// `maven-dependency-plugin` whose `-Dverbose` lists the occurrences Maven omitted (conflicts,
|
||||
/// duplicates; dropped in 3.0, back since 3.2), the newest that `maven` can load; offline it is
|
||||
/// used only when an earlier sync downloaded it, otherwise the newest compatible version in the
|
||||
/// local repository is. Offline without a cached compatible 3.x `maven-help-plugin`,
|
||||
/// `effective-pom` is skipped so `mvn -o` still resolves the dependency tree instead of failing
|
||||
/// to download the help plugin.
|
||||
fn maven_sync_goals(
|
||||
effective: &Path,
|
||||
offline: bool,
|
||||
repo: Option<&Path>,
|
||||
maven: Option<maven::MavenVersion>,
|
||||
) -> Vec<String> {
|
||||
let version = maven::pinned_plugin("maven-dependency-plugin", maven);
|
||||
let jar =
|
||||
format!("org/apache/maven/plugins/maven-dependency-plugin/{version}/maven-dependency-plugin-{version}.jar");
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(jar).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
format!("org.apache.maven.plugins:maven-dependency-plugin:{version}:tree")
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2, maven)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3, maven).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo, maven));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
@@ -295,8 +303,9 @@ pub fn apply_gradle_cache(root: &Path, cache_dir: &Path, model: &mut GradleModel
|
||||
}
|
||||
}
|
||||
// A successful sync from before projects were cached has not seen computed includes,
|
||||
// nor, before resources were read, which launches need Gradle to process them.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources);
|
||||
// nor, before resources were read, which launches need Gradle to process them, nor, before
|
||||
// test tasks were read, which task runs the tests of a test suite.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources || !cache.test_tasks);
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
model.stale = outdated || cache.hash != hash_gradle_files(&gradle::build_files(root, model));
|
||||
@@ -375,11 +384,12 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked_jdk(
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, &options.maven_settings, &options.profiles, options.jdk_version);
|
||||
let mut model = maven::load_with_activation(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
options.jdk_version,
|
||||
&activation,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -414,9 +424,9 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref(), maven::maven_version(command)));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
@@ -526,6 +536,7 @@ pub fn sync_gradle_model(
|
||||
tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() },
|
||||
projects,
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache)
|
||||
}
|
||||
@@ -783,7 +794,7 @@ mod tests {
|
||||
test,
|
||||
src: src.iter().map(|p| core_src(p)).collect(),
|
||||
res: res.iter().map(|p| core_src(p)).collect(),
|
||||
processed: None,
|
||||
..Default::default()
|
||||
};
|
||||
// A settings script's own println comes first; task listing lines follow.
|
||||
let out = format!(
|
||||
@@ -884,6 +895,7 @@ mod tests {
|
||||
})
|
||||
.collect(),
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
apply_gradle_cache(&root, &cache_dir, &mut model);
|
||||
@@ -929,6 +941,7 @@ mod tests {
|
||||
..Default::default()
|
||||
}],
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
..Default::default()
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
@@ -959,15 +972,19 @@ mod tests {
|
||||
assert!(!save_maven_offline(&tmp.path().join("other"), false).unwrap(), "online is the default");
|
||||
}
|
||||
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), None);
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
@@ -978,21 +995,37 @@ mod tests {
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None)[2], DEPENDENCY_TREE);
|
||||
}
|
||||
|
||||
/// #8114: an old Maven gets plugin versions it can load, also for the verbose tree.
|
||||
#[test]
|
||||
fn sync_goals_follow_the_maven_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let goals = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), Some((3, 3, 9)));
|
||||
assert_eq!(
|
||||
goals,
|
||||
[
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom",
|
||||
"-Doutput=e.xml",
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree",
|
||||
"-Dverbose",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -125,8 +125,11 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
let evaluate = crate::maven::plugin_goal(
|
||||
"help:evaluate",
|
||||
crate::maven::local_repository_for(&top.options).as_deref(),
|
||||
crate::maven::maven_version(&top.command),
|
||||
);
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
|
||||
@@ -86,6 +86,8 @@ pub struct EditorAppearanceSettings {
|
||||
pub indent_guides: bool,
|
||||
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
|
||||
pub rainbow_indent_guides: bool,
|
||||
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
|
||||
pub rainbow_indent_guides_fill: bool,
|
||||
/// Right margin and visual guides from Code Style.
|
||||
pub hard_wrap_guides: bool,
|
||||
pub intention_bulb: bool,
|
||||
@@ -114,6 +116,7 @@ impl Default for EditorAppearanceSettings {
|
||||
whitespace_trailing: true,
|
||||
indent_guides: true,
|
||||
rainbow_indent_guides: false,
|
||||
rainbow_indent_guides_fill: false,
|
||||
hard_wrap_guides: true,
|
||||
intention_bulb: true,
|
||||
render_doc_comments: false,
|
||||
@@ -377,6 +380,8 @@ pub struct CodeEditingSettings {
|
||||
pub quick_doc_delay: u32,
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
/// Show the diagnostic producer and rule code beneath each message in editor hover tooltips.
|
||||
pub show_diagnostic_source_on_hover: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
@@ -390,6 +395,7 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_on_hover: true,
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
show_diagnostic_source_on_hover: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
@@ -741,4 +747,15 @@ mod sticky_lines_tests {
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_source_on_hover_defaults_to_true_and_round_trips() {
|
||||
let legacy: CodeEditingSettings = serde_json::from_value(serde_json::json!({"quickDocOnHover": true})).unwrap();
|
||||
assert!(legacy.show_diagnostic_source_on_hover);
|
||||
let hidden: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"showDiagnosticSourceOnHover": false})).unwrap();
|
||||
assert!(!hidden.show_diagnostic_source_on_hover);
|
||||
let serialized = serde_json::to_value(&hidden).unwrap();
|
||||
assert_eq!(serialized["showDiagnosticSourceOnHover"], false);
|
||||
}
|
||||
}
|
||||
@@ -208,6 +208,12 @@ pub enum IdeEvent {
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// An open file was made read-only or writable outside the IDE (`chmod`, a VCS sync), which
|
||||
/// the editor only reads when it opens the file.
|
||||
DocReadOnly {
|
||||
doc: DocId,
|
||||
read_only: bool,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
|
||||
@@ -81,9 +81,61 @@ pub fn strip(src: &str) -> String {
|
||||
cleaned
|
||||
}
|
||||
|
||||
/// Comments and a leading byte order mark turned into spaces, byte for byte, so that offsets
|
||||
/// into the result are offsets into `src`. Line breaks stay, and so do trailing commas.
|
||||
pub fn blank_comments(src: &str) -> String {
|
||||
let mut out = src.as_bytes().to_vec();
|
||||
let blank = |out: &mut [u8]| out.iter_mut().filter(|b| !matches!(b, b'\n' | b'\r')).for_each(|b| *b = b' ');
|
||||
let mut i = 0;
|
||||
if src.starts_with('\u{feff}') {
|
||||
i = '\u{feff}'.len_utf8();
|
||||
blank(&mut out[..i]);
|
||||
}
|
||||
let mut in_str = false;
|
||||
while i < src.len() {
|
||||
let rest = &src.as_bytes()[i..];
|
||||
let comment = match rest {
|
||||
[b'\\', ..] if in_str => {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
[b'"', ..] => {
|
||||
in_str = !in_str;
|
||||
None
|
||||
}
|
||||
[b'/', b'/', ..] if !in_str => Some(rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len())),
|
||||
// An unterminated block comment runs to the end, leaving a document that still parses
|
||||
// only if it was complete before it.
|
||||
[b'/', b'*', ..] if !in_str => {
|
||||
Some(rest[2..].windows(2).position(|w| w == b"*/").map_or(rest.len(), |end| end + 4))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match comment {
|
||||
Some(len) => {
|
||||
blank(&mut out[i..i + len]);
|
||||
i += len;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
// Only whole characters were replaced: comments and the mark start and end on ASCII.
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::strip;
|
||||
use super::{blank_comments, strip};
|
||||
|
||||
#[test]
|
||||
fn blanking_comments_keeps_every_offset_and_trailing_commas() {
|
||||
let src = "\u{feff}{// é\r\n\"a//\\\"\": /* ü\n*/ 1,}";
|
||||
let blank = blank_comments(src);
|
||||
assert_eq!(blank.len(), src.len());
|
||||
assert_eq!(blank.split_whitespace().collect::<Vec<_>>(), ["{", "\"a//\\\"\":", "1,}"]);
|
||||
assert_eq!(blank.find('1'), src.find('1'));
|
||||
assert_eq!(blank_comments("{}/* open é"), "{} ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_comments_and_trailing_commas_outside_strings() {
|
||||
|
||||
@@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`,
|
||||
/// `.bat`) always run through it.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
|
||||
#[cfg(windows)]
|
||||
fn compact_batch_path(cmd: &mut Command) {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Component, Prefix};
|
||||
|
||||
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
// Rust runs these files through cmd.exe.
|
||||
let extension = Path::new(cmd.get_program()).extension();
|
||||
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
|
||||
return;
|
||||
@@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) {
|
||||
Some((_, path)) => path.map(OsStr::to_owned),
|
||||
None => std::env::var_os("PATH"),
|
||||
};
|
||||
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
|
||||
|
||||
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
|
||||
// missing now, keeping search precedence and leaving UNC and relative paths alone.
|
||||
let dirs = std::env::split_paths(&path).filter(|dir| {
|
||||
let Some(path) = path else { return };
|
||||
// The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing
|
||||
// now, leaving UNC and relative paths alone.
|
||||
let present = |dir: &Path| {
|
||||
let local = dir.is_absolute()
|
||||
&& matches!(dir.components().next(), Some(Component::Prefix(p))
|
||||
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
|
||||
!local
|
||||
|| !std::fs::symlink_metadata(dir)
|
||||
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
|
||||
});
|
||||
if let Ok(compact) = std::env::join_paths(dirs)
|
||||
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
|
||||
{
|
||||
};
|
||||
if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) {
|
||||
cmd.env("PATH", compact);
|
||||
}
|
||||
}
|
||||
|
||||
/// The 8.3 form of `dir`, when the volume has one.
|
||||
#[cfg(windows)]
|
||||
fn short_path(dir: &Path) -> Option<std::path::PathBuf> {
|
||||
use std::os::windows::ffi::{OsStrExt, OsStringExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
|
||||
|
||||
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut buf = vec![0u16; wide.len()];
|
||||
let len = u32::try_from(buf.len()).ok()?;
|
||||
// SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated.
|
||||
let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize;
|
||||
// 0 is an error; a value of at least the buffer's length is the size a longer form needs.
|
||||
if written == 0 || written >= buf.len() {
|
||||
return None;
|
||||
}
|
||||
buf.truncate(written);
|
||||
Some(OsString::from_wide(&buf).into())
|
||||
}
|
||||
|
||||
/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later
|
||||
/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping
|
||||
/// the search order; when that is still too long, directories take `shorten`'s form, longest
|
||||
/// first, until it fits. `None` when `path` fits already or nothing got shorter.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn compact_path_list(
|
||||
path: &OsStr,
|
||||
limit: usize,
|
||||
present: impl Fn(&Path) -> bool,
|
||||
shorten: impl Fn(&Path) -> Option<std::path::PathBuf>,
|
||||
) -> Option<OsString> {
|
||||
let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count();
|
||||
let original = width(path);
|
||||
if original <= limit {
|
||||
return None;
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut dirs: Vec<std::path::PathBuf> = std::env::split_paths(path)
|
||||
.filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d))
|
||||
.collect();
|
||||
let mut joined = std::env::join_paths(&dirs).ok()?;
|
||||
if width(&joined) > limit {
|
||||
let mut longest: Vec<usize> = (0..dirs.len()).collect();
|
||||
longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str())));
|
||||
let mut total = width(&joined);
|
||||
for i in longest {
|
||||
if total <= limit {
|
||||
break;
|
||||
}
|
||||
if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) {
|
||||
total -= width(dirs[i].as_os_str()) - width(short.as_os_str());
|
||||
dirs[i] = short;
|
||||
}
|
||||
}
|
||||
joined = std::env::join_paths(&dirs).ok()?;
|
||||
}
|
||||
(width(&joined) < original).then_some(joined)
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
|
||||
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
|
||||
@@ -1295,6 +1353,26 @@ mod tests {
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compacts_a_path_too_long_for_cmd() {
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
let join = |dirs: &[&str]| OsString::from(dirs.join(sep));
|
||||
let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40));
|
||||
let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone"));
|
||||
let present = |d: &Path| !d.ends_with("gone");
|
||||
let never = |_: &Path| None;
|
||||
// Fits already: left alone.
|
||||
assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None);
|
||||
// Later duplicates and missing directories go, the order stays.
|
||||
let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]);
|
||||
assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c])));
|
||||
// Still too long: the longest directories take their short form until it fits.
|
||||
let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy())));
|
||||
let path = join(&[&a, &format!("{b}-longer"), &c]);
|
||||
assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c])));
|
||||
assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
|
||||
@@ -312,20 +312,7 @@ 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 = …`).
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
@@ -340,24 +327,6 @@ pub enum AutoMemoryMode {
|
||||
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")]
|
||||
@@ -371,18 +340,10 @@ pub struct AgentProviderMemoryPolicy {
|
||||
#[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>]`).
|
||||
/// Per-provider cross-session 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
|
||||
@@ -865,19 +826,25 @@ pub enum ToolchainKind {
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
/// A Visual Studio installation: configure, build and run get the environment its
|
||||
/// `vcvarsall.bat` sets up (Windows only).
|
||||
#[serde(rename = "visualStudio")]
|
||||
VisualStudio,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected: from the MinGW directory, else from `PATH`.
|
||||
/// detected from the toolchain installation when it has them, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`).
|
||||
/// The MinGW directory (the one holding `bin`), or the Visual Studio installation directory.
|
||||
pub path: String,
|
||||
/// `vcvarsall.bat`'s architecture argument (`x64`, `x86`, `x64_arm64` …); empty is the host's.
|
||||
pub arch: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make, nmake or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
@@ -1087,6 +1054,8 @@ pub struct GeneralSettings {
|
||||
pub close_tabs_with_window: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
|
||||
pub close_remote_window: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
/// Save all files after `idle_seconds` without input.
|
||||
@@ -1117,6 +1086,7 @@ impl Default for GeneralSettings {
|
||||
close_without_welcome: false,
|
||||
close_tabs_with_window: false,
|
||||
open_project_in: "ask".into(),
|
||||
close_remote_window: "ask".into(),
|
||||
default_project_directory: String::new(),
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
@@ -1912,8 +1882,9 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
/// interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
/// cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
|
||||
@@ -14,4 +14,5 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dunce.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -51,8 +51,14 @@ fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
parse_into(xml, base, &mut acc)?;
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
/// Like [`parse`], merging into the data of other reports.
|
||||
pub(crate) fn parse_into(xml: &str, base: &Path, acc: &mut Accumulator) -> Result<(), quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
@@ -72,7 +78,8 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
// coverlet writes `True`.
|
||||
if attr(&e, "branch").is_some_and(|b| b.eq_ignore_ascii_case("true"))
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
@@ -115,7 +122,7 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -162,6 +169,16 @@ mod tests {
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
/// Written by `dotnet test --collect:"XPlat Code Coverage"` (coverlet.collector 6.0.4).
|
||||
#[test]
|
||||
fn reads_a_coverlet_report() {
|
||||
let suite =
|
||||
parse(include_str!("testdata/coverlet.cobertura.xml"), Path::new("/root")).unwrap().finish("coverlet");
|
||||
let [file] = suite.files.as_slice() else { panic!("{:?}", suite.files) };
|
||||
assert!((file.path.as_ref() as &Path).ends_with("home/dev/dn app/Calc/Calculator.cs"));
|
||||
assert_eq!((file.lines_covered, file.lines_total, file.branches_covered, file.branches_total), (6, 7, 1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! `dotnet test` with coverage: coverlet.collector under VSTest,
|
||||
//! Microsoft.Testing.Extensions.CodeCoverage under Microsoft.Testing.Platform.
|
||||
//!
|
||||
//! The run gets its own results directory, so only this run's reports are read.
|
||||
|
||||
use crate::plan::{missing, ready, unsupported};
|
||||
use crate::{CoveragePrepared, CoverageReportSpec};
|
||||
use ide_run::{RunConfig, wrap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const COLLECTOR: &str = "coverlet.collector";
|
||||
const CODE_COVERAGE: &str = "Microsoft.Testing.Extensions.CodeCoverage";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Runner {
|
||||
VsTest,
|
||||
/// `global.json` selects the testing platform's `dotnet test`.
|
||||
Mtp,
|
||||
/// A testing-platform project run through the VSTest target: its options go after `--`.
|
||||
MtpLegacy,
|
||||
}
|
||||
|
||||
/// What MSBuild says about a project: (testing-platform project, referenced packages).
|
||||
fn evaluation(json: &str) -> Option<(bool, Vec<String>)> {
|
||||
let json: serde_json::Value = serde_json::from_str(&json[json.find('{')?..]).ok()?;
|
||||
let packages: Vec<String> = json["Items"]["PackageReference"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|p| p["Identity"].as_str().map(str::to_ascii_lowercase))
|
||||
.collect();
|
||||
let mtp = json["Properties"]
|
||||
.as_object()
|
||||
.is_some_and(|p| p.values().any(|v| v.as_str().is_some_and(|v| v.eq_ignore_ascii_case("true"))))
|
||||
|| packages.iter().any(|p| p.starts_with("xunit.v3.mtp"));
|
||||
Some((mtp, packages))
|
||||
}
|
||||
|
||||
/// Whether the nearest `global.json` selects Microsoft.Testing.Platform.
|
||||
fn global_mtp(dir: &Path) -> bool {
|
||||
dir.ancestors().find_map(|d| std::fs::read_to_string(d.join("global.json")).ok()).is_some_and(|text| {
|
||||
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
.is_ok_and(|j| j["test"]["runner"] == "Microsoft.Testing.Platform")
|
||||
})
|
||||
}
|
||||
|
||||
/// The project file the configuration tests; none for a solution or a bare `dotnet test`.
|
||||
fn project_file(config: &RunConfig, dir: &Path) -> Option<PathBuf> {
|
||||
config
|
||||
.extras
|
||||
.params
|
||||
.get("project")
|
||||
.into_iter()
|
||||
.chain(config.args.iter().skip(1))
|
||||
.find(|a| Path::new(a).extension().is_some_and(|e| e.to_string_lossy().to_ascii_lowercase().ends_with("proj")))
|
||||
.map(|p| dir.join(p))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(config: &RunConfig, dir: &Path, out: &Path) -> CoveragePrepared {
|
||||
if config.args.first().is_none_or(|a| a != "test") {
|
||||
return unsupported(".NET coverage runs `dotnet test` configurations.");
|
||||
}
|
||||
let project = project_file(config, dir);
|
||||
let evaluated = project.as_ref().and_then(|project| {
|
||||
let mut argv = vec![
|
||||
config.command.clone(),
|
||||
"msbuild".into(),
|
||||
project.to_string_lossy().into_owned(),
|
||||
"-nologo".into(),
|
||||
"-getProperty:IsTestingPlatformApplication,TestingPlatformDotnetTestSupport,EnableMSTestRunner".into(),
|
||||
"-getItem:PackageReference".into(),
|
||||
];
|
||||
if let Some(framework) = config.extras.params.get("framework").filter(|f| !f.is_empty()) {
|
||||
argv.push(format!("-p:TargetFramework={framework}"));
|
||||
}
|
||||
evaluation(&wrap::capture(&argv, dir, config)?)
|
||||
});
|
||||
let project_dir = project.as_deref().and_then(Path::parent).unwrap_or(dir);
|
||||
let runner = if global_mtp(project_dir) {
|
||||
Runner::Mtp
|
||||
} else if evaluated.as_ref().is_some_and(|(mtp, _)| *mtp) {
|
||||
Runner::MtpLegacy
|
||||
} else {
|
||||
Runner::VsTest
|
||||
};
|
||||
let package = if runner == Runner::VsTest { COLLECTOR } else { CODE_COVERAGE };
|
||||
if let Some((project, (_, packages))) = project.as_ref().zip(evaluated.as_ref())
|
||||
&& !packages.iter().any(|p| p.eq_ignore_ascii_case(package))
|
||||
{
|
||||
let target = project.strip_prefix(dir).unwrap_or(project).to_string_lossy();
|
||||
let add = [&config.command, "add", &target, "package", package].map(str::to_owned);
|
||||
return missing(
|
||||
package,
|
||||
format!(".NET coverage needs the {package} package in the test project."),
|
||||
Some((add.to_vec(), dir)),
|
||||
);
|
||||
}
|
||||
launch(config, dir, out, runner, package)
|
||||
}
|
||||
|
||||
fn launch(config: &RunConfig, dir: &Path, out: &Path, runner: Runner, package: &str) -> CoveragePrepared {
|
||||
let results = out.to_string_lossy().into_owned();
|
||||
let mut extra: Vec<String> = match runner {
|
||||
Runner::VsTest => vec!["--collect:XPlat Code Coverage".into()],
|
||||
_ => ["--coverage", "--coverage-output-format", "cobertura"].map(str::to_owned).to_vec(),
|
||||
};
|
||||
extra.extend(["--results-directory".into(), results]);
|
||||
let mut launch = config.clone();
|
||||
// A `dotnet test` configuration type rebuilds its command line from the parameters.
|
||||
launch.extras.params.insert("coverageArgs".into(), serde_json::json!(extra).to_string());
|
||||
let boundary = launch.args.iter().position(|a| a == "--");
|
||||
match runner {
|
||||
Runner::VsTest => {
|
||||
let at = boundary.unwrap_or(launch.args.len());
|
||||
launch.args.splice(at..at, extra);
|
||||
}
|
||||
Runner::Mtp => launch.args.extend(extra),
|
||||
Runner::MtpLegacy => {
|
||||
if boundary.is_none() {
|
||||
launch.args.push("--".into());
|
||||
}
|
||||
launch.args.extend(extra);
|
||||
}
|
||||
}
|
||||
let report = CoverageReportSpec::Cobertura {
|
||||
runner: package.to_owned(),
|
||||
dir: out.to_path_buf().into(),
|
||||
base: dir.to_path_buf().into(),
|
||||
hint: format!("Check the test output, and that every test project references {package}."),
|
||||
};
|
||||
ready(package, &launch, launch.command.clone(), launch.args.clone(), report)
|
||||
}
|
||||
|
||||
/// VSTest writes `<dir>/<guid>/coverage.cobertura.xml`, the testing platform
|
||||
/// `<dir>/<name>.cobertura.xml`. Deeper files are the TRX logger's copies of the same data.
|
||||
pub(crate) fn reports(dir: &Path) -> Vec<PathBuf> {
|
||||
let is_report = |p: &Path| p.is_file() && p.to_string_lossy().ends_with(".cobertura.xml");
|
||||
let entries = |d: &Path| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect::<Vec<_>>();
|
||||
let mut found: Vec<PathBuf> = entries(dir)
|
||||
.into_iter()
|
||||
.flat_map(|p| if p.is_dir() { entries(&p) } else { vec![p] })
|
||||
.filter(|p| is_report(p))
|
||||
.collect();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(args: &[&str]) -> RunConfig {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args,
|
||||
"env": {}, "detected": true, "isTest": true,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn args(runner: Runner, base: &[&str]) -> Vec<String> {
|
||||
match launch(&config(base), Path::new("/p"), Path::new("/o"), runner, "x") {
|
||||
CoveragePrepared::Ready { launch, .. } => launch.args,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_go_where_each_runner_reads_them() {
|
||||
assert_eq!(
|
||||
args(Runner::VsTest, &["test", "--", "A=1"]),
|
||||
["test", "--collect:XPlat Code Coverage", "--results-directory", "/o", "--", "A=1"]
|
||||
);
|
||||
let platform = ["--coverage", "--coverage-output-format", "cobertura", "--results-directory", "/o"];
|
||||
assert_eq!(args(Runner::Mtp, &["test"])[1..], platform);
|
||||
let legacy = args(Runner::MtpLegacy, &["test"]);
|
||||
assert_eq!((legacy[1].as_str(), &legacy[2..]), ("--", platform.map(str::to_owned).as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msbuild_evaluation_names_packages_and_the_platform() {
|
||||
let json = r#"noise {"Properties":{"IsTestingPlatformApplication":""},"Items":{"PackageReference":[{"Identity":"Coverlet.Collector"}]}}"#;
|
||||
assert_eq!(evaluation(json), Some((false, vec!["coverlet.collector".into()])));
|
||||
let json = r#"{"Properties":{"EnableMSTestRunner":"true"},"Items":{"PackageReference":[]}}"#;
|
||||
assert_eq!(evaluation(json), Some((true, vec![])));
|
||||
assert_eq!(evaluation("error MSB1009"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_files_and_global_json() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = project_file(&config(&["test", "a/T.fsproj"]), tmp.path()).unwrap();
|
||||
assert_eq!(project, tmp.path().join("a/T.fsproj"));
|
||||
assert_eq!(project_file(&config(&["test", "All.sln"]), tmp.path()), None);
|
||||
assert!(!global_mtp(&tmp.path().join("a")));
|
||||
std::fs::write(
|
||||
tmp.path().join("global.json"),
|
||||
"{ // x\n\"test\":{\"runner\":\"Microsoft.Testing.Platform\"},}",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(global_mtp(&tmp.path().join("a")));
|
||||
}
|
||||
|
||||
/// One report per test project is merged; the TRX logger's copies are not counted twice.
|
||||
#[test]
|
||||
fn merges_the_reports_of_one_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let xml = include_str!("testdata/coverlet.cobertura.xml");
|
||||
for file in
|
||||
["guid-a/coverage.cobertura.xml", "guid-b/coverage.cobertura.xml", "t/In/host/coverage.cobertura.xml"]
|
||||
{
|
||||
let file = tmp.path().join(file);
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(file, xml).unwrap();
|
||||
}
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "coverlet.collector".into(),
|
||||
dir: tmp.path().to_path_buf().into(),
|
||||
base: tmp.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
let suite = crate::collect(&spec).unwrap();
|
||||
assert_eq!(suite.files[0].lines[0].hits, 2);
|
||||
std::fs::write(tmp.path().join("direct.cobertura.xml"), xml).unwrap();
|
||||
assert_eq!(reports(tmp.path()).len(), 3);
|
||||
// A cancelled or failed build leaves nothing: say why.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "x".into(),
|
||||
dir: empty.path().to_path_buf().into(),
|
||||
base: empty.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
assert!(crate::collect(&spec).unwrap_err().to_string().contains("why"));
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,13 @@
|
||||
//! | 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` |
|
||||
//! | .NET (`dotnet test`) | coverlet.collector, or Microsoft.Testing.Extensions.CodeCoverage | Cobertura XML |
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod dotnet;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -94,6 +96,9 @@ pub enum CoverageReportSpec {
|
||||
SimpleCov { path: IpcPath, base: IpcPath },
|
||||
/// Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`.
|
||||
Jacoco { dir: IpcPath },
|
||||
/// The Cobertura reports `dotnet test` left in its results directory `dir`: one per test
|
||||
/// project and target framework. `hint` explains why there might be none.
|
||||
Cobertura { runner: String, dir: IpcPath, base: IpcPath, hint: String },
|
||||
/// 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.
|
||||
@@ -218,6 +223,19 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
}
|
||||
Ok(acc.finish("JaCoCo"))
|
||||
}
|
||||
CoverageReportSpec::Cobertura { runner, dir, base, hint } => {
|
||||
let reports = dotnet::reports(dir);
|
||||
if reports.is_empty() {
|
||||
return Err(IdeError::not_found(format!("the run produced no coverage report. {hint}")));
|
||||
}
|
||||
let mut acc = Accumulator::default();
|
||||
for report in reports {
|
||||
let xml = std::fs::read_to_string(&report)?;
|
||||
cobertura::parse_into(&xml, base, &mut acc)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", report.display())))?;
|
||||
}
|
||||
Ok(acc.finish(runner))
|
||||
}
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
|
||||
@@ -28,11 +28,15 @@ fn path(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
pub(crate) fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
CoveragePrepared::Unsupported { reason: reason.into() }
|
||||
}
|
||||
|
||||
fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>, &Path)>) -> CoveragePrepared {
|
||||
pub(crate) fn missing(
|
||||
tool: &str,
|
||||
message: impl Into<String>,
|
||||
install: Option<(Vec<String>, &Path)>,
|
||||
) -> CoveragePrepared {
|
||||
CoveragePrepared::MissingTool {
|
||||
tool: tool.to_owned(),
|
||||
message: message.into(),
|
||||
@@ -43,7 +47,7 @@ fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>,
|
||||
}
|
||||
}
|
||||
|
||||
fn ready(
|
||||
pub(crate) fn ready(
|
||||
runner: &str,
|
||||
config: &RunConfig,
|
||||
command: String,
|
||||
@@ -69,6 +73,7 @@ pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared
|
||||
let first = config.args.first().map(String::as_str).unwrap_or_default();
|
||||
match program.as_str() {
|
||||
"cargo" => cargo(config, &dir, out),
|
||||
"dotnet" => crate::dotnet::prepare(config, &dir, out),
|
||||
"go" if first == "test" => go(config, &dir, out),
|
||||
"go" => unsupported("Go coverage is collected by `go test`; run a test configuration with coverage."),
|
||||
"mvn" | "mvnw" => maven(config, &dir),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<coverage line-rate="0.8571" branch-rate="0.5" version="1.9" timestamp="1796282470" lines-covered="6" lines-valid="7" branches-covered="1" branches-valid="2">
|
||||
<sources>
|
||||
<source>/</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="Calc" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<classes>
|
||||
<class name="Calc.Calculator" filename="home/dev/dn app/Calc/Calculator.cs" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<methods>
|
||||
<method name="Add" signature="(System.Int32,System.Int32)" line-rate="1" branch-rate="1" complexity="1">
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
<method name="Sign" signature="(System.Int32)" line-rate="0.8332999999999999" branch-rate="0.5" complexity="2">
|
||||
<lines>
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
</methods>
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Run with Coverage against the real `dotnet` CLI on `fixtures/dotnet-coverage`.
|
||||
//! Skipped without a .NET 10 SDK, except in CI, where the workflow installs one.
|
||||
|
||||
use ide_coverage::{CoveragePrepared, CoverageSuite, collect, prepare};
|
||||
use ide_run::RunConfig;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn has_sdk() -> bool {
|
||||
let found = Command::new("dotnet")
|
||||
.arg("--list-sdks")
|
||||
.output()
|
||||
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).lines().any(|l| l.starts_with("10.")));
|
||||
assert!(found || std::env::var_os("CI").is_none(), "CI needs the .NET 10 SDK");
|
||||
found
|
||||
}
|
||||
|
||||
fn copy(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for entry in std::fs::read_dir(from).unwrap().flatten() {
|
||||
let (name, path) = (entry.file_name(), entry.path());
|
||||
if path.is_dir() {
|
||||
if name != "bin" && name != "obj" {
|
||||
copy(&path, &to.join(name));
|
||||
}
|
||||
} else {
|
||||
std::fs::copy(&path, to.join(name)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn config(args: &[&str]) -> RunConfig {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args,
|
||||
"env": {}, "detected": true, "isTest": true,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Prepares, runs and collects like the IDE does; `out` has a space in its name.
|
||||
fn covered(root: &Path, config: &RunConfig, out: &Path) -> CoverageSuite {
|
||||
std::fs::create_dir_all(out).unwrap();
|
||||
let CoveragePrepared::Ready { launch, report, .. } = prepare(root, config, out) else {
|
||||
panic!("{:?}", prepare(root, config, out));
|
||||
};
|
||||
let cwd = launch.cwd.as_deref().map_or_else(|| root.to_path_buf(), |c| root.join(c));
|
||||
let run = Command::new(&launch.command).args(&launch.args).current_dir(cwd).output().unwrap();
|
||||
assert!(run.status.success(), "{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
collect(&report).unwrap()
|
||||
}
|
||||
|
||||
/// (covered, total) lines of `Calculator.cs`, which must exist on this machine.
|
||||
fn calculator(suite: &CoverageSuite) -> (u32, u32) {
|
||||
let file = suite.files.iter().find(|f| (f.path.as_ref() as &Path).ends_with("Calc/Calculator.cs"));
|
||||
let file = file.unwrap_or_else(|| panic!("{:?}", suite.files));
|
||||
assert!((file.path.as_ref() as &Path).is_file(), "{:?}", file.path);
|
||||
(file.lines_covered, file.lines_total)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vstest_projects_solutions_and_missing_packages() {
|
||||
if !has_sdk() {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root);
|
||||
|
||||
let project = config(&["test", "Add.Tests/Add.Tests.csproj"]);
|
||||
let one = covered(&root, &project, &root.join("out one"));
|
||||
assert_eq!(calculator(&one), (1, 7));
|
||||
// Both test projects of the solution are merged.
|
||||
let all = covered(&root, &config(&["test", "Calc.slnx"]), &root.join("out all"));
|
||||
assert_eq!(calculator(&all), (6, 7));
|
||||
|
||||
let csproj = root.join("Add.Tests/Add.Tests.csproj");
|
||||
let text = std::fs::read_to_string(&csproj).unwrap();
|
||||
let without: Vec<&str> = text.lines().filter(|l| !l.contains("coverlet")).collect();
|
||||
std::fs::write(&csproj, without.join("\n")).unwrap();
|
||||
match prepare(&root, &project, &root.join("out one")) {
|
||||
CoveragePrepared::MissingTool { tool, install: Some(install), .. } => {
|
||||
assert_eq!(tool, "coverlet.collector");
|
||||
assert_eq!(install.args, ["add", "Add.Tests/Add.Tests.csproj", "package", "coverlet.collector"]);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn testing_platform_projects() {
|
||||
if !has_sdk() {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root);
|
||||
// `global.json` is read from the working directory.
|
||||
let mut config = config(&["test", "--project", "Mtp.Tests.csproj"]);
|
||||
config.cwd = Some(root.join("mtp").into());
|
||||
assert_eq!(calculator(&covered(&root, &config, &root.join("out mtp"))), (1, 7));
|
||||
}
|
||||
@@ -51,6 +51,8 @@ pub struct AdapterSpec {
|
||||
pub pinned: Option<ProgramPin>,
|
||||
/// See [`DebuggerConfig::resolve_lazy_variables`].
|
||||
pub resolve_lazy_variables: bool,
|
||||
/// Connect to the one lldb-dap server every such session shares ([`crate::lldb_server`]).
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
/// Built-in adapters used when no language definition names `adapter`.
|
||||
@@ -193,6 +195,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
|
||||
connect: config.connect.clone(),
|
||||
pinned: config.pinned.clone(),
|
||||
resolve_lazy_variables: config.resolve_lazy_variables,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +301,7 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
|
||||
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
|
||||
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
|
||||
fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
pub(crate) fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
|
||||
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
|
||||
(!own).then(|| ide_core::tool_path::search_path_in(cwd))
|
||||
}
|
||||
@@ -744,6 +747,18 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
.ok_or_else(|| missing(&spec))?
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
if spec.shared && spec.transport == Transport::Stdio && spec.connect.is_none() && spec.args.is_empty() {
|
||||
match crate::lldb_server::connect(&spec, &binary).await {
|
||||
Ok(Some(io)) => return Ok(io),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(
|
||||
target: "ide_dap::adapter",
|
||||
"no shared lldb-dap server ({}); starting one for this session",
|
||||
e.message
|
||||
),
|
||||
}
|
||||
}
|
||||
let launch_after_configuration =
|
||||
if spec.adapter == "gdb" { prepare_gdb(&spec, &binary).await? } else { false };
|
||||
let base_args = substitute_root(&spec.args, &spec.cwd);
|
||||
@@ -891,7 +906,7 @@ fn is_port_race(err: &IdeError) -> bool {
|
||||
|| message.contains("exited before accepting connections")
|
||||
}
|
||||
|
||||
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
pub(crate) fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
|
||||
stream: R,
|
||||
name: String,
|
||||
sink: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
|
||||
@@ -103,6 +103,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let session = Session::new(
|
||||
DebugSessionId(1),
|
||||
|
||||
@@ -21,6 +21,8 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod lldb_server;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
@@ -516,6 +518,7 @@ fn is_native(adapter: &str) -> bool {
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
const XCODE_ATTACH: &str = "__openideaXcodeAttach";
|
||||
|
||||
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
|
||||
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
|
||||
@@ -1203,6 +1206,7 @@ impl DebugManager {
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
@@ -1269,7 +1273,7 @@ impl DebugManager {
|
||||
parent: Option<DebugSessionId>,
|
||||
request: String,
|
||||
mut arguments: Value,
|
||||
spec: AdapterSpec,
|
||||
mut spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
@@ -1278,6 +1282,13 @@ impl DebugManager {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
}
|
||||
// Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the
|
||||
// system libraries it parsed, so the next attach skips that (#6665 E7).
|
||||
let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH));
|
||||
spec.shared = xcode_attach == Some(Value::Bool(true))
|
||||
&& adapter_name == "lldb-dap"
|
||||
&& request == "attach"
|
||||
&& arguments.get(RUN_LINK).is_some();
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Cache one lldb-dap server for successive attaches to Xcode runs (#6665 E7).
|
||||
//!
|
||||
//! An iOS app loads about 550 system libraries before its first line runs, and a fresh lldb-dap
|
||||
//! parses all of their symbol tables (about 5 million symbols) on each attach: 1.5 s on an idle
|
||||
//! Mac, far more under load. A server keeps the modules it parsed, so later sessions skip that
|
||||
//! and reach a breakpoint about as fast as Run reaches the same line. LLDB's own on-disk index
|
||||
//! cache would serve the first session too, but Xcode 27.1's lldb crashes on cached symbols.
|
||||
//!
|
||||
//! The server holds about 1 GB, so it ends once no session has been connected for
|
||||
//! [`IDLE_TIMEOUT`]; the next Debug then starts cold, as every Debug did before. A shell holds
|
||||
//! it and ends it when its stdin closes: when the IDE quits or crashes, when the server idles
|
||||
//! out, or when a server for another lldb-dap or environment replaces it.
|
||||
|
||||
use crate::adapter::{AdapterIo, AdapterSpec, adapter_path, pump_lines};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsString;
|
||||
use std::fs::Permissions;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::pin::Pin;
|
||||
use std::process::Stdio;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::UnixStream;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
/// What a server was started with: a session reuses it only when its own start would match.
|
||||
#[derive(PartialEq)]
|
||||
struct Key {
|
||||
binary: PathBuf,
|
||||
cwd: PathBuf,
|
||||
cwd_env: Vec<(OsString, Option<OsString>)>,
|
||||
}
|
||||
|
||||
struct Server {
|
||||
key: Key,
|
||||
socket: PathBuf,
|
||||
/// Recent stderr for the active connection.
|
||||
stderr: Arc<parking_lot::Mutex<Vec<String>>>,
|
||||
idle: Arc<Idle>,
|
||||
/// The shell holding the server; dropping it closes its stdin, which ends the server.
|
||||
_holder: Child,
|
||||
_socket_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
/// When the last session disconnected, or `None` while a session owns the server.
|
||||
type Idle = parking_lot::Mutex<Option<Instant>>;
|
||||
|
||||
type Slot = tokio::sync::Mutex<Option<Server>>;
|
||||
|
||||
static SERVER: LazyLock<Slot> = LazyLock::new(Default::default);
|
||||
|
||||
/// How long a server with no session stays up.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
/// How long a new server may take to listen.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// A connection to a running server; a server that does not take it is replaced.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Starts the server and ends it when the shell's stdin closes (`read` sees EOF) or when the
|
||||
/// server exits on its own (`wait`), so a `binary` without `--connection` fails at once.
|
||||
const HOLDER: &str = "exec 3<&0\n\
|
||||
\"$0\" --connection \"$1\" </dev/null >/dev/null &\n\
|
||||
server=$!\n\
|
||||
(read _ <&3; kill \"$server\" 2>/dev/null) &\n\
|
||||
watcher=$!\n\
|
||||
wait \"$server\"\n\
|
||||
result=$?\n\
|
||||
kill \"$watcher\" 2>/dev/null\n\
|
||||
wait \"$watcher\" 2>/dev/null\n\
|
||||
exit \"$result\"\n";
|
||||
|
||||
/// A connection to the shared server of `binary`, started first when there is none.
|
||||
pub async fn connect(spec: &AdapterSpec, binary: &Path) -> IdeResult<Option<AdapterIo>> {
|
||||
connect_to(&SERVER, spec, binary, IDLE_TIMEOUT).await
|
||||
}
|
||||
|
||||
async fn connect_to(
|
||||
slot: &'static Slot,
|
||||
spec: &AdapterSpec,
|
||||
binary: &Path,
|
||||
idle_timeout: Duration,
|
||||
) -> IdeResult<Option<AdapterIo>> {
|
||||
// The server gets the environment a per-session lldb-dap would: the project's (its Xcode's
|
||||
// `DEVELOPER_DIR`, from `cwd`), the adapter's search path and the spec's own variables.
|
||||
let mut cmd = Command::new("/bin/sh");
|
||||
cmd.current_dir(&spec.cwd);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
cmd.env("PATH", path);
|
||||
}
|
||||
cmd.envs(spec.env.iter().map(|(k, v)| (k, v)));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
|
||||
env.sort();
|
||||
let key = Key { binary: binary.to_path_buf(), cwd: spec.cwd.clone(), cwd_env: env };
|
||||
|
||||
let mut server = slot.lock().await;
|
||||
// A concurrent launch uses its own adapter. Replacing the cached process here would
|
||||
// disconnect the ongoing session, and concurrent sessions would share its stderr.
|
||||
if server.as_ref().is_some_and(|running| running.idle.lock().is_none()) {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(running) = server.as_ref().filter(|s| s.key == key)
|
||||
&& let Ok(Ok(stream)) = tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(&running.socket)).await
|
||||
{
|
||||
running.stderr.lock().clear();
|
||||
return Ok(Some(io(stream, running.stderr.clone(), lease(&running.idle))));
|
||||
}
|
||||
*server = None;
|
||||
let socket_dir = tempfile::Builder::new()
|
||||
.permissions(Permissions::from_mode(0o700))
|
||||
.tempdir()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot create the lldb-dap socket directory: {e}")))?;
|
||||
let socket = socket_dir.path().join("dap.sock");
|
||||
let mut uri = OsString::from("accept://");
|
||||
uri.push(&socket);
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.arg("-c").arg(HOLDER).arg(binary).arg(uri).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
let mut holder = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start lldb-dap: {e}")))?;
|
||||
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
if let Some(err) = holder.stderr.take() {
|
||||
pump_lines(err, spec.adapter.clone(), stderr.clone(), None);
|
||||
}
|
||||
let stream = connect_when_ready(&socket, &mut holder).await?;
|
||||
let idle = Arc::new(Idle::default());
|
||||
let first = lease(&idle);
|
||||
tokio::spawn(end_when_idle(slot, idle.clone(), idle_timeout));
|
||||
*server = Some(Server { key, socket, stderr: stderr.clone(), idle, _holder: holder, _socket_dir: socket_dir });
|
||||
Ok(Some(io(stream, stderr, first)))
|
||||
}
|
||||
|
||||
async fn connect_when_ready(socket: &Path, holder: &mut Child) -> IdeResult<UnixStream> {
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
let error = match UnixStream::connect(socket).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(error) => error,
|
||||
};
|
||||
if let Ok(Some(status)) = holder.try_wait() {
|
||||
return Err(IdeError::unavailable(format!("debug adapter exited before accepting connections ({status})")));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(IdeError::unavailable(format!("could not connect to lldb-dap: {error}")));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's hold on the server, released when its connection's both halves are gone.
|
||||
struct Lease(Arc<Idle>);
|
||||
|
||||
fn lease(idle: &Arc<Idle>) -> Arc<Lease> {
|
||||
*idle.lock() = None;
|
||||
Arc::new(Lease(idle.clone()))
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
*self.0.lock() = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the server in `slot` once no session has been connected to it for `timeout`; returns
|
||||
/// early when another server took its place.
|
||||
async fn end_when_idle(slot: &'static Slot, idle: Arc<Idle>, timeout: Duration) {
|
||||
loop {
|
||||
let since = *idle.lock();
|
||||
let wait = since.map_or(timeout, |at| (at + timeout).saturating_duration_since(Instant::now()));
|
||||
tokio::time::sleep(wait.max(Duration::from_millis(10))).await;
|
||||
let mut server = slot.lock().await;
|
||||
if !server.as_ref().is_some_and(|s| Arc::ptr_eq(&s.idle, &idle)) {
|
||||
return;
|
||||
}
|
||||
if idle.lock().is_some_and(|at| at.elapsed() >= timeout) {
|
||||
*server = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One half of a session's connection, holding the session's [`Lease`].
|
||||
struct Leased<T> {
|
||||
inner: T,
|
||||
_lease: Arc<Lease>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + Unpin> AsyncRead for Leased<T> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncWrite + Unpin> AsyncWrite for Leased<T> {
|
||||
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's streams. When the server dies the session's connection closes and the session
|
||||
/// ends with the server's last stderr lines, whichever session started it.
|
||||
fn io(stream: UnixStream, stderr: Arc<parking_lot::Mutex<Vec<String>>>, lease: Arc<Lease>) -> AdapterIo {
|
||||
let (r, w) = stream.into_split();
|
||||
AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(Leased { inner: r, _lease: lease.clone() }),
|
||||
writer: Box::new(Leased { inner: w, _lease: lease }),
|
||||
// The server is not the session's to stop.
|
||||
child: None,
|
||||
port: None,
|
||||
stderr,
|
||||
program_output: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
/// A stand-in for lldb-dap's server mode: it parses `--connection accept:///path`,
|
||||
/// records each start in `starts`, and answers every connection with its pid and the
|
||||
/// `DEVELOPER_DIR` it was started with.
|
||||
fn fake_lldb_dap(dir: &Path) -> Option<PathBuf> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::process::Command::new("python3").arg("-c").arg("").status().ok()?.success().then_some(())?;
|
||||
let path = dir.join("lldb-dap");
|
||||
let log = dir.join("starts");
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"#!/usr/bin/env python3\nimport os, socket, sys\n\
|
||||
assert sys.argv[1] == '--connection'\n\
|
||||
open({:?}, 'a').write('start\\n')\n\
|
||||
path = sys.argv[2][len('accept://'):]\n\
|
||||
s = socket.socket(socket.AF_UNIX)\n\
|
||||
s.bind(path); s.listen()\n\
|
||||
while True:\n c, _ = s.accept(); c.sendall(f\"{{os.getpid()}} {{os.environ.get('DEVELOPER_DIR', '')}}\".encode()); c.close()\n",
|
||||
log.to_string_lossy(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// The server's pid and `DEVELOPER_DIR`; the session's connection is closed afterwards.
|
||||
async fn server_of(io: AdapterIo) -> (i32, String) {
|
||||
let mut reader = io.reader;
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).await.unwrap();
|
||||
let (pid, dir) = text.split_once(' ').unwrap();
|
||||
(pid.parse().unwrap(), dir.to_owned())
|
||||
}
|
||||
|
||||
fn spec(dir: &Path) -> AdapterSpec {
|
||||
AdapterSpec {
|
||||
adapter: "lldb-dap".into(),
|
||||
command: "lldb-dap".into(),
|
||||
args: Vec::new(),
|
||||
transport: crate::adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: dir.to_path_buf(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
shared: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot() -> &'static Slot {
|
||||
Box::leak(Box::default())
|
||||
}
|
||||
|
||||
fn starts(dir: &Path) -> usize {
|
||||
std::fs::read_to_string(dir.join("starts")).unwrap_or_default().lines().count()
|
||||
}
|
||||
|
||||
fn alive(pid: i32) -> bool {
|
||||
unsafe { libc::kill(pid, 0) == 0 }
|
||||
}
|
||||
|
||||
async fn until_gone(pid: i32) -> bool {
|
||||
for _ in 0..150 {
|
||||
if !alive(pid) {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
|
||||
/// Sessions share one server; it outlives them, and goes when its holder does (the IDE quits).
|
||||
#[tokio::test]
|
||||
async fn sessions_share_one_server_that_ends_with_its_holder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(first.child.is_none(), "a session must not stop the shared server");
|
||||
let first_stderr = first.stderr.clone();
|
||||
let (pid, _) = server_of(first).await;
|
||||
let second = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&second.stderr, &first_stderr), "every session sees the server's errors");
|
||||
assert_eq!(server_of(second).await.0, pid, "the second session reuses the server");
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
|
||||
// Another lldb-dap (the selected Xcode changed) gets its own server; the old one ends.
|
||||
let other_dir = tempfile::tempdir().unwrap();
|
||||
let other = fake_lldb_dap(other_dir.path()).unwrap();
|
||||
let (other_pid, _) =
|
||||
server_of(connect_to(slot, &spec(other_dir.path()), &other, LONG).await.unwrap().unwrap()).await;
|
||||
assert_ne!(other_pid, pid);
|
||||
assert!(until_gone(pid).await, "the replaced server is still running");
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(other_pid).await, "the server outlived its holder");
|
||||
}
|
||||
|
||||
/// The server gets the session's environment, and a session with another Xcode
|
||||
/// (`DEVELOPER_DIR`) does not reuse a server started for a different one.
|
||||
#[tokio::test]
|
||||
async fn a_server_is_reused_only_with_the_same_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let with = |xcode: &str| AdapterSpec { env: vec![("DEVELOPER_DIR".into(), xcode.into())], ..spec(dir.path()) };
|
||||
let (a, dir_a) = server_of(connect_to(slot, &with("/Xcode-a"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_a, "/Xcode-a");
|
||||
let (b, dir_b) = server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await;
|
||||
assert_eq!(dir_b, "/Xcode-b");
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await.0, b);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(b).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_attaches_leave_the_active_server_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
for cwd in [dir.path(), other.path()] {
|
||||
assert!(connect_to(slot, &spec(cwd), &binary, LONG).await.unwrap().is_none());
|
||||
}
|
||||
assert_eq!(starts(dir.path()), 1);
|
||||
let (first_pid, _) = server_of(first).await;
|
||||
assert!(alive(first_pid));
|
||||
|
||||
let replacement = connect_to(slot, &spec(other.path()), &binary, LONG).await.unwrap().unwrap();
|
||||
let (replacement_pid, _) = server_of(replacement).await;
|
||||
assert_ne!(first_pid, replacement_pid, "changing only the working directory replaces an idle server");
|
||||
assert!(until_gone(first_pid).await);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(replacement_pid).await);
|
||||
}
|
||||
|
||||
/// The server ends once no session has been connected for the idle timeout; a connected
|
||||
/// session, or a new one within the timeout, keeps it.
|
||||
#[tokio::test]
|
||||
async fn an_idle_server_ends_and_the_next_session_starts_another() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
|
||||
let slot = slot();
|
||||
let idle = Duration::from_millis(400);
|
||||
let held = connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap();
|
||||
tokio::time::sleep(idle * 2).await;
|
||||
let (pid, _) = server_of(held).await;
|
||||
assert!(alive(pid), "a connected session keeps the server");
|
||||
|
||||
tokio::time::sleep(idle / 4).await;
|
||||
assert_eq!(server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await.0, pid);
|
||||
assert_eq!(starts(dir.path()), 1, "a session within the timeout reuses the server");
|
||||
|
||||
assert!(until_gone(pid).await, "the idle server is still running");
|
||||
let (next, _) = server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await;
|
||||
assert_ne!(next, pid);
|
||||
assert_eq!(starts(dir.path()), 2);
|
||||
*slot.lock().await = None;
|
||||
assert!(until_gone(next).await);
|
||||
}
|
||||
|
||||
/// An lldb-dap without server mode fails at once, so the caller can start it as before.
|
||||
#[tokio::test]
|
||||
async fn an_lldb_dap_without_server_mode_fails_fast() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("lldb-dap");
|
||||
std::fs::write(&binary, "#!/bin/sh\necho \"unknown option $1\" >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let e = connect_to(slot(), &spec(dir.path()), &binary, LONG).await.err().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(e.message.contains("exited before accepting connections"), "{}", e.message);
|
||||
}
|
||||
}
|
||||
@@ -4044,6 +4044,52 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug's attach goes to the shared lldb-dap server, which keeps the system libraries
|
||||
/// parsed by earlier sessions (#6665 E7); other sessions start their own adapter.
|
||||
#[tokio::test]
|
||||
async fn only_an_lldb_dap_attach_to_a_run_shares_the_server() {
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
shared: Arc<parking_lot::Mutex<Vec<bool>>>,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.shared.lock().push(spec.shared);
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let shared: Arc<parking_lot::Mutex<Vec<bool>>> = Arc::default();
|
||||
let launcher = CaptureLauncher {
|
||||
inner: FakeLauncher { log: Arc::default(), script: Script::default() },
|
||||
shared: shared.clone(),
|
||||
};
|
||||
let manager = DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let session = |adapter: &str, request: &str, linked: bool, xcode: bool| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: request.into(),
|
||||
extra_json: Some(
|
||||
if linked {
|
||||
json!({ RUN_LINK: 7, XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
} else {
|
||||
json!({ XCODE_ATTACH: xcode, "pid": 4242 })
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
..config()
|
||||
};
|
||||
for launch in [
|
||||
session("lldb-dap", "attach", true, true),
|
||||
session("lldb-dap", "attach", true, false),
|
||||
session("lldb-dap", "attach", false, true),
|
||||
session("lldb-dap", "launch", true, true),
|
||||
session("debugpy", "attach", true, true),
|
||||
] {
|
||||
let (owner, _) = recording_owner("main");
|
||||
manager.start(launch, owner).await.unwrap();
|
||||
}
|
||||
assert_eq!(*shared.lock(), [true, false, false, false, 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]
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
mod debugpy;
|
||||
mod godot;
|
||||
mod php_debug;
|
||||
mod real_adapters;
|
||||
mod script_debuggers;
|
||||
mod unity;
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1487,29 +1487,44 @@ impl Pool {
|
||||
($c:expr) => {{
|
||||
let mut tx = (&mut **$c).begin().await.map_err(db_err)?;
|
||||
let mut total = 0;
|
||||
let mut failed = None;
|
||||
for (sql, expect_one) in statements {
|
||||
let done = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone()))
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
let n = done.rows_affected();
|
||||
if *expect_one && (n > 1 || (n == 0 && !matches!(self, Pool::Mysql(_)))) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
let n = match sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *tx).await {
|
||||
Ok(done) => done.rows_affected(),
|
||||
Err(e) => {
|
||||
failed = Some(db_err(e));
|
||||
break;
|
||||
}
|
||||
};
|
||||
// MySQL counts the rows a statement matched (sqlx asks for CLIENT_FOUND_ROWS),
|
||||
// so a row left as it was counts and a key that matches none is 0.
|
||||
if *expect_one && n != 1 {
|
||||
failed = Some(IdeError::invalid(format!(
|
||||
"{sql}: expected to change 1 row, changed {n}; nothing was saved"
|
||||
)));
|
||||
break;
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
tx.commit().await.map_err(db_err)?;
|
||||
Ok(total)
|
||||
match failed {
|
||||
None => (tx.commit().await.map(|()| total).map_err(db_err), true),
|
||||
// Rolled back here: a dropped transaction rolls back only when its connection
|
||||
// is next used, and keeps the table's locks in the pool until then.
|
||||
Some(error) => (Err(error), tx.rollback().await.is_ok()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
match &mut conn {
|
||||
let (result, clean) = match &mut conn {
|
||||
Held::Sqlite(c) => transaction!(c),
|
||||
Held::Postgres(c) => transaction!(&mut ***c),
|
||||
Held::Mysql(c) => transaction!(&mut ***c),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if !clean {
|
||||
// A failed rollback must never return an open transaction to the pool.
|
||||
conn.discard().await;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +163,7 @@ pub(super) struct ConsoleSession {
|
||||
|
||||
impl ConsoleSession {
|
||||
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
|
||||
/// `pinned`: a script's, which every statement needs.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute(
|
||||
&self,
|
||||
@@ -173,6 +174,7 @@ impl ConsoleSession {
|
||||
max_rows: usize,
|
||||
request: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
pinned: bool,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let cancel = self.retired.child_token();
|
||||
let mut slot = tokio::select! {
|
||||
@@ -189,7 +191,7 @@ impl ConsoleSession {
|
||||
}
|
||||
let schema = schema.filter(|s| !s.is_empty());
|
||||
if slot.open.is_none() {
|
||||
if !needs_session(statement, pool.driver()) {
|
||||
if !pinned && !needs_session(statement, pool.driver()) {
|
||||
return Ok(None);
|
||||
}
|
||||
slot.open = Some(tokio::select! {
|
||||
|
||||
@@ -157,6 +157,15 @@ pub struct TableInfo {
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// Non-secret identity of an already-connected data source target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConnectedSourceInfo {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: DbDriver,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbColumnInfo")]
|
||||
@@ -395,11 +404,21 @@ pub struct ConsoleId<'a> {
|
||||
pub window: &'a str,
|
||||
pub path: &'a str,
|
||||
expected_manual: Option<bool>,
|
||||
/// Keeps its connection from the first statement on, not from the first that needs one.
|
||||
script: bool,
|
||||
}
|
||||
|
||||
impl<'a> ConsoleId<'a> {
|
||||
pub const fn new(window: &'a str, path: &'a str) -> Self {
|
||||
Self { window, path, expected_manual: None }
|
||||
Self { window, path, expected_manual: None, script: false }
|
||||
}
|
||||
|
||||
/// A run of statements outside any console, `run` naming it uniquely in `window`. It runs on one
|
||||
/// connection, as each database's own client runs a script, and releasing it with
|
||||
/// [`DbManager::release_target_console`] closes that connection instead of returning it to the
|
||||
/// pool with the session state the script left.
|
||||
pub const fn script(window: &'a str, run: &'a str) -> Self {
|
||||
Self { window, path: run, expected_manual: None, script: true }
|
||||
}
|
||||
|
||||
pub fn expecting_manual(mut self, manual: Option<bool>) -> Self {
|
||||
@@ -1299,15 +1318,49 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists non-secret metadata for every currently connected source target on this project/window.
|
||||
/// Never allocates a pool, connects a source, or reads credentials.
|
||||
pub fn connected_sources(&self) -> Vec<ConnectedSourceInfo> {
|
||||
let connected = self.connected();
|
||||
if connected.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources: std::collections::HashMap<String, DataSource> =
|
||||
self.sources().unwrap_or_default().into_iter().map(|s| (s.id.clone(), s)).collect();
|
||||
let mut out: Vec<ConnectedSourceInfo> = connected
|
||||
.into_iter()
|
||||
.filter_map(|source_id| {
|
||||
let (base_id, db_suffix) = split_target(&source_id);
|
||||
let source = sources.get(base_id)?.resolved().ok()?;
|
||||
let database =
|
||||
db_suffix.map(str::to_owned).or_else(|| (!source.database.is_empty()).then_some(source.database));
|
||||
Some(ConnectedSourceInfo { source_id, name: source.name, driver: source.driver, database })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.source_id.cmp(&b.source_id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
|
||||
/// only with [`DbIntrospection::show_system`].
|
||||
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
/// Read schemas using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
async fn schemas_on(pool: &Pool, system: bool) -> IdeResult<Vec<String>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::schemas(p, system).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
|
||||
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1316,10 +1369,20 @@ impl DbManager {
|
||||
|
||||
pub async fn tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
/// Read tables using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
async fn tables_on(pool: &Pool, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::tables(p, schema).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
|
||||
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1337,6 +1400,25 @@ impl DbManager {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Executes a SQL statement using an existing connection only (used by extension hosts).
|
||||
/// Respects read-only connections and never opens a disconnected source or prompts for credentials.
|
||||
pub async fn connected_execute(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
if pool.transaction_read_only() {
|
||||
conn::validate_pg_read_only(statement).map_err(IdeError::invalid)?;
|
||||
}
|
||||
if !conn::cursor_statement(statement) {
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
pool.execute_from(statement, 0, max_rows, cancel).await
|
||||
}
|
||||
|
||||
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
let source = self.source(id)?;
|
||||
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
|
||||
@@ -2154,7 +2236,8 @@ impl DbManager {
|
||||
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
|
||||
}
|
||||
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
|
||||
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
|
||||
// A script has no console transaction: it runs in the data source's manual transaction, if any.
|
||||
let console = console.filter(|c| !c.script && matches!(&*pool, Pool::Postgres(_)));
|
||||
let session = match console {
|
||||
Some(console) => connection.console_transactions.session(console),
|
||||
None => self.sessions.lock().get(id).cloned(),
|
||||
@@ -2378,10 +2461,11 @@ impl DbManager {
|
||||
}
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let binary = binary_columns(&pool, driver, schema, table, edits).await?;
|
||||
let statements = edits
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let sql = sql::edit_statement(driver, schema, table, e).map_err(IdeError::invalid)?;
|
||||
let sql = sql::edit_statement(driver, schema, table, e, &binary).map_err(IdeError::invalid)?;
|
||||
Ok((sql, !matches!(e, DbRowEdit::Insert { .. })))
|
||||
})
|
||||
.collect::<IdeResult<Vec<_>>>()?;
|
||||
@@ -2389,6 +2473,36 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns of `table` whose bytes the grid shows as `0x…` hex, looked up only when an edit
|
||||
/// carries such a value.
|
||||
async fn binary_columns(
|
||||
pool: &Pool,
|
||||
driver: DbDriver,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
edits: &[DbRowEdit],
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let hex =
|
||||
|c: &CellValue| c.value.as_deref().is_some_and(|v| v.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("0x")));
|
||||
let carries_hex = edits.iter().any(|edit| match edit {
|
||||
DbRowEdit::Update { key, values } => key.iter().chain(values).any(hex),
|
||||
DbRowEdit::Insert { values: cells } | DbRowEdit::Delete { key: cells } => cells.iter().any(hex),
|
||||
});
|
||||
// The dialects `sql::binary_column` knows binary types of.
|
||||
if !carries_hex || !matches!(driver, DbDriver::Sqlite | DbDriver::Mysql | DbDriver::SqlServer) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let rows = pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
it.next().flatten().is_some_and(|t| sql::binary_column(driver, &t)).then_some(name)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -208,7 +208,8 @@ impl ConsoleTransactions {
|
||||
auto.entry(key(console)).or_default().clone()
|
||||
};
|
||||
// Boxed: the connect inside would double the size of every statement's future.
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema, console.script))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
|
||||
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
|
||||
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
|
||||
//! Routine and trigger bodies, the mysql client's `DELIMITER` and SQL Server's
|
||||
//! `GO` end statements where each dialect's own client ends them.
|
||||
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
|
||||
|
||||
use crate::DbDriver;
|
||||
@@ -29,6 +31,19 @@ enum State {
|
||||
BlockComment,
|
||||
}
|
||||
|
||||
/// The routine or trigger body a statement holds: what ends the statement, as its `;` may not.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Body {
|
||||
None,
|
||||
/// BEGIN … END blocks (and the CASE … END inside them) outside parentheses: psql's rule for
|
||||
/// PostgreSQL routines, also read in MySQL routines and every T-SQL statement.
|
||||
Blocks,
|
||||
/// A SQLite trigger, which only `;` END `;` ends (sqlite3_complete).
|
||||
Trigger,
|
||||
/// A SQL Server routine: the rest of its batch.
|
||||
Batch,
|
||||
}
|
||||
|
||||
// Starts just after the opening `/*`.
|
||||
fn after_nested_block_comment(mut text: &str) -> &str {
|
||||
let mut depth = 1usize;
|
||||
@@ -74,6 +89,12 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
|
||||
|
||||
/// Every statement of `text` that contains more than whitespace and comments.
|
||||
pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
split_with(text, driver, ";".into()).0
|
||||
}
|
||||
|
||||
/// [`split`] with the mysql client's `delimiter` in effect at the start; also returns the one in
|
||||
/// effect at the end.
|
||||
fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlStatement>, String) {
|
||||
let mysql = driver == DbDriver::Mysql;
|
||||
let clickhouse = driver == DbDriver::Clickhouse;
|
||||
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
|
||||
@@ -114,6 +135,21 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let mut defines = false;
|
||||
// The open string is PostgreSQL's `E'…'`.
|
||||
let mut escape_string = false;
|
||||
let mut body = Body::None;
|
||||
// Block keywords inside parentheses (a parameter named `begin`) count for nothing.
|
||||
let mut parens = 0usize;
|
||||
// The previous `;` of a SQLite trigger.
|
||||
let mut last_semi: Option<usize> = None;
|
||||
let routines = postgres || mysql || sqlite || sql_server;
|
||||
// The next statement starts at `$at`, with nothing open.
|
||||
macro_rules! next_statement {
|
||||
($at:expr) => {{
|
||||
start = $at;
|
||||
has_code = false;
|
||||
(depth, declarations, block, package, script, defines) = (0, false, false, false, false, false);
|
||||
(body, parens, last_semi) = (Body::None, 0, None);
|
||||
}};
|
||||
}
|
||||
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
|
||||
if !has_code {
|
||||
return;
|
||||
@@ -135,6 +171,33 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
while i < chars.len() {
|
||||
let c = chars[i].1;
|
||||
let next = chars.get(i + 1).map(|c| c.1);
|
||||
// Lines the client reads itself instead of sending them.
|
||||
let command = match c {
|
||||
'G' | 'g' => sql_server,
|
||||
'D' | 'd' => mysql && !has_code,
|
||||
_ => false,
|
||||
};
|
||||
if command && state == State::Code && starts_line(&chars, i) {
|
||||
if let Some(end) = go_line(&chars, i) {
|
||||
// sqlcmd and SSMS send the batch so far.
|
||||
push(&mut out, start, i, has_code);
|
||||
next_statement!(end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
if let Some((set, end)) = delimiter_line(&chars, i) {
|
||||
delimiter = set;
|
||||
next_statement!(end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if state == State::Code && delimiter != ";" && text[byte_at(i)..].starts_with(delimiter.as_str()) {
|
||||
push(&mut out, start, i, has_code);
|
||||
i += delimiter.chars().count();
|
||||
next_statement!(i);
|
||||
continue;
|
||||
}
|
||||
match state {
|
||||
State::Code => match c {
|
||||
_ if plsql && !has_code && c.is_alphabetic() => {
|
||||
@@ -164,15 +227,37 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
// Re-read this character as code (it starts BEGIN / DECLARE).
|
||||
continue;
|
||||
}
|
||||
';' if depth == 0 && !declarations && !package => {
|
||||
push(&mut out, start, if block { i + 1 } else { i }, has_code);
|
||||
start = i + 1;
|
||||
has_code = false;
|
||||
block = false;
|
||||
script = false;
|
||||
defines = false;
|
||||
_ if routines && !has_code && c.is_alphabetic() => {
|
||||
body = body_of(&chars, i, driver);
|
||||
has_code = true;
|
||||
// Re-read this character as code.
|
||||
continue;
|
||||
}
|
||||
';' => {
|
||||
let ends = delimiter == ";"
|
||||
&& depth == 0
|
||||
&& !declarations
|
||||
&& !package
|
||||
&& match body {
|
||||
Body::None | Body::Blocks => true,
|
||||
Body::Trigger => last_semi.is_some_and(|semi| only_end(&chars, semi + 1, i)),
|
||||
Body::Batch => false,
|
||||
};
|
||||
if ends {
|
||||
push(&mut out, start, if block { i + 1 } else { i }, has_code);
|
||||
next_statement!(i + 1);
|
||||
} else {
|
||||
has_code = true;
|
||||
last_semi = Some(i);
|
||||
}
|
||||
}
|
||||
_ if body == Body::Blocks
|
||||
&& parens == 0
|
||||
&& ["BEGIN", "CASE", "END"].iter().any(|w| keyword_at(&chars, i, w)) =>
|
||||
{
|
||||
i = block_keyword(&chars, i, driver, &mut depth);
|
||||
has_code = true;
|
||||
}
|
||||
';' => has_code = true,
|
||||
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
|
||||
_ if postgres && (c.is_alphabetic() || c == '_') => {
|
||||
has_code = true;
|
||||
@@ -208,6 +293,12 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i = chars.partition_point(|&(offset, _)| offset < end);
|
||||
continue;
|
||||
}
|
||||
// MySQL runs the code of `/*! … */` and MariaDB that of `/*M! … */`: mysqldump's
|
||||
// SETs and triggers are statements made of them alone.
|
||||
let after = |n: usize| chars.get(i + n).map(|&(_, c)| c);
|
||||
if mysql && (after(2) == Some('!') || (after(2) == Some('M') && after(3) == Some('!'))) {
|
||||
has_code = true;
|
||||
}
|
||||
state = State::BlockComment;
|
||||
i += 1;
|
||||
}
|
||||
@@ -313,6 +404,14 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i = closing.map_or(i + 3, |w| after + w.len()) - 1;
|
||||
has_code = true;
|
||||
}
|
||||
'(' => {
|
||||
parens += 1;
|
||||
has_code = true;
|
||||
}
|
||||
')' => {
|
||||
parens = parens.saturating_sub(1);
|
||||
has_code = true;
|
||||
}
|
||||
c if !c.is_whitespace() => has_code = true,
|
||||
_ => {}
|
||||
},
|
||||
@@ -367,7 +466,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
i += 1;
|
||||
}
|
||||
push(&mut out, start, chars.len(), has_code);
|
||||
out
|
||||
(out, delimiter)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
@@ -381,10 +480,10 @@ enum Unit {
|
||||
Package,
|
||||
}
|
||||
|
||||
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
|
||||
fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
/// The first `n` words from `i`, upper-cased, as long as only whitespace separates them.
|
||||
fn leading_words(chars: &[(usize, char)], mut i: usize, n: usize) -> Vec<String> {
|
||||
let mut words: Vec<String> = Vec::new();
|
||||
while words.len() < 6 {
|
||||
while words.len() < n {
|
||||
let word: String = chars[i.min(chars.len())..]
|
||||
.iter()
|
||||
.map(|&(_, c)| c)
|
||||
@@ -396,6 +495,12 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
i = skip_ws(chars, i + word.chars().count());
|
||||
words.push(word.to_ascii_uppercase());
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
|
||||
fn plsql_unit(chars: &[(usize, char)], i: usize) -> Unit {
|
||||
let words = leading_words(chars, i, 6);
|
||||
let w = |n: usize| words.get(n).map_or("", String::as_str);
|
||||
match w(0) {
|
||||
"DECLARE" | "BEGIN" => return Unit::Block,
|
||||
@@ -413,6 +518,168 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The body a statement starting at `i` may hold, by the rule of the dialect's own client.
|
||||
fn body_of(chars: &[(usize, char)], i: usize, driver: DbDriver) -> Body {
|
||||
let words = leading_words(chars, i, 4);
|
||||
let w = |n: usize| words.get(n).map_or("", String::as_str);
|
||||
match driver {
|
||||
// sqlite3: CREATE [TEMP | TEMPORARY] TRIGGER.
|
||||
DbDriver::Sqlite => {
|
||||
let n = if matches!(w(1), "TEMP" | "TEMPORARY") { 2 } else { 1 };
|
||||
if w(0) == "CREATE" && w(n) == "TRIGGER" { Body::Trigger } else { Body::None }
|
||||
}
|
||||
// psql: CREATE [OR REPLACE] {FUNCTION | PROCEDURE}.
|
||||
DbDriver::Postgres => {
|
||||
let n = if (w(1), w(2)) == ("OR", "REPLACE") { 3 } else { 1 };
|
||||
if w(0) == "CREATE" && matches!(w(n), "FUNCTION" | "PROCEDURE") { Body::Blocks } else { Body::None }
|
||||
}
|
||||
DbDriver::Mysql if mysql_routine(chars, i) => Body::Blocks,
|
||||
// A routine must be alone in its batch, so SQL Server reads the rest of it as the body.
|
||||
DbDriver::SqlServer => {
|
||||
let n = match (w(0), w(1), w(2)) {
|
||||
("CREATE", "OR", "ALTER") => 3,
|
||||
("CREATE" | "ALTER", ..) => 1,
|
||||
_ => return Body::Blocks,
|
||||
};
|
||||
if matches!(w(n), "PROC" | "PROCEDURE" | "FUNCTION" | "TRIGGER") { Body::Batch } else { Body::Blocks }
|
||||
}
|
||||
_ => Body::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a MySQL statement at `i` creates a stored program:
|
||||
/// `CREATE [OR REPLACE] [DEFINER = user] [AGGREGATE] {PROCEDURE | FUNCTION | TRIGGER | EVENT}`.
|
||||
fn mysql_routine(chars: &[(usize, char)], mut i: usize) -> bool {
|
||||
let word = |i: &mut usize| {
|
||||
let word = leading_words(chars, *i, 1).pop().unwrap_or_default();
|
||||
*i = skip_ws(chars, *i + word.chars().count());
|
||||
word
|
||||
};
|
||||
if word(&mut i) != "CREATE" {
|
||||
return false;
|
||||
}
|
||||
let mut next = word(&mut i);
|
||||
if next == "OR" && word(&mut i) == "REPLACE" {
|
||||
next = word(&mut i);
|
||||
}
|
||||
if next == "DEFINER" {
|
||||
// `= 'name'@'host'`, `name@host`, `CURRENT_USER()`…: up to a blank outside quotes.
|
||||
if chars.get(i).is_some_and(|&(_, c)| c == '=') {
|
||||
i = skip_ws(chars, i + 1);
|
||||
}
|
||||
while let Some(&(_, c)) = chars.get(i)
|
||||
&& !c.is_whitespace()
|
||||
{
|
||||
i += 1;
|
||||
if matches!(c, '\'' | '"' | '`') {
|
||||
i = chars[i..].iter().position(|&(_, q)| q == c).map_or(chars.len(), |n| i + n + 1);
|
||||
}
|
||||
}
|
||||
i = skip_ws(chars, i);
|
||||
next = word(&mut i);
|
||||
}
|
||||
if next == "AGGREGATE" {
|
||||
next = word(&mut i);
|
||||
}
|
||||
matches!(next.as_str(), "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT")
|
||||
}
|
||||
|
||||
/// [`word_at`] for a keyword, which a MySQL / T-SQL `@variable` or a qualified `t.end` is not.
|
||||
fn keyword_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
|
||||
word_at(chars, i, word) && chars[..i].last().is_none_or(|&(_, c)| c != '@' && c != '.')
|
||||
}
|
||||
|
||||
/// Counts the BEGIN, CASE or END at `i` into the block `depth` of a body. Returns the index of
|
||||
/// its last character, or of the word after END that belongs to it.
|
||||
fn block_keyword(chars: &[(usize, char)], i: usize, driver: DbDriver, depth: &mut usize) -> usize {
|
||||
if word_at(chars, i, "BEGIN") {
|
||||
// T-SQL's BEGIN TRAN, BEGIN DIALOG… are statements.
|
||||
let after = skip_ws(chars, i + 5);
|
||||
let statement = driver == DbDriver::SqlServer
|
||||
&& ["TRAN", "TRANSACTION", "DISTRIBUTED", "DIALOG", "CONVERSATION"]
|
||||
.iter()
|
||||
.any(|w| word_at(chars, after, w));
|
||||
if !statement {
|
||||
*depth += 1;
|
||||
}
|
||||
return i + 4;
|
||||
}
|
||||
if word_at(chars, i, "CASE") {
|
||||
// Its END closes it, not the block; outside a block it holds no `;` (psql).
|
||||
if *depth > 0 {
|
||||
*depth += 1;
|
||||
}
|
||||
return i + 3;
|
||||
}
|
||||
// MySQL's END IF / LOOP / REPEAT / WHILE close statements that opened no block, and T-SQL's
|
||||
// END CONVERSATION is a statement; END CASE / TRY / CATCH close what they name.
|
||||
let (closing, neutral): (&[&str], &[&str]) = match driver {
|
||||
DbDriver::Mysql => (&["CASE"], &["IF", "LOOP", "REPEAT", "WHILE"]),
|
||||
DbDriver::SqlServer => (&["TRY", "CATCH"], &["CONVERSATION"]),
|
||||
_ => (&[], &[]),
|
||||
};
|
||||
let after = skip_ws(chars, i + 3);
|
||||
let named = closing.iter().chain(neutral).find(|w| word_at(chars, after, w));
|
||||
if named.is_none_or(|w| !neutral.contains(w)) {
|
||||
*depth = depth.saturating_sub(1);
|
||||
}
|
||||
named.map_or(i + 2, |w| after + w.len() - 1)
|
||||
}
|
||||
|
||||
/// The end (`\n` or the end of the text) of a SQL Server `GO` line starting at `i`. As in sqlcmd, a
|
||||
/// `--` comment may follow GO and `GO;` is SQL. A repeat count (`GO 2`) is not run here: the line
|
||||
/// is left to the server.
|
||||
fn go_line(chars: &[(usize, char)], i: usize) -> Option<usize> {
|
||||
if !word_at(chars, i, "GO") {
|
||||
return None;
|
||||
}
|
||||
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
|
||||
let rest: String = chars[i + 2..end].iter().map(|&(_, c)| c).collect();
|
||||
let rest = rest.trim_start();
|
||||
(rest.is_empty() || rest.starts_with("--")).then_some(end)
|
||||
}
|
||||
|
||||
/// The mysql client's `DELIMITER x` at `i`: the new delimiter and the end of its line, which the
|
||||
/// command takes whole. An argument the client refuses (none, a backslash) leaves it SQL.
|
||||
fn delimiter_line(chars: &[(usize, char)], i: usize) -> Option<(String, usize)> {
|
||||
if !word_at(chars, i, "DELIMITER") {
|
||||
return None;
|
||||
}
|
||||
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
|
||||
let line: String = chars[i + "DELIMITER".len()..end].iter().map(|&(_, c)| c).collect();
|
||||
let argument = line.strip_prefix([' ', '\t'])?.trim_start_matches([' ', '\t']);
|
||||
let delimiter = match argument.chars().next()? {
|
||||
quote @ ('\'' | '"' | '`') => argument[1..].split(quote).next().unwrap_or_default(),
|
||||
_ => argument.split([' ', '\t', '\r']).next().unwrap_or_default(),
|
||||
};
|
||||
(!delimiter.is_empty() && !delimiter.contains('\\')).then(|| (delimiter.to_owned(), end))
|
||||
}
|
||||
|
||||
/// Whether only END, blanks and comments lie in `from..to`: the `;` END `;` ending a SQLite trigger.
|
||||
fn only_end(chars: &[(usize, char)], from: usize, to: usize) -> bool {
|
||||
let at = past_blanks(chars, from, to);
|
||||
word_at(chars, at, "END") && past_blanks(chars, at + 3, to) == to
|
||||
}
|
||||
|
||||
/// The first index of `i..to` that is neither whitespace nor in a comment.
|
||||
fn past_blanks(chars: &[(usize, char)], mut i: usize, to: usize) -> usize {
|
||||
let starts = |i: usize, s: &str| chars[i..to].iter().map(|&(_, c)| c).take(2).eq(s.chars());
|
||||
while i < to {
|
||||
if chars[i].1.is_whitespace() {
|
||||
i += 1;
|
||||
} else if starts(i, "--") {
|
||||
i = chars[i..to].iter().position(|&(_, c)| c == '\n').map_or(to, |n| i + n);
|
||||
} else if starts(i, "/*") {
|
||||
i = (i + 2..to.saturating_sub(1))
|
||||
.find(|&j| chars[j].1 == '*' && chars[j + 1].1 == '/')
|
||||
.map_or(to, |j| j + 2);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Whether the characters at `i` are the keyword `word` (identifier bounds respected).
|
||||
fn word_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
|
||||
let (before, after) = (chars[..i].last().map(|&(_, c)| c), chars.get(i).map(|&(_, c)| c));
|
||||
@@ -477,7 +744,17 @@ pub fn statement_at(text: &str, offset: u32, driver: DbDriver) -> Option<SqlStat
|
||||
/// selected text itself, split.
|
||||
pub fn statements_in(text: &str, from: u32, to: u32, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let selected = utf16_slice(text, from, to);
|
||||
split(selected, driver).into_iter().map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s }).collect()
|
||||
// A DELIMITER above the selection still holds in it.
|
||||
let delimiter = if driver == DbDriver::Mysql {
|
||||
split_with(utf16_slice(text, 0, from), driver, ";".into()).1
|
||||
} else {
|
||||
";".into()
|
||||
};
|
||||
split_with(selected, driver, delimiter)
|
||||
.0
|
||||
.into_iter()
|
||||
.map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
|
||||
@@ -765,4 +1042,188 @@ mod tests {
|
||||
vec!["select case when a then 1 end, b from t", "select 2"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_triggers_end_at_end_semicolon_like_sqlite3() {
|
||||
let trigger = "CREATE TRIGGER a_ins AFTER INSERT ON a BEGIN\n INSERT INTO log VALUES ('inserted ' || NEW.id);\n \
|
||||
UPDATE a SET n = n + 1 WHERE id = NEW.id;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("CREATE TABLE log (msg TEXT);\n{trigger};\nINSERT INTO a VALUES (1, 0);"), DbDriver::Sqlite),
|
||||
vec!["CREATE TABLE log (msg TEXT)", trigger, "INSERT INTO a VALUES (1, 0)"]
|
||||
);
|
||||
// Only `;` END `;` ends one, whatever CASE … END and comments it holds.
|
||||
let temp = "create temp trigger t after insert on a begin\n select case when new.id > 0 then 1 end;\n \
|
||||
select 2; -- ; END ;\n /* END; */ select 3;\nend\n";
|
||||
assert_eq!(texts(&format!("{temp};select 4"), DbDriver::Sqlite), vec![temp.trim_end(), "select 4"]);
|
||||
// Execute with the caret in the body runs the whole trigger.
|
||||
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n INSERT INTO audit VALUES ('gone');\n \
|
||||
DELETE FROM sessions WHERE expires < datetime('now');\nEND;";
|
||||
let caret = console.find("FROM sessions").unwrap() as u32;
|
||||
let whole = console.trim_end_matches(';');
|
||||
assert_eq!(statement_at(console, caret, DbDriver::Sqlite).map(|s| s.text).as_deref(), Some(whole));
|
||||
// A transaction's BEGIN … END is no body.
|
||||
assert_eq!(texts("BEGIN; DELETE FROM a; END;", DbDriver::Sqlite), vec!["BEGIN", "DELETE FROM a", "END"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_begin_atomic_bodies_like_psql() {
|
||||
let procedure = "CREATE PROCEDURE insert_data(a integer, b integer)\nLANGUAGE SQL\nBEGIN ATOMIC\n \
|
||||
INSERT INTO tbl VALUES (a);\n INSERT INTO tbl VALUES (b);\nEND";
|
||||
let function = "create or replace function classify(x integer) returns text language sql\nbegin atomic\n \
|
||||
select case when x > 0 then 'pos' else 'neg' end;\nend";
|
||||
assert_eq!(
|
||||
texts(
|
||||
&format!("CREATE TABLE tbl (n integer);\n{procedure};\n{function};\nCALL insert_data(1, 2);"),
|
||||
DbDriver::Postgres
|
||||
),
|
||||
vec!["CREATE TABLE tbl (n integer)", procedure, function, "CALL insert_data(1, 2)"]
|
||||
);
|
||||
// Words in parentheses count for nothing, and other statements have no body.
|
||||
let named = "CREATE FUNCTION f(begin int) RETURNS int LANGUAGE sql RETURN 1";
|
||||
assert_eq!(texts(&format!("{named}; SELECT 2"), DbDriver::Postgres), vec![named, "SELECT 2"]);
|
||||
assert_eq!(
|
||||
texts("BEGIN; CALL insert_data(1, 2); END; SELECT case when true then 1 end", DbDriver::Postgres),
|
||||
vec!["BEGIN", "CALL insert_data(1, 2)", "END", "SELECT case when true then 1 end"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_delimiter_lines_set_the_terminator_like_the_mysql_client() {
|
||||
let procedure = "CREATE PROCEDURE p()\nBEGIN\n SELECT 1;\n SELECT 2;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("DELIMITER //\n{procedure} //\nDELIMITER ;\nCALL p();"), DbDriver::Mysql),
|
||||
vec![procedure, "CALL p()"]
|
||||
);
|
||||
// mysqldump's `;;`, a quoted delimiter, a lower-case command and what follows the argument.
|
||||
for (command, delimiter) in
|
||||
[("DELIMITER ;;", ";;"), ("delimiter '$$'", "$$"), (" DELIMITER $$ -- the rest is ignored", "$$")]
|
||||
{
|
||||
assert_eq!(
|
||||
texts(&format!("{command}\n{procedure}{delimiter}\nSELECT 3{delimiter}"), DbDriver::Mysql),
|
||||
vec![procedure, "SELECT 3"],
|
||||
"{command}"
|
||||
);
|
||||
}
|
||||
// Only at the start of a statement; an empty or backslashed argument is no command.
|
||||
for sql in ["SELECT 1\nDELIMITER //\n", "DELIMITER\n", "DELIMITER \\\\\n"] {
|
||||
assert_eq!(texts(&format!("{sql}SELECT 2"), DbDriver::Mysql), vec![format!("{sql}SELECT 2")]);
|
||||
}
|
||||
// A selection between the DELIMITER lines runs with the delimiter set above it.
|
||||
let script = format!("DELIMITER //\n{procedure} //\nSELECT 3 //\nDELIMITER ;");
|
||||
let from = script.find("CREATE").unwrap() as u32;
|
||||
let to = script.find("\nDELIMITER ;").unwrap() as u32;
|
||||
let selected: Vec<_> = statements_in(&script, from, to, DbDriver::Mysql).into_iter().map(|s| s.text).collect();
|
||||
assert_eq!(selected, vec![procedure, "SELECT 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_routine_bodies_keep_their_statements() {
|
||||
let trigger =
|
||||
"CREATE TRIGGER t_bi BEFORE INSERT ON t FOR EACH ROW BEGIN\n SET NEW.a = 1;\n SET NEW.b = 2;\nEND";
|
||||
let procedure = "CREATE DEFINER=`root`@`%` PROCEDURE p(IN n INT)\nBEGIN\n DECLARE i INT DEFAULT 0;\n \
|
||||
lbl: LOOP\n SET i = i + 1;\n IF i >= n THEN LEAVE lbl; END IF;\n END LOOP lbl;\n \
|
||||
CASE WHEN i > 1 THEN SELECT 'many'; ELSE SELECT 'one'; END CASE;\n \
|
||||
SELECT CASE WHEN i = 3 THEN 'three' END AS c;\nEND";
|
||||
let event = "CREATE EVENT e ON SCHEDULE EVERY 1 HOUR ENDS NOW() + INTERVAL 1 DAY DO BEGIN DELETE FROM t; END";
|
||||
let function = "CREATE DEFINER = CURRENT_USER() FUNCTION f() RETURNS INT DETERMINISTIC BEGIN\n \
|
||||
SET @begin = 1;\n RETURN (SELECT t.end FROM t LIMIT 1);\nEND";
|
||||
assert_eq!(
|
||||
texts(
|
||||
&format!("{trigger};\n{procedure};\n{event};\n{function};\nINSERT INTO t (id) VALUES (1);"),
|
||||
DbDriver::Mysql
|
||||
),
|
||||
vec![trigger, procedure, event, function, "INSERT INTO t (id) VALUES (1)"]
|
||||
);
|
||||
// Outside a routine BEGIN starts a transaction.
|
||||
assert_eq!(texts("BEGIN; DELETE FROM t; COMMIT", DbDriver::Mysql), vec!["BEGIN", "DELETE FROM t", "COMMIT"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_executable_comments_are_statements() {
|
||||
// Lines of a mysqldump 8.4 dump: its SETs and triggers are code the server runs.
|
||||
let trigger = "/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `orders_ai` AFTER INSERT \
|
||||
ON `orders` FOR EACH ROW BEGIN\n UPDATE customers SET orders_count = orders_count + 1 WHERE id = \
|
||||
NEW.customer_id;\nEND */";
|
||||
let procedure = "CREATE DEFINER=`root`@`localhost` PROCEDURE `add_order`(IN p_id INT)\nBEGIN\n \
|
||||
INSERT INTO orders (id) VALUES (p_id);\nEND";
|
||||
let dump = format!(
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n\
|
||||
INSERT INTO `orders` VALUES (10,1,'first; with a semicolon');\n\
|
||||
/*!50003 SET character_set_client = latin1 */ ;\nDELIMITER ;;\n{trigger};;\nDELIMITER ;\n\
|
||||
/*!50003 DROP PROCEDURE IF EXISTS `add_order` */;\nDELIMITER ;;\n{procedure} ;;\nDELIMITER ;\n\
|
||||
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*M!100100 SET @x = 1 */;\n\
|
||||
/* a note */;\n-- Dump completed\n"
|
||||
);
|
||||
assert_eq!(
|
||||
texts(&dump, DbDriver::Mysql),
|
||||
vec![
|
||||
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */",
|
||||
"INSERT INTO `orders` VALUES (10,1,'first; with a semicolon')",
|
||||
"/*!50003 SET character_set_client = latin1 */",
|
||||
trigger,
|
||||
"/*!50003 DROP PROCEDURE IF EXISTS `add_order` */",
|
||||
procedure,
|
||||
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */",
|
||||
"/*M!100100 SET @x = 1 */",
|
||||
]
|
||||
);
|
||||
// The `;` inside one stays in it, also without DELIMITER.
|
||||
let inline = "/*!50003 TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN SET NEW.n = 1; END */";
|
||||
assert_eq!(texts(&format!("{inline};\nSELECT 2"), DbDriver::Mysql), vec![inline, "SELECT 2"]);
|
||||
// Elsewhere they are comments.
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert_eq!(texts("/*!40101 SET NAMES utf8 */;\nSELECT 2", driver), vec!["SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_go_lines_end_batches_like_sqlcmd() {
|
||||
let procedure = "CREATE PROCEDURE p AS\nBEGIN\n SET NOCOUNT ON;\n SELECT a FROM t;\nEND";
|
||||
assert_eq!(
|
||||
texts(&format!("CREATE TABLE t (a int)\nGO\n{procedure}\n go -- done\nEXEC p\nGo"), DbDriver::SqlServer),
|
||||
vec!["CREATE TABLE t (a int)", procedure, "EXEC p"]
|
||||
);
|
||||
// GO in a string or comment, `GOTO`, `GO 2` (a repeat count) and `GO;` are left to the server.
|
||||
for sql in ["SELECT 'a\nGO\n'", "/* a\nGO\n*/ SELECT 1", "SELECT 1\nGOTO x", "SELECT 1\nGO 2"] {
|
||||
assert_eq!(texts(&format!("{sql}\nSELECT 2"), DbDriver::SqlServer), vec![format!("{sql}\nSELECT 2")]);
|
||||
}
|
||||
assert_eq!(texts("SELECT 1\nGO;\nSELECT 2", DbDriver::SqlServer), vec!["SELECT 1\nGO", "SELECT 2"]);
|
||||
let script = format!("SELECT 0\nGO\n{procedure}\nGO\nSELECT 3");
|
||||
let caret = script.find("SELECT a").unwrap() as u32;
|
||||
assert_eq!(statement_at(&script, caret, DbDriver::SqlServer).map(|s| s.text).as_deref(), Some(procedure));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_routines_run_to_the_end_of_their_batch() {
|
||||
for routine in [
|
||||
"CREATE PROCEDURE p AS SELECT 1 AS one; SELECT 2 AS two;",
|
||||
"create or alter function f() returns int as begin declare @n int = 1; return @n; end;",
|
||||
"ALTER PROC p AS SET NOCOUNT ON; SELECT 1",
|
||||
"CREATE TRIGGER tr ON t AFTER INSERT AS INSERT INTO log VALUES (1); INSERT INTO log VALUES (2)",
|
||||
] {
|
||||
assert_eq!(texts(routine, DbDriver::SqlServer), vec![routine]);
|
||||
assert_eq!(texts(&format!("{routine}\nGO\nEXEC p"), DbDriver::SqlServer), vec![routine, "EXEC p"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sql_server_blocks_keep_their_statements() {
|
||||
let block =
|
||||
"IF OBJECT_ID('t') IS NOT NULL\nBEGIN\n INSERT INTO t VALUES (2);\n INSERT INTO t VALUES (3);\nEND";
|
||||
let tried = "BEGIN TRY\n SELECT 1/0 AS boom;\nEND TRY\nBEGIN CATCH\n \
|
||||
SELECT CASE WHEN ERROR_NUMBER() > 0 THEN 1 END;\n DECLARE @begin int = 1;\nEND CATCH";
|
||||
assert_eq!(
|
||||
texts(&format!("{block};\n{tried};\nBEGIN TRAN;\nINSERT INTO t VALUES (4);\nCOMMIT;"), DbDriver::SqlServer),
|
||||
vec![block, tried, "BEGIN TRAN", "INSERT INTO t VALUES (4)", "COMMIT"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_commands_and_bodies_of_other_dialects_are_sql() {
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::Clickhouse, DbDriver::Jdbc] {
|
||||
assert_eq!(texts("SELECT 1\nGO\nSELECT 2", driver), vec!["SELECT 1\nGO\nSELECT 2"]);
|
||||
assert_eq!(texts("DELIMITER //\nSELECT 1 //", driver), vec!["DELIMITER //\nSELECT 1 //"]);
|
||||
assert_eq!(texts("CREATE PROCEDURE p AS SELECT 1; SELECT 2", driver).len(), 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
+112
-26
@@ -22,10 +22,6 @@ pub fn quote_literal(driver: DbDriver, value: &str) -> String {
|
||||
format!("'{s}'")
|
||||
}
|
||||
|
||||
fn literal_or_null(driver: DbDriver, v: Option<&str>) -> String {
|
||||
v.map_or_else(|| "NULL".to_owned(), |v| quote_literal(driver, v))
|
||||
}
|
||||
|
||||
pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
if schema.is_empty() {
|
||||
quote_ident(driver, table)
|
||||
@@ -626,19 +622,56 @@ pub enum DbRowEdit {
|
||||
Delete { key: Vec<CellValue> },
|
||||
}
|
||||
|
||||
fn where_key(driver: DbDriver, key: &[CellValue]) -> String {
|
||||
/// Whether a column of type `data_type` (as [`columns`] lists it) holds bytes that the grid
|
||||
/// shows as `0x…` hex. PostgreSQL shows `bytea` as its own `\x…` input text.
|
||||
pub fn binary_column(driver: DbDriver, data_type: &str) -> bool {
|
||||
let t = data_type.to_ascii_lowercase();
|
||||
match driver {
|
||||
DbDriver::Sqlite => t.contains("blob"),
|
||||
DbDriver::Mysql => t.contains("blob") || t.contains("binary"),
|
||||
DbDriver::SqlServer => matches!(t.as_str(), "binary" | "varbinary" | "image" | "timestamp" | "rowversion"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The literal of `value` for a column: the bytes of a `0x…` hex value in a binary column, else text.
|
||||
fn column_literal(driver: DbDriver, column: &str, value: &str, binary: &[String]) -> String {
|
||||
let hex = value.strip_prefix("0x").or_else(|| value.strip_prefix("0X"));
|
||||
match hex {
|
||||
Some(hex)
|
||||
if hex.len() % 2 == 0
|
||||
&& hex.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& binary.iter().any(|b| b.eq_ignore_ascii_case(column)) =>
|
||||
{
|
||||
if driver == DbDriver::SqlServer {
|
||||
format!("0x{hex}")
|
||||
} else {
|
||||
format!("X'{hex}'")
|
||||
}
|
||||
}
|
||||
_ => quote_literal(driver, value),
|
||||
}
|
||||
}
|
||||
|
||||
fn where_key(driver: DbDriver, key: &[CellValue], binary: &[String]) -> String {
|
||||
key.iter()
|
||||
.map(|c| match &c.value {
|
||||
Some(v) => format!("{} = {}", quote_ident(driver, &c.column), quote_literal(driver, v)),
|
||||
Some(v) => format!("{} = {}", quote_ident(driver, &c.column), column_literal(driver, &c.column, v, binary)),
|
||||
None => format!("{} IS NULL", quote_ident(driver, &c.column)),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" AND ")
|
||||
}
|
||||
|
||||
/// The DML statement for `edit`. Values are written as quoted literals, which
|
||||
/// every supported database coerces to the column type.
|
||||
pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowEdit) -> Result<String, String> {
|
||||
/// The DML statement for `edit`. Values are written as quoted literals, which every supported
|
||||
/// database coerces to the column type, except the `0x…` hex of the `binary` columns: their bytes.
|
||||
pub fn edit_statement(
|
||||
driver: DbDriver,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
edit: &DbRowEdit,
|
||||
binary: &[String],
|
||||
) -> Result<String, String> {
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Err("Custom JDBC table editing is unsupported".into());
|
||||
}
|
||||
@@ -646,6 +679,9 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
return Err("ClickHouse table editing is unsupported: primary keys do not uniquely identify rows and edits require transactions".into());
|
||||
}
|
||||
let target = qualified(driver, schema, table);
|
||||
let literal = |c: &CellValue| {
|
||||
c.value.as_deref().map_or_else(|| "NULL".to_owned(), |v| column_literal(driver, &c.column, v, binary))
|
||||
};
|
||||
match edit {
|
||||
DbRowEdit::Update { key, values } => {
|
||||
if key.is_empty() {
|
||||
@@ -654,13 +690,9 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
if values.is_empty() {
|
||||
return Err("nothing to update".into());
|
||||
}
|
||||
let set: Vec<String> = values
|
||||
.iter()
|
||||
.map(|c| {
|
||||
format!("{} = {}", quote_ident(driver, &c.column), literal_or_null(driver, c.value.as_deref()))
|
||||
})
|
||||
.collect();
|
||||
Ok(format!("UPDATE {target} SET {} WHERE {}", set.join(", "), where_key(driver, key)))
|
||||
let set: Vec<String> =
|
||||
values.iter().map(|c| format!("{} = {}", quote_ident(driver, &c.column), literal(c))).collect();
|
||||
Ok(format!("UPDATE {target} SET {} WHERE {}", set.join(", "), where_key(driver, key, binary)))
|
||||
}
|
||||
DbRowEdit::Insert { values } => {
|
||||
if values.is_empty() {
|
||||
@@ -675,14 +707,14 @@ pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowE
|
||||
});
|
||||
}
|
||||
let cols: Vec<String> = values.iter().map(|c| quote_ident(driver, &c.column)).collect();
|
||||
let vals: Vec<String> = values.iter().map(|c| literal_or_null(driver, c.value.as_deref())).collect();
|
||||
let vals: Vec<String> = values.iter().map(literal).collect();
|
||||
Ok(format!("INSERT INTO {target} ({}) VALUES ({})", cols.join(", "), vals.join(", ")))
|
||||
}
|
||||
DbRowEdit::Delete { key } => {
|
||||
if key.is_empty() {
|
||||
return Err("rows can only be deleted in tables with a primary key".into());
|
||||
}
|
||||
Ok(format!("DELETE FROM {target} WHERE {}", where_key(driver, key)))
|
||||
Ok(format!("DELETE FROM {target} WHERE {}", where_key(driver, key, binary)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1288,7 +1320,7 @@ mod tests {
|
||||
DbRowEdit::Insert { values: vec![cv("name", Some("new"))] },
|
||||
DbRowEdit::Insert { values: vec![] },
|
||||
] {
|
||||
let error = edit_statement(DbDriver::Clickhouse, "default", "events", &edit).unwrap_err();
|
||||
let error = edit_statement(DbDriver::Clickhouse, "default", "events", &edit, &[]).unwrap_err();
|
||||
assert!(error.contains("primary keys do not uniquely identify rows"));
|
||||
}
|
||||
}
|
||||
@@ -1315,21 +1347,74 @@ mod tests {
|
||||
DbDriver::Sqlite,
|
||||
"main",
|
||||
"t",
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("name", Some("O'Brien")), cv("note", None)] }
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("name", Some("O'Brien")), cv("note", None)] },
|
||||
&[]
|
||||
)
|
||||
.unwrap(),
|
||||
"UPDATE \"main\".\"t\" SET \"name\" = 'O''Brien', \"note\" = NULL WHERE \"id\" = '1'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "t", &DbRowEdit::Insert { values: vec![cv("a", Some("x"))] })
|
||||
edit_statement(DbDriver::Mysql, "db", "t", &DbRowEdit::Insert { values: vec![cv("a", Some("x"))] }, &[])
|
||||
.unwrap(),
|
||||
"INSERT INTO `db`.`t` (`a`) VALUES ('x')"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![cv("k", None)] }).unwrap(),
|
||||
edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![cv("k", None)] }, &[]).unwrap(),
|
||||
"DELETE FROM \"s\".\"t\" WHERE \"k\" IS NULL"
|
||||
);
|
||||
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }).is_err());
|
||||
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }, &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_write_the_bytes_of_the_hex_a_binary_cell_shows() {
|
||||
let binary = ["id".to_owned(), "data".to_owned()];
|
||||
let update = DbRowEdit::Update {
|
||||
key: vec![cv("id", Some("0x0102"))],
|
||||
values: vec![cv("DATA", Some("0xcaff")), cv("name", Some("0xCAFF"))],
|
||||
};
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Sqlite, "main", "files", &update, &binary).unwrap(),
|
||||
"UPDATE \"main\".\"files\" SET \"DATA\" = X'caff', \"name\" = '0xCAFF' WHERE \"id\" = X'0102'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "files", &update, &binary).unwrap(),
|
||||
"UPDATE `db`.`files` SET `DATA` = X'caff', `name` = '0xCAFF' WHERE `id` = X'0102'"
|
||||
);
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::SqlServer, "dbo", "files", &update, &binary).unwrap(),
|
||||
"UPDATE [dbo].[files] SET [DATA] = 0xcaff, [name] = '0xCAFF' WHERE [id] = 0x0102"
|
||||
);
|
||||
// Empty bytes, NULL, and text that is not whole bytes of hex.
|
||||
let insert = DbRowEdit::Insert {
|
||||
values: vec![cv("id", Some("0x")), cv("data", None), cv("data", Some("0xCAF")), cv("data", Some("plain"))],
|
||||
};
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::SqlServer, "dbo", "files", &insert, &binary).unwrap(),
|
||||
"INSERT INTO [dbo].[files] ([id], [data], [data], [data]) VALUES (0x, NULL, '0xCAF', 'plain')"
|
||||
);
|
||||
let delete = DbRowEdit::Delete { key: vec![cv("id", Some("0X0A0B"))] };
|
||||
assert_eq!(
|
||||
edit_statement(DbDriver::Mysql, "db", "files", &delete, &binary).unwrap(),
|
||||
"DELETE FROM `db`.`files` WHERE `id` = X'0A0B'"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_columns_by_dialect() {
|
||||
for (driver, binary, text) in [
|
||||
(DbDriver::Sqlite, &["BLOB", "blob"][..], &["TEXT", "", "INTEGER"][..]),
|
||||
(DbDriver::Mysql, &["binary(16)", "varbinary(8)", "tinyblob", "longblob"], &["varchar(16)", "bit(1)"]),
|
||||
(
|
||||
DbDriver::SqlServer,
|
||||
&["binary", "varbinary", "image", "timestamp"],
|
||||
&["varchar", "nvarchar", "uniqueidentifier"],
|
||||
),
|
||||
(DbDriver::Postgres, &[], &["bytea", "text"]),
|
||||
(DbDriver::Oracle, &[], &["RAW", "BLOB"]),
|
||||
] {
|
||||
assert!(binary.iter().all(|t| binary_column(driver, t)), "{driver:?} {binary:?}");
|
||||
assert!(!text.iter().any(|t| binary_column(driver, t)), "{driver:?} {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1463,12 +1548,13 @@ mod tests {
|
||||
DbDriver::Oracle,
|
||||
"hr",
|
||||
"t",
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("n", Some("x"))] }
|
||||
&DbRowEdit::Update { key: key.clone(), values: vec![cv("n", Some("x"))] },
|
||||
&[]
|
||||
)
|
||||
.unwrap(),
|
||||
"UPDATE \"hr\".\"t\" SET \"n\" = 'x' WHERE \"id\" = '1'"
|
||||
);
|
||||
assert!(edit_statement(DbDriver::Oracle, "hr", "t", &DbRowEdit::Insert { values: vec![] }).is_err());
|
||||
assert!(edit_statement(DbDriver::Oracle, "hr", "t", &DbRowEdit::Insert { values: vec![] }, &[]).is_err());
|
||||
use crate::DbObjectKind as K;
|
||||
let (q, col) = object_ddl(DbDriver::Oracle, "hr", K::Procedure, "p").unwrap();
|
||||
assert!(q.contains("DBMS_METADATA.GET_DDL('PROCEDURE'") && col == 0);
|
||||
@@ -1702,7 +1788,7 @@ mod tests {
|
||||
table_page(driver, "PUBLIC", "ORDERS", None, &[], 50, 25),
|
||||
"SELECT * FROM \"PUBLIC\".\"ORDERS\" LIMIT 26 OFFSET 50"
|
||||
);
|
||||
assert!(edit_statement(driver, "PUBLIC", "T", &DbRowEdit::Insert { values: vec![] }).is_err());
|
||||
assert!(edit_statement(driver, "PUBLIC", "T", &DbRowEdit::Insert { values: vec![] }, &[]).is_err());
|
||||
assert_eq!(crate::conn::begin_statement(driver), "BEGIN");
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,11 @@
|
||||
mod clickhouse;
|
||||
mod jdbc;
|
||||
mod mysql;
|
||||
mod pg_console_sessions;
|
||||
mod pg_console_transactions;
|
||||
mod postgres;
|
||||
mod snowflake;
|
||||
mod sqlite;
|
||||
mod sqlite_console_sessions;
|
||||
mod sqlserver;
|
||||
mod ssh_tunnel;
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager, DbOptions};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbRowEdit};
|
||||
|
||||
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
|
||||
|
||||
@@ -304,6 +304,78 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn submits_binary_keys_and_values_as_bytes_and_a_missed_key_fails() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for sql in [
|
||||
"DROP DATABASE IF EXISTS oi_binary",
|
||||
"CREATE DATABASE oi_binary",
|
||||
"CREATE TABLE oi_binary.files (id BINARY(16) PRIMARY KEY, name VARCHAR(20), data VARBINARY(8))",
|
||||
"INSERT INTO oi_binary.files VALUES (UUID_TO_BIN('3f06af63-a93c-11e4-9797-00505690773f'), 'a', 0xCAFE), \
|
||||
(0x01, 'b', NULL)",
|
||||
] {
|
||||
db.execute("m", sql, 1, &c).await?;
|
||||
}
|
||||
let page = db.table_page("m", "oi_binary", "files", None, &[], 0, 10, &c).await?;
|
||||
let mut ids: Vec<String> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
ids.sort();
|
||||
assert_eq!(ids, ["0x01000000000000000000000000000000", "0x3F06AF63A93C11E4979700505690773F"]);
|
||||
let cell = |column: &str, value: &str| CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
DbRowEdit::Update {
|
||||
key: vec![cell("id", &ids[1])],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
DbRowEdit::Delete { key: vec![cell("id", &ids[0])] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("m", "oi_binary", "files", &edits).await?, 2);
|
||||
let r = db.execute("m", "SELECT HEX(id), name, HEX(data), LENGTH(data) FROM oi_binary.files", 10, &c).await?;
|
||||
let row = ["3F06AF63A93C11E4979700505690773F", "renamed", "CAFF", "2"].map(|v| Some(v.to_owned()));
|
||||
assert_eq!(r.rows, [row]);
|
||||
// The connection counts matched rows: an edit that leaves the row as it is counts it, and a
|
||||
// key that matches no row fails instead of reporting 0 rows changed.
|
||||
let same = DbRowEdit::Update { key: vec![cell("id", &ids[1])], values: vec![cell("name", "renamed")] };
|
||||
assert_eq!(db.apply_edits("m", "oi_binary", "files", &[same]).await?, 1);
|
||||
let missed = DbRowEdit::Update { key: vec![cell("id", "0x02")], values: vec![cell("name", "lost")] };
|
||||
let error = db.apply_edits("m", "oi_binary", "files", &[missed]).await.unwrap_err();
|
||||
assert!(error.message.contains("expected to change 1 row, changed 0"), "{}", error.message);
|
||||
db.execute("m", "DROP DATABASE oi_binary", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_script_keeps_routine_bodies_and_delimiter_blocks_whole() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in ["DROP DATABASE IF EXISTS oi_split", "CREATE DATABASE oi_split"] {
|
||||
db.execute("m", stmt, 1, &c).await?;
|
||||
}
|
||||
// A trigger written without DELIMITER, one as mysqldump writes it (in executable comments), then
|
||||
// a procedure in the mysql client's DELIMITER form.
|
||||
let script = "CREATE TABLE oi_split.t (id INT PRIMARY KEY, a INT, b INT);\n\
|
||||
CREATE TABLE oi_split.log (id INT);\n\
|
||||
CREATE TRIGGER oi_split.t_bi BEFORE INSERT ON oi_split.t FOR EACH ROW BEGIN\n \
|
||||
SET NEW.a = 1;\n SET NEW.b = 2;\nEND;\nDELIMITER ;;\n\
|
||||
/*!50003 CREATE*/ /*!50017 DEFINER=CURRENT_USER*/ /*!50003 TRIGGER oi_split.t_ai AFTER INSERT ON \
|
||||
oi_split.t FOR EACH ROW BEGIN\n INSERT INTO oi_split.log VALUES (NEW.id);\nEND */;;\n\
|
||||
DELIMITER //\nCREATE PROCEDURE oi_split.p()\nBEGIN\n \
|
||||
INSERT INTO oi_split.t (id) VALUES (1);\n INSERT INTO oi_split.t (id) VALUES (2);\nEND //\n\
|
||||
DELIMITER ;\nCALL oi_split.p();";
|
||||
for statement in ide_db::split::split(script, DbDriver::Mysql) {
|
||||
db.execute("m", &statement.text, 10, &c).await?;
|
||||
}
|
||||
let r = db
|
||||
.execute("m", "SELECT count(*), sum(a), sum(b), (SELECT count(*) FROM oi_split.log) FROM oi_split.t", 1, &c)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("2".into()), Some("2".into()), Some("4".into()), Some("2".into())]]);
|
||||
db.execute("m", "DROP DATABASE oi_split", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
File renamed without changes.
File renamed without changes.
+24
-2
@@ -566,6 +566,28 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_script_keeps_begin_atomic_bodies_whole() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for cleanup in ["DROP PROCEDURE IF EXISTS oi_split_insert", "DROP TABLE IF EXISTS oi_split"] {
|
||||
db.execute("p", cleanup, 1, &c).await?;
|
||||
}
|
||||
// The example of the CREATE PROCEDURE manual page, run statement by statement as the console does.
|
||||
let script = "CREATE TABLE oi_split (n integer);\nCREATE PROCEDURE oi_split_insert(a integer, b integer)\n\
|
||||
LANGUAGE SQL\nBEGIN ATOMIC\n INSERT INTO oi_split VALUES (a);\n INSERT INTO oi_split VALUES (b);\nEND;\n\
|
||||
CALL oi_split_insert(1, 2);";
|
||||
for statement in ide_db::split::split(script, DbDriver::Postgres) {
|
||||
db.execute("p", &statement.text, 10, &c).await?;
|
||||
}
|
||||
assert_eq!(db.execute("p", "SELECT count(*) FROM oi_split", 1, &c).await?.rows, [[Some("2".into())]]);
|
||||
for cleanup in ["DROP PROCEDURE oi_split_insert", "DROP TABLE oi_split"] {
|
||||
db.execute("p", cleanup, 1, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -679,7 +701,7 @@ async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target
|
||||
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
|
||||
arguments: vec![
|
||||
"--exact".into(),
|
||||
"postgres_tunnel_fixture".into(),
|
||||
"postgres::postgres_tunnel_fixture".into(),
|
||||
"--skip".into(),
|
||||
"listen={localPort}".into(),
|
||||
"--skip".into(),
|
||||
@@ -736,7 +758,7 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
|
||||
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
|
||||
arguments: vec![
|
||||
"--exact".into(),
|
||||
"postgres_tunnel_fixture".into(),
|
||||
"postgres::postgres_tunnel_fixture".into(),
|
||||
"--skip".into(),
|
||||
"listen={localPort}".into(),
|
||||
"--skip".into(),
|
||||
+1
-1
@@ -320,7 +320,7 @@ async fn explorer_metadata_against_a_real_account() {
|
||||
// each is either answered or refused by Snowflake (an edition or privilege it needs), never
|
||||
// misread by the client. `USE` goes to what the session already has.
|
||||
let fixture: serde_json::Value =
|
||||
serde_json::from_str(include_str!("fixtures/snowflake/commands.json")).expect("the fixture parses");
|
||||
serde_json::from_str(include_str!("../fixtures/snowflake/commands.json")).expect("the fixture parses");
|
||||
let mut statements: Vec<(String, String)> = fixture["commands"]
|
||||
.as_array()
|
||||
.expect("commands")
|
||||
@@ -227,6 +227,37 @@ async fn pages_sorts_filters_and_edits_in_a_transaction() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn submits_binary_keys_and_values_as_bytes() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
for sql in [
|
||||
"CREATE TABLE files (id BLOB PRIMARY KEY, name TEXT, data BLOB)",
|
||||
"INSERT INTO files VALUES (x'0102', 'a', x'CAFE'), (x'0304', 'b', NULL)",
|
||||
] {
|
||||
db.execute("s1", sql, 1, &c).await?;
|
||||
}
|
||||
let page = db.table_page("s1", "main", "files", None, &[], 0, 10, &c).await?;
|
||||
let shown: Vec<_> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
assert_eq!(shown, ["0x0102", "0x0304"]);
|
||||
let cell = |column: &str, value: &str| CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
DbRowEdit::Update {
|
||||
key: vec![cell("id", "0x0102")],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
DbRowEdit::Delete { key: vec![cell("id", "0x0304")] },
|
||||
DbRowEdit::Insert { values: vec![cell("id", "0x05"), cell("name", "0x0A"), cell("data", "0x")] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("s1", "main", "files", &edits).await?, 3);
|
||||
let r = db.execute("s1", "SELECT hex(id), name, typeof(data), hex(data) FROM files ORDER BY id", 10, &c).await?;
|
||||
let cells = |row: &[&str]| row.iter().map(|v| Some(v.to_string())).collect::<Vec<_>>();
|
||||
// A hex-looking value of a text column stays text.
|
||||
assert_eq!(r.rows, [cells(&["0102", "renamed", "blob", "CAFF"]), cells(&["05", "0x0A", "blob", ""])]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_connection_and_disconnect() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
@@ -417,6 +448,38 @@ async fn lists_triggers_and_their_ddl() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scripts_and_execute_at_the_caret_keep_trigger_bodies_whole() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
// A script runs its statements one by one, as the console and Run SQL Script do.
|
||||
let script = "CREATE TABLE log (msg TEXT);\nCREATE TRIGGER users_added AFTER INSERT ON users BEGIN\n \
|
||||
INSERT INTO log VALUES ('added ' || NEW.name);\n UPDATE users SET note = 'logged' WHERE id = NEW.id;\nEND;\n\
|
||||
INSERT INTO users (name) VALUES ('dee');";
|
||||
for statement in ide_db::split::split(script, DbDriver::Sqlite) {
|
||||
db.execute("s1", &statement.text, 10, &c).await?;
|
||||
}
|
||||
let r = db
|
||||
.execute("s1", "SELECT (SELECT group_concat(msg) FROM log), (SELECT note FROM users WHERE name = 'dee')", 1, &c)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("added dee".into()), Some("logged".into())]]);
|
||||
// Execute with the caret on the body's DELETE creates the trigger and deletes nothing.
|
||||
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n DELETE FROM log;\nEND;";
|
||||
let caret = console.find("FROM log").unwrap() as u32;
|
||||
let statement = ide_db::split::statement_at(console, caret, DbDriver::Sqlite).unwrap();
|
||||
db.execute("s1", &statement.text, 10, &c).await?;
|
||||
let r = db
|
||||
.execute(
|
||||
"s1",
|
||||
"SELECT (SELECT count(*) FROM log), (SELECT count(*) FROM sqlite_master WHERE type = 'trigger')",
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(r.rows, [[Some("1".into()), Some("2".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
|
||||
let (tmp, db) = setup().await;
|
||||
File renamed without changes.
+100
@@ -96,6 +96,106 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
/// Edits made from what the grid shows: a binary cell is `0x…` hex.
|
||||
#[tokio::test]
|
||||
async fn sqlserver_submits_binary_keys_and_values_as_bytes() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s".into(),
|
||||
name: "sqlserver".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: "tempdb".into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.set_password("s", parts.next().map(str::to_owned), false).await.unwrap();
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("oi_binary_{}", std::process::id());
|
||||
db.execute(
|
||||
"s",
|
||||
&format!("CREATE TABLE dbo.{table} (id varbinary(16) PRIMARY KEY, name nvarchar(20), data varbinary(8))"),
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
db.execute("s", &format!("INSERT INTO dbo.{table} VALUES (0x0102, 'a', 0xCAFE), (0x0304, 'b', NULL)"), 1, &c)
|
||||
.await
|
||||
.unwrap();
|
||||
let page = db.table_page("s", "dbo", &table, None, &[], 0, 10, &c).await.unwrap();
|
||||
let mut ids: Vec<_> = page.result.rows.iter().map(|r| r[0].clone().unwrap()).collect();
|
||||
ids.sort();
|
||||
assert_eq!(ids, ["0x0102", "0x0304"]);
|
||||
let cell = |column: &str, value: &str| ide_db::CellValue { column: column.into(), value: Some(value.into()) };
|
||||
let edits = [
|
||||
ide_db::DbRowEdit::Update {
|
||||
key: vec![cell("id", "0x0102")],
|
||||
values: vec![cell("name", "renamed"), cell("data", "0xCAFF")],
|
||||
},
|
||||
ide_db::DbRowEdit::Delete { key: vec![cell("id", "0x0304")] },
|
||||
];
|
||||
assert_eq!(db.apply_edits("s", "dbo", &table, &edits).await.unwrap(), 2);
|
||||
let r = db
|
||||
.execute(
|
||||
"s",
|
||||
&format!("SELECT CONVERT(varchar(40), id, 1), name, CONVERT(varchar(40), data, 1) FROM dbo.{table}"),
|
||||
10,
|
||||
&c,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.rows, [["0x0102", "renamed", "0xCAFF"].map(|v| Some(v.to_owned()))]);
|
||||
db.execute("s", &format!("DROP TABLE dbo.{table}"), 1, &c).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_scripts_keep_go_batches_and_routine_bodies_whole() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let source = DataSource {
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.next().unwrap().into(),
|
||||
port: Some(parts.next().unwrap().parse().unwrap()),
|
||||
user: parts.next().unwrap().into(),
|
||||
database: "tempdb".into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let pool = Pool::connect(&source, parts.next(), None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let (table, proc) =
|
||||
(format!("dbo.oi_split_{}", std::process::id()), format!("dbo.oi_split_p_{}", std::process::id()));
|
||||
// An SSMS-style script, run statement by statement as the console does.
|
||||
let script = format!(
|
||||
"CREATE TABLE {table} (a int)\nGO\nCREATE PROCEDURE {proc} AS\nBEGIN\n SET NOCOUNT ON;\n \
|
||||
INSERT INTO {table} VALUES (1);\n INSERT INTO {table} VALUES (2);\nEND\nGO\nEXEC {proc}"
|
||||
);
|
||||
for statement in ide_db::split::split(&script, DbDriver::SqlServer) {
|
||||
pool.execute(&statement.text, 10, &cancel).await.unwrap();
|
||||
}
|
||||
assert_eq!(pool.rows(&format!("SELECT count(*) FROM {table}"), 1).await.unwrap(), [[Some("2".into())]]);
|
||||
// Without GO, SQL Server reads the rest of the batch as the body.
|
||||
let body = format!("CREATE PROCEDURE {proc}_q AS SELECT 1 AS one; SELECT 2 AS two;");
|
||||
for statement in ide_db::split::split(&body, DbDriver::SqlServer) {
|
||||
pool.execute(&statement.text, 10, &cancel).await.unwrap();
|
||||
}
|
||||
let definition = pool.rows(&format!("SELECT OBJECT_DEFINITION(OBJECT_ID('{proc}_q'))"), 1).await.unwrap();
|
||||
assert_eq!(definition, [[Some(body)]]);
|
||||
pool.execute(&format!("DROP PROCEDURE {proc}; DROP PROCEDURE {proc}_q; DROP TABLE {table}"), 1, &cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
File renamed without changes.
@@ -7,8 +7,9 @@
|
||||
|
||||
use crate::{
|
||||
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
|
||||
DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject,
|
||||
DockerProcessList, DockerSnapshot, DockerVolume, parse_info, split_csv,
|
||||
DockerContainerStatsSample, DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine,
|
||||
DockerNetwork, DockerObject, DockerProcessList, DockerSnapshot, DockerVolume, EngineStatsState,
|
||||
parse_engine_stats_frame, parse_info, split_csv,
|
||||
};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::Deserialize;
|
||||
@@ -66,17 +67,25 @@ pub(crate) fn address(ep: &DockerEndpoint) -> Option<Address> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a daemon host URL (`unix:///path`, `tcp://host:port`, `http://host:port`)
|
||||
/// into a direct Engine API address when no TLS or Windows named pipe is required.
|
||||
pub(crate) fn address_from_url(url: &str) -> Option<Address> {
|
||||
let host = url.trim();
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match host.split_once("://") {
|
||||
Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())),
|
||||
Some(("tcp", rest)) | Some(("http", rest)) => host_port(rest).map(|(host, port)| Address::Tcp { host, port }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The default endpoint's daemon: `DOCKER_HOST` when it is a plain socket or
|
||||
/// TCP address, else the unix socket (Windows named pipes need the CLI).
|
||||
fn default_address(docker_host: Option<&str>) -> Option<Address> {
|
||||
if let Some(host) = docker_host.map(str::trim).filter(|h| !h.is_empty()) {
|
||||
return match host.split_once("://") {
|
||||
Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())),
|
||||
Some(("tcp", rest)) | Some(("http", rest)) => {
|
||||
host_port(rest).map(|(host, port)| Address::Tcp { host, port })
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
return address_from_url(host);
|
||||
}
|
||||
if cfg!(unix) { Some(Address::UnixSocket("/var/run/docker.sock".into())) } else { None }
|
||||
}
|
||||
@@ -623,9 +632,77 @@ fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How often a log stream that has nothing to read checks for cancellation.
|
||||
fn unix_now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How often a log or stats stream that has nothing to read checks for cancellation.
|
||||
const LOG_POLL: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Streams live resource samples for running container `id` directly from the Docker
|
||||
/// Engine HTTP API (`GET /containers/{id}/stats?stream=true`) until the container stops
|
||||
/// or `cancel` fires.
|
||||
pub(crate) fn container_stats_stream(
|
||||
addr: &Address,
|
||||
id: &str,
|
||||
timeout: Duration,
|
||||
cancel: &CancellationToken,
|
||||
on_sample: &dyn Fn(DockerContainerStatsSample),
|
||||
) -> IdeResult<()> {
|
||||
let path = format!("/containers/{}/stats?stream=true", path_segment(id));
|
||||
let mut conn = Conn::connect(addr, timeout)?;
|
||||
conn.write_all(
|
||||
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n").as_bytes(),
|
||||
)?;
|
||||
let head = read_head(&mut conn)?;
|
||||
if !(200..300).contains(&head.status) {
|
||||
let body = read_body(&mut conn, &head)?;
|
||||
check(Response { status: head.status, body })?;
|
||||
}
|
||||
conn.set_timeouts(LOG_POLL);
|
||||
let mut framing = BodyFraming::from_head(&head);
|
||||
let mut partial = Vec::new();
|
||||
let mut payload = Vec::new();
|
||||
let mut state = EngineStatsState::default();
|
||||
let mut buf = [0u8; 8192];
|
||||
while !framing.done() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match conn.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
payload.clear();
|
||||
framing.decode(&buf[..n], &mut payload)?;
|
||||
for &b in &payload {
|
||||
if b == b'\n' {
|
||||
let line = line_text(&partial);
|
||||
partial.clear();
|
||||
if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) {
|
||||
on_sample(sample);
|
||||
}
|
||||
} else {
|
||||
partial.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
|
||||
) => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
if !partial.is_empty() {
|
||||
let line = line_text(&partial);
|
||||
if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) {
|
||||
on_sample(sample);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiContainerInspect {
|
||||
@@ -723,32 +800,30 @@ enum ChunkState {
|
||||
Done,
|
||||
}
|
||||
|
||||
impl LogDecoder {
|
||||
fn new(head: &Head, tty: bool) -> Self {
|
||||
let body = if head.chunked {
|
||||
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
|
||||
impl BodyFraming {
|
||||
fn from_head(head: &Head) -> Self {
|
||||
if head.chunked {
|
||||
Self::Chunked { state: ChunkState::Size, line: Vec::new() }
|
||||
} else if let Some(n) = head.length {
|
||||
BodyFraming::Length(n)
|
||||
Self::Length(n)
|
||||
} else {
|
||||
BodyFraming::Close
|
||||
};
|
||||
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
|
||||
Self::Close
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self) -> bool {
|
||||
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
|
||||
matches!(self, Self::Chunked { state: ChunkState::Done, .. } | Self::Length(0))
|
||||
}
|
||||
|
||||
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
|
||||
let mut payload = Vec::new();
|
||||
match &mut self.body {
|
||||
BodyFraming::Close => payload.extend_from_slice(bytes),
|
||||
BodyFraming::Length(left) => {
|
||||
fn decode(&mut self, mut bytes: &[u8], payload: &mut Vec<u8>) -> IdeResult<()> {
|
||||
match self {
|
||||
Self::Close => payload.extend_from_slice(bytes),
|
||||
Self::Length(left) => {
|
||||
let take = (*left).min(bytes.len());
|
||||
payload.extend_from_slice(&bytes[..take]);
|
||||
*left -= take;
|
||||
}
|
||||
BodyFraming::Chunked { state, line } => {
|
||||
Self::Chunked { state, line } => {
|
||||
while !bytes.is_empty() {
|
||||
match *state {
|
||||
ChunkState::Done => break,
|
||||
@@ -791,6 +866,29 @@ impl LogDecoder {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LogDecoder {
|
||||
fn new(head: &Head, tty: bool) -> Self {
|
||||
Self {
|
||||
body: BodyFraming::from_head(head),
|
||||
tty,
|
||||
header: Vec::new(),
|
||||
frame_left: 0,
|
||||
frame_stderr: false,
|
||||
partial: [Vec::new(), Vec::new()],
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self) -> bool {
|
||||
self.body.done()
|
||||
}
|
||||
|
||||
fn feed(&mut self, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
|
||||
let mut payload = Vec::new();
|
||||
self.body.decode(bytes, &mut payload)?;
|
||||
self.frames(&payload, emit);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1443,4 +1541,65 @@ mod tests {
|
||||
assert_eq!(path_segment("a/b"), "a%2Fb");
|
||||
assert_eq!(path_segment(" sha256:ab "), "sha256%3Aab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_stats_stream_reads_chunked_ndjson_samples() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut sock, _) = listener.accept().unwrap();
|
||||
let mut req_buf = [0u8; 512];
|
||||
let n = sock.read(&mut req_buf).unwrap();
|
||||
let req = String::from_utf8_lossy(&req_buf[..n]);
|
||||
assert!(req.starts_with("GET /containers/c1/stats?stream=true HTTP/1.1\r\n"));
|
||||
let f1 = concat!(
|
||||
r#"{"read":"2026-12-04T18:12:06Z","pids_stats":{"current":3},"#,
|
||||
r#""cpu_stats":{"cpu_usage":{"total_usage":200},"system_cpu_usage":1000,"online_cpus":2},"#,
|
||||
r#""precpu_stats":{"cpu_usage":{"total_usage":100},"system_cpu_usage":500,"online_cpus":2},"#,
|
||||
r#""memory_stats":{"usage":52428800,"limit":104857600},"#,
|
||||
r#""networks":{"eth0":{"rx_bytes":1000,"tx_bytes":500}},"#,
|
||||
r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":8192}]}}"#,
|
||||
"\n",
|
||||
);
|
||||
let f2 = concat!(
|
||||
r#"{"read":"2026-12-04T18:12:07Z","pids_stats":{"current":4},"#,
|
||||
r#""cpu_stats":{"cpu_usage":{"total_usage":250},"system_cpu_usage":1500,"online_cpus":2},"#,
|
||||
r#""memory_stats":{"usage":62914560,"limit":104857600},"#,
|
||||
r#""networks":{"eth0":{"rx_bytes":2500,"tx_bytes":900}},"#,
|
||||
r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":16384}]}}"#,
|
||||
"\n",
|
||||
);
|
||||
let mut resp =
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
|
||||
for chunk in [f1.as_bytes(), f2.as_bytes()] {
|
||||
resp.extend(format!("{:x}\r\n", chunk.len()).as_bytes());
|
||||
resp.extend(chunk);
|
||||
resp.extend(b"\r\n");
|
||||
}
|
||||
resp.extend(b"0\r\n\r\n");
|
||||
sock.write_all(&resp).unwrap();
|
||||
});
|
||||
|
||||
let samples = std::sync::Mutex::new(Vec::new());
|
||||
let cancel = CancellationToken::new();
|
||||
container_stats_stream(
|
||||
&Address::Tcp { host: "127.0.0.1".into(), port },
|
||||
"c1",
|
||||
Duration::from_secs(5),
|
||||
&cancel,
|
||||
&|s| samples.lock().unwrap().push(s),
|
||||
)
|
||||
.unwrap();
|
||||
server.join().unwrap();
|
||||
|
||||
let samples = samples.into_inner().unwrap();
|
||||
assert_eq!(samples.len(), 2);
|
||||
assert!((samples[0].cpu_percent - 40.0).abs() < 1e-6);
|
||||
assert_eq!(samples[0].mem_used_bytes, 52_428_800);
|
||||
assert_eq!(samples[0].disk_write_bytes, 8192);
|
||||
// Second frame lacked precpu_stats and used saved EngineStatsState: (50/500)*2*100 = 20%.
|
||||
assert!((samples[1].cpu_percent - 20.0).abs() < 1e-6);
|
||||
assert_eq!(samples[1].net_rx_bytes, 2500);
|
||||
assert_eq!(samples[1].pids, 4);
|
||||
}
|
||||
}
|
||||
@@ -343,6 +343,75 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
fn unix_now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Resolves `ep` to a direct Docker Engine API socket/TCP address when reachable
|
||||
/// without TLS or named pipes, including `Default`/`Context` daemons such as
|
||||
/// Docker Desktop (`desktop-linux`), OrbStack, or Colima.
|
||||
fn resolve_engine_address(ep: &DockerEndpoint) -> Option<engine::Address> {
|
||||
if std::env::var_os("OPENIDEA_DOCKER").is_some() {
|
||||
return None;
|
||||
}
|
||||
match ep {
|
||||
DockerEndpoint::Socket { .. } | DockerEndpoint::Tcp { .. } => engine::address(ep),
|
||||
DockerEndpoint::Default => {
|
||||
if docker_executable().is_none() {
|
||||
return engine::address(ep);
|
||||
}
|
||||
let url = default_daemon_url(
|
||||
ide_core::process::host_var_os("DOCKER_CONTEXT").as_deref().and_then(|v| v.to_str()),
|
||||
ide_core::process::host_var_os("DOCKER_HOST").as_deref().and_then(|v| v.to_str()),
|
||||
|name| context_host(&DockerEndpoint::Default, name),
|
||||
)
|
||||
.ok()?;
|
||||
engine::address_from_url(&url).or_else(|| engine::address(ep))
|
||||
}
|
||||
DockerEndpoint::Context { name } => {
|
||||
let url = context_host(&DockerEndpoint::Default, Some(name.trim())).ok()?;
|
||||
engine::address_from_url(&url)
|
||||
}
|
||||
DockerEndpoint::Ssh { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams live resource samples for running container `id` until it stops or `cancel` fires.
|
||||
/// Prefers the direct Engine HTTP API (`GET /containers/{id}/stats?stream=true`) for exact
|
||||
/// byte counters with zero CLI process overhead; falls back to streaming `docker stats`.
|
||||
pub fn stream_container_stats(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_sample: &dyn Fn(DockerContainerStatsSample),
|
||||
) -> IdeResult<()> {
|
||||
let id = check_id(id)?;
|
||||
if let Some(addr) = resolve_engine_address(ep) {
|
||||
let emitted = std::cell::Cell::new(false);
|
||||
let res = engine::container_stats_stream(&addr, id, QUICK, cancel, &|sample| {
|
||||
emitted.set(true);
|
||||
on_sample(sample);
|
||||
});
|
||||
match res {
|
||||
Ok(()) => return Ok(()),
|
||||
// If cancelled, or samples already streamed, or CLI is absent, propagate directly.
|
||||
Err(e) if cancel.is_cancelled() || emitted.get() || docker_executable().is_none() => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("direct Docker stats stream unavailable, falling back to CLI: {}", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
let args = ["stats", "--no-trunc", "--format", "{{json .}}", id];
|
||||
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| {
|
||||
if stream == Stream::Stdout
|
||||
&& let Some(sample) = parse_cli_stats_sample(&line, unix_now_ms())
|
||||
{
|
||||
on_sample(sample);
|
||||
}
|
||||
})?;
|
||||
if ok { Ok(()) } else { Err(failure(&args, &stderr.join("\n"), "")) }
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
pub fn host_resources(ep: &DockerEndpoint) -> IdeResult<DockerHostResources> {
|
||||
if docker_executable().is_none()
|
||||
|
||||
@@ -145,6 +145,37 @@ pub struct DockerContainerStats {
|
||||
pub pids: String,
|
||||
}
|
||||
|
||||
/// One time-series resource sample for a running container (from Docker Engine
|
||||
/// `GET /containers/{id}/stats?stream=true` or the `docker stats` CLI stream fallback).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerContainerStatsSample {
|
||||
/// Sample timestamp as Unix epoch milliseconds.
|
||||
pub timestamp_ms: u64,
|
||||
/// CPU utilization percentage (may exceed 100.0 on multi-core containers).
|
||||
pub cpu_percent: f64,
|
||||
/// Number of CPUs visible to this container/daemon, if reported.
|
||||
pub online_cpus: Option<u32>,
|
||||
/// Working memory usage in bytes (excluding reclaimable page cache, matching `docker stats`).
|
||||
pub mem_used_bytes: u64,
|
||||
/// Effective memory limit in bytes (container cgroup limit or Docker VM memory).
|
||||
pub mem_limit_bytes: u64,
|
||||
/// Memory usage percentage (`0.0..=100.0`).
|
||||
pub mem_percent: f64,
|
||||
/// Cumulative network bytes received across all interfaces.
|
||||
pub net_rx_bytes: u64,
|
||||
/// Cumulative network bytes transmitted across all interfaces.
|
||||
pub net_tx_bytes: u64,
|
||||
/// Cumulative block device bytes read.
|
||||
pub disk_read_bytes: u64,
|
||||
/// Cumulative block device bytes written.
|
||||
pub disk_write_bytes: u64,
|
||||
/// Current PID count inside the container.
|
||||
pub pids: u64,
|
||||
/// True when I/O or memory counters came from rounded CLI strings rather than raw Engine API bytes.
|
||||
pub approximate_io: bool,
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -517,6 +548,342 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Previous CPU counters retained across Engine API stats frames so CPU% stays
|
||||
/// accurate even when the daemon omits `precpu_stats` on the first frame.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct EngineStatsState {
|
||||
prev_cpu_total: Option<u64>,
|
||||
prev_system_cpu: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiStatsFrame {
|
||||
read: String,
|
||||
pids_stats: ApiPidsStats,
|
||||
blkio_stats: ApiBlkioStats,
|
||||
storage_stats: ApiStorageStats,
|
||||
cpu_stats: ApiCpuStats,
|
||||
precpu_stats: ApiCpuStats,
|
||||
memory_stats: ApiMemoryStats,
|
||||
networks: Option<BTreeMap<String, ApiNetworkStats>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiPidsStats {
|
||||
current: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiBlkioStats {
|
||||
io_service_bytes_recursive: Option<Vec<ApiBlkioEntry>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiBlkioEntry {
|
||||
op: String,
|
||||
value: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiStorageStats {
|
||||
read_size_bytes: Option<u64>,
|
||||
write_size_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiCpuStats {
|
||||
cpu_usage: ApiCpuUsage,
|
||||
system_cpu_usage: Option<u64>,
|
||||
online_cpus: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiCpuUsage {
|
||||
total_usage: u64,
|
||||
percpu_usage: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiMemoryStats {
|
||||
usage: Option<u64>,
|
||||
limit: Option<u64>,
|
||||
privateworkingset: Option<u64>,
|
||||
stats: Option<BTreeMap<String, u64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ApiNetworkStats {
|
||||
rx_bytes: u64,
|
||||
tx_bytes: u64,
|
||||
}
|
||||
|
||||
fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
|
||||
let y = year - i64::from(month <= 2);
|
||||
let era = y.div_euclid(400);
|
||||
let yoe = (y - era * 400) as u64;
|
||||
let m = month as u64;
|
||||
let d = day as u64;
|
||||
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe as i64 - 719_468
|
||||
}
|
||||
|
||||
/// Parses an RFC3339 timestamp (`YYYY-MM-DDTHH:MM:SS(.frac)?(Z|±HH:MM)`) into Unix
|
||||
/// epoch milliseconds, rejecting Docker's zero timestamp (`0001-01-01…`).
|
||||
pub fn parse_rfc3339_ms(raw: &str) -> Option<u64> {
|
||||
let s = raw.trim();
|
||||
if s.len() < 20 {
|
||||
return None;
|
||||
}
|
||||
let b = s.as_bytes();
|
||||
if b[4] != b'-'
|
||||
|| b[7] != b'-'
|
||||
|| (b[10] != b'T' && b[10] != b't' && b[10] != b' ')
|
||||
|| b[13] != b':'
|
||||
|| b[16] != b':'
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let year: i64 = s[0..4].parse().ok()?;
|
||||
let month: u32 = s[5..7].parse().ok()?;
|
||||
let day: u32 = s[8..10].parse().ok()?;
|
||||
let hour: u64 = s[11..13].parse().ok()?;
|
||||
let minute: u64 = s[14..16].parse().ok()?;
|
||||
let second: u64 = s[17..19].parse().ok()?;
|
||||
if year <= 1 || !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
|
||||
return None;
|
||||
}
|
||||
let mut rest = &s[19..];
|
||||
let mut millis: u64 = 0;
|
||||
if let Some(after_dot) = rest.strip_prefix('.') {
|
||||
let digits_len = after_dot.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let frac = &after_dot[..digits_len];
|
||||
let mut scale = 100u64;
|
||||
for ch in frac.bytes().take(3) {
|
||||
millis += u64::from(ch - b'0') * scale;
|
||||
scale /= 10;
|
||||
}
|
||||
rest = &after_dot[digits_len..];
|
||||
}
|
||||
let offset_secs: i64 = if rest.eq_ignore_ascii_case("Z") {
|
||||
0
|
||||
} else if rest.len() == 6 && (rest.starts_with('+') || rest.starts_with('-')) && rest.as_bytes()[3] == b':' {
|
||||
let sign = if rest.starts_with('-') { -1i64 } else { 1i64 };
|
||||
let oh: i64 = rest[1..3].parse().ok()?;
|
||||
let om: i64 = rest[4..6].parse().ok()?;
|
||||
if oh > 23 || om > 59 {
|
||||
return None;
|
||||
}
|
||||
sign * (oh * 3600 + om * 60)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let days = days_from_civil(year, month, day);
|
||||
let secs = days * 86_400 + (hour * 3600 + minute * 60 + second) as i64 - offset_secs;
|
||||
if secs < 0 {
|
||||
return None;
|
||||
}
|
||||
Some((secs as u64).saturating_mul(1000).saturating_add(millis))
|
||||
}
|
||||
|
||||
/// Parses one newline-delimited JSON frame from Docker Engine `GET /containers/{id}/stats`.
|
||||
/// Returns `None` for malformed lines or Docker's empty final frame after a container stops.
|
||||
pub fn parse_engine_stats_frame(
|
||||
line: &str,
|
||||
state: &mut EngineStatsState,
|
||||
fallback_timestamp_ms: u64,
|
||||
) -> Option<DockerContainerStatsSample> {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.starts_with('{') {
|
||||
return None;
|
||||
}
|
||||
let frame: ApiStatsFrame = serde_json::from_str(trimmed).ok()?;
|
||||
|
||||
let mem_limit = frame.memory_stats.limit.unwrap_or(0);
|
||||
let sys_cpu = frame.cpu_stats.system_cpu_usage.unwrap_or(0);
|
||||
let raw_usage = frame.memory_stats.usage.unwrap_or(0);
|
||||
let private_ws = frame.memory_stats.privateworkingset.unwrap_or(0);
|
||||
|
||||
// When a container stops mid-stream, Docker sends a final zeroed frame with read="0001-01-01…".
|
||||
if frame.read.starts_with("0001-01-01") && mem_limit == 0 && sys_cpu == 0 && raw_usage == 0 && private_ws == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let timestamp_ms = parse_rfc3339_ms(&frame.read).unwrap_or(fallback_timestamp_ms);
|
||||
|
||||
let online_cpus = frame
|
||||
.cpu_stats
|
||||
.online_cpus
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| frame.cpu_stats.cpu_usage.percpu_usage.as_ref().map(|v| v.len() as u32).filter(|&n| n > 0));
|
||||
|
||||
let cur_cpu = frame.cpu_stats.cpu_usage.total_usage;
|
||||
let (pre_cpu, pre_sys) = match frame.precpu_stats.system_cpu_usage.filter(|&s| s > 0) {
|
||||
Some(s) => (frame.precpu_stats.cpu_usage.total_usage, s),
|
||||
None => (state.prev_cpu_total.unwrap_or(0), state.prev_system_cpu.unwrap_or(0)),
|
||||
};
|
||||
state.prev_cpu_total = Some(cur_cpu);
|
||||
state.prev_system_cpu = Some(sys_cpu);
|
||||
|
||||
let cpu_delta = cur_cpu.saturating_sub(pre_cpu);
|
||||
let system_delta = sys_cpu.saturating_sub(pre_sys);
|
||||
let cpu_percent = if system_delta > 0 && cpu_delta > 0 {
|
||||
(cpu_delta as f64 / system_delta as f64) * f64::from(online_cpus.unwrap_or(1)) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Match Docker CLI `calculateMemUsageUnixNoCache`: subtract inactive_file (cgroup v2)
|
||||
// or total_inactive_file (cgroup v1) when below raw usage; fall back to Windows privateworkingset.
|
||||
let mem_used_bytes = if raw_usage > 0 {
|
||||
let reclaimable = frame
|
||||
.memory_stats
|
||||
.stats
|
||||
.as_ref()
|
||||
.and_then(|s| s.get("total_inactive_file").or_else(|| s.get("inactive_file")).copied())
|
||||
.filter(|&v| v < raw_usage)
|
||||
.unwrap_or(0);
|
||||
raw_usage - reclaimable
|
||||
} else {
|
||||
private_ws
|
||||
};
|
||||
let mem_percent = if mem_limit > 0 { (mem_used_bytes as f64 / mem_limit as f64) * 100.0 } else { 0.0 };
|
||||
|
||||
let (mut net_rx_bytes, mut net_tx_bytes) = (0u64, 0u64);
|
||||
if let Some(nets) = frame.networks {
|
||||
for net in nets.values() {
|
||||
net_rx_bytes = net_rx_bytes.saturating_add(net.rx_bytes);
|
||||
net_tx_bytes = net_tx_bytes.saturating_add(net.tx_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
let (mut disk_read_bytes, mut disk_write_bytes) = (0u64, 0u64);
|
||||
let mut saw_blkio = false;
|
||||
if let Some(entries) = frame.blkio_stats.io_service_bytes_recursive {
|
||||
for entry in entries {
|
||||
if entry.op.eq_ignore_ascii_case("read") {
|
||||
disk_read_bytes = disk_read_bytes.saturating_add(entry.value);
|
||||
saw_blkio = true;
|
||||
} else if entry.op.eq_ignore_ascii_case("write") {
|
||||
disk_write_bytes = disk_write_bytes.saturating_add(entry.value);
|
||||
saw_blkio = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !saw_blkio {
|
||||
disk_read_bytes = frame.storage_stats.read_size_bytes.unwrap_or(0);
|
||||
disk_write_bytes = frame.storage_stats.write_size_bytes.unwrap_or(0);
|
||||
}
|
||||
|
||||
Some(DockerContainerStatsSample {
|
||||
timestamp_ms,
|
||||
cpu_percent,
|
||||
online_cpus,
|
||||
mem_used_bytes,
|
||||
mem_limit_bytes: mem_limit,
|
||||
mem_percent,
|
||||
net_rx_bytes,
|
||||
net_tx_bytes,
|
||||
disk_read_bytes,
|
||||
disk_write_bytes,
|
||||
pids: frame.pids_stats.current.unwrap_or(0),
|
||||
approximate_io: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_unit_bytes(raw: &str) -> u64 {
|
||||
let s = raw.trim();
|
||||
if s.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let split = s.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(s.len());
|
||||
let num = match s[..split].trim().parse::<f64>() {
|
||||
Ok(v) if v.is_finite() && v > 0.0 => v,
|
||||
_ => return 0,
|
||||
};
|
||||
let unit = s[split..].trim();
|
||||
let mult: f64 = match unit {
|
||||
"" | "B" => 1.0,
|
||||
"KiB" | "Ki" => 1024.0,
|
||||
"MiB" | "Mi" => 1024.0 * 1024.0,
|
||||
"GiB" | "Gi" => 1024.0 * 1024.0 * 1024.0,
|
||||
"TiB" | "Ti" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
|
||||
"PiB" | "Pi" => 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0,
|
||||
"kB" | "KB" | "K" | "k" => 1000.0,
|
||||
"MB" | "M" => 1000.0 * 1000.0,
|
||||
"GB" | "G" => 1000.0 * 1000.0 * 1000.0,
|
||||
"TB" | "T" => 1000.0 * 1000.0 * 1000.0 * 1000.0,
|
||||
"PB" | "P" => 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
(num * mult).round().max(0.0) as u64
|
||||
}
|
||||
|
||||
fn parse_pair_bytes(raw: &str) -> (u64, u64) {
|
||||
let mut parts = raw.split('/');
|
||||
let a = parts.next().map(parse_unit_bytes).unwrap_or(0);
|
||||
let b = parts.next().map(parse_unit_bytes).unwrap_or(0);
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Parses one line of `docker stats --no-trunc --format '{{json .}}'` (stripping any
|
||||
/// leading ANSI screen-clear control codes Docker CLI emits before each JSON object).
|
||||
pub fn parse_cli_stats_sample(line: &str, timestamp_ms: u64) -> Option<DockerContainerStatsSample> {
|
||||
let start = line.find('{')?;
|
||||
let end = line.rfind('}')?;
|
||||
if end < start {
|
||||
return None;
|
||||
}
|
||||
let raw: RawStats = serde_json::from_str(&line[start..=end]).ok()?;
|
||||
let cpu_percent = raw
|
||||
.cpu_perc
|
||||
.trim()
|
||||
.trim_end_matches('%')
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && *v >= 0.0)
|
||||
.unwrap_or(0.0);
|
||||
let (mem_used_bytes, mem_limit_bytes) = parse_pair_bytes(&raw.mem_usage);
|
||||
let mem_percent = raw
|
||||
.mem_perc
|
||||
.trim()
|
||||
.trim_end_matches('%')
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && *v >= 0.0)
|
||||
.unwrap_or_else(|| {
|
||||
if mem_limit_bytes > 0 { (mem_used_bytes as f64 / mem_limit_bytes as f64) * 100.0 } else { 0.0 }
|
||||
});
|
||||
let (net_rx_bytes, net_tx_bytes) = parse_pair_bytes(&raw.net_io);
|
||||
let (disk_read_bytes, disk_write_bytes) = parse_pair_bytes(&raw.block_io);
|
||||
let pids = raw.pids.trim().parse::<u64>().unwrap_or(0);
|
||||
Some(DockerContainerStatsSample {
|
||||
timestamp_ms,
|
||||
cpu_percent,
|
||||
online_cpus: None,
|
||||
mem_used_bytes,
|
||||
mem_limit_bytes,
|
||||
mem_percent,
|
||||
net_rx_bytes,
|
||||
net_tx_bytes,
|
||||
disk_read_bytes,
|
||||
disk_write_bytes,
|
||||
pids,
|
||||
approximate_io: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// `docker info --format` template for daemon / VM CPU and memory capacity.
|
||||
pub const INFO_FORMAT: &str =
|
||||
r#"{"NCPU":{{json .NCPU}},"MemTotal":{{json .MemTotal}},"OperatingSystem":{{json .OperatingSystem}}}"#;
|
||||
@@ -937,4 +1304,100 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(found.id, "running-c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_rfc3339_timestamps() {
|
||||
assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0));
|
||||
assert_eq!(parse_rfc3339_ms("2026-12-04T18:12:06.250999999Z"), Some(1_796_407_926_250));
|
||||
assert_eq!(parse_rfc3339_ms("2026-12-04T10:12:06.5-08:00"), Some(1_796_407_926_500));
|
||||
assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_engine_stats_frames_for_cgroup_v1_v2_and_stopped_containers() {
|
||||
let mut state = EngineStatsState::default();
|
||||
// cgroup v2 frame with multi-core CPU (> 100%), multiple interfaces, and blkio.
|
||||
let frame = r#"{
|
||||
"read": "2026-12-04T18:12:06.500000000Z",
|
||||
"pids_stats": { "current": 17 },
|
||||
"blkio_stats": {
|
||||
"io_service_bytes_recursive": [
|
||||
{ "major": 259, "minor": 0, "op": "read", "value": 274000000 },
|
||||
{ "major": 259, "minor": 0, "op": "write", "value": 11400000000 },
|
||||
{ "major": 259, "minor": 0, "op": "sync", "value": 999 }
|
||||
]
|
||||
},
|
||||
"cpu_stats": {
|
||||
"cpu_usage": { "total_usage": 250000000 },
|
||||
"system_cpu_usage": 2000000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"precpu_stats": {
|
||||
"cpu_usage": { "total_usage": 100000000 },
|
||||
"system_cpu_usage": 1500000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"memory_stats": {
|
||||
"usage": 1000000000,
|
||||
"stats": { "inactive_file": 100000000 },
|
||||
"limit": 4000000000
|
||||
},
|
||||
"networks": {
|
||||
"eth0": { "rx_bytes": 280000000, "tx_bytes": 1000000 },
|
||||
"eth1": { "rx_bytes": 1000000, "tx_bytes": 200000 }
|
||||
}
|
||||
}"#;
|
||||
let sample = parse_engine_stats_frame(frame, &mut state, 0).unwrap();
|
||||
assert_eq!(sample.timestamp_ms, 1_796_407_926_500);
|
||||
// (150M / 500M) * 4 * 100 = 120%
|
||||
assert!((sample.cpu_percent - 120.0).abs() < 1e-6);
|
||||
assert_eq!(sample.online_cpus, Some(4));
|
||||
assert_eq!(sample.mem_used_bytes, 900_000_000);
|
||||
assert_eq!(sample.mem_limit_bytes, 4_000_000_000);
|
||||
assert!((sample.mem_percent - 22.5).abs() < 1e-6);
|
||||
assert_eq!(sample.net_rx_bytes, 281_000_000);
|
||||
assert_eq!(sample.net_tx_bytes, 1_200_000);
|
||||
assert_eq!(sample.disk_read_bytes, 274_000_000);
|
||||
assert_eq!(sample.disk_write_bytes, 11_400_000_000);
|
||||
assert_eq!(sample.pids, 17);
|
||||
assert!(!sample.approximate_io);
|
||||
|
||||
// Next frame omits `precpu_stats`: uses saved EngineStatsState from previous frame.
|
||||
let frame2 = r#"{
|
||||
"read": "2026-12-04T18:12:07.500000000Z",
|
||||
"cpu_stats": {
|
||||
"cpu_usage": { "total_usage": 300000000 },
|
||||
"system_cpu_usage": 2500000000,
|
||||
"online_cpus": 4
|
||||
},
|
||||
"memory_stats": {
|
||||
"usage": 500000000,
|
||||
"stats": { "total_inactive_file": 50000000 },
|
||||
"limit": 4000000000
|
||||
}
|
||||
}"#;
|
||||
let sample2 = parse_engine_stats_frame(frame2, &mut state, 0).unwrap();
|
||||
// (50M / 500M) * 4 * 100 = 40%
|
||||
assert!((sample2.cpu_percent - 40.0).abs() < 1e-6);
|
||||
assert_eq!(sample2.mem_used_bytes, 450_000_000);
|
||||
|
||||
// Final stopped-container empty frame is ignored.
|
||||
let stopped = r#"{"read":"0001-01-01T00:00:00Z","cpu_stats":{},"memory_stats":{}}"#;
|
||||
assert_eq!(parse_engine_stats_frame(stopped, &mut state, 1234), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_cli_stats_stream_lines_with_ansi_screen_clear() {
|
||||
let line = "\x1b[2J\x1b[H{\"CPUPerc\":\"12.34%\",\"MemUsage\":\"891.8MiB / 114.3GiB\",\"MemPerc\":\"0.76%\",\"NetIO\":\"281MB / 1.2MB\",\"BlockIO\":\"274MB / 11.4GB\",\"PIDs\":\"17\"}";
|
||||
let sample = parse_cli_stats_sample(line, 42_000).unwrap();
|
||||
assert_eq!(sample.timestamp_ms, 42_000);
|
||||
assert!((sample.cpu_percent - 12.34).abs() < 1e-6);
|
||||
assert!(sample.mem_used_bytes > 930_000_000 && sample.mem_used_bytes < 940_000_000);
|
||||
assert_eq!(sample.net_rx_bytes, 281_000_000);
|
||||
assert_eq!(sample.net_tx_bytes, 1_200_000);
|
||||
assert_eq!(sample.disk_read_bytes, 274_000_000);
|
||||
assert_eq!(sample.disk_write_bytes, 11_400_000_000);
|
||||
assert_eq!(sample.pids, 17);
|
||||
assert!(sample.approximate_io);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ pub enum Capability {
|
||||
DatabaseSources,
|
||||
/// Read table metadata of connected project sources; never rows or credentials.
|
||||
DatabaseSchema,
|
||||
/// Execute SQL statements against connected project database sources.
|
||||
DatabaseQuery,
|
||||
VcsRead,
|
||||
VcsWrite,
|
||||
/// The Maven / Gradle dependency graph the IDE resolved.
|
||||
@@ -73,6 +75,10 @@ pub enum Capability {
|
||||
JavaAgent,
|
||||
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
|
||||
Agents,
|
||||
/// Read stdout and stderr lines from Run and Debug consoles in trusted projects (API 1.21).
|
||||
RunOutput,
|
||||
/// Query running IDE language servers for symbol types, definitions, references and outlines (API 1.21).
|
||||
CodeSemantics,
|
||||
}
|
||||
|
||||
/// How a grant is presented (plan 4.2).
|
||||
@@ -90,9 +96,13 @@ pub enum Risk {
|
||||
impl Capability {
|
||||
pub fn risk(&self) -> Risk {
|
||||
match self {
|
||||
Self::ProjectRead | Self::EditorRead | Self::Storage | Self::Events | Self::VcsRead | Self::BuildRead => {
|
||||
Risk::Low
|
||||
}
|
||||
Self::ProjectRead
|
||||
| Self::EditorRead
|
||||
| Self::Storage
|
||||
| Self::Events
|
||||
| Self::VcsRead
|
||||
| Self::BuildRead
|
||||
| Self::CodeSemantics => Risk::Low,
|
||||
Self::EditorWrite
|
||||
| Self::DatabaseSources
|
||||
| Self::DatabaseSchema
|
||||
@@ -105,10 +115,12 @@ impl Capability {
|
||||
| Self::InputEvents
|
||||
| Self::Clipboard
|
||||
| Self::ClipboardRead
|
||||
| Self::Agents => Risk::Medium,
|
||||
| Self::Agents
|
||||
| Self::RunOutput => Risk::Medium,
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
| Self::DatabaseQuery
|
||||
| Self::IdeCommands
|
||||
| Self::Ipc(_)
|
||||
| Self::Process(_)
|
||||
@@ -134,6 +146,7 @@ impl Capability {
|
||||
Self::ProjectWrite => "Create and change files in the open project".into(),
|
||||
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
|
||||
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
|
||||
Self::DatabaseQuery => "Execute SQL queries and statements on connected database sources in trusted projects".into(),
|
||||
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
|
||||
Self::VcsRead => "Read version control state".into(),
|
||||
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
|
||||
@@ -171,6 +184,10 @@ impl Capability {
|
||||
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
|
||||
Self::JavaAgent => "Run code inside the Java applications you start".into(),
|
||||
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
|
||||
Self::RunOutput => "Read stdout and stderr output from Run and Debug consoles in trusted projects".into(),
|
||||
Self::CodeSemantics => {
|
||||
"Query language server symbol definitions, types, references and outlines in trusted projects".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +311,7 @@ impl fmt::Display for Capability {
|
||||
Self::IdeCommands => f.write_str("ide.commands"),
|
||||
Self::DatabaseSources => f.write_str("database.sources"),
|
||||
Self::DatabaseSchema => f.write_str("database.schema"),
|
||||
Self::DatabaseQuery => f.write_str("database.query"),
|
||||
Self::VcsRead => f.write_str("vcs.read"),
|
||||
Self::VcsWrite => f.write_str("vcs.write"),
|
||||
Self::BuildRead => f.write_str("build.read"),
|
||||
@@ -315,6 +333,8 @@ impl fmt::Display for Capability {
|
||||
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
|
||||
Self::JavaAgent => f.write_str("java.agent"),
|
||||
Self::Agents => f.write_str("agents"),
|
||||
Self::RunOutput => f.write_str("run.output"),
|
||||
Self::CodeSemantics => f.write_str("code.semantics"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -389,6 +409,7 @@ impl FromStr for Capability {
|
||||
"ide.commands" => Self::IdeCommands,
|
||||
"database.sources" => Self::DatabaseSources,
|
||||
"database.schema" => Self::DatabaseSchema,
|
||||
"database.query" => Self::DatabaseQuery,
|
||||
"vcs.read" => Self::VcsRead,
|
||||
"vcs.write" => Self::VcsWrite,
|
||||
"build.read" => Self::BuildRead,
|
||||
@@ -400,6 +421,8 @@ impl FromStr for Capability {
|
||||
"clipboard.read" => Self::ClipboardRead,
|
||||
"java.agent" => Self::JavaAgent,
|
||||
"agents" => Self::Agents,
|
||||
"run.output" => Self::RunOutput,
|
||||
"code.semantics" => Self::CodeSemantics,
|
||||
_ => return Err(format!("unknown capability {s:?}")),
|
||||
})
|
||||
}
|
||||
@@ -700,6 +723,23 @@ mod database_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_query_is_a_separate_high_risk_grant_requiring_api21() {
|
||||
let cap: Capability = "database.query".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseQuery);
|
||||
assert_eq!(cap.to_string(), "database.query");
|
||||
assert_eq!(cap.risk(), Risk::High);
|
||||
assert!(!cap.auto_migrates());
|
||||
for other in [Capability::ProjectRead, Capability::DatabaseSources, Capability::DatabaseSchema] {
|
||||
assert!(!other.covers(&cap));
|
||||
}
|
||||
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
|
||||
let text = format!(
|
||||
"id='query'\nname='Query'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.query']"
|
||||
);
|
||||
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
|
||||
let cap: Capability = "database.sources".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseSources);
|
||||
|
||||
@@ -169,6 +169,7 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"document-changed",
|
||||
"websocket-ready",
|
||||
"run-started",
|
||||
"run-output",
|
||||
"run-exited",
|
||||
"terminal-exited",
|
||||
"content-tab-action",
|
||||
@@ -430,9 +431,15 @@ impl Manifest {
|
||||
if matches!(cap, Capability::DatabaseSchema) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 20)?;
|
||||
}
|
||||
if matches!(cap, Capability::DatabaseQuery) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 21)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::RunOutput | Capability::CodeSemantics) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 21)?;
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
@@ -476,7 +483,7 @@ impl Manifest {
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "run-started") {
|
||||
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output")) {
|
||||
self.needs_api(&format!("`{event}`"), 21)?;
|
||||
}
|
||||
if !seen.insert(event) {
|
||||
|
||||
@@ -1999,6 +1999,7 @@ impl AutomationService {
|
||||
config: auto.config.clone(),
|
||||
isolation,
|
||||
base,
|
||||
worktree_path: None,
|
||||
mcp_overrides: auto.mcp_overrides.clone(),
|
||||
skill_overrides: auto.skill_overrides.clone(),
|
||||
memory_overrides: auto.memory_overrides.clone(),
|
||||
|
||||
@@ -31,6 +31,7 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub(crate) mod singleflight;
|
||||
pub mod svn;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
|
||||
@@ -803,6 +803,10 @@ fn shell_invocation(shell: Option<&str>, line: &str) -> (String, Vec<String>) {
|
||||
"cmd" => (line.to_owned(), Vec::new()),
|
||||
"pwsh" | "powershell" => {
|
||||
args.retain(|a| a != "-l");
|
||||
// As in the terminal: script shims such as npm.ps1 run under the default policy.
|
||||
if cfg!(windows) {
|
||||
args.extend(["-ExecutionPolicy".to_owned(), "Bypass".to_owned()]);
|
||||
}
|
||||
args.extend(["-NoLogo".to_owned(), "-Command".to_owned(), line.to_owned()]);
|
||||
(program, args)
|
||||
}
|
||||
@@ -1141,7 +1145,12 @@ mod tests {
|
||||
assert_eq!(shell_invocation(Some("/bin/zsh"), "ls -a").1, ["-l", "-c", "ls -a"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/bash --norc"), "ls").1, ["--norc", "-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/tcsh"), "ls").1, ["-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, ["-NoLogo", "-Command", "ls"]);
|
||||
let pwsh: &[&str] = if cfg!(windows) {
|
||||
&["-ExecutionPolicy", "Bypass", "-NoLogo", "-Command", "ls"]
|
||||
} else {
|
||||
&["-NoLogo", "-Command", "ls"]
|
||||
};
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, pwsh);
|
||||
assert_eq!(shell_invocation(Some("cmd.exe"), "dir /b"), ("dir /b".to_owned(), Vec::new()));
|
||||
}
|
||||
|
||||
|
||||
@@ -939,8 +939,10 @@ impl Walk {
|
||||
continue;
|
||||
}
|
||||
let Ok(in_base) = entry.path.strip_prefix(base) else { continue };
|
||||
let in_base = in_base.to_string_lossy().replace('\\', "/");
|
||||
let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m);
|
||||
if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
|
||||
if mask.is_some_and(|m| !m.matches(&in_base) || (entry.kind == EntryKind::Dir && m.excludes_dir(&in_base)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match entry.kind {
|
||||
|
||||
@@ -7,12 +7,12 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView,
|
||||
AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy,
|
||||
AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog,
|
||||
AgentPluginPreview, AgentPluginSettings, AgentProbe, AgentPrompt, AgentProvider, AgentProviderMemoryPolicy,
|
||||
AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode,
|
||||
AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus,
|
||||
CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryOverrides,
|
||||
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
|
||||
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
|
||||
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
|
||||
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult,
|
||||
McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
@@ -101,8 +101,10 @@ pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<i
|
||||
}
|
||||
|
||||
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
|
||||
/// Reads provider config and resolves the agent executable on PATH, so it runs on the
|
||||
/// blocking pool.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_refresh_models(
|
||||
pub async fn agent_refresh_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
@@ -111,7 +113,8 @@ pub fn agent_refresh_models(
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
// Refreshes the selected agent's model catalog without sending a prompt.
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.refresh_models(&provider, force, model.as_deref())).await
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
@@ -142,8 +145,8 @@ pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Ve
|
||||
host.project(window)?.agents.set_builtin_additional_args(&id, args)
|
||||
}
|
||||
|
||||
/// Environment variables built-in agent `id` starts with (saved in its agent file);
|
||||
/// an empty map clears them.
|
||||
/// Environment variables built-in agent `id`, or an instance of one, starts with (saved in
|
||||
/// its agent file); an empty map clears them.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_set_env(
|
||||
host: &Host,
|
||||
@@ -250,6 +253,42 @@ fn spawn_login_pty(
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_login_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: &str,
|
||||
) -> IdeResult<(std::path::PathBuf, LoginLaunch, String)> {
|
||||
let agent = id.to_owned();
|
||||
match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let base = agents.base_provider_id(&agent);
|
||||
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
|
||||
Ok((root, launch, base))
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let secrets = host.agent_secrets.clone();
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let (launch, base) = host
|
||||
.blocking(move || {
|
||||
let base = ide_agent::base_provider_id_without_project(Some(&custom_dir), &agent);
|
||||
ide_agent::login_launch_without_project(
|
||||
Some(&custom_dir),
|
||||
Some(secrets.as_ref()),
|
||||
&cwd_for_lookup,
|
||||
&agent,
|
||||
)
|
||||
.map(|launch| (launch, base))
|
||||
})
|
||||
.await?;
|
||||
Ok((cwd, launch, base))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
@@ -261,28 +300,9 @@ pub async fn agent_login_spawn(
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let agent = id.clone();
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &agent)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
let (cwd, mut launch, base) = resolve_login_launch(host, window, &id).await?;
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
use_device_auth(host.environment.is_remote(), &id, &mut launch.args);
|
||||
use_device_auth(host.environment.is_remote(), &base, &mut launch.args);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -306,8 +326,8 @@ pub async fn agent_gh_login_spawn(
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file; refuses built-in and
|
||||
/// ACP Registry ids and taken ids.
|
||||
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent
|
||||
/// file; refuses built-in and ACP Registry ids and taken ids.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_custom_save(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -523,6 +543,19 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
|
||||
project.agents.create(request).await
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) a Git branch in an idle task's working directory.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_checkout_branch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
branch: String,
|
||||
create: bool,
|
||||
) -> IdeResult<ide_vcs::CheckoutOutcome> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.checkout_branch(&task, &branch, create).await
|
||||
}
|
||||
|
||||
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
@@ -1773,7 +1806,7 @@ fn memory_settings_layers(
|
||||
}
|
||||
|
||||
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
|
||||
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
|
||||
s.providers.is_empty()
|
||||
}
|
||||
|
||||
fn persist_memory_settings(
|
||||
@@ -1834,82 +1867,53 @@ pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemo
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
|
||||
/// never modifying the file on disk.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_mode(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
scope: McpScope,
|
||||
mode: AgentMemoryMode,
|
||||
agents: Vec<String>,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let id = id.trim().to_owned();
|
||||
if id.is_empty() {
|
||||
return Err(IdeError::invalid("a memory entry needs an id"));
|
||||
}
|
||||
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
|
||||
layer.entries.remove(&id).is_some()
|
||||
} else {
|
||||
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
|
||||
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
if apply(&mut user) {
|
||||
persist_memory_settings(host, None, scope, &user)?;
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws =
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
|
||||
if apply(ws) {
|
||||
let updated = ws.clone();
|
||||
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
|
||||
/// globally or for one `provider` in `scope`.
|
||||
/// Sets the cross-session auto-memory policy for one `provider` in `scope`.
|
||||
/// For native-config providers (Hermes), writes the agent's own config file directly.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_auto(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
provider: Option<String>,
|
||||
provider: String,
|
||||
mode: AutoMemoryMode,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let raw_provider = provider.trim();
|
||||
if raw_provider.is_empty() {
|
||||
return Err(IdeError::invalid("a provider id is required to configure auto-memory"));
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let base = project.as_ref().map(|p| p.agents.base_provider_id(raw_provider));
|
||||
let resolved_provider = base.as_deref().unwrap_or(raw_provider);
|
||||
let supported = ide_agent::memory::supported_auto_memory_modes(resolved_provider);
|
||||
if supported.is_empty() {
|
||||
return Err(IdeError::invalid(format!("Auto-memory control is not supported for `{raw_provider}`")));
|
||||
}
|
||||
if !supported.contains(&mode) {
|
||||
return Err(IdeError::invalid(format!("Auto-memory mode `{mode:?}` is not supported for `{raw_provider}`")));
|
||||
}
|
||||
|
||||
if ide_agent::memory::is_native_config_auto_memory(resolved_provider) {
|
||||
let provider_owned = resolved_provider.to_owned();
|
||||
let home = host.home_dir();
|
||||
blocking(move || {
|
||||
ide_agent::memory::set_hermes_auto_memory(&provider_owned, mode, home.as_deref()).map_err(IdeError::invalid)
|
||||
})
|
||||
.await?;
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
|
||||
for p in host.projects() {
|
||||
p.sink.emit(event.clone());
|
||||
}
|
||||
return current_memory_catalog(host, project.as_deref()).await;
|
||||
}
|
||||
|
||||
let key = ide_agent::memory::provider_key(resolved_provider).to_owned();
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let prov_key = provider
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
match &prov_key {
|
||||
None => {
|
||||
let changed = layer.auto_memory != mode;
|
||||
layer.auto_memory = mode;
|
||||
changed
|
||||
}
|
||||
Some(key) => {
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
}
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(&key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
@@ -2887,6 +2891,45 @@ mod tests {
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resolve_login_launch_without_project_reads_instance_env_from_secrets() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Host::new(crate::HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("data"),
|
||||
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: std::sync::Arc::default(),
|
||||
sink_for: Box::new(|_| std::sync::Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let bin = tmp.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" });
|
||||
std::fs::write(&bin, if cfg!(windows) { "@echo off\r\n" } else { "#!/bin/sh\n" }).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let agents_dir = host.config_dir.join("agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
std::fs::write(
|
||||
agents_dir.join("claude.toml"),
|
||||
format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(agents_dir.join("claude-work.toml"), "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"\"\n")
|
||||
.unwrap();
|
||||
host.agent_secrets.set("agent/claude-work/env/CLAUDE_CONFIG_DIR", "/home/me/.claude-work").unwrap();
|
||||
|
||||
let (_, launch, base) = resolve_login_launch(&host, "no-project", "claude-work").await.unwrap();
|
||||
assert_eq!(base, "claude");
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
@@ -2911,6 +2954,7 @@ ide_command::domain!(
|
||||
agent_automation_save,
|
||||
agent_automation_set_enabled,
|
||||
agent_automation_snapshot,
|
||||
agent_checkout_branch,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
@@ -2946,7 +2990,6 @@ ide_command::domain!(
|
||||
agent_memory_promote,
|
||||
agent_memory_reset_provider,
|
||||
agent_memory_set_auto,
|
||||
agent_memory_set_mode,
|
||||
agent_plugins_add_marketplace,
|
||||
agent_plugins_browse_marketplace,
|
||||
agent_plugins_install,
|
||||
|
||||
Loaded 100 of 1376 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача